import path from "node:path"; import type { CommandRegistry } from "./commandRegistry"; import { Logger } from "tslog"; import { MODULE_META_KEY } from "@/base/ModuleBase"; const logger = new Logger({ type: "pretty", name: "loadModules", }); export async function loadModules( registry: CommandRegistry, prefix: string, pattern = "src/commands/**/*.ts", options?: { namespace?: string }, ): Promise { const glob = new Bun.Glob(pattern); for await (const file of glob.scan(".")) { const absPath = path.resolve(file); logger.debug(`Loading module from "${absPath}"`); const mod = await import(Bun.pathToFileURL(absPath).href); for (const exported of Object.values(mod)) { if (isModuleCtor(exported)) { const instance = new exported(); registry.registerModule(prefix, instance, options); } } } } function isModuleCtor(val: unknown): val is new () => object { return typeof val === "function" && Reflect.hasMetadata(MODULE_META_KEY, val); }