Yet another Fluxer bot built with TypeScript and Bun
at develop 37 lines 1.0 kB view raw
1import path from "node:path"; 2import type { CommandRegistry } from "./commandRegistry"; 3import { Logger } from "tslog"; 4import { MODULE_META_KEY } from "@/base/ModuleBase"; 5 6const logger = new Logger({ 7 type: "pretty", 8 name: "loadModules", 9}); 10 11export async function loadModules( 12 registry: CommandRegistry, 13 prefix: string, 14 pattern = "src/commands/**/*.ts", 15 options?: { namespace?: string }, 16): Promise<void> { 17 const glob = new Bun.Glob(pattern); 18 19 for await (const file of glob.scan(".")) { 20 const absPath = path.resolve(file); 21 22 logger.debug(`Loading module from "${absPath}"`); 23 24 const mod = await import(Bun.pathToFileURL(absPath).href); 25 26 for (const exported of Object.values(mod)) { 27 if (isModuleCtor(exported)) { 28 const instance = new exported(); 29 registry.registerModule(prefix, instance, options); 30 } 31 } 32 } 33} 34 35function isModuleCtor(val: unknown): val is new () => object { 36 return typeof val === "function" && Reflect.hasMetadata(MODULE_META_KEY, val); 37}