kozukata-toa/src/servers/titles/utils/reflection.ts

42 lines
895 B
TypeScript

/* eslint-disable cadence/no-instanceof */
function IsRecord<T = string>(v: unknown): v is Record<string, T> {
return v !== null && typeof v === "object" && !Array.isArray(v);
}
export function GetClassMethods(className: unknown): Array<string> {
if (typeof className !== "function" || !("prototype" in className)) {
throw new Error("Not a class");
}
if (!IsRecord(className.prototype)) {
throw new Error("Not a class");
}
const ret = new Set<string>();
function methods(obj: Record<number | string | symbol, unknown> | null | undefined) {
if (obj === null || obj === undefined) {
return;
}
const ps = Object.getOwnPropertyNames(obj);
for (const p of ps) {
try {
if (obj[p] instanceof Function) {
ret.add(p);
}
} catch {
continue;
}
}
methods(Object.getPrototypeOf(obj));
}
methods(className.prototype);
return Array.from(ret);
}