commandkit 1.0.0-dev.20250520125246 → 1.0.0-dev.20250521020104
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/components.cjs +1 -0
- package/components.d.ts +1 -0
- package/config.cjs +5 -0
- package/config.d.ts +1 -0
- package/dist/CommandKit-jZCy9fZX.d.ts +914 -0
- package/dist/CommandKit.d.ts +13 -0
- package/dist/CommandKit.js +16 -0
- package/dist/CommandKit.js.map +1 -0
- package/dist/app/commands/AppCommandRunner.d.ts +13 -0
- package/dist/app/commands/AppCommandRunner.js +3 -0
- package/dist/app/commands/AppCommandRunner.js.map +1 -0
- package/dist/app/commands/Context.d.ts +13 -0
- package/dist/app/commands/Context.js +3 -0
- package/dist/app/commands/Context.js.map +1 -0
- package/dist/app/commands/MessageCommandParser.d.ts +60 -0
- package/dist/app/commands/MessageCommandParser.js +2 -0
- package/dist/app/commands/MessageCommandParser.js.map +1 -0
- package/dist/app/commands/helpers.d.ts +7 -0
- package/dist/app/commands/helpers.js +2 -0
- package/dist/app/commands/helpers.js.map +1 -0
- package/dist/app/events/EventWorkerContext.d.ts +28 -0
- package/dist/app/events/EventWorkerContext.js +2 -0
- package/dist/app/events/EventWorkerContext.js.map +1 -0
- package/dist/app/handlers/AppCommandHandler.d.ts +13 -0
- package/dist/app/handlers/AppCommandHandler.js +8 -0
- package/dist/app/handlers/AppCommandHandler.js.map +1 -0
- package/dist/app/handlers/AppEventsHandler.d.ts +13 -0
- package/dist/app/handlers/AppEventsHandler.js +3 -0
- package/dist/app/handlers/AppEventsHandler.js.map +1 -0
- package/dist/app/index.d.ts +15 -0
- package/dist/app/index.js +8 -0
- package/dist/app/index.js.map +1 -0
- package/dist/app/middleware/signals.d.ts +18 -0
- package/dist/app/middleware/signals.js +2 -0
- package/dist/app/middleware/signals.js.map +1 -0
- package/dist/app/register/CommandRegistrar.d.ts +13 -0
- package/dist/app/register/CommandRegistrar.js +3 -0
- package/dist/app/register/CommandRegistrar.js.map +1 -0
- package/dist/app/router/CommandsRouter.d.ts +65 -0
- package/dist/app/router/CommandsRouter.js +2 -0
- package/dist/app/router/CommandsRouter.js.map +1 -0
- package/dist/app/router/EventsRouter.d.ts +88 -0
- package/dist/app/router/EventsRouter.js +2 -0
- package/dist/app/router/EventsRouter.js.map +1 -0
- package/dist/app/router/index.d.ts +3 -0
- package/dist/app/router/index.js +2 -0
- package/dist/app/router/index.js.map +1 -0
- package/dist/cli/app-process.d.ts +5 -0
- package/dist/cli/app-process.js +3 -0
- package/dist/cli/app-process.js.map +1 -0
- package/dist/cli/build.d.ts +24 -0
- package/dist/cli/build.js +49 -0
- package/dist/cli/build.js.map +1 -0
- package/dist/cli/common.d.ts +31 -0
- package/dist/cli/common.js +10 -0
- package/dist/cli/common.js.map +1 -0
- package/dist/cli/development.d.ts +3 -0
- package/dist/cli/development.js +55 -0
- package/dist/cli/development.js.map +1 -0
- package/dist/cli/env.d.ts +15 -0
- package/dist/cli/env.js +2 -0
- package/dist/cli/env.js.map +1 -0
- package/dist/cli/generators.d.ts +4 -0
- package/dist/cli/generators.js +42 -0
- package/dist/cli/generators.js.map +1 -0
- package/dist/cli/information.d.ts +3 -0
- package/dist/cli/information.js +7 -0
- package/dist/cli/information.js.map +1 -0
- package/dist/cli/init.d.ts +10 -0
- package/dist/cli/init.js +100 -0
- package/dist/cli/init.js.map +1 -0
- package/dist/cli/parse-env.d.ts +3 -0
- package/dist/cli/parse-env.js +2 -0
- package/dist/cli/parse-env.js.map +1 -0
- package/dist/cli/production.d.ts +6 -0
- package/dist/cli/production.js +50 -0
- package/dist/cli/production.js.map +1 -0
- package/dist/cli/type-checker.d.ts +7 -0
- package/dist/cli/type-checker.js +5 -0
- package/dist/cli/type-checker.js.map +1 -0
- package/dist/cli/utils.d.ts +5 -0
- package/dist/cli/utils.js +2 -0
- package/dist/cli/utils.js.map +1 -0
- package/dist/components/common/EventInterceptor.d.ts +82 -0
- package/dist/components/common/EventInterceptor.js +2 -0
- package/dist/components/common/EventInterceptor.js.map +1 -0
- package/dist/components/common/element.d.ts +29 -0
- package/dist/components/common/element.js +2 -0
- package/dist/components/common/element.js.map +1 -0
- package/dist/components/common/types.d.ts +3 -0
- package/dist/components/common/types.js +2 -0
- package/dist/components/common/types.js.map +1 -0
- package/dist/components/index.d.ts +22 -0
- package/dist/components/index.js +16 -0
- package/dist/components/index.js.map +1 -0
- package/dist/components/v1/action-row/ActionRow.d.ts +18 -0
- package/dist/components/v1/action-row/ActionRow.js +2 -0
- package/dist/components/v1/action-row/ActionRow.js.map +1 -0
- package/dist/components/v1/button/Button.d.ts +31 -0
- package/dist/components/v1/button/Button.js +16 -0
- package/dist/components/v1/button/Button.js.map +1 -0
- package/dist/components/v1/button/ButtonKit.d.ts +66 -0
- package/dist/components/v1/button/ButtonKit.js +16 -0
- package/dist/components/v1/button/ButtonKit.js.map +1 -0
- package/dist/components/v1/modal/Modal.d.ts +57 -0
- package/dist/components/v1/modal/Modal.js +16 -0
- package/dist/components/v1/modal/Modal.js.map +1 -0
- package/dist/components/v1/modal/ModalKit.d.ts +64 -0
- package/dist/components/v1/modal/ModalKit.js +16 -0
- package/dist/components/v1/modal/ModalKit.js.map +1 -0
- package/dist/components/v1/select-menu/ChannelSelectMenuKit.d.ts +49 -0
- package/dist/components/v1/select-menu/ChannelSelectMenuKit.js +16 -0
- package/dist/components/v1/select-menu/ChannelSelectMenuKit.js.map +1 -0
- package/dist/components/v1/select-menu/MentionableSelectMenuKit.d.ts +49 -0
- package/dist/components/v1/select-menu/MentionableSelectMenuKit.js +16 -0
- package/dist/components/v1/select-menu/MentionableSelectMenuKit.js.map +1 -0
- package/dist/components/v1/select-menu/RoleSelectMenuKit.d.ts +49 -0
- package/dist/components/v1/select-menu/RoleSelectMenuKit.js +16 -0
- package/dist/components/v1/select-menu/RoleSelectMenuKit.js.map +1 -0
- package/dist/components/v1/select-menu/SelectMenu.d.ts +40 -0
- package/dist/components/v1/select-menu/SelectMenu.js +16 -0
- package/dist/components/v1/select-menu/SelectMenu.js.map +1 -0
- package/dist/components/v1/select-menu/StringSelectMenuKit.d.ts +49 -0
- package/dist/components/v1/select-menu/StringSelectMenuKit.js +16 -0
- package/dist/components/v1/select-menu/StringSelectMenuKit.js.map +1 -0
- package/dist/components/v1/select-menu/UserSelectMenuKit.d.ts +49 -0
- package/dist/components/v1/select-menu/UserSelectMenuKit.js +16 -0
- package/dist/components/v1/select-menu/UserSelectMenuKit.js.map +1 -0
- package/dist/components/v1/select-menu/common.d.ts +23 -0
- package/dist/components/v1/select-menu/common.js +2 -0
- package/dist/components/v1/select-menu/common.js.map +1 -0
- package/dist/components/v2/common.d.ts +7 -0
- package/dist/components/v2/common.js +2 -0
- package/dist/components/v2/common.js.map +1 -0
- package/dist/components/v2/container.d.ts +8 -0
- package/dist/components/v2/container.js +2 -0
- package/dist/components/v2/container.js.map +1 -0
- package/dist/components/v2/file.d.ts +8 -0
- package/dist/components/v2/file.js +2 -0
- package/dist/components/v2/file.js.map +1 -0
- package/dist/components/v2/index.d.ts +7 -0
- package/dist/components/v2/index.js +2 -0
- package/dist/components/v2/index.js.map +1 -0
- package/dist/components/v2/media-gallery.d.ts +15 -0
- package/dist/components/v2/media-gallery.js +2 -0
- package/dist/components/v2/media-gallery.js.map +1 -0
- package/dist/components/v2/section.d.ts +16 -0
- package/dist/components/v2/section.js +2 -0
- package/dist/components/v2/section.js.map +1 -0
- package/dist/components/v2/separator.d.ts +7 -0
- package/dist/components/v2/separator.js +2 -0
- package/dist/components/v2/separator.js.map +1 -0
- package/dist/components/v2/text-display.d.ts +10 -0
- package/dist/components/v2/text-display.js +2 -0
- package/dist/components/v2/text-display.js.map +1 -0
- package/dist/config/config.d.ts +28 -0
- package/dist/config/config.js +3 -0
- package/dist/config/config.js.map +1 -0
- package/dist/config/default.d.ts +20 -0
- package/dist/config/default.js +3 -0
- package/dist/config/default.js.map +1 -0
- package/dist/config/loader.d.ts +25 -0
- package/dist/config/loader.js +11 -0
- package/dist/config/loader.js.map +1 -0
- package/dist/config/types.d.ts +83 -0
- package/dist/config/types.js +2 -0
- package/dist/config/types.js.map +1 -0
- package/dist/config/utils.d.ts +26 -0
- package/dist/config/utils.js +2 -0
- package/dist/config/utils.js.map +1 -0
- package/dist/context/async-context.d.ts +13 -0
- package/dist/context/async-context.js +16 -0
- package/dist/context/async-context.js.map +1 -0
- package/dist/context/environment.d.ts +13 -0
- package/dist/context/environment.js +3 -0
- package/dist/context/environment.js.map +1 -0
- package/dist/events/CommandKitEventsChannel.d.ts +13 -0
- package/dist/events/CommandKitEventsChannel.js +2 -0
- package/dist/events/CommandKitEventsChannel.js.map +1 -0
- package/dist/flags/feature-flags.d.ts +13 -0
- package/dist/flags/feature-flags.js +16 -0
- package/dist/flags/feature-flags.js.map +1 -0
- package/dist/flags/store.d.ts +13 -0
- package/dist/flags/store.js +2 -0
- package/dist/flags/store.js.map +1 -0
- package/dist/index.d.ts +51 -2024
- package/dist/index.js +43 -6912
- package/dist/index.js.map +1 -1
- package/dist/logger/DefaultLogger.d.ts +28 -0
- package/dist/logger/DefaultLogger.js +3 -0
- package/dist/logger/DefaultLogger.js.map +1 -0
- package/dist/logger/ILogger.d.ts +9 -0
- package/dist/logger/ILogger.js +2 -0
- package/dist/logger/ILogger.js.map +1 -0
- package/dist/logger/Logger.d.ts +15 -0
- package/dist/logger/Logger.js +3 -0
- package/dist/logger/Logger.js.map +1 -0
- package/dist/plugins/CompilerPlugin.d.ts +13 -0
- package/dist/plugins/CompilerPlugin.js +2 -0
- package/dist/plugins/CompilerPlugin.js.map +1 -0
- package/dist/plugins/PluginCommon.d.ts +13 -0
- package/dist/plugins/PluginCommon.js +2 -0
- package/dist/plugins/PluginCommon.js.map +1 -0
- package/dist/plugins/RuntimePlugin.d.ts +13 -0
- package/dist/plugins/RuntimePlugin.js +2 -0
- package/dist/plugins/RuntimePlugin.js.map +1 -0
- package/dist/plugins/index.d.ts +15 -0
- package/dist/plugins/index.js +3 -0
- package/dist/plugins/index.js.map +1 -0
- package/dist/plugins/plugin-runtime/CommandKitPluginRuntime.d.ts +13 -0
- package/dist/plugins/plugin-runtime/CommandKitPluginRuntime.js +3 -0
- package/dist/plugins/plugin-runtime/CommandKitPluginRuntime.js.map +1 -0
- package/dist/plugins/plugin-runtime/CompilerPluginRuntime.d.ts +13 -0
- package/dist/plugins/plugin-runtime/CompilerPluginRuntime.js +3 -0
- package/dist/plugins/plugin-runtime/CompilerPluginRuntime.js.map +1 -0
- package/dist/plugins/plugin-runtime/builtin/CommonDirectiveTransformer.d.ts +26 -0
- package/dist/plugins/plugin-runtime/builtin/CommonDirectiveTransformer.js +3 -0
- package/dist/plugins/plugin-runtime/builtin/CommonDirectiveTransformer.js.map +1 -0
- package/dist/plugins/plugin-runtime/builtin/MacroPlugin.d.ts +23 -0
- package/dist/plugins/plugin-runtime/builtin/MacroPlugin.js +3 -0
- package/dist/plugins/plugin-runtime/builtin/MacroPlugin.js.map +1 -0
- package/dist/plugins/plugin-runtime/runtime.d.ts +13 -0
- package/dist/plugins/plugin-runtime/runtime.js +2 -0
- package/dist/plugins/plugin-runtime/runtime.js.map +1 -0
- package/dist/plugins/plugin-runtime/types.d.ts +72 -0
- package/dist/plugins/plugin-runtime/types.js +2 -0
- package/dist/plugins/plugin-runtime/types.js.map +1 -0
- package/dist/plugins/types.d.ts +13 -0
- package/dist/plugins/types.js +2 -0
- package/dist/plugins/types.js.map +1 -0
- package/dist/types.d.ts +13 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/dist/utils/clone.d.ts +3 -0
- package/dist/utils/clone.js +2 -0
- package/dist/utils/clone.js.map +1 -0
- package/dist/utils/colors.d.ts +5 -0
- package/dist/utils/colors.js +2 -0
- package/dist/utils/colors.js.map +1 -0
- package/dist/utils/constants.d.ts +15 -0
- package/dist/utils/constants.js +2 -0
- package/dist/utils/constants.js.map +1 -0
- package/dist/utils/dev-hooks.d.ts +13 -0
- package/dist/utils/dev-hooks.js +3 -0
- package/dist/utils/dev-hooks.js.map +1 -0
- package/dist/utils/error-codes.d.ts +14 -0
- package/dist/utils/error-codes.js +2 -0
- package/dist/utils/error-codes.js.map +1 -0
- package/dist/utils/get-paths.d.ts +4 -0
- package/dist/utils/get-paths.js +2 -0
- package/dist/utils/get-paths.js.map +1 -0
- package/dist/utils/resolve-file-url.d.ts +9 -0
- package/dist/utils/resolve-file-url.js +2 -0
- package/dist/utils/resolve-file-url.js.map +1 -0
- package/dist/utils/types-package.d.ts +4 -0
- package/dist/utils/types-package.js +14 -0
- package/dist/utils/types-package.js.map +1 -0
- package/dist/utils/utilities.d.ts +40 -0
- package/dist/utils/utilities.js +3 -0
- package/dist/utils/utilities.js.map +1 -0
- package/dist/utils/warn-unstable.d.ts +4 -0
- package/dist/utils/warn-unstable.js +2 -0
- package/dist/utils/warn-unstable.js.map +1 -0
- package/dist/version.d.ts +6 -0
- package/dist/version.js +2 -0
- package/dist/version.js.map +1 -0
- package/hooks.cjs +48 -0
- package/hooks.d.ts +18 -0
- package/jsx-runtime.cjs +1 -1
- package/jsx-runtime.d.ts +1 -1
- package/package.json +32 -5
- package/plugin.cjs +10 -0
- package/plugin.d.ts +9 -0
- package/jsx-runtime.mjs +0 -5
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/app/router/CommandsRouter.ts"],"sourcesContent":["import { Collection } from 'discord.js';\nimport { Dirent, existsSync } from 'node:fs';\nimport { readdir } from 'node:fs/promises';\nimport { basename, extname, join, normalize } from 'node:path';\n\nexport interface Command {\n id: string;\n name: string;\n path: string;\n relativePath: string;\n parentPath: string;\n middlewares: Array<string>;\n category: string | null;\n}\n\nexport interface Middleware {\n id: string;\n name: string;\n path: string;\n relativePath: string;\n parentPath: string;\n global: boolean;\n command: string | null;\n}\n\nexport interface ParsedCommandData {\n commands: Record<string, Command>;\n middlewares: Record<string, Middleware>;\n}\n\nexport interface CommandsRouterOptions {\n entrypoint: string;\n}\n\nconst MIDDLEWARE_PATTERN = /^\\+middleware\\.(m|c)?(j|t)sx?$/;\nconst COMMAND_MIDDLEWARE_PATTERN =\n/^\\+([^+().][^().]*)\\.middleware\\.(m|c)?(j|t)sx?$/;\nconst GLOBAL_MIDDLEWARE_PATTERN = /^\\+global-middleware\\.(m|c)?(j|t)sx?$/;\nconst COMMAND_PATTERN = /^([^+().][^().]*)\\.(m|c)?(j|t)sx?$/;\nconst CATEGORY_PATTERN = /^\\(.+\\)$/;\n\nexport class CommandsRouter {\n private commands = new Collection<string, Command>();\n private middlewares = new Collection<string, Middleware>();\n\n public constructor(private readonly options: CommandsRouterOptions) {}\n\n public populate(data: ParsedCommandData) {\n for (const [id, command] of Object.entries(data.commands)) {\n this.commands.set(id, command);\n }\n\n for (const [id, middleware] of Object.entries(data.middlewares)) {\n this.middlewares.set(id, middleware);\n }\n }\n\n public isValidPath(): boolean {\n return existsSync(this.options.entrypoint);\n }\n\n private isCommand(name: string): boolean {\n return COMMAND_PATTERN.test(name);\n }\n\n private isMiddleware(name: string): boolean {\n return (\n MIDDLEWARE_PATTERN.test(name) ||\n GLOBAL_MIDDLEWARE_PATTERN.test(name) ||\n COMMAND_MIDDLEWARE_PATTERN.test(name));\n\n }\n\n private isCategory(name: string): boolean {\n return CATEGORY_PATTERN.test(name);\n }\n\n public clear() {\n this.commands.clear();\n this.middlewares.clear();\n }\n\n public async scan() {\n const entries = await readdir(this.options.entrypoint, {\n withFileTypes: true\n });\n\n for (const entry of entries) {\n // ignore _ prefixed files\n if (entry.name.startsWith('_')) continue;\n\n const fullPath = join(this.options.entrypoint, entry.name);\n\n if (entry.isDirectory()) {\n const category = this.isCategory(entry.name) ?\n entry.name.slice(1, -1) :\n null;\n\n await this.traverse(fullPath, category);\n } else {\n await this.handle(entry);\n }\n }\n\n await this.applyMiddlewares();\n\n return this.toJSON();\n }\n\n public getData() {\n return {\n commands: this.commands,\n middlewares: this.middlewares\n };\n }\n\n public toJSON() {\n return {\n commands: Object.fromEntries(this.commands.entries()),\n middlewares: Object.fromEntries(this.middlewares.entries())\n };\n }\n\n private async traverse(path: string, category: string | null) {\n const entries = await readdir(path, {\n withFileTypes: true\n });\n\n for (const entry of entries) {\n // ignore _ prefixed files\n if (entry.name.startsWith('_')) continue;\n\n if (entry.isFile()) {\n if (this.isCommand(entry.name) || this.isMiddleware(entry.name)) {\n await this.handle(entry, category);\n }\n } else if (\n entry.isDirectory() &&\n this.isCategory(entry.name) &&\n category)\n {\n // nested category\n const nestedCategory = this.isCategory(entry.name) ?\n `${category}:${entry.name.slice(1, -1)}` :\n null;\n await this.traverse(join(path, entry.name), nestedCategory);\n }\n\n // TODO: handle subcommands\n }\n }\n\n private async handle(entry: Dirent, category: string | null = null) {\n const name = entry.name;\n const path = join(entry.parentPath, entry.name);\n\n if (this.isCommand(name)) {\n const command: Command = {\n id: crypto.randomUUID(),\n name: basename(path, extname(path)),\n path,\n category,\n parentPath: entry.parentPath,\n relativePath: this.replaceEntrypoint(path),\n middlewares: []\n };\n\n this.commands.set(command.id, command);\n } else if (this.isMiddleware(name)) {\n const middleware: Middleware = {\n id: crypto.randomUUID(),\n name: basename(path, extname(path)),\n path,\n relativePath: this.replaceEntrypoint(path),\n parentPath: entry.parentPath,\n global: GLOBAL_MIDDLEWARE_PATTERN.test(name),\n command: COMMAND_MIDDLEWARE_PATTERN.test(name) ?\n name.split('.')[0] || null :\n null\n };\n\n this.middlewares.set(middleware.id, middleware);\n }\n }\n\n private applyMiddlewares() {\n this.commands.forEach((command) => {\n const commandPath = command.parentPath;\n const samePathMiddlewares = Array.from(this.middlewares.values()).\n filter((middleware) => {\n if (middleware.global) return true;\n if (middleware.command) return middleware.command === command.name;\n return middleware.parentPath === commandPath;\n }).\n map((middleware) => middleware.id);\n\n command.middlewares = Array.from(\n new Set([...command.middlewares, ...samePathMiddlewares])\n );\n });\n }\n\n private replaceEntrypoint(path: string) {\n const normalized = normalize(path);\n return normalized.replace(this.options.entrypoint, '');\n }\n}"],"mappings":"4dAAA,IAAAA,EAAA,GAAAC,EAAAD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AAS,IAAIP,EAAQ,GAAIA,CAAO,CACvC,SAAW,KAAK,aAAaE,CAAI,EAAG,CAClC,IAAMD,EAAyB,CAC7B,GAAI,OAAO,WAAW,EACtB,QAAM,YAASM,KAAM,WAAQA,CAAI,CAAC,EAClC,KAAAA,EACA,aAAc,KAAK,kBAAkBA,CAAI,EACzC,WAAYH,EAAM,WAClB,OAAQX,EAA0B,KAAKS,CAAI,EAC3C,QAASV,EAA2B,KAAKU,CAAI,GAC7CA,EAAK,MAAM,GAAG,EAAE,CAAC,GAAK,IAExB,EAEA,KAAK,YAAY,IAAID,EAAW,GAAIA,CAAU,CAChD,CACF,CAEQ,kBAAmB,CACzB,KAAK,SAAS,QAASD,GAAY,CACjC,IAAMS,EAAcT,EAAQ,WACtBU,EAAsB,MAAM,KAAK,KAAK,YAAY,OAAO,CAAC,EAChE,OAAQT,GACFA,EAAW,OAAe,GAC1BA,EAAW,QAAgBA,EAAW,UAAYD,EAAQ,KACvDC,EAAW,aAAeQ,CAClC,EACD,IAAKR,GAAeA,EAAW,EAAE,EAEjCD,EAAQ,YAAc,MAAM,KAC1B,IAAI,IAAI,CAAC,GAAGA,EAAQ,YAAa,GAAGU,CAAmB,CAAC,CAC1D,CACF,CAAC,CACH,CAEQ,kBAAkBH,EAAc,CAEtC,SADmB,aAAUA,CAAI,EACf,QAAQ,KAAK,QAAQ,WAAY,EAAE,CACvD,CACF,EArK4BI,EAAAf,EAAA,kBAArB,IAAMgB,EAANhB","names":["CommandsRouter_exports","__export","CommandsRouter","__toCommonJS","import_discord","import_node_fs","import_promises","import_node_path","MIDDLEWARE_PATTERN","COMMAND_MIDDLEWARE_PATTERN","GLOBAL_MIDDLEWARE_PATTERN","COMMAND_PATTERN","CATEGORY_PATTERN","_CommandsRouter","options","data","id","command","middleware","name","entries","entry","fullPath","category","path","nestedCategory","commandPath","samePathMiddlewares","__name","CommandsRouter"]}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Configuration options for the EventsRouter
|
|
3
|
+
* @interface EventsRouterOptions
|
|
4
|
+
*/
|
|
5
|
+
interface EventsRouterOptions {
|
|
6
|
+
/** Root directory path where event handlers are located */
|
|
7
|
+
entrypoints: string[];
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Represents a parsed event with its handlers
|
|
11
|
+
* @interface ParsedEvent
|
|
12
|
+
*/
|
|
13
|
+
interface ParsedEvent {
|
|
14
|
+
/** Name of the event derived from directory name */
|
|
15
|
+
event: string;
|
|
16
|
+
/** Absolute path to the event directory */
|
|
17
|
+
path: string;
|
|
18
|
+
/** Array of file paths to event listener handlers */
|
|
19
|
+
listeners: string[];
|
|
20
|
+
/** Namespace of the event */
|
|
21
|
+
namespace: string | null;
|
|
22
|
+
}
|
|
23
|
+
/** Collection of event names to their parsed metadata */
|
|
24
|
+
type EventsTree = Record<string, ParsedEvent>;
|
|
25
|
+
/**
|
|
26
|
+
* Router for discovering and managing event handler files in a directory structure.
|
|
27
|
+
* Events are represented by directories, and handlers are files within those directories.
|
|
28
|
+
*/
|
|
29
|
+
declare class EventsRouter {
|
|
30
|
+
private options;
|
|
31
|
+
/** Internal storage of parsed events */
|
|
32
|
+
private events;
|
|
33
|
+
/**
|
|
34
|
+
* Creates a new EventsRouter instance
|
|
35
|
+
* @param options - Configuration options for the router
|
|
36
|
+
* @throws Error if entrypoint is not provided
|
|
37
|
+
*/
|
|
38
|
+
constructor(options: EventsRouterOptions);
|
|
39
|
+
/**
|
|
40
|
+
* Adds new entrypoints to the router
|
|
41
|
+
* @param entrypoints - Array of new entrypoint paths
|
|
42
|
+
*/
|
|
43
|
+
addEntrypoints(entrypoints: string[]): void;
|
|
44
|
+
/**
|
|
45
|
+
* Find a parsed event by its name
|
|
46
|
+
* @param event - Name of the event to find
|
|
47
|
+
* @returns Parsed event metadata or null if not found
|
|
48
|
+
*/
|
|
49
|
+
match(event: string): ParsedEvent | null;
|
|
50
|
+
/**
|
|
51
|
+
* Get the entrypoint directory path
|
|
52
|
+
* @returns Entrypoint directory path
|
|
53
|
+
*/
|
|
54
|
+
get entrypoints(): string[];
|
|
55
|
+
/**
|
|
56
|
+
* Checks if the entrypoint path is valid
|
|
57
|
+
*/
|
|
58
|
+
isValidPath(): boolean;
|
|
59
|
+
/**
|
|
60
|
+
* Clear all parsed events
|
|
61
|
+
*/
|
|
62
|
+
clear(): void;
|
|
63
|
+
/**
|
|
64
|
+
* Reload and re-scan the entrypoint directory for events
|
|
65
|
+
* @returns Promise resolving to the updated events tree
|
|
66
|
+
*/
|
|
67
|
+
reload(): Promise<EventsTree>;
|
|
68
|
+
/**
|
|
69
|
+
* Scan the entrypoint directory for events and their handlers
|
|
70
|
+
* @returns Promise resolving to the events tree
|
|
71
|
+
*/
|
|
72
|
+
scan(): Promise<EventsTree>;
|
|
73
|
+
/**
|
|
74
|
+
* Convert the internal events Collection to a plain object
|
|
75
|
+
* @returns Events tree as a plain object
|
|
76
|
+
*/
|
|
77
|
+
toJSON(): EventsTree;
|
|
78
|
+
/**
|
|
79
|
+
* Recursively scan a directory for event handlers
|
|
80
|
+
* @param event - Name of the event
|
|
81
|
+
* @param path - Path to the event directory
|
|
82
|
+
* @param listeners - Array to collect listener file paths
|
|
83
|
+
* @returns Promise resolving to the parsed event metadata
|
|
84
|
+
*/
|
|
85
|
+
private scanEvent;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export { EventsRouter, type EventsRouterOptions, type EventsTree, type ParsedEvent };
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";var o=Object.defineProperty;var E=Object.getOwnPropertyDescriptor;var b=Object.getOwnPropertyNames;var w=Object.prototype.hasOwnProperty;var h=(i,t)=>o(i,"name",{value:t,configurable:!0});var P=(i,t)=>{for(var n in t)o(i,n,{get:t[n],enumerable:!0})},x=(i,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of b(t))!w.call(i,r)&&r!==n&&o(i,r,{get:()=>t[r],enumerable:!(s=E(t,r))||s.enumerable});return i};var O=i=>x(o({},"__esModule",{value:!0}),i);var S={};P(S,{EventsRouter:()=>l});module.exports=O(S);var v=require("discord.js"),g=require("fs"),p=require("fs/promises"),a=require("path");var m=class m{constructor(t){this.options=t;var n;if(t.entrypoints&&(t.entrypoints=Array.from(new Set(t.entrypoints))),!((n=t.entrypoints)!=null&&n.length))throw new Error("Entrypoint directory must be provided")}events=new v.Collection;addEntrypoints(t){this.options.entrypoints=Array.from(new Set([...this.options.entrypoints,...t]))}match(t){return this.events.get(t)??null}get entrypoints(){return this.options.entrypoints}isValidPath(){return this.entrypoints.every(t=>(0,g.existsSync)(t))}clear(){this.events.clear()}async reload(){return this.clear(),this.scan()}async scan(){for(let t of this.entrypoints){let n=await(0,p.readdir)(t,{withFileTypes:!0});for(let s of n)if(s.isDirectory()){let r=(0,a.join)(t,s.name);await this.scanEvent(s.name,r,null,[],!0)}}return Object.fromEntries(this.events)}toJSON(){return Object.fromEntries(this.events)}async scanEvent(t,n,s=null,r=[],d=!1){let u=await(0,p.readdir)(n,{withFileTypes:!0}),f=d&&/^\(.+\)$/.test(t),y=f?t.slice(1,-1):s??null;u.sort((e,c)=>e.name.localeCompare(c.name));for(let e of u)if(!e.name.startsWith("_")){if(e.isDirectory()){let c=(0,a.join)(n,e.name);await this.scanEvent(e.name,c,y,r);continue}e.isFile()&&/\.(m|c)?(j|t)sx?$/.test(e.name)&&r.push((0,a.join)(e.parentPath,e.name))}if(!f){let e=this.events.get(t);if(e){e.listeners=Array.from(new Set([...e.listeners,...r]));return}this.events.set(t,{event:t,path:n,listeners:r,namespace:y})}}};h(m,"EventsRouter");var l=m;0&&(module.exports={EventsRouter});
|
|
2
|
+
//# sourceMappingURL=EventsRouter.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/app/router/EventsRouter.ts"],"sourcesContent":["import { Collection } from 'discord.js';\nimport { existsSync } from 'node:fs';\nimport { readdir } from 'node:fs/promises';\nimport { join } from 'node:path';\n\n/**\n * Configuration options for the EventsRouter\n * @interface EventsRouterOptions\n */\nexport interface EventsRouterOptions {\n /** Root directory path where event handlers are located */\n entrypoints: string[];\n}\n\n/**\n * Represents a parsed event with its handlers\n * @interface ParsedEvent\n */\nexport interface ParsedEvent {\n /** Name of the event derived from directory name */\n event: string;\n /** Absolute path to the event directory */\n path: string;\n /** Array of file paths to event listener handlers */\n listeners: string[];\n /** Namespace of the event */\n namespace: string | null;\n}\n\n/** Collection of event names to their parsed metadata */\nexport type EventsTree = Record<string, ParsedEvent>;\n\n/**\n * Router for discovering and managing event handler files in a directory structure.\n * Events are represented by directories, and handlers are files within those directories.\n */\nexport class EventsRouter {\n /** Internal storage of parsed events */\n private events = new Collection<string, ParsedEvent>();\n\n /**\n * Creates a new EventsRouter instance\n * @param options - Configuration options for the router\n * @throws Error if entrypoint is not provided\n */\n public constructor(private options: EventsRouterOptions) {\n if (options.entrypoints) {\n options.entrypoints = Array.from(new Set(options.entrypoints));\n }\n\n if (!options.entrypoints?.length) {\n throw new Error('Entrypoint directory must be provided');\n }\n }\n\n /**\n * Adds new entrypoints to the router\n * @param entrypoints - Array of new entrypoint paths\n */\n public addEntrypoints(entrypoints: string[]) {\n this.options.entrypoints = Array.from(\n new Set([...this.options.entrypoints, ...entrypoints])\n );\n }\n\n /**\n * Find a parsed event by its name\n * @param event - Name of the event to find\n * @returns Parsed event metadata or null if not found\n */\n public match(event: string): ParsedEvent | null {\n return this.events.get(event) ?? null;\n }\n\n /**\n * Get the entrypoint directory path\n * @returns Entrypoint directory path\n */\n public get entrypoints(): string[] {\n return this.options.entrypoints;\n }\n\n /**\n * Checks if the entrypoint path is valid\n */\n public isValidPath() {\n return this.entrypoints.every((entrypoint) => existsSync(entrypoint));\n }\n\n /**\n * Clear all parsed events\n */\n public clear() {\n this.events.clear();\n }\n\n /**\n * Reload and re-scan the entrypoint directory for events\n * @returns Promise resolving to the updated events tree\n */\n public async reload() {\n this.clear();\n return this.scan();\n }\n\n /**\n * Scan the entrypoint directory for events and their handlers\n * @returns Promise resolving to the events tree\n */\n public async scan(): Promise<EventsTree> {\n for (const entrypoint of this.entrypoints) {\n const dirs = await readdir(entrypoint, { withFileTypes: true });\n\n for (const dir of dirs) {\n if (dir.isDirectory()) {\n const path = join(entrypoint, dir.name);\n await this.scanEvent(dir.name, path, null, [], true);\n }\n }\n }\n\n return Object.fromEntries(this.events);\n }\n\n /**\n * Convert the internal events Collection to a plain object\n * @returns Events tree as a plain object\n */\n public toJSON(): EventsTree {\n return Object.fromEntries(this.events);\n }\n\n /**\n * Recursively scan a directory for event handlers\n * @param event - Name of the event\n * @param path - Path to the event directory\n * @param listeners - Array to collect listener file paths\n * @returns Promise resolving to the parsed event metadata\n */\n private async scanEvent(\n event: string,\n path: string,\n _namespace: string | null = null,\n listeners: string[] = [],\n isRoot = false)\n : Promise<void> {\n const files = await readdir(path, { withFileTypes: true });\n const isNamespace = isRoot && /^\\(.+\\)$/.test(event);\n\n // if event = (something) pattern then namespace is something\n const namespace = isNamespace ? event.slice(1, -1) : _namespace ?? null;\n\n files.sort((a, b) => a.name.localeCompare(b.name));\n\n for (const file of files) {\n if (file.name.startsWith('_')) continue;\n\n if (file.isDirectory()) {\n const nextPath = join(path, file.name);\n await this.scanEvent(file.name, nextPath, namespace, listeners);\n continue;\n }\n\n if (file.isFile() && /\\.(m|c)?(j|t)sx?$/.test(file.name)) {\n listeners.push(join(file.parentPath, file.name));\n }\n }\n\n if (!isNamespace) {\n const existing = this.events.get(event);\n\n if (existing) {\n existing.listeners = Array.from(\n new Set([...existing.listeners, ...listeners])\n );\n\n return;\n }\n\n this.events.set(event, { event, path, listeners, namespace });\n }\n }\n}"],"mappings":"4dAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,kBAAAE,IAAA,eAAAC,EAAAH,GAAA,IAAAI,EAA2B,sBAC3BC,EAA2B,cAC3BC,EAAwB,uBACxBC,EAAqB,gBAiCd,IAAMC,EAAN,MAAMA,CAAa,CASjB,YAAoBC,E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,EAG7CU,EAAYD,EAAcT,EAAM,MAAM,EAAG,EAAE,EAAIK,GAAc,KAEnEG,EAAM,KAAK,CAACG,EAAGC,IAAMD,EAAE,KAAK,cAAcC,EAAE,IAAI,CAAC,EAEjD,QAAWC,KAAQL,EACjB,GAAI,CAAAK,EAAK,KAAK,WAAW,GAAG,EAE5B,IAAIA,EAAK,YAAY,EAAG,CACtB,IAAMC,KAAW,QAAKV,EAAMS,EAAK,IAAI,EACrC,MAAM,KAAK,UAAUA,EAAK,KAAMC,EAAUJ,EAAWJ,CAAS,EAC9D,QACF,CAEIO,EAAK,OAAO,GAAK,oBAAoB,KAAKA,EAAK,IAAI,GACrDP,EAAU,QAAK,QAAKO,EAAK,WAAYA,EAAK,IAAI,CAAC,EAInD,GAAI,CAACJ,EAAa,CAChB,IAAMM,EAAW,KAAK,OAAO,IAAIf,CAAK,EAEtC,GAAIe,EAAU,CACZA,EAAS,UAAY,MAAM,KACzB,IAAI,IAAI,CAAC,GAAGA,EAAS,UAAW,GAAGT,CAAS,CAAC,CAC/C,EAEA,MACF,CAEA,KAAK,OAAO,IAAIN,EAAO,CAAE,MAAAA,EAAO,KAAAI,EAAM,UAAAE,EAAW,UAAAI,CAAU,CAAC,CAC9D,CACF,CACF,EAlJ0BM,EAAApB,EAAA,gBAAnB,IAAMqB,EAANrB","names":["EventsRouter_exports","__export","EventsRouter","__toCommonJS","import_discord","import_node_fs","import_promises","import_node_path","_EventsRouter","options","_a","entrypoints","event","entrypoint","dirs","dir","path","_namespace","listeners","isRoot","files","isNamespace","namespace","a","b","file","nextPath","existing","__name","EventsRouter"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";var l=Object.defineProperty;var M=Object.getOwnPropertyDescriptor;var O=Object.getOwnPropertyNames;var j=Object.prototype.hasOwnProperty;var m=(a,t)=>l(a,"name",{value:t,configurable:!0});var R=(a,t)=>{for(var i in t)l(a,i,{get:t[i],enumerable:!0})},N=(a,t,i,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let e of O(t))!j.call(a,e)&&e!==i&&l(a,e,{get:()=>t[e],enumerable:!(r=M(t,e))||r.enumerable});return a};var S=a=>N(l({},"__esModule",{value:!0}),a);var W={};R(W,{CommandsRouter:()=>u,EventsRouter:()=>g});module.exports=S(W);var p=require("discord.js"),D=require("fs"),h=require("fs/promises"),s=require("path");var $=/^\+middleware\.(m|c)?(j|t)sx?$/,P=/^\+([^+().][^().]*)\.middleware\.(m|c)?(j|t)sx?$/,x=/^\+global-middleware\.(m|c)?(j|t)sx?$/,_=/^([^+().][^().]*)\.(m|c)?(j|t)sx?$/,F=/^\(.+\)$/,f=class f{constructor(t){this.options=t}commands=new p.Collection;middlewares=new p.Collection;populate(t){for(let[i,r]of Object.entries(t.commands))this.commands.set(i,r);for(let[i,r]of Object.entries(t.middlewares))this.middlewares.set(i,r)}isValidPath(){return(0,D.existsSync)(this.options.entrypoint)}isCommand(t){return _.test(t)}isMiddleware(t){return $.test(t)||x.test(t)||P.test(t)}isCategory(t){return F.test(t)}clear(){this.commands.clear(),this.middlewares.clear()}async scan(){let t=await(0,h.readdir)(this.options.entrypoint,{withFileTypes:!0});for(let i of t){if(i.name.startsWith("_"))continue;let r=(0,s.join)(this.options.entrypoint,i.name);if(i.isDirectory()){let e=this.isCategory(i.name)?i.name.slice(1,-1):null;await this.traverse(r,e)}else await this.handle(i)}return await this.applyMiddlewares(),this.toJSON()}getData(){return{commands:this.commands,middlewares:this.middlewares}}toJSON(){return{commands:Object.fromEntries(this.commands.entries()),middlewares:Object.fromEntries(this.middlewares.entries())}}async traverse(t,i){let r=await(0,h.readdir)(t,{withFileTypes:!0});for(let e of r)if(!e.name.startsWith("_")){if(e.isFile())(this.isCommand(e.name)||this.isMiddleware(e.name))&&await this.handle(e,i);else if(e.isDirectory()&&this.isCategory(e.name)&&i){let o=this.isCategory(e.name)?`${i}:${e.name.slice(1,-1)}`:null;await this.traverse((0,s.join)(t,e.name),o)}}}async handle(t,i=null){let r=t.name,e=(0,s.join)(t.parentPath,t.name);if(this.isCommand(r)){let o={id:crypto.randomUUID(),name:(0,s.basename)(e,(0,s.extname)(e)),path:e,category:i,parentPath:t.parentPath,relativePath:this.replaceEntrypoint(e),middlewares:[]};this.commands.set(o.id,o)}else if(this.isMiddleware(r)){let o={id:crypto.randomUUID(),name:(0,s.basename)(e,(0,s.extname)(e)),path:e,relativePath:this.replaceEntrypoint(e),parentPath:t.parentPath,global:x.test(r),command:P.test(r)&&r.split(".")[0]||null};this.middlewares.set(o.id,o)}}applyMiddlewares(){this.commands.forEach(t=>{let i=t.parentPath,r=Array.from(this.middlewares.values()).filter(e=>e.global?!0:e.command?e.command===t.name:e.parentPath===i).map(e=>e.id);t.middlewares=Array.from(new Set([...t.middlewares,...r]))})}replaceEntrypoint(t){return(0,s.normalize)(t).replace(this.options.entrypoint,"")}};m(f,"CommandsRouter");var u=f;var A=require("discord.js"),T=require("fs"),y=require("fs/promises"),c=require("path");var w=class w{constructor(t){this.options=t;var i;if(t.entrypoints&&(t.entrypoints=Array.from(new Set(t.entrypoints))),!((i=t.entrypoints)!=null&&i.length))throw new Error("Entrypoint directory must be provided")}events=new A.Collection;addEntrypoints(t){this.options.entrypoints=Array.from(new Set([...this.options.entrypoints,...t]))}match(t){return this.events.get(t)??null}get entrypoints(){return this.options.entrypoints}isValidPath(){return this.entrypoints.every(t=>(0,T.existsSync)(t))}clear(){this.events.clear()}async reload(){return this.clear(),this.scan()}async scan(){for(let t of this.entrypoints){let i=await(0,y.readdir)(t,{withFileTypes:!0});for(let r of i)if(r.isDirectory()){let e=(0,c.join)(t,r.name);await this.scanEvent(r.name,e,null,[],!0)}}return Object.fromEntries(this.events)}toJSON(){return Object.fromEntries(this.events)}async scanEvent(t,i,r=null,e=[],o=!1){let v=await(0,y.readdir)(i,{withFileTypes:!0}),b=o&&/^\(.+\)$/.test(t),E=b?t.slice(1,-1):r??null;v.sort((n,d)=>n.name.localeCompare(d.name));for(let n of v)if(!n.name.startsWith("_")){if(n.isDirectory()){let d=(0,c.join)(i,n.name);await this.scanEvent(n.name,d,E,e);continue}n.isFile()&&/\.(m|c)?(j|t)sx?$/.test(n.name)&&e.push((0,c.join)(n.parentPath,n.name))}if(!b){let n=this.events.get(t);if(n){n.listeners=Array.from(new Set([...n.listeners,...e]));return}this.events.set(t,{event:t,path:i,listeners:e,namespace:E})}}};m(w,"EventsRouter");var g=w;0&&(module.exports={CommandsRouter,EventsRouter});
|
|
2
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/app/router/index.ts","../../../src/app/router/CommandsRouter.ts","../../../src/app/router/EventsRouter.ts"],"sourcesContent":["export * from './CommandsRouter';\nexport * from './EventsRouter';","import { Collection } from 'discord.js';\nimport { Dirent, existsSync } from 'node:fs';\nimport { readdir } from 'node:fs/promises';\nimport { basename, extname, join, normalize } from 'node:path';\n\nexport interface Command {\n id: string;\n name: string;\n path: string;\n relativePath: string;\n parentPath: string;\n middlewares: Array<string>;\n category: string | null;\n}\n\nexport interface Middleware {\n id: string;\n name: string;\n path: string;\n relativePath: string;\n parentPath: string;\n global: boolean;\n command: string | null;\n}\n\nexport interface ParsedCommandData {\n commands: Record<string, Command>;\n middlewares: Record<string, Middleware>;\n}\n\nexport interface CommandsRouterOptions {\n entrypoint: string;\n}\n\nconst MIDDLEWARE_PATTERN = /^\\+middleware\\.(m|c)?(j|t)sx?$/;\nconst COMMAND_MIDDLEWARE_PATTERN =\n/^\\+([^+().][^().]*)\\.middleware\\.(m|c)?(j|t)sx?$/;\nconst GLOBAL_MIDDLEWARE_PATTERN = /^\\+global-middleware\\.(m|c)?(j|t)sx?$/;\nconst COMMAND_PATTERN = /^([^+().][^().]*)\\.(m|c)?(j|t)sx?$/;\nconst CATEGORY_PATTERN = /^\\(.+\\)$/;\n\nexport class CommandsRouter {\n private commands = new Collection<string, Command>();\n private middlewares = new Collection<string, Middleware>();\n\n public constructor(private readonly options: CommandsRouterOptions) {}\n\n public populate(data: ParsedCommandData) {\n for (const [id, command] of Object.entries(data.commands)) {\n this.commands.set(id, command);\n }\n\n for (const [id, middleware] of Object.entries(data.middlewares)) {\n this.middlewares.set(id, middleware);\n }\n }\n\n public isValidPath(): boolean {\n return existsSync(this.options.entrypoint);\n }\n\n private isCommand(name: string): boolean {\n return COMMAND_PATTERN.test(name);\n }\n\n private isMiddleware(name: string): boolean {\n return (\n MIDDLEWARE_PATTERN.test(name) ||\n GLOBAL_MIDDLEWARE_PATTERN.test(name) ||\n COMMAND_MIDDLEWARE_PATTERN.test(name));\n\n }\n\n private isCategory(name: string): boolean {\n return CATEGORY_PATTERN.test(name);\n }\n\n public clear() {\n this.commands.clear();\n this.middlewares.clear();\n }\n\n public async scan() {\n const entries = await readdir(this.options.entrypoint, {\n withFileTypes: true\n });\n\n for (const entry of entries) {\n // ignore _ prefixed files\n if (entry.name.startsWith('_')) continue;\n\n const fullPath = join(this.options.entrypoint, entry.name);\n\n if (entry.isDirectory()) {\n const category = this.isCategory(entry.name) ?\n entry.name.slice(1, -1) :\n null;\n\n await this.traverse(fullPath, category);\n } else {\n await this.handle(entry);\n }\n }\n\n await this.applyMiddlewares();\n\n return this.toJSON();\n }\n\n public getData() {\n return {\n commands: this.commands,\n middlewares: this.middlewares\n };\n }\n\n public toJSON() {\n return {\n commands: Object.fromEntries(this.commands.entries()),\n middlewares: Object.fromEntries(this.middlewares.entries())\n };\n }\n\n private async traverse(path: string, category: string | null) {\n const entries = await readdir(path, {\n withFileTypes: true\n });\n\n for (const entry of entries) {\n // ignore _ prefixed files\n if (entry.name.startsWith('_')) continue;\n\n if (entry.isFile()) {\n if (this.isCommand(entry.name) || this.isMiddleware(entry.name)) {\n await this.handle(entry, category);\n }\n } else if (\n entry.isDirectory() &&\n this.isCategory(entry.name) &&\n category)\n {\n // nested category\n const nestedCategory = this.isCategory(entry.name) ?\n `${category}:${entry.name.slice(1, -1)}` :\n null;\n await this.traverse(join(path, entry.name), nestedCategory);\n }\n\n // TODO: handle subcommands\n }\n }\n\n private async handle(entry: Dirent, category: string | null = null) {\n const name = entry.name;\n const path = join(entry.parentPath, entry.name);\n\n if (this.isCommand(name)) {\n const command: Command = {\n id: crypto.randomUUID(),\n name: basename(path, extname(path)),\n path,\n category,\n parentPath: entry.parentPath,\n relativePath: this.replaceEntrypoint(path),\n middlewares: []\n };\n\n this.commands.set(command.id, command);\n } else if (this.isMiddleware(name)) {\n const middleware: Middleware = {\n id: crypto.randomUUID(),\n name: basename(path, extname(path)),\n path,\n relativePath: this.replaceEntrypoint(path),\n parentPath: entry.parentPath,\n global: GLOBAL_MIDDLEWARE_PATTERN.test(name),\n command: COMMAND_MIDDLEWARE_PATTERN.test(name) ?\n name.split('.')[0] || null :\n null\n };\n\n this.middlewares.set(middleware.id, middleware);\n }\n }\n\n private applyMiddlewares() {\n this.commands.forEach((command) => {\n const commandPath = command.parentPath;\n const samePathMiddlewares = Array.from(this.middlewares.values()).\n filter((middleware) => {\n if (middleware.global) return true;\n if (middleware.command) return middleware.command === command.name;\n return middleware.parentPath === commandPath;\n }).\n map((middleware) => middleware.id);\n\n command.middlewares = Array.from(\n new Set([...command.middlewares, ...samePathMiddlewares])\n );\n });\n }\n\n private replaceEntrypoint(path: string) {\n const normalized = normalize(path);\n return normalized.replace(this.options.entrypoint, '');\n }\n}","import { Collection } from 'discord.js';\nimport { existsSync } from 'node:fs';\nimport { readdir } from 'node:fs/promises';\nimport { join } from 'node:path';\n\n/**\n * Configuration options for the EventsRouter\n * @interface EventsRouterOptions\n */\nexport interface EventsRouterOptions {\n /** Root directory path where event handlers are located */\n entrypoints: string[];\n}\n\n/**\n * Represents a parsed event with its handlers\n * @interface ParsedEvent\n */\nexport interface ParsedEvent {\n /** Name of the event derived from directory name */\n event: string;\n /** Absolute path to the event directory */\n path: string;\n /** Array of file paths to event listener handlers */\n listeners: string[];\n /** Namespace of the event */\n namespace: string | null;\n}\n\n/** Collection of event names to their parsed metadata */\nexport type EventsTree = Record<string, ParsedEvent>;\n\n/**\n * Router for discovering and managing event handler files in a directory structure.\n * Events are represented by directories, and handlers are files within those directories.\n */\nexport class EventsRouter {\n /** Internal storage of parsed events */\n private events = new Collection<string, ParsedEvent>();\n\n /**\n * Creates a new EventsRouter instance\n * @param options - Configuration options for the router\n * @throws Error if entrypoint is not provided\n */\n public constructor(private options: EventsRouterOptions) {\n if (options.entrypoints) {\n options.entrypoints = Array.from(new Set(options.entrypoints));\n }\n\n if (!options.entrypoints?.length) {\n throw new Error('Entrypoint directory must be provided');\n }\n }\n\n /**\n * Adds new entrypoints to the router\n * @param entrypoints - Array of new entrypoint paths\n */\n public addEntrypoints(entrypoints: string[]) {\n this.options.entrypoints = Array.from(\n new Set([...this.options.entrypoints, ...entrypoints])\n );\n }\n\n /**\n * Find a parsed event by its name\n * @param event - Name of the event to find\n * @returns Parsed event metadata or null if not found\n */\n public match(event: string): ParsedEvent | null {\n return this.events.get(event) ?? null;\n }\n\n /**\n * Get the entrypoint directory path\n * @returns Entrypoint directory path\n */\n public get entrypoints(): string[] {\n return this.options.entrypoints;\n }\n\n /**\n * Checks if the entrypoint path is valid\n */\n public isValidPath() {\n return this.entrypoints.every((entrypoint) => existsSync(entrypoint));\n }\n\n /**\n * Clear all parsed events\n */\n public clear() {\n this.events.clear();\n }\n\n /**\n * Reload and re-scan the entrypoint directory for events\n * @returns Promise resolving to the updated events tree\n */\n public async reload() {\n this.clear();\n return this.scan();\n }\n\n /**\n * Scan the entrypoint directory for events and their handlers\n * @returns Promise resolving to the events tree\n */\n public async scan(): Promise<EventsTree> {\n for (const entrypoint of this.entrypoints) {\n const dirs = await readdir(entrypoint, { withFileTypes: true });\n\n for (const dir of dirs) {\n if (dir.isDirectory()) {\n const path = join(entrypoint, dir.name);\n await this.scanEvent(dir.name, path, null, [], true);\n }\n }\n }\n\n return Object.fromEntries(this.events);\n }\n\n /**\n * Convert the internal events Collection to a plain object\n * @returns Events tree as a plain object\n */\n public toJSON(): EventsTree {\n return Object.fromEntries(this.events);\n }\n\n /**\n * Recursively scan a directory for event handlers\n * @param event - Name of the event\n * @param path - Path to the event directory\n * @param listeners - Array to collect listener file paths\n * @returns Promise resolving to the parsed event metadata\n */\n private async scanEvent(\n event: string,\n path: string,\n _namespace: string | null = null,\n listeners: string[] = [],\n isRoot = false)\n : Promise<void> {\n const files = await readdir(path, { withFileTypes: true });\n const isNamespace = isRoot && /^\\(.+\\)$/.test(event);\n\n // if event = (something) pattern then namespace is something\n const namespace = isNamespace ? event.slice(1, -1) : _namespace ?? null;\n\n files.sort((a, b) => a.name.localeCompare(b.name));\n\n for (const file of files) {\n if (file.name.startsWith('_')) continue;\n\n if (file.isDirectory()) {\n const nextPath = join(path, file.name);\n await this.scanEvent(file.name, nextPath, namespace, listeners);\n continue;\n }\n\n if (file.isFile() && /\\.(m|c)?(j|t)sx?$/.test(file.name)) {\n listeners.push(join(file.parentPath, file.name));\n }\n }\n\n if (!isNamespace) {\n const existing = this.events.get(event);\n\n if (existing) {\n existing.listeners = Array.from(\n new Set([...existing.listeners, ...listeners])\n );\n\n return;\n }\n\n this.events.set(event, { event, path, listeners, namespace });\n }\n }\n}"],"mappings":"4dAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,oBAAAE,EAAA,iBAAAC,IAAA,eAAAC,EAAAJ,GCAA,IAAAK,EAA2B,sBAC3BC,EAAmC,cACnCC,EAAwB,uBACxBC,EAAmD,gBA+BnD,IAAMC,EAAqB,iCACrBC,EACN,mDACMC,EAA4B,wCAC5BC,EAAkB,qCAClBC,EAAmB,WAEZC,EAAN,MAAMA,CAAe,CAInB,YAA6BC,EAAgC,CAAhC,aAAAA,CAAiC,CAH7D,SAAW,IAAI,aACf,YAAc,IAAI,aAInB,SAASC,EAAyB,CACvC,OAAW,CAACC,EAAIC,CAAO,IAAK,OAAO,QAAQF,EAAK,QAAQ,EACtD,KAAK,SAAS,IAAIC,EAAIC,CAAO,EAG/B,OAAW,CAACD,EAAIE,CAAU,IAAK,OAAO,QAAQ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AEA,KAAK,OAAO,IAAIN,EAAO,CAAE,MAAAA,EAAO,KAAAI,EAAM,UAAAE,EAAW,UAAAI,CAAU,CAAC,CAC9D,CACF,CACF,EAlJ0BM,EAAApB,EAAA,gBAAnB,IAAMqB,EAANrB","names":["router_exports","__export","CommandsRouter","EventsRouter","__toCommonJS","import_discord","import_node_fs","import_promises","import_node_path","MIDDLEWARE_PATTERN","COMMAND_MIDDLEWARE_PATTERN","GLOBAL_MIDDLEWARE_PATTERN","COMMAND_PATTERN","CATEGORY_PATTERN","_CommandsRouter","options","data","id","command","middleware","name","entries","entry","fullPath","category","path","nestedCategory","commandPath","samePathMiddlewares","__name","CommandsRouter","import_discord","import_node_fs","import_promises","import_node_path","_EventsRouter","options","_a","entrypoints","event","entrypoint","dirs","dir","path","_namespace","listeners","isRoot","files","isNamespace","namespace","a","b","file","nextPath","existing","__name","EventsRouter"]}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
"use strict";var E=Object.create;var s=Object.defineProperty;var w=Object.getOwnPropertyDescriptor;var M=Object.getOwnPropertyNames;var O=Object.getPrototypeOf,k=Object.prototype.hasOwnProperty;var n=(e,t)=>s(e,"name",{value:t,configurable:!0});var C=(e,t)=>{for(var o in t)s(e,o,{get:t[o],enumerable:!0})},m=(e,t,o,c)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of M(t))!k.call(e,r)&&r!==o&&s(e,r,{get:()=>t[r],enumerable:!(c=w(t,r))||c.enumerable});return e};var _=(e,t,o)=>(o=e!=null?E(O(e)):{},m(t||!e||!e.__esModule?s(o,"default",{value:e,enumerable:!0}):o,e)),D=e=>m(s({},"__esModule",{value:!0}),e);var H={};C(H,{createAppProcess:()=>V});module.exports=D(H);var T=require("child_process");function d(e=!1){let t={NODE_ENV:"development",COMMANDKIT_IS_DEV:"true"};return e?Object.assign({},t):Object.assign({},process.env,t)}n(d,"DevEnv");function l(e=!1){let t={NODE_ENV:"production",COMMANDKIT_IS_DEV:"false"};return e?Object.assign({},t):Object.assign({},process.env,t)}n(l,"ProdEnv");var u=[".env",".env.local"],N=[".env.development",".env.development.local"],P=[".env.production",".env.production.local"],L=[...u,...N],U=[...u,...P];var v=require("path"),S=require("fs");var j=require("rimraf"),h=require("path"),K=_(require("fs"));var f=require("picocolors"),y=(0,f.createColors)(!0);var x=require("fs/promises"),I=require("path");var W=Symbol("kCommandKitCacheTag"),A=process.env.COMMANDKIT_IS_DEV==="true",X=process.env.COMMANDKIT_IS_TEST==="true",Y=process.env.COMMANDKIT_BOOTSTRAP_MODE||"development";var b=require("fs");var F=require("child_process");function R(e){process.stdout.write(e),process.stdout.write(`
|
|
2
|
+
`)}n(R,"write");function g(e){R(y.red(`Error: ${e}`)),process.exit(1)}n(g,"panic");function $(e){return e?["pipe","pipe","pipe","ipc"]:["pipe","pipe","pipe"]}n($,"getStdio");function V(e,t,o){var a,p;(0,S.existsSync)((0,v.join)(t,e))||g(`Could not locate the entrypoint file: ${e}`);let c=$(o),r=(0,T.spawn)("node",[`--title="CommandKit ${o?"Development":"Production"}"`,"--enable-source-maps",e],{cwd:t,windowsHide:!0,env:o?d():l(),stdio:c});return(a=r.stdout)==null||a.pipe(process.stdout),(p=r.stderr)==null||p.pipe(process.stderr),r}n(V,"createAppProcess");0&&(module.exports={createAppProcess});
|
|
3
|
+
//# sourceMappingURL=app-process.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/cli/app-process.ts","../../src/cli/env.ts","../../src/cli/common.ts","../../src/utils/colors.ts","../../src/utils/types-package.ts","../../src/utils/constants.ts"],"sourcesContent":["import { IOType, spawn } from 'node:child_process';\nimport { DevEnv, ProdEnv } from './env';\nimport { join } from 'node:path';\nimport { existsSync } from 'node:fs';\nimport { panic } from './common';\n\nfunction getStdio(supportsCommands: boolean) {\n if (supportsCommands) {\n return ['pipe', 'pipe', 'pipe', 'ipc'];\n }\n\n return ['pipe', 'pipe', 'pipe'];\n}\n\nexport function createAppProcess(\nfileName: string,\ncwd: string,\nisDev: boolean)\n{\n if (!existsSync(join(cwd, fileName))) {\n panic(`Could not locate the entrypoint file: ${fileName}`);\n }\n\n const stdio = getStdio(isDev) as IOType[];\n\n const ps = spawn(\n 'node',\n [\n `--title=\"CommandKit ${isDev ? 'Development' : 'Production'}\"`,\n '--enable-source-maps',\n fileName],\n\n {\n cwd,\n windowsHide: true,\n env: isDev ? DevEnv() : ProdEnv(),\n stdio\n }\n );\n\n ps.stdout?.pipe(process.stdout);\n ps.stderr?.pipe(process.stderr);\n\n return ps;\n}","export function DevEnv(_static = false) {\n const common = {\n NODE_ENV: 'development',\n COMMANDKIT_IS_DEV: 'true'\n };\n\n if (_static) return Object.assign({}, common);\n\n return Object.assign({}, process.env, common);\n}\n\nexport function ProdEnv(_static = false) {\n const common = {\n NODE_ENV: 'production',\n COMMANDKIT_IS_DEV: 'false'\n };\n\n if (_static) return Object.assign({}, common);\n\n return Object.assign({}, process.env, common);\n}\n\nexport const CommonEnvFiles = ['.env', '.env.local'];\nexport const DevEnvFiles = ['.env.development', '.env.development.local'];\nexport const ProdEnvFiles = ['.env.production', '.env.production.local'];\n\nexport const devEnvFileArgs = [...CommonEnvFiles, ...DevEnvFiles];\n\nexport const prodEnvFileArgs = [...CommonEnvFiles, ...ProdEnvFiles];","import { rimrafSync } from 'rimraf';\nimport { join } from 'node:path';\nimport fs from 'node:fs';\nimport colors from '../utils/colors';\nimport { ResolvedCommandKitConfig } from '../config/utils';\nimport { generateTypesPackage } from '../utils/types-package';\nimport { execSync } from 'node:child_process';\n\nlet ts: typeof import('typescript') | undefined;\n\nexport function write(message: any) {\n process.stdout.write(message);\n process.stdout.write('\\n');\n}\n\nexport function findEntrypoint(dir: string) {\n const target = join(dir, 'sharding-manager.js');\n\n // if sharding manager exists, return that file instead\n if (fs.existsSync(target)) return target;\n\n return join(dir, 'index.js');\n}\n\n/**\n * @returns {never}\n */\nexport function panic(message: any): never {\n write(colors.red(`Error: ${message}`));\n process.exit(1);\n}\n\nexport function findPackageJSON() {\n const cwd = process.cwd();\n const target = join(cwd, 'package.json');\n\n if (!fs.existsSync(target)) {\n panic('Could not find package.json in current directory.');\n }\n\n return JSON.parse(fs.readFileSync(target, 'utf8'));\n}\n\nasync function ensureTypeScript(target: string) {\n const isTypeScript = /\\.(c|m)?tsx?$/.test(target);\n\n if (!isTypeScript) return false;\n if (process.features.typescript) return true;\n\n await loadTypeScript();\n\n return true;\n}\n\nlet packageManager: string;\n\nfunction detectPackageManager() {\n if (packageManager) return packageManager;\n\n const lockfiles = {\n 'yarn.lock': 'yarn',\n 'pnpm-lock.yaml': 'pnpm',\n 'package-lock.json': 'npm',\n 'bun.lock': 'bun',\n 'bun.lockb': 'bun'\n };\n\n for (const [lockfile, manager] of Object.entries(lockfiles)) {\n if (fs.existsSync(join(process.cwd(), lockfile))) {\n packageManager = manager;\n break;\n }\n }\n\n if (!packageManager) {\n packageManager = 'npm';\n }\n\n return packageManager;\n}\n\nexport async function loadTypeScript(e?: string) {\n if (ts) return ts;\n\n try {\n ts = await import('typescript');\n } catch (e) {\n if (e instanceof Error && 'code' in e && e.code === 'MODULE_NOT_FOUND') {\n try {\n const packageManager = detectPackageManager();\n\n execSync(`${packageManager} add typescript`, {\n stdio: 'inherit',\n cwd: process.cwd()\n });\n\n console.log(\n colors.cyan(\n `TypeScript has been installed automatically, restarting...`\n )\n );\n\n ts = await import('typescript');\n\n return ts;\n } catch {\n panic(\n 'TypeScript is not installed and could not be installed automatically. Please install it manually.'\n );\n }\n }\n panic(e || 'TypeScript must be installed to use TypeScript config files.');\n }\n\n return ts;\n}\n\nexport async function loadConfigFileFromPath(\ntarget: string)\n: Promise<ResolvedCommandKitConfig> {\n await ensureExists(target);\n\n const isTs = await ensureTypeScript(target);\n\n if (isTs && ts) {\n const { transpileModule } = ts;\n const src = fs.readFileSync(target, 'utf8');\n const { outputText } = transpileModule(src, {\n compilerOptions: {\n module: ts.ModuleKind.ESNext,\n target: ts.ScriptTarget.ESNext,\n moduleResolution: ts.ModuleResolutionKind.NodeNext\n },\n fileName: target\n });\n\n const nodeModulesPath = await generateTypesPackage();\n\n const tmpFile = join(nodeModulesPath, 'compiled-commandkit.config.mjs');\n\n fs.writeFileSync(tmpFile, outputText);\n\n target = tmpFile;\n }\n\n /**\n * @type {import('..').CommandKitConfig}\n */\n const config = await import(`file://${target}`).then(\n (conf) => conf.default || conf\n );\n\n return config;\n}\n\nasync function ensureExists(loc: string) {\n const exists = fs.existsSync(loc);\n\n if (!exists) {\n throw new Error(`File not found: ${loc}`);\n }\n}\n\nexport function erase(dir: string) {\n rimrafSync(dir);\n}\n\nexport async function copyLocaleFiles(_from: string, _to: string) {\n const resolvedFrom = join(process.cwd(), _from);\n const resolvedTo = join(process.cwd(), _to);\n\n const localePaths = ['app/locales'];\n const srcLocalePaths = localePaths.map((path) => join(resolvedFrom, path));\n const destLocalePaths = localePaths.map((path) => join(resolvedTo, path));\n\n for (const localePath of srcLocalePaths) {\n if (!fs.existsSync(localePath)) {\n continue;\n }\n\n // copy localePath to destLocalePath\n const destLocalePath = destLocalePaths[srcLocalePaths.indexOf(localePath)];\n\n if (!fs.existsSync(destLocalePath)) {\n fs.promises.mkdir(destLocalePath, { recursive: true });\n }\n\n await fs.promises.cp(localePath, destLocalePath, {\n recursive: true,\n force: true\n });\n }\n}","import { createColors } from 'picocolors';\n\nexport default createColors(true);","import { mkdir, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { COMMANDKIT_IS_DEV } from './constants';\nimport { existsSync } from 'node:fs';\n\nexport async function generateTypesPackage(force = false) {\n const location = join(process.cwd(), 'node_modules', 'commandkit-types');\n if (!COMMANDKIT_IS_DEV && !force) return location;\n const packageJSON = join(location, 'package.json');\n const index = join(location, 'index.js');\n const types = join(location, 'index.d.ts');\n const command = join(location, 'command.d.ts');\n\n const packageJSONContent = {\n name: 'commandkit-types',\n version: '1.0.0',\n description: 'CommandKit types package',\n type: 'commonjs',\n main: 'index.js',\n types: 'index.d.ts'\n };\n\n const indexContent = `module.exports = {};`;\n\n // Restructuring the type declarations to properly extend rather than replace types\n const typesContent = `// Main types index file - imports all type declarations\nimport './command';\nexport {};\n`;\n\n // Properly set up command types to extend the CommandTypeData interface\n const commandTypesContent = `// Auto-generated command types\n export {};\ndeclare module 'commandkit' {\n type CommandTypeData = string\n}`;\n\n await mkdir(location, { recursive: true }).catch(() => {});\n await writeFile(packageJSON, JSON.stringify(packageJSONContent, null, 2));\n await writeFile(index, indexContent);\n await writeFile(types, typesContent);\n await writeFile(command, commandTypesContent);\n\n return location;\n}\n\nexport async function rewriteCommandDeclaration(data: string) {\n const commandTypesContent = `// Auto-generated command types\n declare module 'commandkit' {\n ${data}\n}\n export {};\n`;\n\n const location = join(process.cwd(), 'node_modules', 'commandkit-types');\n\n if (!existsSync(location)) return;\n\n const type = join(location, 'command.d.ts');\n\n await writeFile(type, commandTypesContent, { encoding: 'utf-8' });\n}","export const COMMANDKIT_CACHE_TAG = Symbol('kCommandKitCacheTag');\n\nexport const COMMANDKIT_IS_DEV = process.env.COMMANDKIT_IS_DEV === 'true';\n\nexport const COMMANDKIT_IS_TEST = process.env.COMMANDKIT_IS_TEST === 'true';\n\nexport const COMMANDKIT_BOOTSTRAP_MODE = (process.env.\nCOMMANDKIT_BOOTSTRAP_MODE || 'development') as 'development' | 'production';\n\n/**\n * Types of Hot Module Replacement events\n */\nexport const HMREventType = {\n ReloadCommands: 'reload-commands',\n ReloadEvents: 'reload-events',\n Unknown: 'unknown'\n} as const;\n\nexport type HMREventType = (typeof HMREventType)[keyof typeof HMREventType];"],"mappings":"6mBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,sBAAAE,IAAA,eAAAC,EAAAH,GAAA,IAAAI,EAA8B,yBCAvB,SAASC,EAAOC,EAAU,GAAO,CACtC,IAAMC,EAAS,CACb,SAAU,cACV,kBAAmB,MACrB,EAEA,OAAID,EAAgB,OAAO,OAAO,CAAC,EAAGC,CAAM,EAErC,OAAO,OAAO,CAAC,EAAG,QAAQ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EAAA,YAQF,SAASG,EAChBC,EACAC,EACAC,EACA,CAlBA,IAAAC,EAAAC,KAmBO,iBAAW,QAAKH,EAAKD,CAAQ,CAAC,GACjCK,EAAM,yCAAyCL,CAAQ,EAAE,EAG3D,IAAMM,EAAQV,EAASM,CAAK,EAEtBK,KAAK,SACT,OACA,CACA,uBAAuBL,EAAQ,cAAgB,YAAY,IAC3D,uBACAF,CAAQ,EAER,CACE,IAAAC,EACA,YAAa,GACb,IAAKC,EAAQM,EAAO,EAAIC,EAAQ,EAChC,MAAAH,CACF,CACF,EAEA,OAAAH,EAAAI,EAAG,SAAH,MAAAJ,EAAW,KAAK,QAAQ,SACxBC,EAAAG,EAAG,SAAH,MAAAH,EAAW,KAAK,QAAQ,QAEjBG,CACT,CA9BgBT,EAAAC,EAAA","names":["app_process_exports","__export","createAppProcess","__toCommonJS","import_node_child_process","DevEnv","_static","common","__name","ProdEnv","CommonEnvFiles","DevEnvFiles","ProdEnvFiles","devEnvFileArgs","prodEnvFileArgs","import_node_path","import_node_fs","import_rimraf","import_node_path","import_node_fs","import_picocolors","colors_default","import_promises","import_node_path","COMMANDKIT_CACHE_TAG","COMMANDKIT_IS_DEV","COMMANDKIT_IS_TEST","COMMANDKIT_BOOTSTRAP_MODE","import_node_fs","import_node_child_process","write","message","__name","panic","message","write","colors_default","__name","getStdio","supportsCommands","__name","createAppProcess","fileName","cwd","isDev","_a","_b","panic","stdio","ps","DevEnv","ProdEnv"]}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { a6 as CompilerPlugin } from '../CommandKit-jZCy9fZX.js';
|
|
2
|
+
import { MaybeArray } from '../components/common/types.js';
|
|
3
|
+
import 'discord.js';
|
|
4
|
+
import 'node:events';
|
|
5
|
+
import '../components/common/element.js';
|
|
6
|
+
import '../components/v1/button/ButtonKit.js';
|
|
7
|
+
import '../components/common/EventInterceptor.js';
|
|
8
|
+
import '../components/v1/modal/ModalKit.js';
|
|
9
|
+
import '../app/commands/MessageCommandParser.js';
|
|
10
|
+
import 'diagnostics_channel';
|
|
11
|
+
import '../app/router/CommandsRouter.js';
|
|
12
|
+
import '../app/router/EventsRouter.js';
|
|
13
|
+
import '../plugins/plugin-runtime/types.js';
|
|
14
|
+
import '../utils/constants.js';
|
|
15
|
+
|
|
16
|
+
interface ApplicationBuildOptions {
|
|
17
|
+
plugins?: MaybeArray<CompilerPlugin>[] | Array<CompilerPlugin>;
|
|
18
|
+
esbuildPlugins?: any[];
|
|
19
|
+
isDev?: boolean;
|
|
20
|
+
configPath?: string;
|
|
21
|
+
}
|
|
22
|
+
declare function buildApplication({ plugins, esbuildPlugins, isDev, configPath, }: ApplicationBuildOptions): Promise<void>;
|
|
23
|
+
|
|
24
|
+
export { type ApplicationBuildOptions, buildApplication };
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"use strict";var qe=Object.create;var A=Object.defineProperty;var ze=Object.getOwnPropertyDescriptor;var Je=Object.getOwnPropertyNames;var Ye=Object.getPrototypeOf,Xe=Object.prototype.hasOwnProperty;var n=(r,e)=>A(r,"name",{value:e,configurable:!0});var Qe=(r,e)=>{for(var t in e)A(r,t,{get:e[t],enumerable:!0})},ie=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of Je(e))!Xe.call(r,a)&&a!==t&&A(r,a,{get:()=>e[a],enumerable:!(i=ze(e,a))||i.enumerable});return r};var b=(r,e,t)=>(t=r!=null?qe(Ye(r)):{},ie(e||!r||!r.__esModule?A(t,"default",{value:r,enumerable:!0}):t,r)),Ze=r=>ie(A({},"__esModule",{value:!0}),r);var Qt={};Qe(Qt,{buildApplication:()=>Jt});module.exports=Ze(Qt);var je=require("tsup");var ae=require("crypto");var V=class V{constructor(e){this.options=e}id=(0,ae.randomUUID)();loadedAt=Date.now();async activate(e){}async deactivate(e){}};n(V,"PluginCommon");var B=V;var W=class W extends B{type="compiler";async transform(e){return null}async resolve(e){return null}async onBuildStart(){}async onBuildEnd(){}};n(W,"CompilerPlugin");var E=W;var _t=require("discord.js");var O={ExitMiddleware:Symbol("kExitMiddleware"),ForwardedCommand:Symbol("kForwardedCommand"),InvalidCommandPrefix:Symbol("kInvalidCommandPrefix"),PluginCaptureHandle:Symbol("kPluginCaptureHandle")};var Pe=require("async_hooks");var Lt=b(require("events"));var se=require("picocolors"),l=(0,se.createColors)(!0);var nt=require("discord.js");var q=require("discord.js");var rt=require("discord.js");var le=require("discord.js");var z=require("discord.js");var ce=require("discord.js");var me=require("discord.js");var ue=require("discord.js");var de=require("discord.js");var pe=require("discord.js");var ot=require("discord.js");var v=require("discord.js");var it=require("discord.js");var he=require("discord.js");var $=require("discord.js");var at=require("discord.js");var st=require("discord.js");var Re=require("discord.js");var mt=require("fs"),ut=require("path");var ii=Symbol("kCommandKitCacheTag"),K=process.env.COMMANDKIT_IS_DEV==="true",ai=process.env.COMMANDKIT_IS_TEST==="true",si=process.env.COMMANDKIT_BOOTSTRAP_MODE||"development";var J=class J extends E{name="MacroPlugin";macroTransformer;async activate(){let e=await import("use-macro");this.macroTransformer=new e.MacroTransformer}async deactivate(){this.macroTransformer=null}async transform(e){if(!this.options.enabled)return null;let{contents:t,loader:i}=await this.macroTransformer.transform(e.contents.toString(),e.path);return{contents:t,loader:i}}};n(J,"MacroPlugin");var F=J;var Ce={plugins:[new F({enabled:!0})],esbuildPlugins:[],compilerOptions:{macro:{development:!1}},static:!0,typescript:{ignoreBuildErrors:!1},distDir:"dist",env:{},sourceMap:{development:!0,production:!0},typedCommands:!0};var lt=Ce;function Y(){return lt}n(Y,"getConfig");var xe=require("async_hooks");var Mi=Symbol("commandkitEventWorker"),ct=new xe.AsyncLocalStorage;var $t=require("path");var I=require("discord.js");var dt=b(require("path"));var N=require("discord.js");var X=require("discord.js");var ht=require("discord.js");var pt=require("crypto");var M=require("fs/promises"),D=require("path");var gt=require("fs");async function Q(r=!1){let e=(0,D.join)(process.cwd(),"node_modules","commandkit-types");if(!K&&!r)return e;let t=(0,D.join)(e,"package.json"),i=(0,D.join)(e,"index.js"),a=(0,D.join)(e,"index.d.ts"),s=(0,D.join)(e,"command.d.ts"),m={name:"commandkit-types",version:"1.0.0",description:"CommandKit types package",type:"commonjs",main:"index.js",types:"index.d.ts"},u="module.exports = {};",c=`// Main types index file - imports all type declarations
|
|
2
|
+
import './command';
|
|
3
|
+
export {};
|
|
4
|
+
`,d=`// Auto-generated command types
|
|
5
|
+
export {};
|
|
6
|
+
declare module 'commandkit' {
|
|
7
|
+
type CommandTypeData = string
|
|
8
|
+
}`;return await(0,M.mkdir)(e,{recursive:!0}).catch(()=>{}),await(0,M.writeFile)(t,JSON.stringify(m,null,2)),await(0,M.writeFile)(i,u),await(0,M.writeFile)(a,c),await(0,M.writeFile)(s,d),e}n(Q,"generateTypesPackage");var xt=require("discord.js"),yt=require("fs"),bt=require("fs/promises"),U=require("path");var Et=require("discord.js"),vt=require("fs"),wt=require("fs/promises"),Mt=require("path");var It=require("discord.js");var Ie=require("fs"),Se=require("path");var St=require("rimraf"),S=require("path"),y=b(require("fs"));var ve=require("child_process");var h;function Rt(r){process.stdout.write(r),process.stdout.write(`
|
|
9
|
+
`)}n(Rt,"write");function Ee(r){Rt(l.red(`Error: ${r}`)),process.exit(1)}n(Ee,"panic");async function Pt(r){return/\.(c|m)?tsx?$/.test(r)?(process.features.typescript||await Z(),!0):!1}n(Pt,"ensureTypeScript");var T;function Kt(){if(T)return T;let r={"yarn.lock":"yarn","pnpm-lock.yaml":"pnpm","package-lock.json":"npm","bun.lock":"bun","bun.lockb":"bun"};for(let[e,t]of Object.entries(r))if(y.default.existsSync((0,S.join)(process.cwd(),e))){T=t;break}return T||(T="npm"),T}n(Kt,"detectPackageManager");async function Z(r){if(h)return h;try{h=await import("typescript")}catch(e){if(e instanceof Error&&"code"in e&&e.code==="MODULE_NOT_FOUND")try{let t=Kt();return(0,ve.execSync)(`${t} add typescript`,{stdio:"inherit",cwd:process.cwd()}),console.log(l.cyan("TypeScript has been installed automatically, restarting...")),h=await import("typescript"),h}catch{Ee("TypeScript is not installed and could not be installed automatically. Please install it manually.")}Ee(e||"TypeScript must be installed to use TypeScript config files.")}return h}n(Z,"loadTypeScript");async function we(r){if(await Dt(r),await Pt(r)&&h){let{transpileModule:i}=h,a=y.default.readFileSync(r,"utf8"),{outputText:s}=i(a,{compilerOptions:{module:h.ModuleKind.ESNext,target:h.ScriptTarget.ESNext,moduleResolution:h.ModuleResolutionKind.NodeNext},fileName:r}),m=await Q(),u=(0,S.join)(m,"compiled-commandkit.config.mjs");y.default.writeFileSync(u,s),r=u}return await import(`file://${r}`).then(i=>i.default||i)}n(we,"loadConfigFileFromPath");async function Dt(r){if(!y.default.existsSync(r))throw new Error(`File not found: ${r}`)}n(Dt,"ensureExists");async function Me(r,e){let t=(0,S.join)(process.cwd(),r),i=(0,S.join)(process.cwd(),e),a=["app/locales"],s=a.map(u=>(0,S.join)(t,u)),m=a.map(u=>(0,S.join)(i,u));for(let u of s){if(!y.default.existsSync(u))continue;let c=m[s.indexOf(u)];y.default.existsSync(c)||y.default.promises.mkdir(c,{recursive:!0}),await y.default.promises.cp(u,c,{recursive:!0,force:!0})}}n(Me,"copyLocaleFiles");var Tt=["commandkit.config.js","commandkit.config.mjs","commandkit.config.cjs","commandkit.config.ts"];function kt(r){return Tt.map(e=>(0,Se.join)(r,e))}n(kt,"getPossibleConfigPaths");function At(r){let e=kt(r);for(let t of e)if((0,Ie.existsSync)(t))return{path:t,isTypeScript:/\.ts$/.test(t)};return null}n(At,"findConfigFile");var ee=null;async function te(r=process.cwd()){if(ee)return ee;let e=At(r);if(!e)return Y();let t=await we(e.path);return ee=t,t}n(te,"loadConfigFile");var Ft=require("fs");var Bt=b(require("events"));var Ot=require("discord.js");var El=Symbol("commandkitCommandWorker"),Nt=new Pe.AsyncLocalStorage;function f(){return Nt.getStore()}n(f,"getContext");var Ut={autocomplete:"Autocomplete",messageContextMenu:"MessageContextMenu",userContextMenu:"UserContextMenu",chatInput:"ChatInputCommand",message:"Message"},Ht={0:l.blue,1:l.green,2:l.yellow,3:l.red,4:l.white},jt={0:l.bgBlue,1:l.bgGreen,2:l.bgYellow,3:l.bgRed,4:l.bgWhite},H={vertical:"\u2502",horizontalDown:"\u252C",horizontalUp:"\u2534",verticalRight:"\u251C",corner:"\u2514"},ne=class ne{constructor(e=process.stdout,t=process.stderr){this.stdout=e;this.stderr=t;this.logger=new console.Console(this.stdout,this.stderr)}logger;_formatTime(e){let t=e.getHours().toString().padStart(2,"0"),i=e.getMinutes().toString().padStart(2,"0"),a=e.getSeconds().toString().padStart(2,"0"),s=e.getMilliseconds().toString().padStart(3,"0");return`${t}:${i}:${a}.${s}`}_getContext(){let e=f();if(!e)return"";let t=e.variables.get("execHandlerKind"),i=e.variables.get("commandHandlerType"),a=e.variables.get("currentCommandName");if(!t&&!i)return"";let s=Ut[t];if(!s&&!i)return"";let m=e.variables.get("forwardedBy"),u=e.variables.get("forwardedTo"),c=a?l.magenta(`/${a}`)+" ":"",d=u?`${l.yellowBright(`(${m||a} \u2192 ${u})`)} `:"";return l.dim(`${H.vertical} `)+l.cyanBright(`${c}${d}${s?l.gray(`[${s}]`):""}`.trim())}_getLevelLabel(e){let t;switch(e){case 0:t="[DEBUG]";break;case 1:t="[INFO]";break;case 2:t="[WARN]";break;case 3:t="[ERROR]";break;default:t="[LOG]"}return`${jt[e](l.whiteBright(` ${t} `))} `}_getPrefix(e){let t=this._formatTime(new Date);return`${this._getLevelLabel(e)}${l.dim(H.vertical)} ${l.dim(t)}`}_log(e,...t){let i=this._getPrefix(e),a=this._getContext(),s=Ht[e];a?this.logger.log(`${i}
|
|
10
|
+
${a} ${l.dim(H.corner)}`,...t.map(m=>s(m))):this.logger.log(`${i} ${l.dim(H.corner)}`,...t.map(m=>s(m)))}debug(...e){this._log(0,...e)}error(...e){this._log(3,...e)}log(...e){this._log(4,...e)}info(...e){this._log(1,...e)}warn(...e){this._log(2,...e)}};n(ne,"DefaultLogger");var j=ne;function Gt(r){let e=r;if(!(e!=null&&e.provider))throw new Error("A logger provider must be provided.");let t=["log","error","warn","info","debug"],i={configure(a){e=a}};for(let a of t)i[a]=(...s)=>{e.provider[a](...s)};return i}n(Gt,"createLogger");var w=Gt({provider:new j});var De=require("fs/promises");var Ke=/\.(c|m)?(t|j)sx?$/,re=class re{constructor(e){this.plugins=e}name="CompilerPluginRuntime";getPlugins(){return this.plugins}isEmpty(){return!this.plugins.length}async onLoad(e){var s,m;let i=await(0,De.readFile)(e.path,"utf8"),a=(s=e.path)==null?void 0:s.split(".").pop();for(let u of this.plugins)try{let c=await((m=u.transform)==null?void 0:m.call(u,{contents:i,path:e.path,loader:a,args:e}));if(!c)continue;c.contents&&(i=c.contents),c.loader&&(a=c.loader)}catch(c){let d=c instanceof Error?c:new Error(c);return{pluginName:u.name,errors:[{text:d.message,detail:(d==null?void 0:d.stack)??d,location:null}]}}return{contents:i,loader:a}}async onResolve(e){var i;let t={};for(let a of this.plugins)try{let s=await((i=a.resolve)==null?void 0:i.call(a,e));if(!s)continue;t={...t,...s}}catch(s){let m=s instanceof Error?s:new Error(s);return{errors:[{text:m.message,detail:(m==null?void 0:m.stack)??m,location:null}]}}return t}async onStart(){var e;for(let t of this.plugins)try{await((e=t.onBuildStart)==null?void 0:e.call(t))}catch(i){console.error(`Plugin ${t.name} failed to run onBuildStart with ${(i==null?void 0:i.stack)||i}`)}}async onEnd(){var e;for(let t of this.plugins)try{await((e=t.onBuildEnd)==null?void 0:e.call(t))}catch(i){console.error(`Plugin ${t.name} failed to run onBuildEnd with ${(i==null?void 0:i.stack)||i}`)}}async onDispose(){var e;for(let t of this.plugins)try{await((e=t.deactivate)==null?void 0:e.call(t,this))}catch(i){console.error(`Plugin ${t.name} failed to deactivate with ${(i==null?void 0:i.stack)||i}`)}}async onInit(){var e;for(let t of this.plugins)try{await((e=t.activate)==null?void 0:e.call(t,this))}catch(i){console.error(`Plugin ${t.name} failed to activate with ${(i==null?void 0:i.stack)||i}`)}}async cleanup(){await this.onEnd(),await this.onDispose()}async setup(e){this.plugins.length&&(await this.onInit(),await e.onResolve({filter:Ke},this.onResolve.bind(this)),await e.onLoad({filter:Ke},this.onLoad.bind(this)),await e.onStart(this.onStart.bind(this)),e.onEnd(async()=>{await this.onEnd()}),e.onDispose(async()=>{await this.onDispose()}))}toEsbuildPlugin(){return{name:this.name,setup:this.setup.bind(this)}}};n(re,"CompilerPluginRuntime");var G=re;function Te(r){let t=class t extends E{name=r.name;onBuildEnd(){var a;return(a=r.onBuildEnd)==null?void 0:a.call(r)}onBuildStart(){var a;return(a=r.onBuildStart)==null?void 0:a.call(r)}async transform(a){var s;return(s=r.transform)==null?void 0:s.call(r,a)}async resolve(a){var s;return(s=r.resolve)==null?void 0:s.call(r,a)}};n(t,"EsbuildPluginCompat");let e=t;return e}n(Te,"fromEsbuildPlugin");var Ge=require("fs/promises"),_e=require("path");function ke(r=!1){let e={NODE_ENV:"development",COMMANDKIT_IS_DEV:"true"};return r?Object.assign({},e):Object.assign({},process.env,e)}n(ke,"DevEnv");function Ae(r=!1){let e={NODE_ENV:"production",COMMANDKIT_IS_DEV:"false"};return r?Object.assign({},e):Object.assign({},process.env,e)}n(Ae,"ProdEnv");var Be=[".env",".env.local"],Vt=[".env.development",".env.development.local"],Wt=[".env.production",".env.production.local"],Oe=[...Be,...Vt],Le=[...Be,...Wt];var Ve=require("rimraf");var $e=require("fs");var _=require("path");var qt="TypeScript must be installed in order to use the type checker. Please install it using `npm install typescript` or `yarn add typescript`";function zt(r,e,t){let i=r.flattenDiagnosticMessageText(e.messageText,`
|
|
11
|
+
`);if(!e.file)return`${l.red("error")}: ${i}`;let{line:a,character:s}=r.getLineAndCharacterOfPosition(e.file,e.start),m=(0,_.relative)(t,e.file.fileName),u=`${a+1}:${s+1}`,c=e.code?`TS${e.code}`:"";return[`${l.bold(l.cyan(m))}:${l.bold(l.yellow(u))} - ${l.red("error")} ${l.gray(c)}`,`${i}`].join(`
|
|
12
|
+
`)}n(zt,"formatDiagnostic");async function Fe(r){let e=(0,_.join)(r,"tsconfig.json");if(!(0,$e.existsSync)(e))return;let t=await Z(qt),i={getCanonicalFileName:n(c=>c,"getCanonicalFileName"),getCurrentDirectory:t.sys.getCurrentDirectory,getNewLine:n(()=>t.sys.newLine,"getNewLine")},a=t.readConfigFile(e,t.sys.readFile);a.error&&(console.error(l.red(`Error reading tsconfig.json: ${t.formatDiagnostic(a.error,i)}`)),process.exit(1));let s=t.parseJsonConfigFileContent(a.config,t.sys,r);s.options.noEmit=!0;let m=t.createProgram({rootNames:s.fileNames,options:s.options,projectReferences:s.projectReferences}),u=[...m.getOptionsDiagnostics(),...m.getGlobalDiagnostics(),...m.getSyntacticDiagnostics(),...m.getSemanticDiagnostics()];if(u.length>0){console.log(""),console.error(l.bold(l.red("Type checking failed with the following errors:"))),console.log("");let c=new Map;for(let L of u){let k=L.file?L.file.fileName:"Global";c.has(k)||c.set(k,[]),c.get(k).push(L)}let d=u.length,oe=0;for(let[L,k]of c)for(let We of k)oe++,console.log(zt(t,We,r)),oe<d&&console.log("");console.log(""),console.error(l.bold(l.red(`Found ${d} error${d>1?"s":""}`))),console.log(""),process.exit(1)}console.log(l.green("\u2713 Type checking completed successfully."))}n(Fe,"performTypeCheck");async function Jt({plugins:r,esbuildPlugins:e,isDev:t,configPath:i}){var u;let a=await te(i);!t&&!((u=a==null?void 0:a.typescript)!=null&&u.ignoreBuildErrors)&&await Fe(i||process.cwd());let s=new G(r||[]),m=s.isEmpty()?[]:[s.toEsbuildPlugin()];e!=null&&e.length&&m.push(...e.map(Te));try{let c=t?".commandkit":a.distDir;await(0,Ve.rimraf)(c),await(0,je.build)({esbuildPlugins:m,watch:!1,banner:{js:t?"":"/* Optimized production build generated by commandkit */"},cjsInterop:!0,dts:!1,clean:!0,format:["esm"],shims:!0,keepNames:!0,minify:!1,esbuildOptions:n(d=>(d.jsx="automatic",d.jsxImportSource="commandkit",d),"esbuildOptions"),minifyIdentifiers:!1,minifySyntax:!1,silent:!!t,splitting:!0,skipNodeModulesBundle:!0,name:"CommandKit",sourcemap:!0,target:"node16",outDir:c,env:t?ke(!0):Ae(!0),entry:["src",`!${a.distDir}`,"!.commandkit","!**/*.test.*","!**/*.spec.*"]}),await Me("src",c),await Xt(i||process.cwd(),!!t,a.distDir)}catch(c){console.error("Build failed:",c),c instanceof Error&&console.error("Error details:",c.stack),process.exit(1)}finally{await s.cleanup()}}n(Jt,"buildApplication");var Ne=n(r=>`// --- Environment Variables Loader ---
|
|
13
|
+
const $env = [${(r?Oe:Le).map(e=>`"${e}"`).join(", ")}];
|
|
14
|
+
for (const file of $env) {
|
|
15
|
+
try {
|
|
16
|
+
process.loadEnvFile(file);
|
|
17
|
+
console.log('\\x1b[36m\u2714 Loaded \\x1b[0m\\x1b[33m%s\\x1b[0m', file);
|
|
18
|
+
} catch {}
|
|
19
|
+
}
|
|
20
|
+
`,"envScript"),Ue=["// --- CommandKit require() polyfill ---",' if (typeof require === "undefined") {',' const { createRequire } = await import("node:module");'," const __require = createRequire(import.meta.url);",' Object.defineProperty(globalThis, "require", {'," value: (id) => {"," return __require(id);"," },"," configurable: true,"," enumerable: false,"," writable: true,"," });"," }","// --- CommandKit require() polyfill ---"].join(`
|
|
21
|
+
`),Yt=["// --- CommandKit Anti-Crash Monitor ---"," // 'uncaughtException' event is supposed to be used to perform synchronous cleanup before shutting down the process"," // instead of using it as a means to resume operation."," // But it exists here due to compatibility reasons with discord bot ecosystem."," const p = (t) => `\\x1b[31m${t}\\x1b[0m`, b = '[CommandKit Anti-Crash Monitor]', l = console.log, e1 = 'uncaughtException', e2 = 'unhandledRejection';"," if (!process.eventNames().includes(e1)) // skip if it is already handled"," process.on(e1, (e) => {"," l(p(`${b} Uncaught Exception`)); l(p(b), p(e.stack || e));"," })"," if (!process.eventNames().includes(e2)) // skip if it is already handled"," process.on(e2, (r) => {"," l(p(`${b} Unhandled promise rejection`)); l(p(`${b} ${r.stack || r}`));"," });","// --- CommandKit Anti-Crash Monitor ---"].join(`
|
|
22
|
+
`),He=n(r=>`;await (async () => {
|
|
23
|
+
${r.join(`
|
|
24
|
+
|
|
25
|
+
`)}
|
|
26
|
+
})();`,"wrapInAsyncIIFE");async function Xt(r,e,t){let i=`/* Entrypoint File Generated By CommandKit */
|
|
27
|
+
${e?`
|
|
28
|
+
|
|
29
|
+
// Injected for development
|
|
30
|
+
${He([Ne(e),Yt,Ue])}
|
|
31
|
+
|
|
32
|
+
`:He([Ne(e),Ue])}
|
|
33
|
+
|
|
34
|
+
import { CommandKit } from 'commandkit';
|
|
35
|
+
|
|
36
|
+
async function bootstrap() {
|
|
37
|
+
const app = await import('./app.js').then((m) => m.default ?? m);
|
|
38
|
+
const commandkit = new CommandKit({
|
|
39
|
+
client: app,
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
await commandkit.start();
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
await bootstrap().catch((e) => {
|
|
46
|
+
console.error('Failed to bootstrap CommandKit application:\\n', e.stack);
|
|
47
|
+
})
|
|
48
|
+
`;await(0,Ge.writeFile)((0,_e.join)(r,e?".commandkit":t||"dist","index.js"),i)}n(Xt,"injectEntryFile");0&&(module.exports={buildApplication});
|
|
49
|
+
//# sourceMappingURL=build.js.map
|