commandkit 0.1.11-dev.20250213170637 → 0.1.11-dev.20250214040728

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/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../node_modules/.pnpm/tsup@8.3.5_jiti@1.21.7_postcss@8.4.49_tsx@4.19.2_typescript@5.7.3_yaml@2.7.0/node_modules/tsup/assets/cjs_shims.js","../src/cli/common.ts","../src/cli/parse-env.ts","../src/cli/esbuild-plugins/use-cache.ts","../src/cli/esbuild-plugins/plugin.ts","../src/cli/build.ts","../src/cli/development.ts","../src/cli/production.ts","../src/index.ts","../src/CommandKit.ts","../src/legacy/handlers/index.ts","../src/legacy/handlers/command-handler/CommandHandler.ts","../src/utils/clone.ts","../src/utils/colors.ts","../src/utils/get-paths.ts","../src/utils/resolve-file-url.ts","../src/legacy/handlers/command-handler/functions/loadCommandsWithRest.ts","../src/legacy/handlers/command-handler/functions/registerCommands.ts","../src/legacy/handlers/command-handler/utils/areSlashCommandsDifferent.ts","../src/legacy/handlers/command-handler/validations/index.ts","../src/legacy/handlers/command-handler/validations/devOnly.ts","../src/legacy/handlers/command-handler/validations/permissions.ts","../src/context/async-context.ts","../src/utils/error-codes.ts","../src/context/environment.ts","../src/app/commands/Context.ts","../src/app/i18n/Localization.ts","../src/legacy/handlers/event-handler/EventHandler.ts","../src/legacy/handlers/validation-handler/ValidationHandler.ts","../src/cache/CacheProvider.ts","../src/cache/MemoryCache.ts","../src/components/index.ts","../src/components/action-row/ActionRow.ts","../src/components/button/ButtonKit.ts","../src/components/button/Button.ts","../src/components/modal/ModalKit.ts","../src/components/modal/Modal.ts","../src/components/common/element.ts","../src/utils/warn-unstable.ts","../src/components/common/types.ts","../src/components/common/EventInterceptor.ts","../src/app/i18n/DefaultLocalizationStrategy.ts","../src/utils/utilities.ts","../src/utils/constants.ts","../src/app/command-handler/AppCommandHandler.ts","../src/app/commands/MessageCommandParser.ts","../src/app/router/index.ts","../src/app/router/CommandsRouter.ts","../src/app/router/EventsRouter.ts","../src/config.ts","../src/cache/index.ts","../src/cache/cache.ts","../src/app/index.ts","../src/app/i18n/LocalizationStrategy.ts","../src/app/i18n/Translation.ts","../src/app/middleware/signals.ts","../src/cli/init.ts"],"sourcesContent":["// Shim globals in cjs bundle\n// There's a weird bug that esbuild will always inject importMetaUrl\n// if we export it as `const importMetaUrl = ... __filename ...`\n// But using a function will not cause this issue\n\nconst getImportMetaUrl = () =>\ntypeof document === 'undefined' ?\nnew URL(`file:${__filename}`).href :\ndocument.currentScript && document.currentScript.src ||\nnew URL('main.js', document.baseURI).href;\n\nexport const importMetaUrl = /* @__PURE__ */getImportMetaUrl();","// @ts-check\n\nimport { rimrafSync } from 'rimraf';\nimport { join } from 'node:path';\nimport fs from 'node:fs';\n\nconst resetColor = '\\x1b[0m';\n\nexport const Colors = {\n reset: (text: string) => `${text}${resetColor}`,\n bright: (text: string) => `\\x1b[1m${text}${resetColor}`,\n dim: (text: string) => `\\x1b[2m${text}${resetColor}`,\n underscore: (text: string) => `\\x1b[4m${text}${resetColor}`,\n blink: (text: string) => `\\x1b[5m${text}${resetColor}`,\n reverse: (text: string) => `\\x1b[7m${text}${resetColor}`,\n hidden: (text: string) => `\\x1b[8m${text}${resetColor}`,\n\n black: (text: string) => `\\x1b[30m${text}${resetColor}`,\n red: (text: string) => `\\x1b[31m${text}${resetColor}`,\n green: (text: string) => `\\x1b[32m${text}${resetColor}`,\n yellow: (text: string) => `\\x1b[33m${text}${resetColor}`,\n blue: (text: string) => `\\x1b[34m${text}${resetColor}`,\n magenta: (text: string) => `\\x1b[35m${text}${resetColor}`,\n cyan: (text: string) => `\\x1b[36m${text}${resetColor}`,\n white: (text: string) => `\\x1b[37m${text}${resetColor}`,\n\n bgBlack: (text: string) => `\\x1b[40m${text}${resetColor}`,\n bgRed: (text: string) => `\\x1b[41m${text}${resetColor}`,\n bgGreen: (text: string) => `\\x1b[42m${text}${resetColor}`,\n bgYellow: (text: string) => `\\x1b[43m${text}${resetColor}`,\n bgBlue: (text: string) => `\\x1b[44m${text}${resetColor}`,\n bgMagenta: (text: string) => `\\x1b[45m${text}${resetColor}`,\n bgCyan: (text: string) => `\\x1b[46m${text}${resetColor}`,\n bgWhite: (text: string) => `\\x1b[47m${text}${resetColor}`\n};\n\nexport function write(message: any) {\n process.stdout.write(message);\n process.stdout.write('\\n');\n}\n\n/**\n * @returns {never}\n */\nexport function panic(message: any) {\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\nconst possibleFileNames = [\n'commandkit.json',\n'commandkit.config.json',\n'commandkit.js',\n'commandkit.config.js',\n'commandkit.mjs',\n'commandkit.config.mjs',\n'commandkit.cjs',\n'commandkit.config.cjs',\n'commandkit.ts',\n'commandkit.mts',\n'commandkit.cts'];\n\n\nexport async function findCommandKitConfig(src: string) {\n const cwd = process.cwd();\n const locations = src ?\n [join(cwd, src)] :\n possibleFileNames.map((name) => join(cwd, name));\n\n for (const location of locations) {\n try {\n return await loadConfigInner(location);\n } catch (e) {\n continue;\n }\n }\n\n panic(`Could not locate commandkit config from ${cwd}`);\n}\n\nfunction ensureTypeScript(target: string) {\n const isTypeScript = /\\.(c|m)tsx?$/.test(target);\n\n if (isTypeScript && !process.features.typescript) {\n panic(\n 'You are trying to load commandkit config file that is written in typescript. The current Node.js version does not have TypeScript feature enabled.'\n );\n }\n}\n\nasync function loadConfigInner(target: string) {\n const isJSON = target.endsWith('.json');\n\n await ensureExists(target);\n\n ensureTypeScript(target);\n\n /**\n * @type {import('..').CommandKitConfig}\n */\n // @ts-ignore\n const config = await import(`file://${target}`, {\n with: isJSON ? { type: 'json' } : undefined\n }).then((conf) => conf.default || conf);\n\n return config;\n}\n\nasync function ensureExists(loc: string) {\n await fs.promises.access(loc, fs.constants.F_OK);\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', 'src/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}","// @ts-check\n\nimport { randomUUID } from 'node:crypto';\n\nconst valuesMap = {\n true: true,\n false: false,\n null: null,\n undefined: undefined,\n __UUIDv4__: () => randomUUID()\n};\n\nconst VALUE_PREFIXES = {\n JSON: 'JSON::',\n DATE: 'DATE::'\n};\n\nfunction catcher(fn: Function) {\n try {\n fn();\n return true;\n } catch {\n return false;\n }\n}\n\nexport function parseEnv(src: any) {\n for (const key in src) {\n const value = src[key];\n\n if (typeof value !== 'string') continue;\n\n if (value.startsWith(VALUE_PREFIXES.JSON)) {\n catcher(\n () => src[key] = JSON.parse(value.replace(VALUE_PREFIXES.JSON, ''))\n );\n continue;\n }\n\n if (value.startsWith(VALUE_PREFIXES.DATE)) {\n src[key] = new Date(value.replace(VALUE_PREFIXES.DATE, ''));\n continue;\n }\n\n if (value.includes(',')) {\n src[key] = value.split(',').map((v) => v.trim());\n continue;\n }\n\n if (/^[0-9]+n$/.test(value)) {\n src[key] = BigInt(value);\n continue;\n }\n\n if (value in valuesMap) {\n src[key] =\n // @ts-ignore\n typeof valuesMap[value] === 'function' ?\n // @ts-ignore\n valuesMap[value]() :\n // @ts-ignore\n valuesMap[value];\n continue;\n }\n }\n\n return src;\n}","import * as parser from '@babel/parser';\nimport _traverse from '@babel/traverse';\nimport _generate from '@babel/generator';\nimport * as t from '@babel/types';\n\n// @ts-ignore\nconst traverse = _traverse.default || _traverse;\n// @ts-ignore\nconst generate = _generate.default || _generate;\n\nconst IMPORT_PATH = 'commandkit';\nconst DIRECTIVE = 'use cache';\nconst CACHE_IDENTIFIER =\n'super_duper_secret_internal_for_use_cache_directive_of_commandkit_cli_do_not_use_it_directly_or_you_will_be_fired_from_your_job_kthxbai';\n\nconst generateRandomString = (length = 6) => {\n const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';\n return Array.from(\n { length },\n () => chars[Math.floor(Math.random() * chars.length)]\n ).join('');\n};\n\nexport const cacheDirectivePlugin = async (source: string, args: any) => {\n const ast = parser.parse(source, {\n sourceType: 'module',\n plugins: ['typescript', 'jsx']\n });\n\n let state = {\n needsImport: false,\n hasExistingImport: false,\n cacheIdentifierName: CACHE_IDENTIFIER,\n modifications: []\n };\n\n // First pass: check for naming collisions and collect modifications\n traverse(ast, {\n Program: {\n enter(path: any) {\n const binding = path.scope.getBinding(CACHE_IDENTIFIER);\n if (binding) {\n state.cacheIdentifierName = `${CACHE_IDENTIFIER}_${generateRandomString()}`;\n }\n }\n },\n\n ImportDeclaration(path: any) {\n if (\n path.node.source.value === IMPORT_PATH &&\n path.node.specifiers.some(\n (spec: any) =>\n t.isImportSpecifier(spec) &&\n // @ts-ignore\n spec.imported.name === CACHE_IDENTIFIER\n ))\n {\n state.hasExistingImport = true;\n if (state.cacheIdentifierName !== CACHE_IDENTIFIER) {\n // @ts-ignore\n state.modifications.push(() => {\n path.node.specifiers.forEach((spec: any) => {\n if (\n t.isImportSpecifier(spec) &&\n // @ts-ignore\n spec.imported.name === CACHE_IDENTIFIER)\n {\n spec.local.name = state.cacheIdentifierName;\n }\n });\n });\n }\n }\n },\n\n 'FunctionDeclaration|FunctionExpression|ArrowFunctionExpression'(\n path: any)\n {\n const body = t.isBlockStatement(path.node.body) ? path.node.body : null;\n const hasUseCache = body?.directives?.some(\n (d: any) => d.value.value === DIRECTIVE\n );\n\n if (!hasUseCache && !t.isBlockStatement(path.node.body)) {\n const parentFunction = path.findParent(\n (p: any) =>\n (p.isFunction() || p.isProgram()) && 'directives' in p.node\n );\n if (\n !parentFunction?.node.directives?.some(\n (d: any) => d.value.value === DIRECTIVE\n ))\n {\n return;\n }\n }\n\n if (hasUseCache || !t.isBlockStatement(path.node.body)) {\n // Check if the function is async\n if (!path.node.async) {\n throw new Error(\n `\"${DIRECTIVE}\" directive may only be used in async functions at ${args.path}`\n );\n }\n\n state.needsImport = true;\n const isDeclaration = t.isFunctionDeclaration(path.node);\n const name = isDeclaration ? path.node.id?.name : undefined;\n\n // Create a new body without the 'use cache' directive\n const newBody = t.isBlockStatement(path.node.body) ?\n t.blockStatement(\n path.node.body.body,\n path.node.body.directives.filter(\n (d: any) => d.value.value !== DIRECTIVE\n )\n ) :\n path.node.body;\n\n const wrapped = t.callExpression(\n t.identifier(state.cacheIdentifierName),\n [t.arrowFunctionExpression(path.node.params, newBody, true)]\n );\n\n // @ts-ignore\n state.modifications.push(() => {\n if (name) {\n path.replaceWith(\n t.variableDeclaration('const', [\n t.variableDeclarator(t.identifier(name), wrapped)]\n )\n );\n } else if (!t.isVariableDeclarator(path.parent)) {\n path.replaceWith(wrapped);\n } else {\n path.parent.init = wrapped;\n }\n });\n }\n }\n });\n\n // Apply all collected modifications\n if (state.modifications.length > 0) {\n // Add import if needed\n if (state.needsImport && !state.hasExistingImport) {\n ast.program.body.unshift(\n t.importDeclaration(\n [\n t.importSpecifier(\n t.identifier(state.cacheIdentifierName),\n t.identifier(CACHE_IDENTIFIER)\n )],\n\n t.stringLiteral(IMPORT_PATH)\n )\n );\n }\n\n // Apply collected modifications\n // @ts-ignore\n state.modifications.forEach((modify) => modify());\n }\n\n const { code } = generate(ast);\n return {\n contents: code,\n loader: args.path.split('.').pop()\n };\n};","import { MacroTransformer } from 'use-macro';\nimport { cacheDirectivePlugin } from './use-cache';\nimport { readFile } from 'node:fs/promises';\n\nconst defaultConfig = {\n 'use-macro': true,\n 'use-cache': true,\n 'jsx-importsource': true\n};\n\ninterface CommandKitEsbuildPluginConfig {\n 'use-macro'?: boolean;\n 'jsx-importsource'?: boolean;\n 'use-cache'?: boolean;\n}\n\nexport const commandkitPlugin = (config?: CommandKitEsbuildPluginConfig) => {\n config = Object.assign({}, defaultConfig, config);\n\n const plugins = [\n {\n name: 'use-macro',\n plugin: async (content: string, args: any) => {\n const transformer = new MacroTransformer();\n const { contents } = await transformer.transform(content, args.path);\n return contents;\n }\n },\n {\n name: 'use-cache',\n plugin: async (content: string, args: any) => {\n const { contents } = await cacheDirectivePlugin(content, args);\n return contents;\n }\n }].\n filter((p) => {\n return !!config[p.name as keyof CommandKitEsbuildPluginConfig];\n });\n\n return {\n name: 'commandkit-transformer-plugin',\n setup(build: any) {\n if (!plugins.length) return;\n\n const fileFilter = /\\.(c|m)?(t|j)sx?$/;\n\n build.onLoad({ filter: fileFilter }, async (args: any) => {\n const source = await readFile(args.path, 'utf8');\n const loader = args.path.split('.').pop();\n\n let contents = source;\n\n for (const _plugin of plugins) {\n const { plugin, name } = _plugin;\n try {\n contents = await plugin(contents, args);\n } catch (e) {\n const err = new Error(`Plugin ${name} failed with ${e}`);\n err.stack = e instanceof Error ? e.stack : '';\n\n throw err;\n }\n }\n\n return {\n contents,\n loader\n };\n });\n }\n };\n};","// @ts-check\n\nimport { readFile, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { build } from 'tsup';\nimport {\n Colors,\n copyLocaleFiles,\n erase,\n findCommandKitConfig,\n panic,\n write } from\n'./common.js';\nimport ora from 'ora';\nimport { commandkitPlugin } from './esbuild-plugins/plugin';\n\nexport async function bootstrapProductionBuild(config: any) {\n const {\n sourcemap = false,\n minify = false,\n outDir = 'dist',\n antiCrash = true,\n src,\n main,\n requirePolyfill: polyfillRequire\n } = await findCommandKitConfig(config);\n\n const status = ora('Creating optimized production build...\\n').start();\n const start = performance.now();\n\n erase(outDir);\n\n try {\n await build({\n clean: true,\n format: ['esm'],\n dts: false,\n skipNodeModulesBundle: true,\n minify,\n shims: true,\n banner: {\n js: '/* Optimized production build generated by CommandKit */'\n },\n sourcemap,\n keepNames: true,\n outDir,\n silent: true,\n watch: false,\n cjsInterop: true,\n splitting: false,\n entry: [src, '!dist', '!.commandkit', `!${outDir}`],\n esbuildPlugins: [commandkitPlugin()],\n jsxFactory: 'CommandKit.createElement',\n jsxFragment: 'CommandKit.Fragment',\n async onSuccess() {\n await copyLocaleFiles(src, '.commandkit');\n }\n });\n\n await injectShims(outDir, main, antiCrash, polyfillRequire);\n\n status.succeed(\n Colors.green(\n `Build completed in ${(performance.now() - start).toFixed(2)}ms!`\n )\n );\n write(\n Colors.green(\n `\\nRun ${Colors.magenta(`commandkit start`)} ${Colors.green(\n 'to start your bot.'\n )}`\n )\n );\n } catch (e) {\n status.fail(\n `Build failed after ${(performance.now() - start).toFixed(2)}ms!`\n );\n panic(e);\n }\n}\n\nexport async function injectShims(\noutDir: string,\nmain: string,\nantiCrash: boolean,\npolyfillRequire: boolean)\n{\n const path = join(process.cwd(), outDir, main);\n\n const head = ['\\n\\n;await (async()=>{', \" 'use strict';\"].join('\\n');\n const tail = '\\n})();';\n const requireScript = polyfillRequire ?\n [\n '// --- CommandKit require() polyfill ---',\n ' if (typeof require === \"undefined\") {',\n ' const { createRequire } = await import(\"node:module\");',\n ' const __require = createRequire(import.meta.url);',\n ' Object.defineProperty(globalThis, \"require\", {',\n ' value: (id) => {',\n ' return __require(id);',\n ' },',\n ' configurable: true,',\n ' enumerable: false,',\n ' writable: true,',\n ' });',\n ' }',\n '// --- CommandKit require() polyfill ---'].\n join('\\n') :\n '';\n\n const antiCrashScript = antiCrash ?\n [\n '// --- CommandKit Anti-Crash Monitor ---',\n \" // 'uncaughtException' event is supposed to be used to perform synchronous cleanup before shutting down the process\",\n ' // instead of using it as a means to resume operation.',\n ' // But it exists here due to compatibility reasons with discord bot ecosystem.',\n \" const p = (t) => `\\\\x1b[33m${t}\\\\x1b[0m`, b = '[CommandKit Anti-Crash Monitor]', l = console.log, e1 = 'uncaughtException', e2 = 'unhandledRejection';\",\n ' if (!process.eventNames().includes(e1)) // skip if it is already handled',\n ' process.on(e1, (e) => {',\n ' l(p(`${b} Uncaught Exception`)); l(p(b), p(e.stack || e));',\n ' })',\n ' if (!process.eventNames().includes(e2)) // skip if it is already handled',\n ' process.on(e2, (r) => {',\n ' l(p(`${b} Unhandled promise rejection`)); l(p(`${b} ${r.stack || r}`));',\n ' });',\n '// --- CommandKit Anti-Crash Monitor ---'].\n join('\\n') :\n '';\n\n const contents = await readFile(path, 'utf-8');\n const finalScript = [\n head,\n requireScript,\n antiCrashScript,\n tail,\n '\\n\\n',\n contents].\n join('\\n');\n\n return writeFile(path, finalScript);\n}","// @ts-check\nimport { config as dotenv } from 'dotenv';\nimport { join } from 'node:path';\nimport { build } from 'tsup';\nimport {\n Colors,\n copyLocaleFiles,\n erase,\n findCommandKitConfig,\n panic,\n write } from\n'./common';\nimport { parseEnv } from './parse-env';\nimport child_process from 'node:child_process';\nimport ora from 'ora';\nimport { injectShims } from './build';\nimport { commandkitPlugin } from './esbuild-plugins/plugin';\n\nconst RESTARTING_MSG_PATTERN = /^Restarting '|\".+'|\"\\n?$/;\nconst FAILED_RUNNING_PATTERN = /^Failed running '.+'|\"\\n?$/;\n\nexport async function bootstrapDevelopmentServer(opts: any) {\n const {\n src,\n main,\n watch = Boolean(opts.noWatch),\n nodeOptions = [],\n envExtra = true,\n clearRestartLogs = true,\n outDir,\n requirePolyfill\n } = await findCommandKitConfig(opts.config);\n\n if (!src) {\n panic('Could not find src in commandkit.json');\n }\n\n if (!main) {\n panic('Could not find main in commandkit.json');\n }\n\n const watchMode = watch;\n const status = ora(\n Colors.green('Starting a development server...\\n')\n ).start();\n const start = performance.now();\n\n if (watchMode && !nodeOptions.includes('--watch')) {\n nodeOptions.push('--watch');\n } else if (!watchMode && nodeOptions.includes('--watch')) {\n nodeOptions.splice(nodeOptions.indexOf('--watch'), 1);\n }\n\n if (!nodeOptions.includes('--enable-source-maps')) {\n nodeOptions.push('--enable-source-maps');\n }\n\n erase('.commandkit');\n\n try {\n await build({\n clean: true,\n format: ['esm'],\n dts: false,\n skipNodeModulesBundle: true,\n minify: false,\n shims: true,\n sourcemap: 'inline',\n keepNames: true,\n outDir: '.commandkit',\n silent: true,\n entry: [src, '!dist', '!.commandkit', `!${outDir}`].filter(Boolean),\n watch: watchMode,\n cjsInterop: true,\n splitting: false,\n jsxFactory: 'CommandKit.createElement',\n jsxFragment: 'CommandKit.Fragment',\n async onSuccess() {\n await copyLocaleFiles(src, '.commandkit');\n return await injectShims('.commandkit', main, false, requirePolyfill);\n },\n esbuildPlugins: [\n commandkitPlugin({\n 'use-macro': false\n })]\n\n });\n\n status.succeed(\n Colors.green(\n `Dev server started in ${(performance.now() - start).toFixed(2)}ms!\\n`\n )\n );\n\n if (watchMode) write(Colors.cyan('Watching for file changes...\\n'));\n\n const processEnv = {};\n\n const env = dotenv({\n path: join(process.cwd(), '.env'),\n processEnv\n });\n\n if (envExtra) {\n parseEnv(processEnv);\n }\n\n if (env.error) {\n write(Colors.yellow(`[DOTENV] Warning: ${env.error.message}`));\n }\n\n if (env.parsed) {\n write(Colors.blue('[DOTENV] Loaded .env file!'));\n }\n\n const ps: child_process.ChildProcessWithoutNullStreams =\n child_process.spawn(\n 'node',\n [...nodeOptions, join(process.cwd(), '.commandkit', main)],\n {\n env: {\n ...process.env,\n ...processEnv,\n NODE_ENV: 'development',\n // @ts-expect-error\n COMMANDKIT_DEV: true,\n // @ts-expect-error\n COMMANDKIT_PRODUCTION: false\n },\n cwd: process.cwd()\n }\n );\n\n let isLastLogRestarting = false,\n hasStarted = false;\n\n ps.stdout.on('data', (data) => {\n const message = data.toString();\n\n if (FAILED_RUNNING_PATTERN.test(message)) {\n write(Colors.cyan('Failed running the bot, waiting for changes...'));\n isLastLogRestarting = false;\n if (!hasStarted) hasStarted = true;\n return;\n }\n\n if (clearRestartLogs && !RESTARTING_MSG_PATTERN.test(message)) {\n write(message);\n isLastLogRestarting = false;\n } else {\n if (isLastLogRestarting || !hasStarted) {\n if (!hasStarted) hasStarted = true;\n return;\n }\n write(Colors.cyan('⌀ Restarting the bot...'));\n isLastLogRestarting = true;\n }\n\n if (!hasStarted) hasStarted = true;\n });\n\n ps.stderr.on('data', (data) => {\n const message = data.toString();\n\n if (\n message.includes(\n 'ExperimentalWarning: Watch mode is an experimental feature and might change at any time'\n ))\n\n return;\n\n write(Colors.red(message));\n });\n\n ps.on('close', (code) => {\n write('\\n');\n process.exit(code ?? 0);\n });\n\n ps.on('error', (err) => {\n panic(err);\n });\n } catch (e) {\n status.fail(\n `Error occurred after ${(performance.now() - start).toFixed(2)}ms!\\n`\n );\n panic(e instanceof Error ? e.stack : e);\n }\n}","// @ts-check\nimport { config as dotenv } from 'dotenv';\nimport { existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { Colors, findCommandKitConfig, panic, write } from './common';\nimport { parseEnv } from './parse-env';\nimport child_process from 'node:child_process';\n\nexport async function bootstrapProductionServer(config: any) {\n const {\n main,\n outDir = 'dist',\n envExtra = true,\n sourcemap\n } = await findCommandKitConfig(config);\n\n if (!existsSync(join(process.cwd(), outDir, main))) {\n panic(\n 'Could not find production build, maybe run `commandkit build` first?'\n );\n }\n\n try {\n const processEnv = {};\n\n const env = dotenv({\n path: join(process.cwd(), '.env'),\n processEnv\n });\n\n if (envExtra) {\n parseEnv(processEnv);\n }\n\n if (env.error) {\n write(Colors.yellow(`[DOTENV] Warning: ${env.error.message}`));\n }\n\n if (env.parsed) {\n write(Colors.blue('[DOTENV] Loaded .env file!'));\n }\n\n const ps: child_process.ChildProcessWithoutNullStreams =\n child_process.spawn(\n 'node',\n [\n sourcemap ? '--enable-source-maps' : '',\n join(process.cwd(), outDir, main)].\n filter(Boolean),\n {\n env: {\n ...process.env,\n ...processEnv,\n NODE_ENV: 'production',\n // @ts-expect-error\n COMMANDKIT_DEV: false,\n // @ts-expect-error\n COMMANDKIT_PROD: true\n },\n cwd: process.cwd()\n }\n );\n\n ps.stdout.on('data', (data) => {\n write(data.toString());\n });\n\n ps.stderr.on('data', (data) => {\n write(Colors.red(data.toString()));\n });\n\n ps.on('close', (code) => {\n write('\\n');\n process.exit(code ?? 0);\n });\n\n ps.on('error', (err) => {\n panic(err);\n });\n } catch (e) {\n panic(e);\n }\n}","import { CommandKit } from './CommandKit';\n\nexport default CommandKit;\n\nexport * from './CommandKit';\nexport * from './components';\nexport * from './config';\nexport * from './context/async-context';\nexport * from './context/environment';\nexport * from './cache/index';\nexport * from './app/index';\nexport type * from './types';\n\n\n\n\n\n\n/**\n * The current version of CommandKit.\n */\nexport const version = /* @__MACRO__ $version */\"0.1.11-dev.20250213170637\";\n\n// cli\nexport { bootstrapCommandkitCLI } from './cli/init';","import EventEmitter from 'node:events';\nimport {\n CommandHandler,\n EventHandler,\n ValidationHandler } from\n'./legacy/handlers';\nimport type {\n CommandKitData,\n CommandKitOptions,\n CommandObject,\n ReloadOptions } from\n'./types';\nimport colors from './utils/colors';\nimport { CacheProvider } from './cache/CacheProvider';\nimport { MemoryCache } from './cache/MemoryCache';\nimport { createElement, Fragment } from './components';\nimport { EventInterceptor } from './components/common/EventInterceptor';\nimport { Awaitable, Locale, Message } from 'discord.js';\nimport { DefaultLocalizationStrategy } from './app/i18n/DefaultLocalizationStrategy';\nimport { findAppDirectory } from './utils/utilities';\nimport { join } from 'node:path';\nimport { AppCommandHandler } from './app/command-handler/AppCommandHandler';\nimport { LocalizationStrategy } from './app/i18n/LocalizationStrategy';\nimport { CommandsRouter, EventsRouter } from './app/router';\n\nexport interface CommandKitConfiguration {\n defaultLocale: Locale;\n localizationStrategy: LocalizationStrategy;\n getMessageCommandPrefix: (message: Message) => Awaitable<string | string[]>;\n}\n\nexport class CommandKit extends EventEmitter {\n #data: CommandKitData;\n public readonly eventInterceptor: EventInterceptor;\n\n public static readonly createElement = createElement;\n public static readonly Fragment = Fragment;\n\n public readonly config: CommandKitConfiguration = {\n defaultLocale: Locale.EnglishUS,\n localizationStrategy: new DefaultLocalizationStrategy(this),\n getMessageCommandPrefix: () => '!'\n };\n\n public commandsRouter!: CommandsRouter;\n public eventsRouter!: EventsRouter;\n public appCommandsHandler = new AppCommandHandler(this);\n\n static instance: CommandKit | undefined = undefined;\n\n /**\n * Create a new command and event handler with CommandKit.\n *\n * @param options - The default CommandKit configuration.\n * @see {@link https://commandkit.js.org/docs/guide/commandkit-setup}\n */\n constructor(options: CommandKitOptions) {\n if (CommandKit.instance) {\n process.emitWarning(\n 'CommandKit instance already exists. Having multiple instance in same project is discouraged and it may lead to unexpected behavior.',\n {\n code: 'MultiInstanceWarning'\n }\n );\n }\n\n if (!options.client) {\n throw new Error(\n colors.red('\"client\" is required when instantiating CommandKit.')\n );\n }\n\n if (options.validationsPath && !options.commandsPath) {\n throw new Error(\n colors.red('\"commandsPath\" is required when \"validationsPath\" is set.')\n );\n }\n\n super();\n\n options.debugCommands ??= process.env.NODE_ENV !== 'production';\n\n if (\n options.cacheProvider !== null && (\n !options.cacheProvider ||\n !(options.cacheProvider instanceof CacheProvider)))\n {\n options.cacheProvider = new MemoryCache();\n }\n\n this.eventInterceptor = new EventInterceptor(options.client);\n\n this.#data = options;\n\n this.#init().then(() => {\n // Increment client listeners count, as commandkit registers internal event listeners.\n this.incrementClientListenersCount();\n });\n\n if (!CommandKit.instance) {\n CommandKit.instance = this;\n }\n }\n\n /**\n * Sets the prefix resolver for the command handler.\n * @param resolver The resolver function.\n */\n setPrefixResolver(\n resolver: (message: Message) => Awaitable<string | string[]>)\n {\n this.config.getMessageCommandPrefix = resolver;\n return this;\n }\n\n /**\n * Sets the default locale for the command handler.\n * @param locale The default locale.\n */\n setDefaultLocale(locale: Locale) {\n this.config.defaultLocale = locale;\n return this;\n }\n\n /**\n * Sets the localization strategy for the command handler.\n * @param strategy The localization strategy.\n */\n setLocalizationStrategy(strategy: LocalizationStrategy) {\n this.config.localizationStrategy = strategy;\n return this;\n }\n\n /**\n * Resolves the current cache provider.\n */\n getCacheProvider(): CacheProvider | null {\n const provider = this.#data.cacheProvider;\n return provider ?? null;\n }\n\n /**\n * Whether or not to debug the command handler.\n */\n isDebuggingCommands() {\n return this.#data.debugCommands || false;\n }\n\n /**\n * Get the client attached to this CommandKit instance.\n */\n get client() {\n return this.#data.client;\n }\n\n /**\n * Get command handler instance.\n */\n get commandHandler() {\n return this.#data.commandHandler;\n }\n\n /**\n * (Private) Initialize CommandKit.\n */\n async #init() {\n // <!-- Setup event handler -->\n if (this.#data.eventsPath) {\n const eventHandler = new EventHandler({\n client: this.#data.client,\n eventsPath: this.#data.eventsPath,\n commandKitInstance: this\n });\n\n await eventHandler.init();\n\n this.#data.eventHandler = eventHandler;\n }\n\n // <!-- Setup validation handler -->\n if (this.#data.validationsPath) {\n const validationHandler = new ValidationHandler({\n validationsPath: this.#data.validationsPath\n });\n\n await validationHandler.init();\n\n this.#data.validationHandler = validationHandler;\n }\n\n // <!-- Setup command handler -->\n if (this.#data.commandsPath) {\n const commandHandler = new CommandHandler({\n client: this.#data.client,\n commandsPath: this.#data.commandsPath,\n devGuildIds: this.#data.devGuildIds || [],\n devUserIds: this.#data.devUserIds || [],\n devRoleIds: this.#data.devRoleIds || [],\n validationHandler: this.#data.validationHandler,\n skipBuiltInValidations: this.#data.skipBuiltInValidations || false,\n commandkitInstance: this,\n bulkRegister: this.#data.bulkRegister || false\n });\n\n this.#data.commandHandler = commandHandler;\n\n await this.#initApp();\n await commandHandler.init();\n }\n }\n\n async #initApp() {\n const appDir = this.getAppDirectory();\n if (!appDir) return;\n\n const commandsPath = this.getPath('commands')!;\n const events = this.getPath('events')!;\n\n this.commandsRouter = new CommandsRouter({\n entrypoint: commandsPath\n });\n\n this.eventsRouter = new EventsRouter({\n entrypoint: events\n });\n\n await this.#initEvents();\n await this.#initCommands();\n }\n\n async #initCommands() {\n if (this.commandsRouter.isValidPath()) {\n await this.commandsRouter.scan();\n }\n\n await this.appCommandsHandler.loadCommands();\n }\n\n async #initEvents() {\n if (this.eventsRouter.isValidPath()) {\n await this.eventsRouter.scan();\n }\n\n if (!this.#data.eventHandler) return;\n\n for (const event of Object.values(this.eventsRouter.toJSON())) {\n this.#data.eventHandler.registerExternal(event);\n }\n\n this.#data.eventHandler.resyncListeners();\n }\n\n /**\n * Updates application commands with the latest from \"commandsPath\".\n */\n async reloadCommands(type?: ReloadOptions) {\n if (!this.#data.commandHandler) return;\n await this.#data.commandHandler.reloadCommands(type);\n }\n\n /**\n * Updates application events with the latest from \"eventsPath\".\n */\n async reloadEvents() {\n if (!this.#data.eventHandler) return;\n await this.#data.eventHandler.reloadEvents(this.#data.commandHandler);\n }\n\n /**\n * Updates application command validations with the latest from \"validationsPath\".\n */\n async reloadValidations() {\n if (!this.#data.validationHandler) return;\n await this.#data.validationHandler.reloadValidations();\n }\n\n /**\n * @returns An array of objects of all the commands that CommandKit is handling.\n */\n get commands(): CommandObject[] {\n if (!this.#data.commandHandler) {\n return [];\n }\n\n const commands = this.#data.commandHandler.commands.map((cmd) => {\n const { run, autocomplete, ...command } = cmd;\n return command;\n });\n\n return commands;\n }\n\n /**\n * @returns The path to the commands folder which was set when instantiating CommandKit.\n */\n get commandsPath(): string | undefined {\n return this.#data.commandsPath;\n }\n\n /**\n * @returns The path to the events folder which was set when instantiating CommandKit.\n */\n get eventsPath(): string | undefined {\n return this.#data.eventsPath;\n }\n\n /**\n * @returns The path to the validations folder which was set when instantiating CommandKit.\n */\n get validationsPath(): string | undefined {\n return this.#data.validationsPath;\n }\n\n /**\n * @returns An array of all the developer user IDs which was set when instantiating CommandKit.\n */\n get devUserIds(): string[] {\n return this.#data.devUserIds || [];\n }\n\n /**\n * @returns An array of all the developer guild IDs which was set when instantiating CommandKit.\n */\n get devGuildIds(): string[] {\n return this.#data.devGuildIds || [];\n }\n\n /**\n * @returns An array of all the developer role IDs which was set when instantiating CommandKit.\n */\n get devRoleIds(): string[] {\n return this.#data.devRoleIds || [];\n }\n\n /**\n * Increment the client listeners count.\n */\n incrementClientListenersCount() {\n this.#data.client.setMaxListeners(this.#data.client.getMaxListeners() + 1);\n }\n\n /**\n * Decrement the client listeners count.\n */\n decrementClientListenersCount() {\n this.#data.client.setMaxListeners(this.#data.client.getMaxListeners() - 1);\n }\n\n /**\n * Path to the app directory. Returns `null` if not found.\n * The lookup order is:\n * - `./app`\n * - `./src/app`\n */\n getAppDirectory() {\n return findAppDirectory();\n }\n\n getPath(to: 'locales' | 'commands' | 'events') {\n const appDir = this.getAppDirectory();\n if (!appDir) return null;\n\n switch (to) {\n case 'locales':\n return join(appDir, 'locales');\n case 'commands':\n return join(appDir, 'commands');\n case 'events':\n return join(appDir, 'events');\n default:\n return to satisfies never;\n }\n }\n}","export * from './command-handler/CommandHandler';\nexport * from './event-handler/EventHandler';\nexport * from './validation-handler/ValidationHandler';","import { CacheType, Events, Interaction, Message } from 'discord.js';\nimport type {\n CommandData,\n CommandFileObject,\n ReloadOptions } from\n'../../../types';\nimport { clone } from '../../../utils/clone';\nimport colors from '../../../utils/colors';\nimport { getFilePaths } from '../../../utils/get-paths';\nimport { toFileURL } from '../../../utils/resolve-file-url';\nimport loadCommandsWithRest from './functions/loadCommandsWithRest';\nimport registerCommands from './functions/registerCommands';\nimport type {\n CommandHandlerData,\n CommandHandlerOptions,\n CommandKitInteraction } from\n'./typings';\nimport builtInValidationsFunctions from './validations';\nimport {\n makeContextAwareFunction,\n useEnvironment } from\n'../../../context/async-context';\nimport {\n afterCommand,\n CommandKitEnvironment,\n CommandKitEnvironmentType } from\n'../../../context/environment';\nimport {\n CommandExecutionMode,\n MiddlewareContext } from\n'../../../app/commands/Context';\nimport { CommandKitErrorCodes, isErrorType } from '../../../utils/error-codes';\n\nexport interface hCommandContext {\n interaction: CommandKitInteraction;\n command: CommandData;\n}\n\n/**\n * A handler for client application commands.\n */\nexport class CommandHandler {\n #data: CommandHandlerData;\n\n constructor({ ...options }: CommandHandlerOptions) {\n this.#data = {\n ...options,\n builtInValidations: [],\n commands: []\n };\n }\n\n async init() {\n await this.#buildCommands();\n\n this.#buildBuiltInValidations();\n\n const devOnlyCommands = this.#data.commands.filter(\n (cmd) => cmd.options?.devOnly\n );\n\n if (devOnlyCommands.length && !this.#data.devGuildIds.length) {\n process.emitWarning(\n colors.yellow(\n 'You have commands marked as \"devOnly\", but \"devGuildIds\" have not been set.'\n )\n );\n }\n\n if (\n devOnlyCommands.length &&\n !this.#data.devUserIds.length &&\n !this.#data.devRoleIds.length)\n {\n process.emitWarning(\n colors.yellow(\n 'You have commands marked as \"devOnly\", but \"devUserIds\" or \"devRoleIds\" have not been set.'\n )\n );\n }\n\n if (this.#data.bulkRegister) {\n await loadCommandsWithRest({\n client: this.#data.client,\n devGuildIds: this.#data.devGuildIds,\n commands: this.#data.commands\n });\n } else {\n await registerCommands({\n client: this.#data.client,\n devGuildIds: this.#data.devGuildIds,\n commands: this.#data.commands\n });\n }\n\n this.handleCommands();\n }\n\n async #buildCommands() {\n const allowedExtensions = /\\.(js|mjs|cjs|ts)$/i;\n const paths = await getFilePaths(this.#data.commandsPath, true);\n\n const commandFilePaths = paths.filter((path) =>\n allowedExtensions.test(path)\n );\n\n for (const commandFilePath of commandFilePaths) {\n const modulePath = toFileURL(commandFilePath);\n\n const importedObj = await import(`${modulePath}?t=${Date.now()}`);\n let commandObj: CommandFileObject = clone(importedObj); // Make commandObj extensible\n\n // If it's CommonJS, invalidate the import cache\n if (typeof module !== 'undefined' && typeof require !== 'undefined') {\n delete require.cache[require.resolve(commandFilePath)];\n }\n\n const compactFilePath =\n commandFilePath.split(process.cwd())[1] || commandFilePath;\n\n if (commandObj.default)\n commandObj = commandObj.default as CommandFileObject;\n\n // Ensure builder properties\n if (importedObj.default) {\n commandObj.data = importedObj.default.data;\n } else {\n commandObj.data = importedObj.data;\n }\n\n if (!commandObj.data) {\n process.emitWarning(\n colors.yellow(\n `Ignoring: Command file ${compactFilePath} does not export \"data\".`\n )\n );\n continue;\n }\n\n if (!commandObj.data.name) {\n process.emitWarning(\n colors.yellow(\n `Ignoring: Command file ${compactFilePath} does not export \"data.name\".`\n )\n );\n continue;\n }\n\n if (!commandObj.run) {\n process.emitWarning(\n colors.yellow(\n `Ignoring: Command file ${commandObj.data.name} does not export \"run\".`\n )\n );\n continue;\n }\n\n if (typeof commandObj.run !== 'function') {\n process.emitWarning(\n colors.yellow(\n `Ignoring: Command file ${commandObj.data.name} does not export \"run\" as a function.`\n )\n );\n continue;\n }\n\n commandObj.filePath = commandFilePath;\n\n let commandCategory =\n commandFilePath.\n split(this.#data.commandsPath)[1]?.\n replace(/\\\\\\\\|\\\\/g, '/').\n split('/')[1] || null;\n\n if (commandCategory && allowedExtensions.test(commandCategory)) {\n commandObj.category = null;\n } else {\n commandObj.category = commandCategory;\n }\n\n this.#data.commands.push(commandObj);\n }\n\n if (this.#data.commandkitInstance.appCommandsHandler) {\n const handler = this.#data.commandkitInstance.appCommandsHandler;\n\n const commands = handler.getCommandsArray();\n\n // this.#data.commands.push(...commands);\n\n for (const cmd of commands) {\n const idx = this.#data.commands.findIndex(\n (c) => c.data.name === cmd.name\n );\n\n if (idx !== -1) {\n // @ts-ignore\n this.#data.commands[idx] = { data: cmd };\n } else {\n // @ts-ignore\n this.#data.commands.push({ data: cmd });\n }\n }\n }\n }\n\n #buildBuiltInValidations() {\n for (const builtInValidationFunction of builtInValidationsFunctions) {\n this.#data.builtInValidations.push(builtInValidationFunction);\n }\n }\n\n async #commandFinalizer() {\n const env = useEnvironment();\n\n await env.runDeferredFunctions();\n\n // Clear all deferred functions if we somehow missed them\n env.clearAllDeferredFunctions();\n }\n\n async #requestExternalHandler(interaction: Interaction<CacheType> | Message) {\n const handler = this.#data.commandkitInstance.appCommandsHandler;\n if (!handler) return false;\n\n if (\n !(interaction instanceof Message) &&\n !(interaction.isCommand() || interaction.isAutocomplete()))\n {\n return false;\n }\n\n const targetCommand = await handler.prepareCommandRun(interaction);\n\n if (!targetCommand) return false;\n\n const environment = useEnvironment();\n\n environment.variables.set('commandHandlerType', 'app');\n\n const { command, middlewares, messageCommandParser } = targetCommand;\n\n const context = new MiddlewareContext(this.#data.commandkitInstance, {\n executionMode:\n interaction instanceof Message ?\n CommandExecutionMode.Message :\n interaction.isChatInputCommand() ?\n CommandExecutionMode.SlashCommand :\n interaction.isUserContextMenuCommand() ?\n CommandExecutionMode.UserContextMenu :\n interaction.isMessageContextMenuCommand() ?\n CommandExecutionMode.MessageContextMenu :\n interaction.isAutocomplete() ?\n CommandExecutionMode.Autocomplete :\n null as never,\n interaction: interaction instanceof Message ? <never> null : interaction,\n message: interaction instanceof Message ? interaction : <never> null,\n messageCommandParser\n });\n\n const exec = async () => {\n if (middlewares.length > 0) {\n for (const middleware of middlewares) {\n try {\n await middleware.data.beforeExecute(context);\n } catch (e) {\n if (isErrorType(e, CommandKitErrorCodes.ExitMiddleware)) {\n break;\n } else if (\n isErrorType(e, [\n CommandKitErrorCodes.DMOnlyException,\n CommandKitErrorCodes.GuildOnlyException,\n CommandKitErrorCodes.ForwardedCommand]\n ))\n {\n // do nothing\n return;\n }\n throw e;\n }\n }\n }\n\n let postStageRunner = true;\n\n try {\n const commandContext = context.clone({\n environment\n });\n\n if (interaction instanceof Message) {\n environment.variables.set('execHandlerKind', 'message');\n await command.data.message?.(commandContext);\n } else {\n switch (true) {\n case interaction.isChatInputCommand():\n {\n environment.variables.set('execHandlerKind', 'chatInput');\n await command.data.chatInput?.(commandContext);\n }\n break;\n case interaction.isUserContextMenuCommand():\n {\n environment.variables.set('execHandlerKind', 'userContextMenu');\n await command.data.userContextMenu?.(commandContext);\n }\n break;\n case interaction.isMessageContextMenuCommand():\n {\n environment.variables.set(\n 'execHandlerKind',\n 'messageContextMenu'\n );\n await command.data.messageContextMenu?.(commandContext);\n }\n break;\n case interaction.isAutocomplete():\n {\n environment.variables.set('execHandlerKind', 'autocomplete');\n await command.data.autocomplete?.(commandContext);\n }\n break;\n default:\n break;\n }\n }\n } catch (e) {\n console.log(e);\n if (isErrorType(e, CommandKitErrorCodes.ExitMiddleware)) {\n postStageRunner = false;\n } else if (\n isErrorType(e, [\n CommandKitErrorCodes.DMOnlyException,\n CommandKitErrorCodes.GuildOnlyException,\n CommandKitErrorCodes.ForwardedCommand]\n ))\n {\n // do nothing\n return;\n } else {\n throw e;\n }\n }\n\n if (postStageRunner && middlewares.length > 0) {\n for (const middleware of middlewares) {\n try {\n await middleware.data.afterExecute(context);\n } catch (e) {\n if (isErrorType(e, CommandKitErrorCodes.ExitMiddleware)) {\n break;\n } else if (\n isErrorType(e, [\n CommandKitErrorCodes.DMOnlyException,\n CommandKitErrorCodes.GuildOnlyException,\n CommandKitErrorCodes.ForwardedCommand]\n ))\n {\n // do nothing\n return;\n }\n throw e;\n }\n }\n }\n };\n\n const shouldDebug = this.#data.commandkitInstance.isDebuggingCommands();\n\n if (!shouldDebug) {\n return exec();\n }\n\n afterCommand((env) => {\n const error = env.getExecutionError();\n const marker = env.getMarker();\n const time = `${env.getExecutionTime().toFixed(2)}ms`;\n\n if (error) {\n console.error(\n colors.red(\n `[${marker} - ${time}] Error executing command: ${error.stack || error}`\n )\n );\n return;\n }\n\n console.log(\n colors.cyan('(app ✨)') +\n colors.reset(' ') +\n colors.green(`[${marker} - ${time}] Command executed successfully`)\n );\n });\n\n try {\n environment.markStart(`${command.data.command.name}`);\n const res = await exec();\n\n return res;\n } finally {\n environment.markEnd();\n }\n }\n\n async #interactionHandler(interaction: Interaction<CacheType>) {\n // check if external handler can handle the interaction\n try {\n const result = await this.#requestExternalHandler(interaction);\n\n if (result !== false) return;\n } catch (e) {\n console.error(e);\n }\n\n if (\n !interaction.isChatInputCommand() &&\n !interaction.isContextMenuCommand() &&\n !interaction.isAutocomplete())\n\n return;\n\n const isAutocomplete = interaction.isAutocomplete();\n\n const targetCommand = this.#data.commands.find(\n (cmd) => cmd.data.name === interaction.commandName\n );\n\n if (!targetCommand) return;\n\n const env = useEnvironment();\n\n env.variables.set('commandHandlerType', 'legacy');\n env.variables.set('interaction', interaction);\n\n const { data, options, run, autocomplete, ...rest } = targetCommand;\n\n // Skip if autocomplete handler is not defined\n if (isAutocomplete && !autocomplete) return;\n\n const executor = async () => {\n const commandObj = {\n data: targetCommand.data,\n options: targetCommand.options,\n ...rest\n };\n\n if (this.#data.validationHandler) {\n let canRun = true;\n\n for (const validationFunction of this.#data.validationHandler.\n validations) {\n const stopValidationLoop = await validationFunction({\n interaction,\n commandObj,\n client: this.#data.client,\n handler: this.#data.commandkitInstance\n });\n\n if (stopValidationLoop) {\n canRun = false;\n break;\n }\n }\n\n if (!canRun) return;\n }\n\n let canRun = true;\n\n // If custom validations pass and !skipBuiltInValidations, run built-in CommandKit validation functions\n if (!this.#data.skipBuiltInValidations) {\n for (const validation of this.#data.builtInValidations) {\n const stopValidationLoop = validation({\n targetCommand,\n interaction,\n handlerData: this.#data\n });\n\n if (stopValidationLoop) {\n canRun = false;\n break;\n }\n }\n }\n\n if (!canRun) return;\n\n const command = targetCommand[isAutocomplete ? 'autocomplete' : 'run']!;\n\n const context = {\n interaction,\n client: this.#data.client,\n handler: this.#data.commandkitInstance\n };\n\n const shouldDebug = this.#data.commandkitInstance.isDebuggingCommands();\n\n if (!shouldDebug) {\n return command(context);\n }\n\n afterCommand((env) => {\n const error = env.getExecutionError();\n const marker = env.getMarker();\n const time = `${env.getExecutionTime().toFixed(2)}ms`;\n\n if (error) {\n console.error(\n colors.red(\n `[${marker} - ${time}] Error executing command: ${error.stack || error}`\n )\n );\n return;\n }\n\n console.log(\n colors.green(`[${marker} - ${time}] Command executed successfully`)\n );\n });\n\n try {\n env.markStart(interaction.commandName);\n const res = await command(context);\n\n return res;\n } finally {\n env.markEnd();\n }\n };\n\n return executor();\n }\n\n handleCommands() {\n this.#data.client.on(Events.InteractionCreate, (interaction) => {\n const env = new CommandKitEnvironment(this.#data.commandkitInstance);\n env.setType(CommandKitEnvironmentType.CommandHandler);\n\n return makeContextAwareFunction(\n env,\n this.#interactionHandler.bind(this),\n this.#commandFinalizer.bind(this)\n )(interaction);\n });\n\n this.#data.client.on(Events.MessageCreate, (message) => {\n const env = new CommandKitEnvironment(this.#data.commandkitInstance);\n env.setType(CommandKitEnvironmentType.CommandHandler);\n\n return makeContextAwareFunction(\n env,\n this.#requestExternalHandler.bind(this),\n this.#commandFinalizer.bind(this)\n )(message);\n });\n }\n\n get commands() {\n return this.#data.commands;\n }\n\n async reloadCommands(type?: ReloadOptions) {\n if (!this.#data.commandsPath) {\n throw new Error(\n colors.red(\n 'Cannot reload commands as \"commandsPath\" was not provided when instantiating CommandKit.'\n )\n );\n }\n\n this.#data.commands = [];\n\n // Re-build commands tree\n await this.#buildCommands();\n\n if (this.#data.bulkRegister) {\n await loadCommandsWithRest({\n client: this.#data.client,\n devGuildIds: this.#data.devGuildIds,\n commands: this.#data.commands,\n reloading: true,\n type\n });\n } else {\n await registerCommands({\n client: this.#data.client,\n devGuildIds: this.#data.devGuildIds,\n commands: this.#data.commands,\n reloading: true,\n type\n });\n }\n }\n}","import rfdc from 'rfdc';\n\nexport const clone = rfdc();","const resetColor = '\\x1b[0m';\n\nexport default {\n reset: (text: string) => `${text}${resetColor}`,\n bright: (text: string) => `\\x1b[1m${text}${resetColor}`,\n dim: (text: string) => `\\x1b[2m${text}${resetColor}`,\n underscore: (text: string) => `\\x1b[4m${text}${resetColor}`,\n blink: (text: string) => `\\x1b[5m${text}${resetColor}`,\n reverse: (text: string) => `\\x1b[7m${text}${resetColor}`,\n hidden: (text: string) => `\\x1b[8m${text}${resetColor}`,\n\n black: (text: string) => `\\x1b[30m${text}${resetColor}`,\n red: (text: string) => `\\x1b[31m${text}${resetColor}`,\n green: (text: string) => `\\x1b[32m${text}${resetColor}`,\n yellow: (text: string) => `\\x1b[33m${text}${resetColor}`,\n blue: (text: string) => `\\x1b[34m${text}${resetColor}`,\n magenta: (text: string) => `\\x1b[35m${text}${resetColor}`,\n cyan: (text: string) => `\\x1b[36m${text}${resetColor}`,\n white: (text: string) => `\\x1b[37m${text}${resetColor}`,\n\n bgBlack: (text: string) => `\\x1b[40m${text}${resetColor}`,\n bgRed: (text: string) => `\\x1b[41m${text}${resetColor}`,\n bgGreen: (text: string) => `\\x1b[42m${text}${resetColor}`,\n bgYellow: (text: string) => `\\x1b[43m${text}${resetColor}`,\n bgBlue: (text: string) => `\\x1b[44m${text}${resetColor}`,\n bgMagenta: (text: string) => `\\x1b[45m${text}${resetColor}`,\n bgCyan: (text: string) => `\\x1b[46m${text}${resetColor}`,\n bgWhite: (text: string) => `\\x1b[47m${text}${resetColor}`\n};","import path from 'path';\nimport fs from 'fs/promises';\n\nexport async function getFilePaths(\ndirectory: string,\nnesting?: boolean)\n: Promise<string[]> {\n let filePaths: string[] = [];\n\n if (!directory) return filePaths;\n\n const files = await fs.readdir(directory, { withFileTypes: true });\n\n for (const file of files) {\n const filePath = path.join(directory, file.name);\n\n if (file.isFile()) {\n filePaths.push(filePath);\n }\n\n if (nesting && file.isDirectory()) {\n filePaths = [...filePaths, ...(await getFilePaths(filePath, true))];\n }\n }\n\n return filePaths;\n}\n\nexport async function getFolderPaths(\ndirectory: string,\nnesting?: boolean)\n: Promise<string[]> {\n let folderPaths: string[] = [];\n\n if (!directory) return folderPaths;\n\n const folders = await fs.readdir(directory, { withFileTypes: true });\n\n for (const folder of folders) {\n const folderPath = path.join(directory, folder.name);\n\n if (folder.isDirectory()) {\n folderPaths.push(folderPath);\n\n if (nesting) {\n folderPaths = [\n ...folderPaths,\n ...(await getFolderPaths(folderPath, true))];\n\n }\n }\n }\n\n return folderPaths;\n}","import path from 'path';\n\n/**\n * Convert a local file path to a file URL.\n * @param filePath - The local file's path.\n * @returns - The converted file URL.\n */\nexport function toFileURL(filePath: string) {\n const resolvedPath = path.resolve(filePath);\n return 'file://' + resolvedPath.replace(/\\\\\\\\|\\\\/g, '/');\n}","import type { ApplicationCommandDataResolvable, Client } from 'discord.js';\nimport type { CommandFileObject, ReloadOptions } from '../../../../types';\n\nimport colors from '../../../../utils/colors';\n\ntype LoadCommandsWithRestProps = {\n /**\n * The main client.\n */\n client: Client;\n\n /**\n * An array of command objects.\n */\n commands: CommandFileObject[];\n\n /**\n * An array of developer guild IDs.\n */\n devGuildIds: string[];\n\n /**\n * A boolean indicating whether these commands are reloading.\n */\n reloading?: boolean;\n\n /**\n * A type for reloading the commands (if this is reloading).\n */\n type?: ReloadOptions;\n};\n\n/**\n * Use REST to load commands.\n * @param props - Options for loading commands.\n */\nexport default async function loadCommandsWithRest(\nprops: LoadCommandsWithRestProps)\n{\n if (props.reloading) {\n if (props.client.isReady()) {\n await handleLoading(\n props.client,\n props.commands,\n props.devGuildIds,\n props.reloading,\n props.type\n );\n } else {\n throw new Error(\n colors.red(`Cannot reload commands when client is not ready.`)\n );\n }\n } else {\n props.client.once('ready', async (c) => {\n await handleLoading(\n c,\n props.commands,\n props.devGuildIds,\n props.reloading,\n props.type\n );\n });\n }\n}\n\n/**\n * Handles loading commands.\n * @param client - The discord.js client instance.\n * @param commands - An array of command file objects.\n * @param devGuildIds - An array of developer guild IDs.\n * @param reloading - A boolean indicating whether this is reloading.\n * @param type - A type for reloading the commands (if this is reloading).\n */\nasync function handleLoading(\nclient: Client<true>,\ncommands: CommandFileObject[],\ndevGuildIds: string[],\nreloading?: boolean,\ntype?: ReloadOptions)\n{\n commands = commands.filter((cmd) => !cmd.options?.deleted);\n const devOnlyCommands = commands.filter((cmd) => cmd.options?.devOnly);\n const globalCommands = commands.filter((cmd) => !cmd.options?.devOnly);\n\n if (type === 'dev') {\n await loadDevCommands(client, devOnlyCommands, devGuildIds, reloading);\n } else if (type === 'global') {\n await loadGlobalCommands(client, globalCommands, reloading);\n } else {\n await loadDevCommands(client, devOnlyCommands, devGuildIds, reloading);\n await loadGlobalCommands(client, globalCommands, reloading);\n }\n}\n\n/**\n * Load commands globally.\n * @param client - The discord.js client instance.\n * @param commands - An array of command file objects.\n * @param reloading - A boolean indicating whether the commands are reloading.\n */\nasync function loadGlobalCommands(\nclient: Client<true>,\ncommands: CommandFileObject[],\nreloading?: boolean)\n{\n const requestBody = commands.map((cmd) => cmd.data);\n\n await client.application.commands.\n set(requestBody as ApplicationCommandDataResolvable[]).\n catch((error) => {\n throw new Error(\n colors.red(\n `Error ${\n reloading ? 'reloading' : 'loading'} global application commands.\\n`\n\n ),\n error\n );\n });\n\n console.log(\n colors.green(\n `${reloading ? 'Reloaded' : 'Loaded'} ${\n requestBody.length} global commands.`\n\n )\n );\n}\n\n/**\n * Load commands for dev guilds.\n * @param client - The discord.js client instance.\n * @param commands - An array of command file objects.\n * @param guildIds - An array of developer guild IDs.\n * @param reloading - A boolean indicating whether the commands are reloading.\n */\nasync function loadDevCommands(\nclient: Client<true>,\ncommands: CommandFileObject[],\nguildIds: string[],\nreloading?: boolean)\n{\n const requestBody = commands.map((cmd) => cmd.data);\n\n for (const guildId of guildIds) {\n const targetGuild =\n client.guilds.cache.get(guildId) || (await client.guilds.fetch(guildId));\n\n if (!targetGuild) {\n process.emitWarning(\n `Cannot ${\n reloading ? 'reload' : 'load'} commands in guild \"${\n guildId}\" - guild doesn't exist or client isn't part of the guild.`\n );\n\n continue;\n }\n\n await targetGuild.commands.\n set(requestBody as ApplicationCommandDataResolvable[]).\n catch((error) => {\n throw new Error(\n colors.red(\n `Error ${\n reloading ? 'reloading' : 'loading'} developer application commands in guild \"${\n\n targetGuild?.name || guildId}\".\\n`\n\n ),\n error\n );\n });\n\n console.log(\n colors.green(\n `${reloading ? 'Reloaded' : 'Loaded'} ${\n requestBody.length} developer commands in guild \"${\n targetGuild.name}\".`\n )\n );\n }\n}","import type {\n Guild,\n Client,\n ApplicationCommandData,\n GuildApplicationCommandManager,\n ApplicationCommandDataResolvable } from\n'discord.js';\nimport type { CommandFileObject, ReloadOptions } from '../../../../types';\n\nimport areSlashCommandsDifferent from '../utils/areSlashCommandsDifferent';\n\nimport colors from '../../../../utils/colors';\n\ntype RegisterCommandProps = {\n client: Client;\n commands: CommandFileObject[];\n devGuildIds: string[];\n reloading?: boolean;\n type?: ReloadOptions;\n};\n\n/**\n * Register client commands to Discord.\n * @param props\n */\nexport default async function registerCommands(props: RegisterCommandProps) {\n if (props.reloading) {\n if (props.client.isReady()) {\n await handleRegistration(\n props.client,\n props.commands,\n props.devGuildIds,\n props.type\n );\n } else {\n throw new Error(\n colors.red(`Cannot reload commands when client is not ready.`)\n );\n }\n } else {\n props.client.once('ready', async (c) => {\n await handleRegistration(\n c,\n props.commands,\n props.devGuildIds,\n props.type\n );\n });\n }\n}\n\nasync function handleRegistration(\nclient: Client<true>,\ncommands: CommandFileObject[],\ndevGuildIds: string[],\ntype?: ReloadOptions)\n{\n const devOnlyCommands = commands.filter((cmd) => cmd.options?.devOnly);\n const globalCommands = commands.filter((cmd) => !cmd.options?.devOnly);\n\n if (type === 'dev') {\n await registerDevCommands(client, devOnlyCommands, devGuildIds);\n } else if (type === 'global') {\n await registerGlobalCommands(client, globalCommands);\n } else {\n await registerDevCommands(client, devOnlyCommands, devGuildIds);\n await registerGlobalCommands(client, globalCommands);\n }\n}\n\nasync function registerGlobalCommands(\nclient: Client<true>,\ncommands: CommandFileObject[])\n{\n const appCommandsManager = client.application.commands;\n await appCommandsManager.fetch();\n\n for (const command of commands) {\n const targetCommand = appCommandsManager.cache.find(\n (cmd) => cmd.name === command.data.name\n );\n\n // <!-- Delete global command -->\n if (command.options?.deleted) {\n if (!targetCommand) {\n process.emitWarning(\n colors.yellow(\n `Ignoring: Command \"${command.data.name}\" is globally marked as deleted.`\n )\n );\n } else {\n await targetCommand.delete().catch((error) => {\n throw new Error(\n colors.red(\n `Failed to delete command \"${command.data.name}\" globally.\\n`\n ),\n error\n );\n });\n\n console.log(\n colors.green(`Deleted command \"${command.data.name}\" globally.`)\n );\n }\n\n continue;\n }\n\n // <!-- Edit global command -->\n if (targetCommand) {\n const commandsAreDifferent = areSlashCommandsDifferent(\n targetCommand,\n command.data\n );\n\n if (commandsAreDifferent) {\n await targetCommand.\n edit(command.data as Partial<ApplicationCommandData>).\n catch((error) => {\n throw new Error(\n colors.red(\n `Failed to edit command \"${command.data.name}\" globally.\\n`\n ),\n error\n );\n });\n\n console.log(\n colors.green(`Edited command \"${command.data.name}\" globally.`)\n );\n\n continue;\n }\n }\n\n // <!-- Register global command -->\n if (targetCommand) continue;\n\n await appCommandsManager.\n create(command.data as ApplicationCommandDataResolvable).\n catch((error) => {\n throw new Error(\n colors.red(\n `Failed to register command \"${command.data.name}\" globally.\\n`\n ),\n error\n );\n });\n\n console.log(\n colors.green(`Registered command \"${command.data.name}\" globally.`)\n );\n }\n}\n\nasync function registerDevCommands(\nclient: Client<true>,\ncommands: CommandFileObject[],\nguildIds: string[])\n{\n const devGuilds: Guild[] = [];\n\n for (const guildId of guildIds) {\n const guild =\n client.guilds.cache.get(guildId) || (await client.guilds.fetch(guildId));\n\n if (!guild) {\n process.emitWarning(\n colors.yellow(\n `Ignoring: Guild ${guildId} doesn't exist or client isn't part of the guild.`\n )\n );\n continue;\n }\n\n devGuilds.push(guild);\n }\n\n const guildCommandsManagers: GuildApplicationCommandManager[] = [];\n\n for (const guild of devGuilds) {\n const guildCommandsManager = guild.commands;\n await guildCommandsManager.fetch();\n\n guildCommandsManagers.push(guildCommandsManager);\n }\n\n for (const command of commands) {\n for (const guildCommands of guildCommandsManagers) {\n const targetCommand = guildCommands.cache.find(\n (cmd) => cmd.name === command.data.name\n );\n\n // <!-- Delete dev command -->\n if (command.options?.deleted) {\n if (!targetCommand) {\n process.emitWarning(\n colors.yellow(\n `Ignoring: Command \"${command.data.name}\" is marked as deleted in ${guildCommands.guild.name}.`\n )\n );\n } else {\n await targetCommand.delete().catch((error) => {\n throw new Error(\n colors.red(\n `Failed to delete command \"${command.data.name}\" in ${guildCommands.guild.name}.`\n ),\n error\n );\n });\n\n console.log(\n colors.green(\n `Deleted command \"${command.data.name}\" in ${guildCommands.guild.name}.`\n )\n );\n }\n\n continue;\n }\n\n // <!-- Edit dev command -->\n if (targetCommand) {\n const commandsAreDifferent = areSlashCommandsDifferent(\n targetCommand,\n command.data\n );\n\n if (commandsAreDifferent) {\n await targetCommand.\n edit(command.data as Partial<ApplicationCommandData>).\n catch((error) => {\n throw new Error(\n colors.red(\n `Failed to edit command \"${command.data.name}\" in ${guildCommands.guild.name}.\\n`\n ),\n error\n );\n });\n\n console.log(\n colors.green(\n `Edited command \"${command.data.name}\" in ${guildCommands.guild.name}.`\n )\n );\n\n continue;\n }\n }\n\n // <!-- Register guild command -->\n if (targetCommand) continue;\n\n await guildCommands.\n create(command.data as ApplicationCommandDataResolvable).\n catch((error) => {\n throw new Error(\n colors.red(\n `Failed to register command \"${command.data.name}\" in ${guildCommands.guild.name}.\\n`\n ),\n error\n );\n });\n\n console.log(\n colors.green(\n `Registered command \"${command.data.name}\" in ${guildCommands.guild.name}.`\n )\n );\n }\n }\n}","function compareLocalizations(\nfirst: Record<string, string> | undefined,\nsecond: Record<string, string> | undefined)\n: boolean {\n if (!first && !second) return true;\n if (!first || !second) return false;\n\n const keys1 = Object.keys(first);\n const keys2 = Object.keys(second);\n if (keys1.length !== keys2.length) return false;\n\n return keys1.every((key) => first[key] === second[key]);\n}\n\nfunction compareArrays(\narr1: any[] | undefined,\narr2: any[] | undefined)\n: boolean {\n if (!arr1 && !arr2) return true;\n if (!arr1 || !arr2) return false;\n if (arr1.length !== arr2.length) return false;\n\n return arr1.every((item, index) => {\n const item2 = arr2[index];\n return Object.keys(item).every((key) => {\n if (Array.isArray(item[key])) {\n return compareArrays(item[key], item2[key]);\n }\n if (key.endsWith('_localizations')) {\n return compareLocalizations(item[key], item2[key]);\n }\n return item[key] === item2[key];\n });\n });\n}\n\nexport default function areSlashCommandsDifferent(\nappCommand: any,\nlocalCommand: any)\n{\n if (!appCommand.options) appCommand.options = [];\n if (!localCommand.options) localCommand.options = [];\n\n if (!appCommand.description) appCommand.description = '';\n if (!localCommand.description) localCommand.description = '';\n\n // Check basic properties\n if (\n localCommand.description !== appCommand.description ||\n localCommand.options?.length !== appCommand.options?.length ||\n !compareLocalizations(\n localCommand.name_localizations,\n appCommand.name_localizations\n ) ||\n !compareLocalizations(\n localCommand.description_localizations,\n appCommand.description_localizations\n ))\n {\n return true;\n }\n\n // Check options in detail\n return !compareArrays(localCommand.options, appCommand.options);\n}","import devOnly from './devOnly';\nimport permissions from './permissions';\n\nexport default [devOnly, permissions];","import type { BuiltInValidationParams } from '../typings';\nimport { MessageFlags } from 'discord.js';\n\nexport default function ({\n interaction,\n targetCommand,\n handlerData\n}: BuiltInValidationParams) {\n if (interaction.isAutocomplete()) return;\n\n if (targetCommand.options?.devOnly) {\n if (\n interaction.inGuild() &&\n !handlerData.devGuildIds.includes(interaction.guildId))\n {\n interaction.reply({\n content: '❌ This command can only be used inside development servers.',\n flags: MessageFlags.Ephemeral\n });\n\n return true;\n }\n\n const guildMember = interaction.guild?.members.cache.get(\n interaction.user.id\n );\n const memberRoles = guildMember?.roles.cache;\n\n let hasDevRole = false;\n\n memberRoles?.forEach((role) => {\n if (handlerData.devRoleIds.includes(role.id)) {\n hasDevRole = true;\n }\n });\n\n const isDevUser =\n handlerData.devUserIds.includes(interaction.user.id) || hasDevRole;\n\n if (!isDevUser) {\n interaction.reply({\n content: '❌ This command can only be used by developers.',\n flags: MessageFlags.Ephemeral\n });\n\n return true;\n }\n }\n}","import type { BuiltInValidationParams } from '../typings';\nimport { EmbedBuilder, MessageFlags } from 'discord.js';\n\nexport default function ({\n interaction,\n targetCommand\n}: BuiltInValidationParams) {\n if (interaction.isAutocomplete()) return;\n const userPermissions = interaction.memberPermissions;\n let userPermissionsRequired = targetCommand.options?.userPermissions;\n let missingUserPermissions: string[] = [];\n\n if (typeof userPermissionsRequired === 'string') {\n userPermissionsRequired = [userPermissionsRequired];\n }\n\n const botPermissions = interaction.guild?.members.me?.permissions;\n let botPermissionsRequired = targetCommand.options?.botPermissions;\n let missingBotPermissions: string[] = [];\n\n if (typeof botPermissionsRequired === 'string') {\n botPermissionsRequired = [botPermissionsRequired];\n }\n\n if (!userPermissionsRequired?.length && !botPermissionsRequired?.length) {\n return;\n }\n\n if (userPermissions && userPermissionsRequired) {\n for (const permission of userPermissionsRequired) {\n const hasPermission = userPermissions.has(permission);\n\n if (!hasPermission) {\n missingUserPermissions.push(permission);\n }\n }\n }\n\n if (botPermissions && botPermissionsRequired) {\n for (const permission of botPermissionsRequired) {\n const hasPermission = botPermissions.has(permission);\n\n if (!hasPermission) {\n missingBotPermissions.push(permission);\n }\n }\n }\n\n if (!missingUserPermissions.length && !missingBotPermissions.length) {\n return;\n }\n\n // Fix casing. e.g. KickMembers -> Kick Members\n const pattern = /([a-z])([A-Z])|([A-Z]+)([A-Z][a-z])/g;\n\n missingUserPermissions = missingUserPermissions.map((str) =>\n str.replace(pattern, '$1$3 $2$4')\n );\n missingBotPermissions = missingBotPermissions.map((str) =>\n str.replace(pattern, '$1$3 $2$4')\n );\n\n let embedDescription = '';\n\n const formatter = new Intl.ListFormat('en', {\n style: 'long',\n type: 'conjunction'\n });\n\n const getPermissionWord = (permissions: string[]) =>\n permissions.length === 1 ? 'permission' : 'permissions';\n\n if (missingUserPermissions.length) {\n const formattedPermissions = missingUserPermissions.map((p) => `\\`${p}\\``);\n const permissionsString = formatter.format(formattedPermissions);\n\n embedDescription += `- You must have the ${permissionsString} ${getPermissionWord(\n missingUserPermissions\n )} to be able to run this command.\\n`;\n }\n\n if (missingBotPermissions.length) {\n const formattedPermissions = missingBotPermissions.map((p) => `\\`${p}\\``);\n const permissionsString = formatter.format(formattedPermissions);\n\n embedDescription += `- I must have the ${permissionsString} ${getPermissionWord(\n missingBotPermissions\n )} to be able to execute this command.\\n`;\n }\n\n const embed = new EmbedBuilder().\n setTitle(`:x: Missing permissions!`).\n setDescription(embedDescription).\n setColor('Red');\n\n interaction.reply({ embeds: [embed], flags: MessageFlags.Ephemeral });\n return true;\n}","import { AsyncLocalStorage } from 'node:async_hooks';\nimport { CommandKitEnvironment } from './environment';\nimport { CommandKitErrorCodes, isCommandKitError } from '../utils/error-codes';\nimport { Interaction, MessageFlags } from 'discord.js';\nimport { CommandKit } from '../CommandKit';\n\nconst context = new AsyncLocalStorage<CommandKitEnvironment>();\n\nexport type GenericFunction<A extends any[] = any[]> = (...args: A) => any;\n\nexport function exitContext<T>(fn: () => T): T {\n return context.exit(fn);\n}\n\n/**\n * Returns a context-aware version of the given function.\n * @param env - The commandkit environment data.\n * @param fn - The target function.\n * @param finalizer - An optional finalizer function to run after the target function. This function will be context-aware.\n * @internal\n */\nexport function makeContextAwareFunction<\n R extends GenericFunction,\n F extends GenericFunction>(\nenv: CommandKitEnvironment, fn: R, finalizer?: F): R {\n const _fn = (...args: any[]) => {\n return context.run(env, async () => {\n try {\n // execute the target function\n const result = await fn(...args);\n\n return result;\n } catch (e) {\n // set the error in the environment data\n if (isCommandKitError(e)) {\n const code = Reflect.get(e, 'code');\n const interaction = env.variables.get('interaction') as Interaction;\n if (!interaction) return;\n\n switch (code) {\n case CommandKitErrorCodes.GuildOnlyException:{\n if (interaction.isRepliable()) {\n await interaction.reply({\n content: 'This command is only available in guilds.',\n flags: MessageFlags.Ephemeral\n });\n }\n return;\n }\n case CommandKitErrorCodes.DMOnlyException:{\n if (interaction.isRepliable()) {\n await interaction.reply({\n content: 'This command is only available in DMs.',\n flags: MessageFlags.Ephemeral\n });\n }\n return;\n }\n }\n\n return;\n }\n\n env.setExecutionError(e as Error);\n } finally {\n if (typeof finalizer === 'function') {\n // execute the finalizer function\n try {\n await finalizer(...args);\n } catch {\n\n // no-op\n }}\n }\n });\n };\n\n return _fn as R;\n}\n\n/**\n * Retrieves commandkit\n * @private\n * @internal\n */\nexport function getCommandKit(): CommandKit | undefined;\nexport function getCommandKit(strict: true): CommandKit;\nexport function getCommandKit(strict: false): CommandKit | undefined;\nexport function getCommandKit(strict = false): CommandKit | undefined {\n const kit = context.getStore()?.commandkit ?? CommandKit.instance;\n\n if (!kit && strict) {\n throw new Error('CommandKit instance not found.');\n }\n\n return kit;\n}\n\n/**\n * Get the current commandkit context.\n * @internal\n */\nexport function getContext(): CommandKitEnvironment | undefined {\n const ctx = context.getStore();\n return ctx;\n}\n\n/**\n * Use current commandkit context. Throws an error if no context is found.\n */\nexport function useEnvironment(): CommandKitEnvironment {\n const ctx = context.getStore();\n if (!ctx) {\n throw new Error(\n 'No commandkit environment found. Please make sure you are inside commandkit handler.'\n );\n }\n\n return ctx;\n}\n\n/**\n * Ensures the command is only available in guilds.\n * Note: do not wrap this function in a try/catch block.\n */\nexport function guildOnly() {\n const env = useEnvironment();\n const interaction: Interaction = env.variables.get('interaction');\n\n if (!interaction) {\n throw new Error('No interaction found in environment.');\n }\n\n if (!interaction.guild) {\n const error = new Error('This command is only available in guilds.');\n Reflect.set(error, 'code', CommandKitErrorCodes.GuildOnlyException);\n\n throw error;\n }\n}\n\n/**\n * Ensures the command is only available in DMs.\n * Note: do not wrap this function in a try/catch block.\n */\nexport function dmOnly() {\n const env = useEnvironment();\n const interaction: Interaction = env.variables.get('interaction');\n\n if (!interaction) {\n throw new Error('No interaction found in environment.');\n }\n\n if (interaction.guild) {\n const error = new Error('This command is only available in DMs.');\n Reflect.set(error, 'code', CommandKitErrorCodes.DMOnlyException);\n\n throw error;\n }\n}","export const CommandKitErrorCodes = {\n GuildOnlyException: Symbol('kGuildOnlyException'),\n DMOnlyException: Symbol('kDMOnlyException'),\n ExitMiddleware: Symbol('kExitMiddleware'),\n ForwardedCommand: Symbol('kForwardedCommand'),\n InvalidCommandPrefix: Symbol('kInvalidCommandPrefix')\n} as const;\n\nexport type CommandKitError = Error & {code: symbol;};\n\nexport function createCommandKitError(code: symbol): CommandKitError {\n const error = new Error() as CommandKitError;\n\n Reflect.set(error, 'code', code);\n\n return error;\n}\n\nexport function isCommandKitError(error: unknown): error is CommandKitError {\n if (!(error instanceof Error)) return false;\n const code = Reflect.get(error, 'code');\n\n for (const key in CommandKitErrorCodes) {\n if (CommandKitErrorCodes[key as keyof typeof CommandKitErrorCodes] === code)\n return true;\n }\n\n return false;\n}\n\nexport function isErrorType(error: unknown, code: symbol | symbol[]): boolean {\n if (!isCommandKitError(error)) return false;\n const errorCode = Reflect.get(error, 'code');\n\n if (!errorCode) return false;\n\n if (Array.isArray(code)) return code.includes(errorCode);\n\n return errorCode === code;\n}","import { randomUUID } from 'node:crypto';\nimport { CommandKit } from '../CommandKit';\nimport { GenericFunction, getContext } from './async-context';\n\nexport interface CommandKitEnvironmentInternalData {\n executionError: Error | null;\n type: CommandKitEnvironmentType | null;\n variables: Map<string, any>;\n deferredFunctions: Map<string, GenericFunction<[CommandKitEnvironment]>>;\n marker: string;\n markStart: number;\n markEnd: number;\n}\n\nexport class CommandKitEnvironment {\n #data: CommandKitEnvironmentInternalData = {\n executionError: null,\n type: null,\n variables: new Map(),\n deferredFunctions: new Map(),\n marker: '',\n markStart: 0,\n markEnd: 0\n };\n\n /**\n * Creates the commandkit execution environment.\n * @param commandkit - The commandkit instance.\n */\n public constructor(public readonly commandkit: CommandKit) {}\n\n /**\n * Get the execution error.\n * @internal\n */\n public getExecutionError(): Error | null {\n return this.#data.executionError;\n }\n\n /**\n * Set the execution error.\n * @param error - The error to set.\n * @internal\n */\n public setExecutionError(error: Error): void {\n if (this.#data.executionError) {\n throw new Error('Execution error already set.');\n }\n\n this.#data.executionError = error;\n }\n\n /**\n * Get the environment type.\n */\n public getType(): CommandKitEnvironmentType {\n const type = this.#data.type;\n\n if (!type) {\n throw new Error('Environment type not set.');\n }\n\n return type;\n }\n\n /**\n * Set the environment type.\n * @param type - The environment type to set.\n * @internal\n */\n public setType(type: CommandKitEnvironmentType): void {\n this.#data.type = type;\n }\n\n /**\n * The variables store for this environment.\n */\n public get variables(): Map<string, any> {\n return this.#data.variables;\n }\n\n /**\n * Register a deferred function.\n * @param fn - The deferred function to register.\n * @returns The deferred function id.\n * @internal\n */\n public registerDeferredFunction(\n fn: GenericFunction<[CommandKitEnvironment]>)\n : string {\n const id = randomUUID();\n this.#data.deferredFunctions.set(id, fn);\n return id;\n }\n\n /**\n * Clear a deferred function by id.\n * @param id - The deferred function id to clear.\n * @internal\n */\n public clearDeferredFunction(id: string): void {\n this.#data.deferredFunctions.delete(id);\n }\n\n /**\n * Run all deferred functions sequentially.\n * @internal\n */\n public async runDeferredFunctions(): Promise<void> {\n for (const [id, fn] of this.#data.deferredFunctions) {\n try {\n await fn(this);\n } catch (e) {\n this.commandkit.emit('unhandledDeferredFunctionRejection', e);\n } finally {\n this.clearDeferredFunction(id);\n }\n }\n }\n\n /**\n * Clear all deferred functions.\n * @internal\n */\n public clearAllDeferredFunctions(): void {\n this.#data.deferredFunctions.clear();\n }\n\n /**\n * Mark the start of a command execution.\n * @param marker - The marker to set.\n * @internal\n */\n public markStart(marker: string): void {\n this.#data.marker = marker;\n this.#data.markStart = performance.now();\n }\n\n /**\n * Mark the end of a command execution.\n * @internal\n */\n public markEnd(): void {\n if (!this.#data.markEnd) this.#data.markEnd = performance.now();\n }\n\n /**\n * Get the marker.\n * @internal\n */\n public getMarker(): string {\n return this.#data.marker;\n }\n\n /**\n * Get the execution time in milliseconds.\n * @internal\n */\n public getExecutionTime(): number {\n return Math.abs(this.#data.markEnd - this.#data.markStart);\n }\n}\n\nexport enum CommandKitEnvironmentType {\n CommandHandler = 'COMMAND_HANDLER',\n}\n\n/**\n * Runs the given function after the current command has finished executing.\n * @param fn The function to run after the current command.\n * @returns The deferred function id. This can be used to cancel the deferred function.\n */\nexport function afterCommand(\nfn: GenericFunction<[CommandKitEnvironment]>)\n: string {\n const env = getContext();\n\n if (!env) {\n throw new Error('after must be called inside commandkit handler.');\n }\n\n return env.registerDeferredFunction(fn);\n}\n\n/**\n * Cancels a deferred function registered with `afterCommand`.\n * @param id The deferred function id to cancel.\n */\nexport function cancelAfterCommand(id: string): void {\n const env = getContext();\n\n if (!env) {\n throw new Error('cancelAfter must be called inside commandkit handler.');\n }\n\n env.clearDeferredFunction(id);\n}","import {\n AutocompleteInteraction,\n ChatInputCommandInteraction,\n ContextMenuCommandInteraction,\n MessageContextMenuCommandInteraction,\n Message,\n Locale,\n User,\n Channel,\n Role,\n Attachment,\n GuildMember,\n Interaction,\n UserContextMenuCommandInteraction } from\n'discord.js';\nimport { CommandKit } from '../../CommandKit';\nimport { Localization } from '../i18n/Localization';\nimport {\n MessageCommandOptions,\n MessageCommandParser } from\n'./MessageCommandParser';\nimport {\n CommandKitErrorCodes,\n createCommandKitError } from\n'../../utils/error-codes';\nimport { CommandKitEnvironment } from '../../context/environment';\nimport { getContext } from '../../context/async-context';\n\nexport const CommandExecutionMode = {\n SlashCommand: 'chatInput',\n MessageContextMenu: 'messageContextMenu',\n UserContextMenu: 'userContextMenu',\n Autocomplete: 'autocomplete',\n Message: 'message'\n} as const;\n\nexport type CommandExecutionMode =\n(typeof CommandExecutionMode)[keyof typeof CommandExecutionMode];\n\nexport interface ContextParameters<T extends CommandExecutionMode> {\n environment?: CommandKitEnvironment;\n executionMode: T;\n // interaction: T extends 'interaction'\n // ?\n // | ChatInputCommandInteraction\n // | ContextMenuCommandInteraction\n // | MessageContextMenuCommandInteraction\n // : never;\n interaction: T extends 'chatInput' ?\n ChatInputCommandInteraction :\n T extends 'messageContextMenu' ?\n MessageContextMenuCommandInteraction :\n T extends 'userContextMenu' ?\n UserContextMenuCommandInteraction :\n T extends 'autocomplete' ?\n AutocompleteInteraction :\n never;\n message: T extends 'message' ? Message : never;\n forwarded?: boolean;\n messageCommandParser?: T extends 'message' ? MessageCommandParser : never;\n}\n\nexport type MessageCommandContext = Context<'message'>;\nexport type InteractionCommandContext = Context<\n 'autocomplete' | 'chatInput' | 'messageContextMenu' | 'userContextMenu'>;\n\nexport type MessageCommandMiddlewareContext = MiddlewareContext<'message'>;\nexport type InteractionCommandMiddlewareContext = MiddlewareContext<\n 'autocomplete' | 'chatInput' | 'messageContextMenu' | 'userContextMenu'>;\n\nexport type SlashCommandContext = Context<'chatInput'>;\nexport type SlashCommandMiddlewareContext = MiddlewareContext<'chatInput'>;\nexport type AutocompleteCommandContext = Context<'autocomplete'>;\nexport type AutocompleteCommandMiddlewareContext =\nMiddlewareContext<'autocomplete'>;\nexport type MessageContextMenuCommandContext = Context<'messageContextMenu'>;\nexport type MessageContextMenuCommandMiddlewareContext =\nMiddlewareContext<'messageContextMenu'>;\nexport type UserContextMenuCommandContext = Context<'userContextMenu'>;\nexport type UserContextMenuCommandMiddlewareContext =\nMiddlewareContext<'userContextMenu'>;\n\nexport type CommandContextOptions<T extends CommandExecutionMode> =\nT extends 'message' ?\nMessageCommandOptions :\nT extends 'chatInput' ?\nChatInputCommandInteraction['options'] :\nT extends 'autocomplete' ?\nAutocompleteInteraction['options'] :\nT extends 'messageContextMenu' ?\nMessageContextMenuCommandInteraction['options'] :\nT extends 'userContextMenu' ?\nUserContextMenuCommandInteraction['options'] :\nnever;\n\nexport class Context<\n ExecutionMode extends CommandExecutionMode = CommandExecutionMode>\n{\n /**\n * The interaction that triggered the command.\n */\n public readonly interaction: ContextParameters<ExecutionMode>['interaction'];\n /**\n * The message that triggered the command.\n */\n public readonly message: ContextParameters<ExecutionMode>['message'];\n\n private _locale: Locale | null = null;\n\n /**\n * Creates a new command context.\n * @param commandkit The command kit instance.\n * @param config The context parameters.\n */\n public constructor(\n public readonly commandkit: CommandKit,\n private readonly config: ContextParameters<ExecutionMode>)\n {\n // these are assigned to readonly properties to make them accessible via object destructuring\n this.interaction = config.interaction;\n this.message = config.message;\n }\n\n public get commandName(): string {\n if (this.isInteraction()) {\n return this.interaction.commandName;\n } else {\n return this.config.messageCommandParser!.getCommand();\n }\n }\n\n public get options(): CommandContextOptions<ExecutionMode> {\n if (this.isMessage()) {\n const parser = this.config.messageCommandParser!;\n // @ts-expect-error\n return parser.options;\n } else {\n const interaction = (<InteractionCommandContext> this).interaction;\n // @ts-expect-error\n return interaction.options;\n }\n }\n\n /**\n * Whether this context was forwarded from another context. This happens when a command forwards its context to another command.\n */\n public get forwarded(): boolean {\n return this.config.forwarded ?? false;\n }\n\n /**\n * Forwards the context to another command. The target handler will be the same as current handler.\n * @param command The command to forward to.\n */\n public async forwardCommand(command: string): Promise<never> {\n const target = await this.commandkit.appCommandsHandler.prepareCommandRun(\n (this.isInteraction() ? this.interaction : this.message) as Interaction\n );\n\n if (!target) {\n throw new Error(\n `Command ${command} not found! If you are trying to forward to a legacy command, ctx.forwardCommand is not compatible with legacy commands.`\n );\n }\n\n const env = this.config.environment ?? getContext();\n\n if (!env) {\n throw new Error('No commandkit environment found.');\n }\n\n const handlers = {\n chatInput: target.command.data.chatInput,\n autocomplete: target.command.data.autocomplete,\n message: target.command.data.message,\n messageContextMenu: target.command.data.messageContextMenu,\n userContextMenu: target.command.data.userContextMenu\n };\n\n const handlerKind = env.variables.get(\n 'execHandlerKind'\n ) as keyof typeof handlers;\n\n if (!handlerKind) {\n throw new Error('No execution handler kind found.');\n }\n\n const handler = handlers[handlerKind];\n\n if (!handler) {\n throw new Error(`No handler found for ${handlerKind}`);\n }\n\n await handler(this.clone({ forwarded: true }));\n\n throw createCommandKitError(CommandKitErrorCodes.ForwardedCommand);\n }\n\n /**\n * The execution mode of the command.\n */\n public get executionMode(): ExecutionMode {\n return this.config.executionMode;\n }\n\n /**\n * Whether the command was triggered by an interaction.\n */\n public isInteraction(): this is InteractionCommandContext {\n return (\n this.executionMode === CommandExecutionMode.SlashCommand ||\n this.executionMode === CommandExecutionMode.Autocomplete ||\n this.executionMode === CommandExecutionMode.MessageContextMenu ||\n this.executionMode === CommandExecutionMode.UserContextMenu);\n\n }\n\n /**\n * Whether the command was triggered by a slash command interaction.\n */\n public isSlashCommand(): this is SlashCommandContext {\n return this.executionMode === CommandExecutionMode.SlashCommand;\n }\n\n /**\n * Whether the command was triggered by an autocomplete interaction.\n */\n public isAutocomplete(): this is AutocompleteCommandContext {\n return this.executionMode === CommandExecutionMode.Autocomplete;\n }\n\n /**\n * Whether the command was triggered by a message context menu interaction.\n */\n public isMessageContextMenu(): this is MessageContextMenuCommandContext {\n return this.executionMode === CommandExecutionMode.MessageContextMenu;\n }\n\n /**\n * Whether the command was triggered by a user context menu interaction.\n */\n public isUserContextMenu(): this is UserContextMenuCommandContext {\n return this.executionMode === CommandExecutionMode.UserContextMenu;\n }\n\n /**\n * Whether the command was triggered by a message.\n */\n public isMessage(): this is Context<'message'> {\n return this.executionMode === CommandExecutionMode.Message;\n }\n\n /**\n * Returns the command identifier.\n */\n public getCommandIdentifier(): string {\n if (this.isInteraction()) {\n return this.interaction.commandName;\n } else {\n return this.message.content.split(' ')[0].slice(1);\n }\n }\n\n /**\n * Returns the locale of the guild where this command was triggered.\n */\n public getGuildLocale(): Locale | null {\n if (this.isInteraction()) {\n return this.interaction.guildLocale;\n } else {\n return this.message.guild?.preferredLocale ?? null;\n }\n }\n\n /**\n * Returns the locale of the user who triggered this command.\n */\n public getUserLocale(): Locale | null {\n if (this.isInteraction()) {\n return this.interaction.locale;\n } else {\n return null;\n }\n }\n\n /**\n * Returns the locale for this command.\n * @param preferUser Whether to prefer the user's locale over the guild's locale.\n * @returns The locale for this command. If no locale is found, the default locale is returned.\n */\n public getLocale(preferUser = false): Locale {\n if (this._locale) return this._locale;\n\n const locale = preferUser ? this.getUserLocale() : this.getGuildLocale();\n\n if (!locale) {\n return this.commandkit.config.defaultLocale;\n }\n\n return locale;\n }\n\n /**\n * Sets the locale for this command.\n * @param locale The locale to set.\n */\n public setLocale(locale: Locale | null): void {\n this._locale = locale;\n }\n\n /**\n * Returns the i18n api for this command.\n * @param locale The locale to use for the i18n api.\n */\n public locale(locale?: Locale) {\n const selectedLocale = locale ?? this.getLocale();\n\n return new Localization(this.commandkit, {\n locale: selectedLocale,\n target: this.getCommandIdentifier()\n });\n }\n\n /**\n * Creates a clone of this context\n */\n public clone(\n config?: Partial<ContextParameters<ExecutionMode>>)\n : Context<ExecutionMode> {\n if (!config) return new Context(this.commandkit, this.config);\n\n return new Context(this.commandkit, { ...this.config, ...config });\n }\n\n public isMiddleware(): this is MiddlewareContext<ExecutionMode> {\n return this instanceof MiddlewareContext;\n }\n}\n\nexport class MiddlewareContext<\n T extends CommandExecutionMode> extends\nContext<T> {\n #cancel = false;\n\n /**\n * Whether the command execution was cancelled.\n */\n public get cancelled(): boolean {\n return this.#cancel;\n }\n\n /**\n * Cancels the command execution.\n */\n public cancel(): void {\n this.#cancel = true;\n }\n}","import { Locale } from 'discord.js';\nimport { CommandKit } from '../../CommandKit';\nimport {\n LocalizationTranslationRequest,\n TranslationResult } from\n'./LocalizationStrategy';\nimport { TranslatableArguments } from './Translation';\n\nexport interface LocalizationConfig {\n /**\n * The locale to use for localization.\n */\n locale: Locale;\n /**\n * The internalization data target.\n */\n target: string;\n}\n\nexport type Translator = (\ntranslatable: string,\nargs?: TranslatableArguments | undefined)\n=> Promise<TranslationResult>;\n\nexport class Localization {\n /**\n * Translates the given translatable object.\n * @param translatable The translatable object to translate.\n */\n public readonly t: Translator;\n\n /**\n * Creates a new localization instance.\n * @param commandkit The command kit instance.\n * @param config The localization configuration.\n */\n public constructor(\n private readonly commandkit: CommandKit,\n private readonly config: LocalizationConfig)\n {\n const strategy = this.commandkit.config.localizationStrategy;\n const { locale, target } = this.config;\n\n // we are doing this so that it can be destructured\n // eg: const { t } = ctx.locale()\n this.t = (translatable, args) => {\n return strategy.translate({\n args,\n key: translatable,\n locale,\n scope: target\n });\n };\n }\n\n /**\n * Get the localization strategy.\n */\n public getStrategy() {\n return this.commandkit.config.localizationStrategy;\n }\n\n /**\n * Get the default locale\n */\n public getDefaultLocale() {\n return this.commandkit.config.defaultLocale;\n }\n\n /**\n * Get the current locale\n */\n public getLocale() {\n return this.config.locale;\n }\n\n /**\n * Get the localization target\n */\n public getTarget() {\n return this.config.target;\n }\n}","import type { EventHandlerOptions, EventHandlerData } from './typings';\nimport type { CommandHandler } from '../command-handler/CommandHandler';\nimport { getFilePaths, getFolderPaths } from '../../../utils/get-paths';\nimport { toFileURL } from '../../../utils/resolve-file-url';\nimport { clone } from '../../../utils/clone';\nimport colors from '../../../utils/colors';\nimport { ParsedEvent } from '../../../app/router';\n\n/**\n * A handler for client events.\n */\nexport class EventHandler {\n #data: EventHandlerData;\n #listening = new Set<string>();\n\n constructor({ ...options }: EventHandlerOptions) {\n this.#data = {\n ...options,\n events: []\n };\n }\n\n async init() {\n await this.#buildEvents();\n this.#registerEvents();\n }\n\n async #buildEvents() {\n const eventFolderPaths = await getFolderPaths(this.#data.eventsPath);\n\n for (const eventFolderPath of eventFolderPaths) {\n const eventName = eventFolderPath.\n replace(/\\\\\\\\|\\\\/g, '/').\n split('/').\n pop() as string;\n\n const allowedExtensions = /\\.(js|mjs|cjs|ts)$/i;\n const eventPaths = await getFilePaths(eventFolderPath, true);\n\n const eventFilePaths = eventPaths.filter((path) =>\n allowedExtensions.test(path)\n );\n\n // const eventObj = {\n // name: eventName,\n // functions: [] as Function[],\n // };\n\n // this.#data.events.push(eventObj);\n\n let eventObj = this.#data.events.find((e) => e.name === eventName);\n\n if (!eventObj) {\n eventObj = {\n name: eventName,\n functions: []\n };\n\n this.#data.events.push(eventObj);\n }\n\n for (const eventFilePath of eventFilePaths) {\n const modulePath = toFileURL(eventFilePath);\n\n let importedFunction = (await import(`${modulePath}?t=${Date.now()}`)).\n default;\n let eventFunction = clone(importedFunction);\n\n // If it's CommonJS, invalidate the import cache\n if (typeof module !== 'undefined' && typeof require !== 'undefined') {\n delete require.cache[require.resolve(eventFilePath)];\n }\n\n if (eventFunction?.default) {\n eventFunction = eventFunction.default;\n }\n\n const compactFilePath =\n eventFilePath.split(process.cwd())[1] || eventFilePath;\n\n if (typeof eventFunction !== 'function') {\n process.emitWarning(\n colors.yellow(\n `Ignoring: Event file ${compactFilePath} does not export a function.`\n )\n );\n continue;\n }\n\n eventObj.functions.push(eventFunction);\n }\n }\n }\n\n async registerExternal(entry: ParsedEvent) {\n const { event, listeners } = entry;\n\n const functions = await Promise.all(\n listeners.map(async (l) =>\n import(`${toFileURL(l)}?t=${Date.now()}`).then((m) => m.default)\n )\n );\n\n const existing = this.#data.events.find((e) => e.name === event);\n\n if (existing) {\n existing.functions.unshift(...functions);\n } else {\n this.#data.events.unshift({\n name: event,\n functions\n });\n }\n }\n\n resyncListeners() {\n const client = this.#data.client;\n const handler = this.#data.commandKitInstance;\n\n for (const eventObj of this.#data.events) {\n if (this.#listening.has(eventObj.name)) continue;\n\n client.on(eventObj.name, async (...params) => {\n for (const eventFunction of eventObj.functions) {\n const stopEventLoop = await eventFunction(...params, client, handler);\n\n if (stopEventLoop) {\n break;\n }\n }\n });\n\n this.#listening.add(eventObj.name);\n }\n }\n\n #registerEvents() {\n const client = this.#data.client;\n const handler = this.#data.commandKitInstance;\n\n for (const eventObj of this.#data.events) {\n client.on(eventObj.name, async (...params) => {\n for (const eventFunction of eventObj.functions) {\n const stopEventLoop = await eventFunction(...params, client, handler);\n\n if (stopEventLoop) {\n break;\n }\n }\n });\n\n this.#listening.add(eventObj.name);\n }\n }\n\n get events() {\n return this.#data.events;\n }\n\n async reloadEvents(commandHandler?: CommandHandler) {\n if (!this.#data.eventsPath) {\n throw new Error(\n colors.red(\n 'Cannot reload events as \"eventsPath\" was not provided when instantiating CommandKit.'\n )\n );\n }\n\n this.#data.events = [];\n\n await this.#buildEvents();\n\n this.#listening.clear();\n this.#data.client.removeAllListeners();\n\n this.#registerEvents();\n\n // Re-register \"interactionCreate\" event for application commands.\n commandHandler?.handleCommands();\n }\n}","import type {\n ValidationHandlerData,\n ValidationHandlerOptions } from\n'./typings';\nimport { toFileURL } from '../../../utils/resolve-file-url';\nimport { getFilePaths } from '../../../utils/get-paths';\nimport { clone } from '../../../utils/clone';\nimport colors from '../../../utils/colors';\n\n/**\n * A handler for command validations.\n */\nexport class ValidationHandler {\n #data: ValidationHandlerData;\n\n constructor({ ...options }: ValidationHandlerOptions) {\n this.#data = {\n ...options,\n validations: []\n };\n }\n\n async init() {\n this.#data.validations = await this.#buildValidations();\n }\n\n async #buildValidations() {\n const allowedExtensions = /\\.(js|mjs|cjs|ts)$/i;\n\n const validationPaths = await getFilePaths(\n this.#data.validationsPath,\n true\n );\n const validationFilePaths = validationPaths.filter((path) =>\n allowedExtensions.test(path)\n );\n\n const validationFunctions: Function[] = [];\n\n for (const validationFilePath of validationFilePaths) {\n const modulePath = toFileURL(validationFilePath);\n\n let importedFunction = (await import(`${modulePath}?t=${Date.now()}`)).\n default;\n let validationFunction = clone(importedFunction);\n\n // If it's CommonJS, invalidate the import cache\n if (typeof module !== 'undefined' && typeof require !== 'undefined') {\n delete require.cache[require.resolve(validationFilePath)];\n }\n\n if (validationFunction?.default) {\n validationFunction = validationFunction.default;\n }\n\n const compactFilePath =\n validationFilePath.split(process.cwd())[1] || validationFilePath;\n\n if (typeof validationFunction !== 'function') {\n process.emitWarning(\n colors.yellow(\n `Ignoring: Validation file ${compactFilePath} does not export a function.`\n )\n );\n continue;\n }\n\n validationFunctions.push(validationFunction);\n }\n\n return validationFunctions;\n }\n\n get validations() {\n return this.#data.validations;\n }\n\n async reloadValidations() {\n if (!this.#data.validationsPath) {\n throw new Error(\n colors.red(\n 'Cannot reload validations as \"validationsPath\" was not provided when instantiating CommandKit.'\n )\n );\n }\n\n const newValidations = await this.#buildValidations();\n\n this.#data.validations = newValidations;\n }\n}","export interface CacheEntry<T = unknown> {\n value: T;\n ttl?: number;\n}\n\nexport abstract class CacheProvider {\n abstract get<T>(key: string): Promise<CacheEntry<T> | undefined>;\n abstract set<T>(key: string, value: T, ttl?: number): Promise<void>;\n abstract exists(key: string): Promise<boolean>;\n abstract delete(key: string): Promise<void>;\n abstract clear(): Promise<void>;\n abstract expire(key: string, ttl: number): Promise<void>;\n}","import { CacheEntry, CacheProvider } from './CacheProvider';\n\nexport class MemoryCache extends CacheProvider {\n #cache = new Map<string, CacheEntry>();\n\n public async get<T>(key: string): Promise<CacheEntry<T> | undefined> {\n const entry = this.#cache.get(key);\n\n if (!entry) {\n return undefined;\n }\n\n if (entry.ttl && Date.now() > entry.ttl) {\n this.#cache.delete(key);\n return undefined;\n }\n\n return entry as CacheEntry<T>;\n }\n\n public async set<T>(key: string, value: T, ttl?: number): Promise<void> {\n const entry: CacheEntry<T> = {\n value,\n ttl: ttl != null ? Date.now() + ttl : undefined\n };\n\n this.#cache.set(key, entry);\n }\n\n public async exists(key: string): Promise<boolean> {\n return this.#cache.has(key);\n }\n\n public async delete(key: string): Promise<void> {\n this.#cache.delete(key);\n }\n\n public async clear(): Promise<void> {\n this.#cache.clear();\n }\n\n public async expire(key: string, ttl: number): Promise<void> {\n const entry = this.#cache.get(key);\n\n if (!entry) return;\n\n const _ttl = Date.now() + ttl;\n\n // delete if _ttl is in the past\n if (_ttl < Date.now()) {\n this.#cache.delete(key);\n return;\n }\n\n entry.ttl = _ttl;\n }\n}","// action row\nexport * from './action-row/ActionRow';\n\n// buttons\nexport * from './button/ButtonKit';\nexport * from './button/Button';\n\n// modals\nexport * from './modal/ModalKit';\nexport * from './modal/Modal';\n\n// common\nexport * from './common/element';\nexport * from './common/types';\nexport * from './common/EventInterceptor';","import { ActionRowBuilder } from 'discord.js';\nimport { AnyCommandKitElement, CommandKitElement } from '../common/element';\n\nexport interface ActionRowProps {\n children?: AnyCommandKitElement[] | AnyCommandKitElement;\n}\n\n/**\n * The action row component.\n * @param props The action row properties.\n * @returns The commandkit element.\n * @example <ActionRow><Button label=\"Click me\" style={ButtonStyle.Primary} customId=\"click_me\" /></ActionRow>\n */\nexport function ActionRow(\nprops: ActionRowProps)\n: CommandKitElement<'action-row'> {\n const row = new ActionRowBuilder();\n\n if (Array.isArray(props.children)) {\n // @ts-ignore\n row.setComponents(...props.children);\n } else if (props.children) {\n // @ts-ignore\n row.setComponents(props.children);\n }\n\n return row;\n}","import {\n type Awaitable,\n type ButtonInteraction,\n ButtonStyle,\n ButtonBuilder,\n Events } from\n'discord.js';\nimport {\n exitContext,\n getCommandKit,\n getContext } from\n'../../context/async-context';\nimport {\n EventInterceptorContextData,\n EventInterceptorErrorHandler } from\n'../common/EventInterceptor';\n\nexport type ButtonKitPredicate = (\ninteraction: ButtonInteraction)\n=> Awaitable<boolean>;\n\n/**\n * The handler to run when a button is clicked. This handler is called with the interaction as the first argument.\n * If the first argument is null, it means that the interaction collector has been destroyed.\n */\nexport type OnButtonKitClick =\nCommandKitButtonBuilderInteractionCollectorDispatch;\n\n/**\n * The handler to run when the interaction collector ends. This handler is called with the reason as the first argument.\n * If the first argument is null, it means that the interaction collector has been destroyed.\n */\nexport type OnButtonKitEnd = CommandKitButtonBuilderOnEnd;\n\n/**\n * The handler to run when a button is clicked. This handler is called with the interaction as the first argument.\n * If the first argument is null, it means that the interaction collector has been destroyed.\n */\nexport type CommandKitButtonBuilderInteractionCollectorDispatch = (\ninteraction: ButtonInteraction,\ncontext: ButtonKit)\n=> Awaitable<void>;\n\nexport type CommandKitButtonBuilderOnEnd = (reason: string) => Awaitable<void>;\n\nexport type CommandKitButtonBuilderInteractionCollectorDispatchContextData =\nEventInterceptorContextData<Events.InteractionCreate>;\n\nexport class ButtonKit extends ButtonBuilder {\n #onClickHandler: CommandKitButtonBuilderInteractionCollectorDispatch | null =\n null;\n #contextData: CommandKitButtonBuilderInteractionCollectorDispatchContextData | null =\n {\n autoReset: true,\n time: 5 * 60 * 1000,\n once: false\n };\n #unsub: (() => void) | null = null;\n\n #getEventInterceptor() {\n const ctx = getContext();\n if (!ctx) return getCommandKit(true).eventInterceptor;\n\n return exitContext(() => ctx.commandkit.eventInterceptor);\n }\n\n /**\n * Sets up an inline interaction collector for this button. This collector by default allows as many interactions as possible if it is actively used.\n * If unused, this expires after 24 hours or custom time if specified.\n * @param handler The handler to run when the button is clicked\n * @param data The context data to use for the interaction collector\n * @returns This button\n * @example\n * ```ts\n * const button = new ButtonKit()\n * .setLabel('Click me')\n * .setStyle(ButtonStyle.Primary)\n * .setCustomId('click_me')\n * .filter((interaction) => interaction.user.id === '1234567890')\n * .onClick(async (interaction) => {\n * await interaction.reply('You clicked me!');\n * });\n *\n * const row = new ActionRowBuilder().addComponents(button);\n *\n * const message = await channel.send({ content: 'Click the button', components: [row] });\n *\n * // Remove onClick handler and destroy the interaction collector\n * button.onClick(null);\n * ```\n */\n public onClick(\n handler: CommandKitButtonBuilderInteractionCollectorDispatch,\n data?: CommandKitButtonBuilderInteractionCollectorDispatchContextData)\n : this {\n if (this.data.style === ButtonStyle.Link) {\n throw new TypeError('Cannot setup \"onClick\" handler on link buttons.');\n }\n\n if (!handler) {\n throw new TypeError(\n 'Cannot setup \"onClick\" without a handler function parameter.'\n );\n }\n\n if (this.#onClickHandler) {\n this.#destroyCollector();\n }\n\n this.#onClickHandler = handler;\n if (data) {\n this.#contextData = {\n autoReset: data.autoReset ?? this.#contextData?.autoReset ?? true,\n time: data.time ?? this.#contextData?.time ?? 5 * 60 * 1000,\n filter: data.filter ?? this.#contextData?.filter,\n onEnd: data.onEnd ?? this.#contextData?.onEnd\n };\n }\n\n this.#setupInteractionCollector();\n\n return this;\n }\n\n public onEnd(handler: CommandKitButtonBuilderOnEnd): this {\n if (this.data.style === ButtonStyle.Link) {\n throw new TypeError('Cannot setup \"onEnd\" handler on link buttons.');\n }\n\n if (!handler) {\n throw new TypeError(\n 'Cannot setup \"onEnd\" without a handler function parameter.'\n );\n }\n\n this.#contextData ??= {};\n this.#contextData.onEnd = handler;\n\n return this;\n }\n\n /**\n * Sets the handler to run when the interaction collector ends.\n * @param handler - The handler to run when the interaction collector ends.\n * @returns This instance of the modal builder.\n */\n public onError(handler: EventInterceptorErrorHandler): this {\n if (!handler) {\n throw new TypeError(\n 'Cannot setup \"onError\" without a handler function parameter.'\n );\n }\n\n this.#contextData ??= {};\n this.#contextData.onError = handler;\n\n return this;\n }\n\n /**\n * Sets a filter for the interaction collector.\n * @param predicate The filter to use for the interaction collector\n */\n public filter(predicate: ButtonKitPredicate): this {\n this.#contextData ??= {\n autoReset: true,\n time: 5 * 60 * 1000\n };\n // @ts-ignore\n this.#contextData.filter = predicate;\n\n return this;\n }\n\n private get customId() {\n // @ts-ignore\n return this.data.custom_id ?? this.data.customId;\n }\n\n #setupInteractionCollector() {\n if (\n this.data.style === ButtonStyle.Link ||\n !this.#contextData ||\n !this.#onClickHandler)\n\n return;\n\n const myCustomId = this.customId ?? null;\n\n if (myCustomId === null) {\n throw new TypeError(\n 'Cannot setup \"onClick\" handler on a button without a custom id.'\n );\n }\n\n const interceptor = this.#getEventInterceptor();\n\n this.#unsub = interceptor.subscribe(\n Events.InteractionCreate,\n async (interaction) => {\n if (!interaction.isButton()) return;\n\n const myCustomId = this.customId ?? null;\n const interactionCustomId = interaction.customId;\n\n if (myCustomId && interactionCustomId !== myCustomId) return;\n\n const filter = this.#contextData?.filter;\n\n if (filter && !(await filter(interaction))) return;\n\n const handler = this.#onClickHandler;\n\n if (!handler) return this.#unsub?.();\n\n return handler(interaction, this);\n },\n this.#contextData\n );\n }\n\n public dispose() {\n this.#destroyCollector();\n return this;\n }\n\n #destroyCollector() {\n this.#unsub?.();\n this.#unsub = null;\n this.#contextData = null;\n this.#onClickHandler = null;\n }\n}","import { ButtonStyle, ComponentEmojiResolvable } from 'discord.js';\nimport {\n ButtonKit,\n CommandKitButtonBuilderOnEnd,\n type CommandKitButtonBuilderInteractionCollectorDispatch,\n type CommandKitButtonBuilderInteractionCollectorDispatchContextData } from\n'./ButtonKit';\nimport { CommandKitElement } from '../common/element';\nimport { MaybeArray } from '../common/types';\nimport { EventInterceptorErrorHandler } from '../common/EventInterceptor';\n\nexport type ButtonChildrenLike = string | number | boolean;\n\nexport interface ButtonProps {\n label?: string;\n style?: ButtonStyle;\n emoji?: ComponentEmojiResolvable;\n disabled?: boolean;\n customId?: string;\n url?: string;\n skuId?: string;\n onClick?: CommandKitButtonBuilderInteractionCollectorDispatch;\n onError?: EventInterceptorErrorHandler;\n options?: CommandKitButtonBuilderInteractionCollectorDispatchContextData;\n onEnd?: CommandKitButtonBuilderOnEnd;\n children?: MaybeArray<ButtonChildrenLike>;\n}\n\n/**\n * The button component.\n * @param props The button properties.\n * @returns The commandkit element.\n * @example <Button style={ButtonStyle.Primary} customId=\"click_me\">Click Me</Button>\n */\nexport function Button(props: ButtonProps): CommandKitElement<'button-kit'> {\n const button = new ButtonKit();\n\n props.style ??= ButtonStyle.Primary;\n\n // auto-generate customId if not provided (only if onClick is set)\n if (props.onClick) {\n props.customId ??= `buttonkit::${crypto.randomUUID()}`;\n }\n\n if (props.customId) {\n button.setCustomId(props.customId);\n }\n\n if (props.onClick) {\n button.onClick(props.onClick, props.options);\n }\n\n if (props.disabled) {\n button.setDisabled(props.disabled);\n }\n\n if (props.emoji) {\n button.setEmoji(props.emoji);\n }\n\n if (props.skuId) {\n button.setSKUId(props.skuId);\n }\n\n if (props.url) {\n button.setURL(props.url);\n }\n\n if (props.style) {\n button.setStyle(props.style);\n }\n\n const label = props.label || props.children;\n\n if (label) {\n button.setLabel(\n Array.isArray(label) ?\n label.join(' ') :\n typeof label === 'string' ?\n label :\n String(label)\n );\n }\n\n if (props.onEnd) {\n button.onEnd(props.onEnd);\n }\n\n if (props.onError) {\n button.onError(props.onError);\n }\n\n return button;\n}","import {\n Awaitable,\n Events,\n ModalBuilder,\n ModalSubmitInteraction } from\n'discord.js';\nimport {\n exitContext,\n getCommandKit,\n getContext } from\n'../../context/async-context';\nimport {\n EventInterceptorContextData,\n EventInterceptorErrorHandler } from\n'../common/EventInterceptor';\n\nexport type ModalKitPredicate = (\ninteraction: ModalSubmitInteraction)\n=> Awaitable<boolean>;\n\n/**\n * The handler to run when a modal is submitted. This handler is called with the interaction as the first argument.\n * If the first argument is null, it means that the interaction collector has been destroyed.\n */\nexport type OnModalKitSubmit =\nCommandKitModalBuilderInteractionCollectorDispatch;\n\n/**\n * The handler to run when the interaction collector ends. This handler is called with the reason as the first argument.\n * If the first argument is null, it means that the interaction collector has been destroyed.\n */\nexport type OnModalKitEnd = CommandKitModalBuilderOnEnd;\n\n/**\n * The handler to run when a modal is submitted. This handler is called with the interaction as the first argument.\n * If the first argument is null, it means that the interaction collector has been destroyed.\n */\nexport type CommandKitModalBuilderInteractionCollectorDispatch = (\ninteraction: ModalSubmitInteraction,\ncontext: ModalKit)\n=> Awaitable<void>;\n\nexport type CommandKitModalBuilderOnEnd = (reason: string) => Awaitable<void>;\n\nexport type CommandKitModalBuilderInteractionCollectorDispatchContextData =\nEventInterceptorContextData<Events.InteractionCreate>;\n\nexport class ModalKit extends ModalBuilder {\n #onSubmitHandler: CommandKitModalBuilderInteractionCollectorDispatch | null =\n null;\n #contextData: CommandKitModalBuilderInteractionCollectorDispatchContextData | null =\n {\n autoReset: false,\n time: 5 * 60 * 1000,\n once: true\n };\n #unsub: (() => void) | null = null;\n\n #getEventInterceptor() {\n const ctx = getContext();\n if (!ctx) return getCommandKit(true).eventInterceptor;\n\n return exitContext(() => ctx.commandkit.eventInterceptor);\n }\n\n /**\n * Sets the handler to run when the modal is submitted.\n * @param handler - The handler to run when the modal is submitted.\n * @param data - The context data for the interaction collector.\n * @returns This instance of the modal builder.\n * @example\n * ```ts\n * const modal = new ModalKit()\n * .setTitle('My Modal')\n * .setCustomId('my-modal')\n * .filter((interaction) => interaction.user.id === '1234567890')\n * .onSubmit(async (interaction) => {\n * await interaction.reply('You submitted the modal!');\n * })\n * .addComponents(actionRow1, actionRow2);\n * ```\n */\n public onSubmit(\n handler: CommandKitModalBuilderInteractionCollectorDispatch,\n data?: CommandKitModalBuilderInteractionCollectorDispatchContextData)\n : this {\n if (!handler) {\n throw new TypeError(\n 'Cannot setup \"onClick\" without a handler function parameter.'\n );\n }\n\n if (this.#onSubmitHandler) {\n this.#destroyCollector();\n }\n\n this.#onSubmitHandler = handler;\n\n if (data) {\n this.#contextData = {\n autoReset: data.autoReset ?? this.#contextData?.autoReset ?? true,\n time: data.time ?? this.#contextData?.time ?? 5 * 60 * 1000,\n filter: data.filter ?? this.#contextData?.filter,\n onEnd: data.onEnd ?? this.#contextData?.onEnd\n };\n }\n\n this.#setupCollector();\n\n return this;\n }\n\n /**\n * Sets the handler to run when the interaction collector ends.\n * @param handler - The handler to run when the interaction collector ends.\n * @returns This instance of the modal builder.\n */\n public onEnd(handler: CommandKitModalBuilderOnEnd): this {\n if (!handler) {\n throw new TypeError(\n 'Cannot setup \"onEnd\" without a handler function parameter.'\n );\n }\n\n this.#contextData ??= {};\n this.#contextData.onEnd = handler;\n\n return this;\n }\n\n /**\n * Sets the handler to run when the interaction collector ends.\n * @param handler - The handler to run when the interaction collector ends.\n * @returns This instance of the modal builder.\n */\n public onError(handler: EventInterceptorErrorHandler): this {\n if (!handler) {\n throw new TypeError(\n 'Cannot setup \"onError\" without a handler function parameter.'\n );\n }\n\n this.#contextData ??= {};\n this.#contextData.onError = handler;\n\n return this;\n }\n\n /**\n * Sets a filter for the interaction collector.\n * @param predicate - The filter to use for the interaction collector.\n * @returns This instance of the modal builder.\n */\n public filter(predicate: ModalKitPredicate): this {\n this.#contextData ??= {\n autoReset: true,\n time: 5 * 60 * 1000\n };\n // @ts-ignore\n this.#contextData.filter = predicate;\n\n return this;\n }\n\n private get customId() {\n // @ts-ignore\n return this.data.custom_id ?? this.data.customId;\n }\n\n #setupCollector() {\n if (!this.#contextData) return;\n\n if (!this.customId) {\n throw new TypeError(\n 'Cannot setup an modal collector without a custom ID.'\n );\n }\n\n const interceptor = this.#getEventInterceptor();\n if (!interceptor) return;\n\n this.#unsub = interceptor.subscribe(\n Events.InteractionCreate,\n async (interaction) => {\n if (!interaction.isModalSubmit()) return;\n\n const myCustomId = this.customId ?? null;\n const interactionCustomId = interaction.customId;\n\n if (myCustomId && interactionCustomId !== myCustomId) return;\n\n const filter = this.#contextData?.filter;\n\n if (filter && !(await filter(interaction))) return;\n\n const handler = this.#onSubmitHandler;\n\n if (!handler) return this.#unsub?.();\n\n return handler(interaction, this);\n },\n this.#contextData\n );\n }\n\n public dispose() {\n this.#destroyCollector();\n return this;\n }\n\n #destroyCollector() {\n this.#unsub?.();\n this.#unsub = null;\n this.#onSubmitHandler = null;\n this.#contextData = null;\n }\n}","import { ActionRowBuilder, TextInputBuilder, TextInputStyle } from 'discord.js';\nimport { MaybeArray } from '../common/types';\nimport { CommandKitElement } from '../common/element';\nimport {\n CommandKitModalBuilderInteractionCollectorDispatchContextData,\n ModalKit,\n OnModalKitEnd,\n OnModalKitSubmit } from\n'./ModalKit';\nimport { EventInterceptorErrorHandler } from '../common/EventInterceptor';\n\nexport interface ModalProps {\n customId?: string;\n title: string;\n children?: MaybeArray<TextInputBuilder | ActionRowBuilder>;\n onSubmit?: OnModalKitSubmit;\n onEnd?: OnModalKitEnd;\n onError?: EventInterceptorErrorHandler;\n options?: CommandKitModalBuilderInteractionCollectorDispatchContextData;\n}\n\n/**\n * The modal component.\n * @param props The modal properties.\n * @returns The commandkit element.\n * @example <Modal title=\"My Modal\" onSubmit={onSubmit}>...</Modal>\n */\nexport function Modal(props: ModalProps): CommandKitElement<'modal'> {\n const modal = new ModalKit();\n\n if (props.title) {\n modal.setTitle(props.title);\n }\n\n if (props.onSubmit) {\n props.customId ??= `modalkit::${crypto.randomUUID()}`;\n }\n\n if (props.customId) {\n modal.setCustomId(props.customId);\n }\n\n if (props.onSubmit) {\n modal.onSubmit(props.onSubmit, props.options);\n }\n\n if (props.children) {\n const childs = (\n Array.isArray(props.children) ? props.children : [props.children]).\n\n map((c) => {\n if (c instanceof ActionRowBuilder) return c;\n if (c instanceof TextInputBuilder)\n return new ActionRowBuilder().addComponents(c);\n }).\n filter((c): c is ActionRowBuilder<TextInputBuilder> => c != null);\n\n modal.addComponents(childs);\n }\n\n if (props.onEnd) {\n modal.onEnd(props.onEnd);\n }\n\n if (props.onError) {\n modal.onError(props.onError);\n }\n\n return modal;\n}\n\nexport interface TextInputProps {\n customId: string;\n label: string;\n placeholder?: string;\n maxLength?: number;\n minLength?: number;\n value?: string;\n required?: boolean;\n}\n\n/**\n * The text input component.\n * @param props The text input properties.\n * @returns The commandkit element.\n * @example <TextInput customId=\"input\" label=\"Input\" style={TextInputStyle.Short} />\n */\nexport function TextInput(\nprops: TextInputProps & {style: TextInputStyle;})\n: CommandKitElement<'text-input'> {\n const input = new TextInputBuilder().setStyle(props.style);\n\n if (props.customId) {\n input.setCustomId(props.customId);\n }\n\n if (props.label) {\n input.setLabel(props.label);\n }\n\n if (props.placeholder) {\n input.setPlaceholder(props.placeholder);\n }\n\n if (props.maxLength) {\n input.setMaxLength(props.maxLength);\n }\n\n if (props.minLength) {\n input.setMinLength(props.minLength);\n }\n\n if (props.value) {\n input.setValue(props.value);\n }\n\n if (props.required) {\n input.setRequired(props.required);\n }\n\n return input;\n}\n\n/**\n * The short text input component.\n * @param props The text input properties.\n * @returns The commandkit element.\n * @example <ShortInput customId=\"input\" label=\"Input\" />\n */\nexport function ShortInput(\nprops: TextInputProps)\n: CommandKitElement<'text-input'> {\n return TextInput({ ...props, style: TextInputStyle.Short });\n}\n\n/**\n * The paragraph text input component.\n * @param props The text input properties.\n * @returns The commandkit element.\n * @example <ParagraphInput customId=\"input\" label=\"Input\" />\n */\nexport function ParagraphInput(\nprops: TextInputProps)\n: CommandKitElement<'text-input'> {\n return TextInput({ ...props, style: TextInputStyle.Paragraph });\n}","import { ActionRowBuilder, TextInputBuilder } from 'discord.js';\nimport type { ButtonKit } from '../button/ButtonKit';\nimport { warnUnstable } from '../../utils/warn-unstable';\nimport { ModalKit } from '../modal/ModalKit';\n\nexport const ElementType = {\n ActionRow: 'action-row',\n Button: 'button-kit',\n Modal: 'modal',\n TextInput: 'text-input'\n} as const;\n\nexport type ElementType = (typeof ElementType)[keyof typeof ElementType];\n\nexport interface CommandKitElementData {\n [ElementType.ActionRow]: ActionRowBuilder;\n [ElementType.Button]: ButtonKit;\n [ElementType.Modal]: ModalKit;\n [ElementType.TextInput]: TextInputBuilder;\n}\n\nexport type CommandKitElement<Type extends ElementType> =\nCommandKitElementData[Type];\n\nexport type AnyCommandKitElement = CommandKitElement<ElementType>;\n\nexport function isCommandKitElement(\nelement: unknown)\n: element is CommandKitElement<ElementType> {\n if (typeof element !== 'object' || element === null) return false;\n if (!Reflect.has(element, 'type')) return false;\n if (!Reflect.has(element, 'data')) return false;\n\n return true;\n}\n\nexport function getElement<\n T extends ElementType,\n E extends CommandKitElement<T>>(\nelement: E): CommandKitElementData[T] {\n return element.data as CommandKitElementData[T];\n}\n\nexport interface FragmentElementProps {\n children: [];\n}\n\nexport function Fragment(\nprops: FragmentElementProps)\n: CommandKitElementData[ElementType][] {\n warnUnstable('CommandKit JSX');\n return Array.isArray(props.children) ? props.children.flat() : props.children;\n}\n\nexport function createElement(\ntype: Function,\nprops: Record<string, unknown>,\n...children: any[])\n: CommandKitElement<ElementType> {\n warnUnstable('CommandKit JSX');\n return type({ ...props, children });\n}","const WARNED_KEYS = new Set<string>();\n\nexport function emitWarning(message: string, code = 'CommandKitWarning') {\n process.emitWarning(message, { code });\n}\n\nexport function warnUnstable(name: string) {\n if (WARNED_KEYS.has(name)) return;\n\n WARNED_KEYS.add(name);\n\n emitWarning(\n `${name} is unstable and may change in future versions.`,\n 'CommandKitUnstableWarning'\n );\n}","export type MaybeArray<T> = T | T[];","import { Awaitable, Client, ClientEvents, Events } from 'discord.js';\n\nexport interface EventInterceptorContextData<E extends keyof ClientEvents> {\n /**\n * The filter to use for the collector.\n */\n filter?: (...args: ClientEvents[E]) => Awaitable<boolean>;\n /**\n * The duration (in ms) that the collector should run for.\n */\n time?: number;\n /**\n * If the collector should automatically reset the timer when a button is clicked.\n */\n autoReset?: boolean;\n /**\n * Whether the collector should run only once.\n */\n once?: boolean;\n /**\n * The handler to run when the collector ends.\n */\n onEnd?: (reason: string) => Awaitable<void>;\n /**\n * The handler to run upon an error.\n */\n onError?: EventInterceptorErrorHandler;\n}\n\nexport type EventInterceptorErrorHandler = (error: Error) => Awaitable<void>;\n\nexport class EventInterceptor {\n private subscribers = new Map<\n keyof ClientEvents,\n Set<(...args: any[]) => void>>(\n );\n private globalHandlers = new Map<\n keyof ClientEvents,\n (...args: any[]) => void>(\n );\n private cleanupTimer: NodeJS.Timeout | null = null;\n\n /**\n * Creates the event interceptor.\n */\n public constructor(public readonly client: Client) {\n this.#cleanupLoop();\n }\n\n #cleanupLoop() {\n if (this.cleanupTimer) clearInterval(this.cleanupTimer);\n\n this.cleanupTimer = setInterval(() => {\n for (const [event, handlers] of this.subscribers) {\n for (const handler of handlers) {\n const options = Reflect.get(\n handler,\n 'options'\n ) as EventInterceptorContextData<keyof ClientEvents> & {\n registeredAt: number;\n };\n\n const isExpired =\n options.time && Date.now() - options.registeredAt > options.time;\n\n if (isExpired) {\n this.unsubscribe(event, handler, 'time');\n }\n }\n }\n }, 60_000).unref();\n }\n\n /**\n * Destroys the event interceptor.\n */\n public destroy(): void {\n if (this.cleanupTimer) {\n clearInterval(this.cleanupTimer);\n this.cleanupTimer = null;\n }\n\n for (const [event, handlers] of this.subscribers) {\n for (const handler of handlers) {\n this.unsubscribe(event, handler, 'destroy');\n }\n }\n\n this.subscribers.clear();\n this.globalHandlers.clear();\n }\n\n /**\n * Whether the event has subscribers.\n * @param event The event to check.\n */\n public hasSubscribers(event: keyof ClientEvents): boolean {\n return this.subscribers.has(event);\n }\n\n /**\n * Returns the number of subscribers for the event.\n * @param event The event to check.\n */\n public getSubscriberCount(event: keyof ClientEvents): number {\n const handlers = this.subscribers.get(event);\n return handlers?.size ?? 0;\n }\n\n /**\n * Whether the event has global handlers.\n */\n public hasGlobalHandlers(): boolean {\n return this.globalHandlers.size > 0;\n }\n\n /**\n * Returns the number of global handlers.\n */\n public getGlobalHandlersCount(): number {\n return this.subscribers.size;\n }\n\n /**\n * Subscribes to an event.\n * @param event The event to subscribe to.\n * @param listener The listener to call when the event is emitted.\n * @returns A function to unsubscribe from the event.\n */\n public subscribe<Event extends keyof ClientEvents>(\n event: Event,\n listener: (...args: ClientEvents[Event]) => void,\n options?: EventInterceptorContextData<Event>)\n : () => void {\n if (!this.subscribers.has(event)) {\n this.subscribers.set(event, new Set());\n this.client.on(event, this.createGlobalHandler(event));\n this.client.setMaxListeners(this.client.getMaxListeners() + 1);\n }\n\n options ??= {};\n\n // @ts-ignore\n options.registeredAt = Date.now();\n\n Reflect.set(listener, 'options', options);\n\n this.subscribers.get(event)!.add(listener);\n\n return () => {\n this.unsubscribe(event, listener);\n };\n }\n\n /**\n * Unsubscribes from an event.\n * @param event The event to unsubscribe from.\n */\n public unsubscribe<Event extends keyof ClientEvents>(\n event: Event,\n listener: (...args: ClientEvents[Event]) => void,\n reason?: string)\n : void {\n const handlers = this.subscribers.get(event);\n if (!handlers) return;\n\n handlers.delete(listener);\n\n if (handlers.size < 1) {\n this.subscribers.delete(event);\n this.client.removeListener(event, this.globalHandlers.get(event)!);\n this.globalHandlers.delete(event);\n this.client.setMaxListeners(\n Math.max(this.client.getMaxListeners() - 1, 0)\n );\n }\n\n Reflect.get(listener, 'options').onEnd?.(reason ?? 'unsubscribe');\n }\n\n /**\n * Creates a global handler for the event.\n * @param event The event to create a global handler for.\n * @returns The global handler.\n */\n private createGlobalHandler<Event extends keyof ClientEvents>(\n event: Event)\n : (...args: ClientEvents[Event]) => void {\n if (this.globalHandlers.has(event)) {\n return this.globalHandlers.get(event)!;\n }\n\n const handler = async (...args: ClientEvents[Event]) => {\n const subscribers = this.subscribers.get(event);\n if (subscribers && subscribers.size > 0) {\n for (const subscriber of subscribers) {\n const options = Reflect.get(\n subscriber,\n 'options'\n ) as EventInterceptorContextData<Event> & {registeredAt: number;};\n\n const isExpired =\n options.time && Date.now() - options.registeredAt > options.time;\n\n if (isExpired) {\n this.unsubscribe(event, subscriber, 'time');\n continue;\n }\n\n if (options.autoReset) {\n options.registeredAt = Date.now();\n }\n\n if (options.filter && !(await options.filter(...args))) {\n continue;\n }\n\n try {\n await subscriber(...args);\n } catch (e) {\n if (options.onError) {\n await options.onError(<Error> e);\n } else {\n throw e;\n }\n } finally {\n if (options.once) {\n this.unsubscribe(event, subscriber, 'once');\n }\n }\n }\n }\n };\n\n this.globalHandlers.set(event, handler);\n\n return handler;\n }\n}","import { Locale } from 'discord.js';\nimport { CommandKit } from '../../CommandKit';\nimport {\n LocalizationStrategy,\n LocalizationTranslationRequest,\n TranslationResult } from\n'./LocalizationStrategy';\nimport { Translation } from './Translation';\nimport { readFile } from 'node:fs/promises';\nimport { join } from 'node:path';\n\nexport class DefaultLocalizationStrategy implements LocalizationStrategy {\n private translations: Map<string, Translation> = new Map();\n\n public constructor(private readonly commandkit: CommandKit) {}\n\n public async locateTranslation(scope: string, locale: Locale) {\n const localesPath = this.commandkit.getPath('locales');\n\n if (!localesPath) return null;\n\n const path = join(localesPath, locale, `${scope}.json`);\n\n try {\n const data = await readFile(path, 'utf-8');\n\n return JSON.parse(data) as Translation;\n } catch {\n return null;\n }\n }\n\n public async getTranslationStrict(scope: string, locale: Locale) {\n const key = `${scope}:${locale}`;\n if (!this.translations.has(key)) {\n const translation = await this.locateTranslation(scope, locale);\n\n if (!translation) {\n throw new Error(`Translation not found for ${key}`);\n }\n\n this.translations.set(key, translation);\n\n return translation;\n }\n\n return this.translations.get(key)!;\n }\n\n public async getTranslation(\n scope: string,\n locale: Locale)\n : Promise<Translation | null> {\n try {\n return this.getTranslationStrict(scope, locale);\n } catch (e) {\n return null;\n }\n }\n\n public async translate(\n request: LocalizationTranslationRequest)\n : Promise<TranslationResult> {\n const { scope, key, args, locale } = request;\n\n const translation = await this.getTranslation(scope, locale);\n\n if (!translation) return `${scope}.${key}`;\n\n const value = translation.translations[key];\n\n const translated = this.applyTranslation(value, args);\n\n return translated || `${scope}.${key}`;\n }\n\n private applyTranslation(\n translation: string,\n args?: Record<string, any>)\n : string {\n if (!translation || !args) return translation;\n\n return translation.replace(/{([^}]+)}/g, (_, key) => {\n return String(args[key] ?? `{${key}}`);\n });\n }\n}","import { existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { COMMANDKIT_IS_DEV } from './constants';\n\nlet appDir: string | null = null;\n\n/**\n * Returns the path to the app directory.\n * @returns The path to the app directory or `null` if not found.\n */\nexport function findAppDirectory(): string | null {\n if (appDir) return appDir;\n\n let root = join(process.cwd(), COMMANDKIT_IS_DEV ? '.commandkit' : 'dist');\n\n if (!existsSync(root)) root = process.cwd();\n\n const dirs = ['app', 'src/app'].map((dir) => join(root, dir));\n\n for (const dir of dirs) {\n if (existsSync(dir)) {\n appDir = dir;\n return dir;\n }\n }\n\n return null;\n}","export const COMMANDKIT_CACHE_TAG = Symbol('kCommandKitCacheTag');\n\nexport const COMMANDKIT_IS_DEV = !!process.env.COMMANDKIT_DEV;","import type { CommandKit } from '../../CommandKit';\nimport {\n Awaitable,\n Collection,\n ContextMenuCommandBuilder,\n Interaction,\n Locale,\n Message,\n SlashCommandBuilder } from\n'discord.js';\nimport { Context } from '../commands/Context';\nimport { toFileURL } from '../../utils/resolve-file-url';\nimport { TranslatableCommandOptions } from '../i18n/Translation';\nimport { MessageCommandParser } from '../commands/MessageCommandParser';\nimport { CommandKitErrorCodes, isErrorType } from '../../utils/error-codes';\nimport { ParsedCommand, ParsedMiddleware } from '../router';\n\ninterface AppCommand {\n command: SlashCommandBuilder | Record<string, any>;\n chatInput?: (ctx: Context) => Awaitable<unknown>;\n autocomplete?: (ctx: Context) => Awaitable<unknown>;\n message?: (ctx: Context) => Awaitable<unknown>;\n messageContextMenu?: (ctx: Context) => Awaitable<unknown>;\n userContextMenu?: (ctx: Context) => Awaitable<unknown>;\n}\n\ninterface AppCommandMiddleware {\n beforeExecute: (ctx: Context) => Awaitable<unknown>;\n afterExecute: (ctx: Context) => Awaitable<unknown>;\n}\n\ninterface LoadedCommand {\n command: ParsedCommand;\n data: AppCommand;\n}\n\ninterface LoadedMiddleware {\n middleware: ParsedMiddleware;\n data: AppCommandMiddleware;\n}\n\nexport interface PreparedAppCommandExecution {\n command: LoadedCommand;\n middlewares: LoadedMiddleware[];\n messageCommandParser?: MessageCommandParser;\n}\n\ntype CommandBuilderLike =\nSlashCommandBuilder |\nContextMenuCommandBuilder |\nRecord<string, any>;\n\nconst commandDataSchema = {\n command: (c: unknown) =>\n c instanceof SlashCommandBuilder ||\n c instanceof ContextMenuCommandBuilder ||\n c && typeof c === 'object',\n chatInput: (c: unknown) => typeof c === 'function',\n autocomplete: (c: unknown) => typeof c === 'function',\n message: (c: unknown) => typeof c === 'function',\n messageContextMenu: (c: unknown) => typeof c === 'function',\n userContextMenu: (c: unknown) => typeof c === 'function'\n};\n\nconst middlewareDataSchema = {\n beforeExecute: (c: unknown) => typeof c === 'function',\n afterExecute: (c: unknown) => typeof c === 'function'\n};\n\nexport class AppCommandHandler {\n private loadedCommands = new Collection<string, LoadedCommand>();\n private loadedMiddlewares = new Collection<string, LoadedMiddleware>();\n\n public constructor(public readonly commandkit: CommandKit) {}\n\n public getCommandsArray() {\n return Array.from(this.loadedCommands.values()).map((v) => {\n if ('toJSON' in v && typeof v.toJSON === 'function') return v.toJSON();\n return v.data.command;\n });\n }\n\n public async prepareCommandRun(\n source: Interaction | Message)\n : Promise<PreparedAppCommandExecution | null> {\n let cmd: string;\n let parser: MessageCommandParser | undefined;\n\n if (source instanceof Message) {\n if (source.author.bot) return null;\n\n const prefix =\n await this.commandkit.config.getMessageCommandPrefix(source);\n\n parser = new MessageCommandParser(\n source,\n Array.isArray(prefix) ? prefix : [prefix],\n (command: string) => {\n const loadedCommand = this.loadedCommands.find((c) => {\n return c.data.command.name === command;\n });\n\n if (!loadedCommand) return null;\n\n const json =\n 'toJSON' in loadedCommand.data.command ?\n loadedCommand.data.command.toJSON() :\n loadedCommand.data.command;\n\n return json.options.reduce(\n (acc: Record<string, unknown>, opt: Record<string, any>) => {\n acc[opt.name] = opt.type;\n return acc;\n },\n {} as Record<string, unknown>\n );\n }\n );\n\n try {\n cmd = parser.getFullCommand();\n } catch (e) {\n if (isErrorType(e, CommandKitErrorCodes.InvalidCommandPrefix)) {\n return null;\n }\n\n console.error(e);\n return null;\n }\n } else {\n if (!source.isCommand()) return null;\n\n cmd = source.commandName;\n\n if (source.isChatInputCommand()) {\n const subcommandGroup = source.options.getSubcommandGroup(false);\n const subcommand = source.options.getSubcommand(false);\n\n if (subcommandGroup) {\n cmd += ` ${subcommandGroup}`;\n }\n\n if (subcommand) {\n cmd += ` ${subcommand}`;\n }\n }\n }\n\n const loadedCommand = this.loadedCommands.find((c) => {\n return c.data.command.name === cmd;\n });\n\n if (!loadedCommand) return null;\n\n return {\n command: loadedCommand,\n middlewares: loadedCommand.command.middlewares.\n map((m) => this.loadedMiddlewares.get(m)).\n filter((m): m is LoadedMiddleware => !!m),\n messageCommandParser: parser\n };\n }\n\n public async loadCommands() {\n const commandsRouter = this.commandkit.commandsRouter;\n\n if (!commandsRouter) {\n throw new Error('Commands router has not yet initialized');\n }\n\n const { commands, middleware } = commandsRouter.getData();\n\n for (const [id, md] of middleware) {\n const data = await import(`${toFileURL(md.fullPath)}?t=${Date.now()}`);\n\n let handlerCount = 0;\n for (const [key, validator] of Object.entries(middlewareDataSchema)) {\n if (data[key] && !(await validator(data[key]))) {\n throw new Error(\n `Invalid export for middleware ${id}: ${key} does not match expected value`\n );\n }\n\n if (data[key]) handlerCount++;\n }\n\n if (handlerCount === 0) {\n throw new Error(\n `Invalid export for middleware ${id}: at least one handler function must be provided`\n );\n }\n\n this.loadedMiddlewares.set(id, { middleware: md, data });\n }\n\n for (const [name, command] of commands) {\n const data = await import(\n `${toFileURL(command.fullPath)}?t=${Date.now()}`\n );\n\n if (!data.command) {\n throw new Error(\n `Invalid export for command ${name}: no command definition found`\n );\n }\n\n let handlerCount = 0;\n\n for (const [key, validator] of Object.entries(commandDataSchema)) {\n if (key !== 'command' && data[key]) handlerCount++;\n if (data[key] && !(await validator(data[key]))) {\n throw new Error(\n `Invalid export for command ${name}: ${key} does not match expected value`\n );\n }\n }\n\n if (handlerCount === 0) {\n throw new Error(\n `Invalid export for command ${name}: at least one handler function must be provided`\n );\n }\n\n const localizedCommand = await this.applyLocalizations({\n ...data.command\n });\n\n this.loadedCommands.set(name, {\n command,\n data: {\n ...data,\n command: localizedCommand\n }\n });\n }\n }\n\n public async applyLocalizations(command: CommandBuilderLike) {\n const localization = this.commandkit.config.localizationStrategy;\n\n const validLocales = Object.values(Locale).filter(\n (v) => typeof v === 'string'\n );\n\n for (const locale of validLocales) {\n const translation = await localization.locateTranslation(\n command.name,\n locale\n );\n\n if (!translation?.command) continue;\n\n if (command instanceof SlashCommandBuilder) {\n if (translation.command.name) {\n command.setNameLocalization(locale, translation.command.name);\n }\n\n if (translation.command.description) {\n command.setDescriptionLocalization(\n locale,\n translation.command.description\n );\n }\n\n const raw = command.toJSON();\n\n if (raw.options?.length && translation.command.options?.length) {\n const opt = translation.command.options.slice();\n let o: TranslatableCommandOptions;\n\n while (o = opt.shift()!) {\n raw.options?.forEach((option) => {\n if (option.name === o.ref) {\n if (option.name) {\n option.name_localizations ??= {};\n option.name_localizations[locale] = o.name;\n }\n\n if (option.description) {\n option.description_localizations ??= {};\n option.description_localizations[locale] = o.description;\n }\n }\n });\n }\n }\n } else if (command instanceof ContextMenuCommandBuilder) {\n if (translation.command.name) {\n command.setNameLocalization(locale, translation.command.name);\n }\n\n const raw = command.toJSON();\n\n return raw;\n } else {\n command.name_localizations ??= {};\n command.name_localizations[locale] = translation.command.name;\n\n if (command.description) {\n command.description_localizations ??= {};\n command.description_localizations[locale] =\n translation.command.description;\n }\n\n if (command.options?.length && translation.command.options?.length) {\n const opt = translation.command.options.slice();\n let o: TranslatableCommandOptions;\n\n while (o = opt.shift()!) {\n command.options.forEach((option: any) => {\n if (option.name === o.ref) {\n if (option.name) {\n option.name_localizations ??= {};\n option.name_localizations[locale] = o.name;\n }\n\n if (option.description) {\n option.description_localizations ??= {};\n option.description_localizations[locale] = o.description;\n }\n }\n });\n }\n }\n }\n }\n\n return command;\n }\n}","import { Channel } from 'diagnostics_channel';\nimport {\n Message,\n ApplicationCommandOptionType,\n GuildMember,\n Attachment,\n User,\n Role,\n CommandInteractionOption } from\n'discord.js';\nimport {\n CommandKitErrorCodes,\n createCommandKitError } from\n'../../utils/error-codes';\n\nexport interface ParsedMessageCommand {\n command: string;\n options: {name: string;value: unknown;}[];\n subcommand?: string;\n subcommandGroup?: string;\n}\n\nexport type MessageCommandOptionsSchema = Record<\n string,\n ApplicationCommandOptionType>;\n\n\nexport class MessageCommandParser {\n #parsed: ParsedMessageCommand | null = null;\n #options: MessageCommandOptions | null = null;\n\n public constructor(\n public message: Message,\n private prefix: string[],\n private schema: (command: string) => MessageCommandOptionsSchema)\n {}\n\n public get options() {\n if (!this.#options) {\n this.#options = new MessageCommandOptions(this);\n }\n\n return this.#options;\n }\n\n public getOption<T>(name: string): T | undefined {\n return this.parse().options.find((o) => o.name === name)?.value as T;\n }\n\n public getCommand(): string {\n return this.parse().command;\n }\n\n public getSubcommand(): string | undefined {\n return this.parse().subcommand;\n }\n\n public getSubcommandGroup(): string | undefined {\n return this.parse().subcommandGroup;\n }\n\n public getPrefix() {\n for (const p of this.prefix) {\n if (this.message.content.startsWith(p)) {\n return p;\n }\n }\n }\n\n public getFullCommand() {\n return [this.getCommand(), this.getSubcommandGroup(), this.getSubcommand()].\n filter((v) => v).\n join(' ');\n }\n\n public parse(): ParsedMessageCommand {\n if (this.#parsed) {\n return this.#parsed;\n }\n\n const content = this.message.content;\n\n const prefix = this.getPrefix();\n\n if (!prefix) {\n throw createCommandKitError(CommandKitErrorCodes.InvalidCommandPrefix);\n }\n\n const parts = content.slice(prefix.length).trim().split(' ');\n const command = parts.shift();\n\n let subcommandGroup: string | undefined;\n let subcommand: string | undefined;\n\n if (command?.includes(':')) {\n const [, group, cmd] = command.split(':');\n\n if (!cmd && group) {\n subcommand = group;\n } else if (cmd && group) {\n subcommandGroup = group;\n subcommand = cmd;\n }\n }\n\n const schema = this.schema(\n [command, subcommandGroup, subcommand].filter(Boolean).join(' ').trim()\n );\n\n const options = parts.\n map((part) => {\n const [name, value] = part.split(':');\n\n if (!(name in schema)) return null;\n\n switch (schema[name]) {\n case ApplicationCommandOptionType.Boolean:\n return { name, value: value === 'true' };\n case ApplicationCommandOptionType.Integer:\n return { name, value: parseInt(value, 10) };\n case ApplicationCommandOptionType.Number:\n return { name, value: parseFloat(value) };\n case ApplicationCommandOptionType.String:\n return { name, value };\n case ApplicationCommandOptionType.User:\n return {\n name,\n value: this.message.mentions.users.find((u) => {\n return u.id === value.replace(/[<@!>]/g, '');\n })\n };\n case ApplicationCommandOptionType.Channel:\n return {\n name,\n value: this.message.mentions.channels.find((c) => {\n return c.id === value.replace(/[<#>]/g, '');\n })\n };\n case ApplicationCommandOptionType.Role:\n return {\n name,\n value: this.message.mentions.roles.find((r) => {\n return r.id === value.replace(/[<@&>]/g, '');\n })\n };\n case ApplicationCommandOptionType.Attachment:\n return {\n name,\n value: this.message.attachments.find((a) => {\n return a.name === value;\n })\n };\n default:\n return null;\n }\n }).\n filter((v) => v !== null);\n\n this.#parsed = {\n command: command!,\n options,\n subcommand,\n subcommandGroup\n };\n\n return this.#parsed;\n }\n}\n\nexport class MessageCommandOptions {\n public constructor(private parser: MessageCommandParser) {}\n\n private assertOption<T>(name: string, required = false) {\n const option = this.parser.getOption<T>(name);\n\n if (required && option === undefined) {\n throw new Error(`Option \"${name}\" is required.`);\n }\n\n return option ?? null;\n }\n\n getMember(name: string): GuildMember | null;\n getMember(name: string, required: true): GuildMember;\n getMember(name: string, required = false) {\n const user = this.assertOption<User>(name, required);\n const member = this.parser.message.guild?.members.cache.get(user?.id!);\n\n if (required && !member) {\n throw new Error(`Member \"${name}\" is required.`);\n }\n\n return member ?? null;\n }\n\n getAttachment(name: string): Attachment | null;\n getAttachment(name: string, required: true): Attachment;\n getAttachment(name: string, required = false) {\n return this.assertOption<Attachment>(name, required);\n }\n\n getBoolean(name: string): boolean | null;\n getBoolean(name: string, required: true): boolean;\n getBoolean(name: string, required = false) {\n return this.assertOption<boolean>(name, required);\n }\n\n getNumber(name: string): number | null;\n getNumber(name: string, required: true): number;\n getNumber(name: string, required = false) {\n return this.assertOption<number>(name, required);\n }\n\n getString(name: string): string | null;\n getString(name: string, required: true): string;\n getString(name: string, required = false) {\n return this.assertOption<string>(name, required);\n }\n\n getInteger(name: string): number | null;\n getInteger(name: string, required: true): number;\n getInteger(name: string, required = false) {\n return this.assertOption<number>(name, required);\n }\n\n getUser(name: string): User | null;\n getUser(name: string, required: true): User;\n getUser(name: string, required = false) {\n return this.assertOption<User>(name, required);\n }\n\n getChannel(name: string): Channel | null;\n getChannel(name: string, required: true): Channel;\n getChannel(name: string, required = false) {\n return this.assertOption<Channel>(name, required);\n }\n\n getRole(name: string): Role | null;\n getRole(name: string, required: true): Role;\n getRole(name: string, required = false) {\n return this.assertOption<Role>(name, required);\n }\n\n getMentionable(\n name: string)\n : NonNullable<CommandInteractionOption['member' | 'role' | 'user']> | null;\n getMentionable(\n name: string,\n required: true)\n : NonNullable<CommandInteractionOption['member' | 'role' | 'user']>;\n getMentionable(\n name: string,\n required = false)\n : NonNullable<CommandInteractionOption['member' | 'role' | 'user']> | null {\n const target = this.assertOption(name, required);\n\n if (\n target instanceof GuildMember ||\n target instanceof User ||\n target instanceof Role)\n {\n return target;\n }\n\n if (required) {\n throw new Error(`Mentionable \"${name}\" is required.`);\n }\n\n return null;\n }\n\n getSubcommand(): string | null;\n getSubcommand(required: true): string;\n getSubcommand(required = false) {\n const sub = this.parser.getSubcommand();\n\n if (required && sub === undefined) {\n throw new Error('Subcommand is required.');\n }\n\n return sub ?? null;\n }\n\n getSubcommandGroup(): string | null;\n getSubcommandGroup(required: true): string;\n getSubcommandGroup(required = false) {\n const sub = this.parser.getSubcommandGroup();\n\n if (required && sub === undefined) {\n throw new Error('Subcommand group is required.');\n }\n\n return sub ?? null;\n }\n}","export * from './CommandsRouter';\nexport * from './EventsRouter';","import { existsSync } from 'node:fs';\nimport { readdir } from 'node:fs/promises';\nimport { join } from 'node:path';\n\n/**\n * Matcher type for identifying command and middleware files.\n * Can be a string suffix (e.g. '.cmd.js'), RegExp pattern, or custom matcher function.\n */\nexport type CommandsRouterMatcher =\nstring |\nRegExp |\n((path: string) => boolean);\n\n/**\n * Maps file type identifiers to their respective matchers.\n * Used to identify command and middleware files in the directory structure.\n */\nexport type CommandsRouterMatchersMap = Record<\n 'command' | 'middleware',\n CommandsRouterMatcher>;\n\n\n/**\n * Configuration options for the CommandsRouter\n */\nexport interface CommandsRouterOptions {\n /**\n * The path to the directory containing the command files.\n */\n entrypoint: string;\n /**\n * The path to the directory containing the middleware files.\n */\n matcher?: Partial<CommandsRouterMatchersMap>;\n}\n\n/**\n * Represents a parsed command with its metadata\n * @interface ParsedCommand\n */\nexport interface ParsedCommand {\n /** Command name derived from the file name without extension */\n name: string;\n /** Absolute file system path to the command file */\n path: string;\n /** Parent command name for nested commands, or null if root-level command */\n parent: string | null;\n /** Array of command segments representing the command hierarchy */\n parentSegments: string[];\n /** Array of middleware IDs that apply to this command */\n middlewares: string[];\n /** Absolute path to this command */\n fullPath: string;\n}\n\n/**\n * Represents a parsed middleware with its metadata\n * @interface ParsedMiddleware\n */\nexport interface ParsedMiddleware {\n /** Unique identifier used to reference this middleware */\n id: string;\n /** Middleware name derived from the file path */\n name: string;\n /** Path to the middleware file, relative to the entrypoint */\n path: string;\n /** Absolute path to the middleware file */\n fullPath: string;\n}\n\n/**\n * Complete tree structure of all commands and middleware\n * @interface CommandsTree\n */\nexport interface CommandsTree {\n /** Map of command names to their parsed metadata */\n commands: Record<string, ParsedCommand>;\n /** Map of middleware IDs to their parsed metadata */\n middleware: Record<string, ParsedMiddleware>;\n}\n\n/**\n * Result of a successful command match operation\n * @interface CommandMatchResult\n */\nexport interface CommandMatchResult {\n /** The matched command metadata */\n command: ParsedCommand;\n /** Array of middleware that apply to the matched command */\n middlewares: ParsedMiddleware[];\n}\n\n/**\n * CommandsRouter handles the discovery and routing of commands and middleware files\n * in a directory structure. It supports nested commands and middleware inheritance.\n */\nexport class CommandsRouter {\n private commands = new Map<string, ParsedCommand>();\n private middlewares = new Map<string, ParsedMiddleware>();\n\n /**\n * Creates a new CommandsRouter instance\n * @param options - Configuration options for the router\n */\n public constructor(private readonly options: CommandsRouterOptions) {\n if (!options.entrypoint) {\n throw new Error('Entrypoint directory must be provided');\n }\n\n options.matcher ??= {};\n options.matcher.command ??= /command\\.(m|c)?(j|t)sx?$/;\n options.matcher.middleware ??= /middleware\\.(m|c)?(j|t)sx?$/;\n }\n\n /**\n * Gets the configured entrypoint directory\n */\n public get entrypoint(): string {\n return this.options.entrypoint;\n }\n\n /**\n * Gets the configured matchers for command and middleware files\n */\n public get matchers(): CommandsRouterMatchersMap {\n return this.options.matcher as CommandsRouterMatchersMap;\n }\n\n /**\n * Returns the cached data of the commands and middleware\n */\n public getData() {\n return {\n commands: this.commands,\n middleware: this.middlewares\n };\n }\n\n /**\n * Checks if the entrypoint path is valid\n */\n public isValidPath() {\n return existsSync(this.entrypoint);\n }\n\n /**\n * Executes a matcher against a file path\n * @param matcher - The matcher to use\n * @param path - The file path to test\n * @returns boolean indicating if the path matches\n */\n private execMatcher(matcher: CommandsRouterMatcher, path: string): boolean {\n if (typeof matcher === 'string') {\n return path.endsWith(matcher);\n }\n\n if (matcher instanceof RegExp) {\n return matcher.test(path);\n }\n\n return matcher(path);\n }\n\n /**\n * Converts an absolute path to a path relative to the entrypoint\n * @param path - The absolute path to convert\n */\n private resolveRelativePath(path: string): string {\n const regex = new RegExp(`^${this.entrypoint}`);\n return path.replace(regex, '');\n }\n\n /**\n * Matches a command by name or path segments\n * @param commandOrSegment - Command name or array of path segments\n * @returns Matched command and its middlewares, or null if no match\n */\n public match(commandOrSegment: string | string[]): CommandMatchResult | null {\n if (!commandOrSegment?.length) return null;\n\n if (Array.isArray(commandOrSegment) && commandOrSegment.length === 1) {\n commandOrSegment = commandOrSegment[0];\n }\n\n if (!Array.isArray(commandOrSegment) && !commandOrSegment.includes(' ')) {\n const command = this.commands.get(commandOrSegment);\n if (!command) return null;\n\n const middlewares = command.middlewares.\n map((id) => this.middlewares.get(id)).\n filter((m): m is ParsedMiddleware => !!m);\n\n return {\n command,\n middlewares\n };\n }\n\n const segments = Array.isArray(commandOrSegment) ?\n commandOrSegment :\n commandOrSegment.split(' ');\n\n const command = Array.from(this.commands.values()).find((cmd) => {\n const commandSegments = cmd.parentSegments;\n\n if (commandSegments.length !== segments.length) return false;\n\n return commandSegments.every((segment, index) => {\n if (segment === '[name]') return true;\n return segment === segments[index];\n });\n });\n\n if (!command) return null;\n\n const middlewares = command.middlewares.\n map((id) => this.middlewares.get(id)).\n filter((m): m is ParsedMiddleware => !!m);\n\n return {\n command,\n middlewares\n };\n }\n\n /**\n * Reloads the commands tree by re-scanning the entrypoint directory\n */\n public async reload(): Promise<CommandsTree> {\n this.clear();\n return this.scan();\n }\n\n /**\n * Clears the internal commands and middleware maps\n */\n public clear(): void {\n this.commands.clear();\n this.middlewares.clear();\n }\n\n /**\n * Scans the entrypoint directory for commands and middleware\n * @returns Promise resolving to the complete commands tree\n */\n public async scan(): Promise<CommandsTree> {\n const files = await this.scanDirectory(this.entrypoint, []);\n\n for (const file of files) {\n if (this.execMatcher(this.matchers.command, file)) {\n const location = this.resolveRelativePath(file);\n const parts = location.split('/');\n\n const parentSegments: string[] = [];\n\n parts.forEach((part, index, arr) => {\n const isLast = index === arr.length - 1;\n\n // ignore last because it's definitely a command source file\n if (isLast) return;\n\n // we ignore groups\n if (!/\\(.+\\)/.test(part)) {\n parentSegments.push(part.trim());\n }\n });\n\n const parent = parentSegments.join(' ');\n const name = parts[parts.length - 1].replace(/\\.(m|c)?(j|t)sx?$/, '');\n\n const command: ParsedCommand = {\n name,\n middlewares: [],\n parent: parent || null,\n path: location,\n fullPath: file,\n parentSegments\n };\n\n this.commands.set(name, command);\n }\n\n if (this.execMatcher(this.matchers.middleware, file)) {\n const location = this.resolveRelativePath(file);\n const name = location.replace(/\\.(m|c)?(j|t)sx?$/, '');\n\n const command = Array.from(this.commands.values()).filter((command) =>\n command.path.startsWith(location)\n );\n\n const id = crypto.randomUUID();\n\n const middleware: ParsedMiddleware = {\n id,\n name,\n path: location,\n fullPath: file\n };\n\n this.middlewares.set(id, middleware);\n\n command.forEach((cmd) => {\n cmd.middlewares.push(id);\n });\n }\n }\n\n return this.toJSON();\n }\n\n /**\n * Converts the internal maps to a serializable object\n * @returns CommandsTree containing all commands and middleware\n */\n public toJSON(): CommandsTree {\n return {\n commands: Object.fromEntries(this.commands),\n middleware: Object.fromEntries(this.middlewares)\n };\n }\n\n /**\n * Recursively scans a directory for files\n * @param dir - Directory to scan\n * @param entries - Accumulator for found files\n * @returns Promise resolving to array of file paths\n */\n private async scanDirectory(\n dir: string,\n entries: string[])\n : Promise<string[]> {\n const files = await readdir(dir, {\n withFileTypes: true\n });\n\n for (const file of files) {\n // for whatever reason\n if (\n file.name === 'node_modules' ||\n file.parentPath.includes('node_modules'))\n {\n continue;\n }\n\n if (file.isDirectory()) {\n const next = join(dir, file.name);\n await this.scanDirectory(next, entries);\n continue;\n }\n\n entries.push(join(dir, file.name));\n }\n\n return entries;\n }\n}","import { 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 entrypoint: 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}\n\n/** Map 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 Map<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.entrypoint) {\n throw new Error('Entrypoint directory must be provided');\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 entrypoint(): string {\n return this.options.entrypoint;\n }\n\n /**\n * Checks if the entrypoint path is valid\n */\n public isValidPath() {\n return existsSync(this.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 const dirs = await readdir(this.entrypoint, { withFileTypes: true });\n\n for (const dir of dirs) {\n if (dir.isDirectory()) {\n const path = join(this.entrypoint, dir.name);\n const event = await this.scanEvent(dir.name, path);\n this.events.set(event.event, event);\n }\n }\n\n return Object.fromEntries(this.events);\n }\n\n /**\n * Convert the internal events map 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 listeners: string[] = [])\n : Promise<ParsedEvent> {\n const files = await readdir(path, { withFileTypes: true });\n\n for (const file of files) {\n if (/node_modules/.test(file.name)) continue;\n\n if (file.isDirectory()) {\n const nextPath = join(path, file.name);\n await this.scanEvent(event, nextPath, 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 return { event, path, listeners };\n }\n}","export interface CommandKitConfig {\n /**\n * The source directory of the project.\n */\n src: string;\n /**\n * The main \"javascript\" file of the project.\n */\n main: string;\n /**\n * Whether or not to use the watch mode. Defaults to `true`.\n */\n watch: boolean;\n /**\n * The output directory of the project. Defaults to `dist`.\n */\n outDir: string;\n /**\n * Whether or not to include extra env utilities. Defaults to `true`.\n */\n envExtra: boolean;\n /**\n * Node.js cli options.\n */\n nodeOptions: string[];\n /**\n * Whether or not to clear default restart logs. Defaults to `true`.\n */\n clearRestartLogs: boolean;\n /**\n * Whether or not to minify the output. Defaults to `false`.\n */\n minify: boolean;\n /**\n * Whether or not to include sourcemaps in production build. Defaults to `false`.\n */\n sourcemap: boolean | 'inline';\n /**\n * Whether or not to include anti-crash handler in production. Defaults to `true`.\n */\n antiCrash: boolean;\n /**\n * Whether or not to polyfill `require` function. Defaults to `true`.\n */\n requirePolyfill: boolean;\n}\n\nlet globalConfig: Partial<CommandKitConfig> = {\n envExtra: true,\n outDir: 'dist',\n watch: true,\n clearRestartLogs: true,\n minify: false,\n sourcemap: false,\n nodeOptions: [],\n antiCrash: true,\n requirePolyfill: true\n};\n\nexport function getConfig(): CommandKitConfig {\n return globalConfig as CommandKitConfig;\n}\n\nconst requiredProps = ['src', 'main'] as const;\n\ntype R = (typeof requiredProps)[number];\n\ntype PartialConfig<T extends CommandKitConfig> = Partial<Omit<T, R>> &\nPick<T, R>;\n\nexport function defineConfig(config: PartialConfig<CommandKitConfig>) {\n for (const prop of requiredProps) {\n if (!config[prop]) {\n throw new Error(\n `[CommandKit Config] Missing required config property: ${prop}`\n );\n }\n }\n\n globalConfig = {\n ...globalConfig,\n ...config\n };\n\n return globalConfig;\n}","export * from './CacheProvider';\nexport * from './MemoryCache';\nexport * from './cache';","import { AsyncLocalStorage } from 'node:async_hooks';\nimport ms from 'ms';\nimport { GenericFunction, getCommandKit } from '../context/async-context';\nimport { randomUUID } from 'node:crypto';\n\nexport type AsyncFunction<R extends any[] = any[], T = any> = (\n...args: R)\n=> Promise<T>;\n\nexport interface CacheTag {\n tag: string;\n ttl: number | string;\n}\n\nexport interface CacheParams extends CacheTag {\n target: GenericFunction;\n memo: GenericFunction;\n}\n\ninterface CacheContext {\n target: GenericFunction;\n params: CacheTag;\n memo?: GenericFunction;\n}\n\nconst CACHED_FUNCTIONS_STORE = new WeakMap<Function, CacheParams>();\nconst TAG_FUNCTION_MAP = new Map<string, Function>();\nconst DEFAULT_TTL = ms('15m');\n\nconst cacheContext = new AsyncLocalStorage<CacheContext>();\n\nconst __identificationKey = `__cache_identification_key_${Date.now()}__${Math.random()}__`;\n\nconst getDefaultCacheTag = (): CacheTag => {\n return {\n tag: randomUUID(),\n ttl: DEFAULT_TTL\n };\n};\n\n/**\n * Cache a function with a specific tag and time-to-live.\n * @param fn The function to cache.\n * @param params The cache tag and time-to-live.\n * @returns The memoized function.\n */\nfunction cache<R extends any[], F extends AsyncFunction<R>>(\nfn: F,\nparams?: Partial<CacheTag>)\n: F {\n params = Object.assign({}, getDefaultCacheTag(), params);\n\n return useCache(fn, __identificationKey, params as CacheTag);\n}\n\n/**\n * **DO NOT USE THIS FUNCTION DIRECTLY**\n * @internal\n * @private\n */\nfunction useCache<R extends any[], F extends AsyncFunction<R>>(\nfn: F,\nid?: string,\ntag?: CacheTag)\n: F {\n if (id !== undefined && id !== __identificationKey) {\n throw new TypeError('useCache may not be called directly.');\n }\n\n const isLocal = id === __identificationKey;\n\n const memoized = (async (...args) => {\n const commandkit = getCommandKit(true);\n const cache = commandkit.getCacheProvider();\n\n if (!cache) {\n throw new Error(\n 'CacheProvider was not found, please provide a cache provider to the CommandKit instance.'\n );\n }\n\n const context = cacheContext.getStore();\n\n if (context === undefined) {\n throw new Error(\n 'useCache must be called inside a function decorated with \"use cache\" directive.'\n );\n }\n\n const entryKey = context.params.tag;\n const entry = await cache.get(entryKey);\n\n // cache hit\n if (entry !== undefined) {\n return entry.value;\n }\n\n const ttl =\n typeof context.params.ttl === 'string' ?\n ms(context.params.ttl) :\n context.params.ttl;\n\n const writeCache = async (...args: any) => {\n const result = await fn(...args);\n\n CACHED_FUNCTIONS_STORE.set(fn, {\n ...context.params,\n target: fn,\n memo: cacheContext.exit(() => wrapper)\n });\n\n if (entryKey !== context.params.tag) {\n TAG_FUNCTION_MAP.delete(entryKey);\n }\n\n TAG_FUNCTION_MAP.set(context.params.tag, fn);\n\n await cache.set(entryKey, result, ttl);\n\n return result;\n };\n\n CACHED_FUNCTIONS_STORE.set(fn, {\n ...context.params,\n target: fn,\n memo: cacheContext.exit(() => wrapper)\n });\n\n TAG_FUNCTION_MAP.set(entryKey, fn);\n\n return writeCache(...args);\n }) as F;\n\n const wrapper = (async (...args: any) => {\n const params =\n CACHED_FUNCTIONS_STORE.get(fn) ?? (\n (isLocal ? tag : null) || getDefaultCacheTag());\n\n return cacheContext.run(\n {\n params,\n target: fn\n },\n () => memoized(...args)\n );\n }) as F;\n\n return wrapper;\n}\n\n/**\n * Tags the current function with the given cache tag name\n * @param tag The cache tag name.\n */\nfunction cacheTag(tag: string): void;\n/**\n * Tags the current function with the given cache tag parameters.\n * @param tag The cache tag parameters.\n */\nfunction cacheTag(tag: CacheTag): void;\n/**\n * Tags the current function with the given cache tag name or parameters.\n * @param tag The cache tag name or parameters.\n */\nfunction cacheTag(tag: CacheTag | string): void {\n if (!tag) {\n throw new TypeError('cacheTag must be called with a tag.');\n }\n\n const context = cacheContext.getStore();\n\n if (context === undefined) {\n throw new Error(\n 'cacheTag must be called inside cache() or a function decorated with \"use cache\" directive.'\n );\n }\n\n let tagObj: CacheTag;\n\n if (typeof tag === 'string') {\n tagObj = {\n tag,\n ttl: context.params?.ttl ?? DEFAULT_TTL\n };\n } else {\n tagObj = tag;\n }\n\n context.params = tagObj;\n}\n\n/**\n * Sets the time-to-live for the current cache tag.\n * @param life The time-to-live value in milliseconds or a string.\n */\nfunction cacheLife(life: string): void;\nfunction cacheLife(life: number): void;\nfunction cacheLife(life: string | number) {\n if (life == null) {\n throw new TypeError('cacheLife must be called with a time-to-live value.');\n }\n\n const context = cacheContext.getStore();\n\n if (context === undefined) {\n throw new Error(\n 'cacheLife must be called inside cache() or a function decorated with \"use cache\" directive.'\n );\n }\n\n if (typeof life === 'string') {\n context.params.ttl = ms(life);\n } else {\n context.params.ttl = life;\n }\n}\n\n/**\n * Invalidates the cache with the given tag.\n * This will immediately remove the cache entry. The next time cache is requested, it will be re-fetched.\n * @param tag The cache tag to invalidate.\n */\nasync function invalidate(tag: string) {\n const commandkit = getCommandKit(true);\n const cache = commandkit.getCacheProvider();\n\n if (!cache) {\n throw new Error(\n 'CacheProvider was not found, please provide a cache provider to the CommandKit instance.'\n );\n }\n\n await cache.delete(tag);\n}\n\n/**\n * Revalidates the cache with the given tag.\n * This will immediately remove the cache entry and re-fetch the value.\n * @param tag The cache tag to revalidate.\n * @param args The arguments to pass to the memoized function (if any).\n * @returns The new value of the cache.\n */\nasync function revalidate<R = any>(\ntag: string,\n...args: any[])\n: Promise<R | undefined> {\n const commandkit = getCommandKit(true);\n const cache = commandkit.getCacheProvider();\n\n if (!cache) {\n throw new Error(\n 'CacheProvider was not found, please provide a cache provider to the CommandKit instance.'\n );\n }\n\n await cache.delete(tag);\n\n const tagFn = TAG_FUNCTION_MAP.get(tag);\n if (!tagFn) return undefined;\n\n const ctx = CACHED_FUNCTIONS_STORE.get(tagFn);\n if (!ctx) return undefined;\n\n return ctx.memo(...args) as R;\n}\n\nexport {\n cache,\n useCache as super_duper_secret_internal_for_use_cache_directive_of_commandkit_cli_do_not_use_it_directly_or_you_will_be_fired_from_your_job_kthxbai,\n cacheTag,\n cacheLife,\n invalidate,\n revalidate };","export * from './command-handler/AppCommandHandler';\nexport * from './commands/Context';\nexport * from './commands/MessageCommandParser';\nexport * from './i18n/DefaultLocalizationStrategy';\nexport * from './i18n/Localization';\nexport * from './i18n/LocalizationStrategy';\nexport * from './i18n/Translation';\nexport * from './middleware/signals';","import type { Locale } from 'discord.js';\nimport type { Translation } from './Translation';\n\nexport interface LocalizationTranslationRequest {\n locale: Locale;\n scope: string;\n key: string;\n args?: Record<string, any> | undefined;\n}\n\nexport type TranslationResult = string;\n\nexport interface LocalizationStrategy {\n locateTranslation(scope: string, locale: Locale): Promise<Translation | null>;\n getTranslation(scope: string, locale: Locale): Promise<Translation | null>;\n getTranslationStrict(scope: string, locale: Locale): Promise<Translation>;\n translate(\n request: LocalizationTranslationRequest)\n : Promise<TranslationResult>;\n}","export interface TranslatableCommand {\n name?: string;\n description?: string;\n options?: TranslatableCommandOptions[];\n}\n\nexport interface TranslatableCommandOptions {\n ref: string;\n name?: string;\n description?: string;\n}\n\nexport interface Translation {\n command: TranslatableCommand;\n translations: TranslatableArguments;\n}\n\nexport type TranslatableArguments = Record<string, string>;","import {\n CommandKitErrorCodes,\n createCommandKitError,\n isCommandKitError } from\n'../../utils/error-codes';\n\n/**\n * Cancel upcoming middleware execution.\n * If this is called inside pre-stage middleware, the next run will be the actual command, skipping all other pre-stage middlewares.\n * If this is called inside a command itself, it will skip all post-stage middlewares.\n * If this is called inside post-stage middleware, it will skip all other post-stage middlewares.\n */\nexport function exitMiddleware(): never {\n throw createCommandKitError(CommandKitErrorCodes.ExitMiddleware);\n}\n\n/**\n * Rethrow the error if it is a CommandKit error.\n * @param error The error to rethrow.\n */\nexport function rethrow(error: unknown): void {\n if (isCommandKitError(error)) throw error;\n}","/**\n * Creates a command line interface for CommandKit.\n * @param argv The arguments passed to the CLI.\n * @param options The options passed to the CLI.\n */\nexport async function bootstrapCommandkitCLI(\nargv: string[],\noptions?: import('commander').ParseOptions | undefined)\n{\n const { Command } = await import('commander');\n const { bootstrapDevelopmentServer } = await import('./development');\n const { bootstrapProductionServer } = await import('./production');\n const { bootstrapProductionBuild } = await import('./build');\n\n const program = new Command('commandkit');\n\n program.\n command('dev').\n description('Start your bot in development mode.').\n option(\n '-c, --config <path>',\n 'Path to your commandkit config file.',\n './commandkit.js'\n ).\n action(() => {\n const options = program.opts();\n bootstrapDevelopmentServer(options);\n });\n\n program.\n command('start').\n description(\n 'Start your bot in production mode after running the build command.'\n ).\n option(\n '-c, --config <path>',\n 'Path to your commandkit.json file.',\n './commandkit.js'\n ).\n action(() => {\n const options = program.opts();\n bootstrapProductionServer(options.config);\n });\n\n program.\n command('build').\n description('Build your project for production usage.').\n option(\n '-c, --config <path>',\n 'Path to your commandkit.json file.',\n './commandkit.json'\n ).\n action(() => {\n const options = program.opts();\n bootstrapProductionBuild(options.config);\n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AAQ,WAmBF,QAAmC","names":["fs","path","import_node_path","import_node_fs","resetColor","import_node_crypto","_traverse","_generate","path","import_promises","build","ora","path","import_promises","import_node_path","ora","dotenv","child_process","import_node_path","import_tsup","import_ora","dotenv","child_process","import_dotenv","import_node_fs","import_node_path","import_node_child_process","import_discord","rfdc","fs","path","import_path","path","import_discord","import_discord","CommandKitEnvironmentType","_data","path","context","canRun","env","_data","path","_data","path","import_discord","import_discord","myCustomId","import_discord","import_discord","_contextData","_unsub","getEventInterceptor_fn","destroyCollector_fn","import_discord","import_discord","import_promises","path","import_node_path","import_node_path","import_discord","import_discord","parser","parser","loadedCommand","import_node_fs","import_promises","import_node_path","path","command","middlewares","import_node_fs","import_promises","import_node_path","path","_data","EventEmitter","appDir","import_node_async_hooks","import_node_crypto","ms","cache","context","args","bootstrapDevelopmentServer","bootstrapProductionServer","bootstrapProductionBuild","options"]}
1
+ {"version":3,"sources":["../../../node_modules/.pnpm/tsup@8.3.5_jiti@1.21.7_postcss@8.4.49_tsx@4.19.2_typescript@5.7.3_yaml@2.7.0/node_modules/tsup/assets/cjs_shims.js","../src/cli/common.ts","../src/cli/parse-env.ts","../src/cli/esbuild-plugins/use-cache.ts","../src/cli/esbuild-plugins/plugin.ts","../src/cli/build.ts","../src/cli/development.ts","../src/cli/production.ts","../src/index.ts","../src/CommandKit.ts","../src/legacy/handlers/index.ts","../src/legacy/handlers/command-handler/CommandHandler.ts","../src/utils/clone.ts","../src/utils/colors.ts","../src/utils/get-paths.ts","../src/utils/resolve-file-url.ts","../src/legacy/handlers/command-handler/functions/loadCommandsWithRest.ts","../src/legacy/handlers/command-handler/functions/registerCommands.ts","../src/legacy/handlers/command-handler/utils/areSlashCommandsDifferent.ts","../src/legacy/handlers/command-handler/validations/index.ts","../src/legacy/handlers/command-handler/validations/devOnly.ts","../src/legacy/handlers/command-handler/validations/permissions.ts","../src/context/async-context.ts","../src/utils/error-codes.ts","../src/context/environment.ts","../src/app/commands/Context.ts","../src/app/i18n/Localization.ts","../src/legacy/handlers/event-handler/EventHandler.ts","../src/legacy/handlers/validation-handler/ValidationHandler.ts","../src/cache/CacheProvider.ts","../src/cache/MemoryCache.ts","../src/components/index.ts","../src/components/action-row/ActionRow.ts","../src/components/button/ButtonKit.ts","../src/components/button/Button.ts","../src/components/modal/ModalKit.ts","../src/components/modal/Modal.ts","../src/components/common/element.ts","../src/utils/warn-unstable.ts","../src/components/common/types.ts","../src/components/common/EventInterceptor.ts","../src/app/i18n/DefaultLocalizationStrategy.ts","../src/utils/utilities.ts","../src/utils/constants.ts","../src/app/command-handler/AppCommandHandler.ts","../src/app/commands/MessageCommandParser.ts","../src/app/router/index.ts","../src/app/router/CommandsRouter.ts","../src/app/router/EventsRouter.ts","../src/config.ts","../src/cache/index.ts","../src/cache/cache.ts","../src/app/index.ts","../src/app/i18n/LocalizationStrategy.ts","../src/app/i18n/Translation.ts","../src/app/middleware/signals.ts","../src/cli/init.ts"],"sourcesContent":["// Shim globals in cjs bundle\n// There's a weird bug that esbuild will always inject importMetaUrl\n// if we export it as `const importMetaUrl = ... __filename ...`\n// But using a function will not cause this issue\n\nconst getImportMetaUrl = () =>\ntypeof document === 'undefined' ?\nnew URL(`file:${__filename}`).href :\ndocument.currentScript && document.currentScript.src ||\nnew URL('main.js', document.baseURI).href;\n\nexport const importMetaUrl = /* @__PURE__ */getImportMetaUrl();","// @ts-check\n\nimport { rimrafSync } from 'rimraf';\nimport { join } from 'node:path';\nimport fs from 'node:fs';\n\nconst resetColor = '\\x1b[0m';\n\nexport const Colors = {\n reset: (text: string) => `${text}${resetColor}`,\n bright: (text: string) => `\\x1b[1m${text}${resetColor}`,\n dim: (text: string) => `\\x1b[2m${text}${resetColor}`,\n underscore: (text: string) => `\\x1b[4m${text}${resetColor}`,\n blink: (text: string) => `\\x1b[5m${text}${resetColor}`,\n reverse: (text: string) => `\\x1b[7m${text}${resetColor}`,\n hidden: (text: string) => `\\x1b[8m${text}${resetColor}`,\n\n black: (text: string) => `\\x1b[30m${text}${resetColor}`,\n red: (text: string) => `\\x1b[31m${text}${resetColor}`,\n green: (text: string) => `\\x1b[32m${text}${resetColor}`,\n yellow: (text: string) => `\\x1b[33m${text}${resetColor}`,\n blue: (text: string) => `\\x1b[34m${text}${resetColor}`,\n magenta: (text: string) => `\\x1b[35m${text}${resetColor}`,\n cyan: (text: string) => `\\x1b[36m${text}${resetColor}`,\n white: (text: string) => `\\x1b[37m${text}${resetColor}`,\n\n bgBlack: (text: string) => `\\x1b[40m${text}${resetColor}`,\n bgRed: (text: string) => `\\x1b[41m${text}${resetColor}`,\n bgGreen: (text: string) => `\\x1b[42m${text}${resetColor}`,\n bgYellow: (text: string) => `\\x1b[43m${text}${resetColor}`,\n bgBlue: (text: string) => `\\x1b[44m${text}${resetColor}`,\n bgMagenta: (text: string) => `\\x1b[45m${text}${resetColor}`,\n bgCyan: (text: string) => `\\x1b[46m${text}${resetColor}`,\n bgWhite: (text: string) => `\\x1b[47m${text}${resetColor}`\n};\n\nexport function write(message: any) {\n process.stdout.write(message);\n process.stdout.write('\\n');\n}\n\n/**\n * @returns {never}\n */\nexport function panic(message: any) {\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\nconst possibleFileNames = [\n'commandkit.json',\n'commandkit.config.json',\n'commandkit.js',\n'commandkit.config.js',\n'commandkit.mjs',\n'commandkit.config.mjs',\n'commandkit.cjs',\n'commandkit.config.cjs',\n'commandkit.ts',\n'commandkit.mts',\n'commandkit.cts'];\n\n\nexport async function findCommandKitConfig(src: string) {\n const cwd = process.cwd();\n const locations = src ?\n [join(cwd, src)] :\n possibleFileNames.map((name) => join(cwd, name));\n\n for (const location of locations) {\n try {\n return await loadConfigInner(location);\n } catch (e) {\n continue;\n }\n }\n\n panic(`Could not locate commandkit config from ${cwd}`);\n}\n\nfunction ensureTypeScript(target: string) {\n const isTypeScript = /\\.(c|m)tsx?$/.test(target);\n\n if (isTypeScript && !process.features.typescript) {\n panic(\n 'You are trying to load commandkit config file that is written in typescript. The current Node.js version does not have TypeScript feature enabled.'\n );\n }\n}\n\nasync function loadConfigInner(target: string) {\n const isJSON = target.endsWith('.json');\n\n await ensureExists(target);\n\n ensureTypeScript(target);\n\n /**\n * @type {import('..').CommandKitConfig}\n */\n // @ts-ignore\n const config = await import(`file://${target}`, {\n with: isJSON ? { type: 'json' } : undefined\n }).then((conf) => conf.default || conf);\n\n return config;\n}\n\nasync function ensureExists(loc: string) {\n await fs.promises.access(loc, fs.constants.F_OK);\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', 'src/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}","// @ts-check\n\nimport { randomUUID } from 'node:crypto';\n\nconst valuesMap = {\n true: true,\n false: false,\n null: null,\n undefined: undefined,\n __UUIDv4__: () => randomUUID()\n};\n\nconst VALUE_PREFIXES = {\n JSON: 'JSON::',\n DATE: 'DATE::'\n};\n\nfunction catcher(fn: Function) {\n try {\n fn();\n return true;\n } catch {\n return false;\n }\n}\n\nexport function parseEnv(src: any) {\n for (const key in src) {\n const value = src[key];\n\n if (typeof value !== 'string') continue;\n\n if (value.startsWith(VALUE_PREFIXES.JSON)) {\n catcher(\n () => src[key] = JSON.parse(value.replace(VALUE_PREFIXES.JSON, ''))\n );\n continue;\n }\n\n if (value.startsWith(VALUE_PREFIXES.DATE)) {\n src[key] = new Date(value.replace(VALUE_PREFIXES.DATE, ''));\n continue;\n }\n\n if (value.includes(',')) {\n src[key] = value.split(',').map((v) => v.trim());\n continue;\n }\n\n if (/^[0-9]+n$/.test(value)) {\n src[key] = BigInt(value);\n continue;\n }\n\n if (value in valuesMap) {\n src[key] =\n // @ts-ignore\n typeof valuesMap[value] === 'function' ?\n // @ts-ignore\n valuesMap[value]() :\n // @ts-ignore\n valuesMap[value];\n continue;\n }\n }\n\n return src;\n}","import * as parser from '@babel/parser';\nimport _traverse from '@babel/traverse';\nimport _generate from '@babel/generator';\nimport * as t from '@babel/types';\n\n// @ts-ignore\nconst traverse = _traverse.default || _traverse;\n// @ts-ignore\nconst generate = _generate.default || _generate;\n\nconst IMPORT_PATH = 'commandkit';\nconst DIRECTIVE = 'use cache';\nconst CACHE_IDENTIFIER =\n'super_duper_secret_internal_for_use_cache_directive_of_commandkit_cli_do_not_use_it_directly_or_you_will_be_fired_from_your_job_kthxbai';\n\nconst generateRandomString = (length = 6) => {\n const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';\n return Array.from(\n { length },\n () => chars[Math.floor(Math.random() * chars.length)]\n ).join('');\n};\n\nexport const cacheDirectivePlugin = async (source: string, args: any) => {\n const ast = parser.parse(source, {\n sourceType: 'module',\n plugins: ['typescript', 'jsx']\n });\n\n let state = {\n needsImport: false,\n hasExistingImport: false,\n cacheIdentifierName: CACHE_IDENTIFIER,\n modifications: []\n };\n\n // First pass: check for naming collisions and collect modifications\n traverse(ast, {\n Program: {\n enter(path: any) {\n const binding = path.scope.getBinding(CACHE_IDENTIFIER);\n if (binding) {\n state.cacheIdentifierName = `${CACHE_IDENTIFIER}_${generateRandomString()}`;\n }\n }\n },\n\n ImportDeclaration(path: any) {\n if (\n path.node.source.value === IMPORT_PATH &&\n path.node.specifiers.some(\n (spec: any) =>\n t.isImportSpecifier(spec) &&\n // @ts-ignore\n spec.imported.name === CACHE_IDENTIFIER\n ))\n {\n state.hasExistingImport = true;\n if (state.cacheIdentifierName !== CACHE_IDENTIFIER) {\n // @ts-ignore\n state.modifications.push(() => {\n path.node.specifiers.forEach((spec: any) => {\n if (\n t.isImportSpecifier(spec) &&\n // @ts-ignore\n spec.imported.name === CACHE_IDENTIFIER)\n {\n spec.local.name = state.cacheIdentifierName;\n }\n });\n });\n }\n }\n },\n\n 'FunctionDeclaration|FunctionExpression|ArrowFunctionExpression'(\n path: any)\n {\n const body = t.isBlockStatement(path.node.body) ? path.node.body : null;\n const hasUseCache = body?.directives?.some(\n (d: any) => d.value.value === DIRECTIVE\n );\n\n if (!hasUseCache && !t.isBlockStatement(path.node.body)) {\n const parentFunction = path.findParent(\n (p: any) =>\n (p.isFunction() || p.isProgram()) && 'directives' in p.node\n );\n if (\n !parentFunction?.node.directives?.some(\n (d: any) => d.value.value === DIRECTIVE\n ))\n {\n return;\n }\n }\n\n if (hasUseCache || !t.isBlockStatement(path.node.body)) {\n // Check if the function is async\n if (!path.node.async) {\n throw new Error(\n `\"${DIRECTIVE}\" directive may only be used in async functions at ${args.path}`\n );\n }\n\n state.needsImport = true;\n const isDeclaration = t.isFunctionDeclaration(path.node);\n const name = isDeclaration ? path.node.id?.name : undefined;\n\n // Create a new body without the 'use cache' directive\n const newBody = t.isBlockStatement(path.node.body) ?\n t.blockStatement(\n path.node.body.body,\n path.node.body.directives.filter(\n (d: any) => d.value.value !== DIRECTIVE\n )\n ) :\n path.node.body;\n\n const wrapped = t.callExpression(\n t.identifier(state.cacheIdentifierName),\n [t.arrowFunctionExpression(path.node.params, newBody, true)]\n );\n\n // @ts-ignore\n state.modifications.push(() => {\n if (name) {\n path.replaceWith(\n t.variableDeclaration('const', [\n t.variableDeclarator(t.identifier(name), wrapped)]\n )\n );\n } else if (!t.isVariableDeclarator(path.parent)) {\n path.replaceWith(wrapped);\n } else {\n path.parent.init = wrapped;\n }\n });\n }\n }\n });\n\n // Apply all collected modifications\n if (state.modifications.length > 0) {\n // Add import if needed\n if (state.needsImport && !state.hasExistingImport) {\n ast.program.body.unshift(\n t.importDeclaration(\n [\n t.importSpecifier(\n t.identifier(state.cacheIdentifierName),\n t.identifier(CACHE_IDENTIFIER)\n )],\n\n t.stringLiteral(IMPORT_PATH)\n )\n );\n }\n\n // Apply collected modifications\n // @ts-ignore\n state.modifications.forEach((modify) => modify());\n }\n\n const { code } = generate(ast);\n return {\n contents: code,\n loader: args.path.split('.').pop()\n };\n};","import { MacroTransformer } from 'use-macro';\nimport { cacheDirectivePlugin } from './use-cache';\nimport { readFile } from 'node:fs/promises';\n\nconst defaultConfig = {\n 'use-macro': true,\n 'use-cache': true,\n 'jsx-importsource': true\n};\n\ninterface CommandKitEsbuildPluginConfig {\n 'use-macro'?: boolean;\n 'jsx-importsource'?: boolean;\n 'use-cache'?: boolean;\n}\n\nexport const commandkitPlugin = (config?: CommandKitEsbuildPluginConfig) => {\n config = Object.assign({}, defaultConfig, config);\n\n const plugins = [\n {\n name: 'use-macro',\n plugin: async (content: string, args: any) => {\n const transformer = new MacroTransformer();\n const { contents } = await transformer.transform(content, args.path);\n return contents;\n }\n },\n {\n name: 'use-cache',\n plugin: async (content: string, args: any) => {\n const { contents } = await cacheDirectivePlugin(content, args);\n return contents;\n }\n }].\n filter((p) => {\n return !!config[p.name as keyof CommandKitEsbuildPluginConfig];\n });\n\n return {\n name: 'commandkit-transformer-plugin',\n setup(build: any) {\n if (!plugins.length) return;\n\n const fileFilter = /\\.(c|m)?(t|j)sx?$/;\n\n build.onLoad({ filter: fileFilter }, async (args: any) => {\n const source = await readFile(args.path, 'utf8');\n const loader = args.path.split('.').pop();\n\n let contents = source;\n\n for (const _plugin of plugins) {\n const { plugin, name } = _plugin;\n try {\n contents = await plugin(contents, args);\n } catch (e) {\n const err = new Error(`Plugin ${name} failed with ${e}`);\n err.stack = e instanceof Error ? e.stack : '';\n\n throw err;\n }\n }\n\n return {\n contents,\n loader\n };\n });\n }\n };\n};","// @ts-check\n\nimport { readFile, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { build } from 'tsup';\nimport {\n Colors,\n copyLocaleFiles,\n erase,\n findCommandKitConfig,\n panic,\n write } from\n'./common.js';\nimport ora from 'ora';\nimport { commandkitPlugin } from './esbuild-plugins/plugin';\n\nexport async function bootstrapProductionBuild(config: any) {\n const {\n sourcemap = false,\n minify = false,\n outDir = 'dist',\n antiCrash = true,\n src,\n main,\n requirePolyfill: polyfillRequire\n } = await findCommandKitConfig(config);\n\n const status = ora('Creating optimized production build...\\n').start();\n const start = performance.now();\n\n erase(outDir);\n\n try {\n await build({\n clean: true,\n format: ['esm'],\n dts: false,\n skipNodeModulesBundle: true,\n minify,\n shims: true,\n banner: {\n js: '/* Optimized production build generated by CommandKit */'\n },\n sourcemap,\n keepNames: true,\n outDir,\n silent: true,\n watch: false,\n cjsInterop: true,\n splitting: false,\n entry: [src, '!dist', '!.commandkit', `!${outDir}`],\n esbuildPlugins: [commandkitPlugin()],\n jsxFactory: 'CommandKit.createElement',\n jsxFragment: 'CommandKit.Fragment',\n async onSuccess() {\n await copyLocaleFiles(src, '.commandkit');\n }\n });\n\n await injectShims(outDir, main, antiCrash, polyfillRequire);\n\n status.succeed(\n Colors.green(\n `Build completed in ${(performance.now() - start).toFixed(2)}ms!`\n )\n );\n write(\n Colors.green(\n `\\nRun ${Colors.magenta(`commandkit start`)} ${Colors.green(\n 'to start your bot.'\n )}`\n )\n );\n } catch (e) {\n status.fail(\n `Build failed after ${(performance.now() - start).toFixed(2)}ms!`\n );\n panic(e);\n }\n}\n\nexport async function injectShims(\noutDir: string,\nmain: string,\nantiCrash: boolean,\npolyfillRequire: boolean)\n{\n const path = join(process.cwd(), outDir, main);\n\n const head = ['\\n\\n;await (async()=>{', \" 'use strict';\"].join('\\n');\n const tail = '\\n})();';\n const requireScript = polyfillRequire ?\n [\n '// --- CommandKit require() polyfill ---',\n ' if (typeof require === \"undefined\") {',\n ' const { createRequire } = await import(\"node:module\");',\n ' const __require = createRequire(import.meta.url);',\n ' Object.defineProperty(globalThis, \"require\", {',\n ' value: (id) => {',\n ' return __require(id);',\n ' },',\n ' configurable: true,',\n ' enumerable: false,',\n ' writable: true,',\n ' });',\n ' }',\n '// --- CommandKit require() polyfill ---'].\n join('\\n') :\n '';\n\n const antiCrashScript = antiCrash ?\n [\n '// --- CommandKit Anti-Crash Monitor ---',\n \" // 'uncaughtException' event is supposed to be used to perform synchronous cleanup before shutting down the process\",\n ' // instead of using it as a means to resume operation.',\n ' // But it exists here due to compatibility reasons with discord bot ecosystem.',\n \" const p = (t) => `\\\\x1b[33m${t}\\\\x1b[0m`, b = '[CommandKit Anti-Crash Monitor]', l = console.log, e1 = 'uncaughtException', e2 = 'unhandledRejection';\",\n ' if (!process.eventNames().includes(e1)) // skip if it is already handled',\n ' process.on(e1, (e) => {',\n ' l(p(`${b} Uncaught Exception`)); l(p(b), p(e.stack || e));',\n ' })',\n ' if (!process.eventNames().includes(e2)) // skip if it is already handled',\n ' process.on(e2, (r) => {',\n ' l(p(`${b} Unhandled promise rejection`)); l(p(`${b} ${r.stack || r}`));',\n ' });',\n '// --- CommandKit Anti-Crash Monitor ---'].\n join('\\n') :\n '';\n\n const contents = await readFile(path, 'utf-8');\n const finalScript = [\n head,\n requireScript,\n antiCrashScript,\n tail,\n '\\n\\n',\n contents].\n join('\\n');\n\n return writeFile(path, finalScript);\n}","// @ts-check\nimport { config as dotenv } from 'dotenv';\nimport { join } from 'node:path';\nimport { build } from 'tsup';\nimport {\n Colors,\n copyLocaleFiles,\n erase,\n findCommandKitConfig,\n panic,\n write } from\n'./common';\nimport { parseEnv } from './parse-env';\nimport child_process from 'node:child_process';\nimport ora from 'ora';\nimport { injectShims } from './build';\nimport { commandkitPlugin } from './esbuild-plugins/plugin';\n\nconst RESTARTING_MSG_PATTERN = /^Restarting '|\".+'|\"\\n?$/;\nconst FAILED_RUNNING_PATTERN = /^Failed running '.+'|\"\\n?$/;\n\nexport async function bootstrapDevelopmentServer(opts: any) {\n const {\n src,\n main,\n watch = Boolean(opts.noWatch),\n nodeOptions = [],\n envExtra = true,\n clearRestartLogs = true,\n outDir,\n requirePolyfill\n } = await findCommandKitConfig(opts.config);\n\n if (!src) {\n panic('Could not find src in commandkit.json');\n }\n\n if (!main) {\n panic('Could not find main in commandkit.json');\n }\n\n const watchMode = watch;\n const status = ora(\n Colors.green('Starting a development server...\\n')\n ).start();\n const start = performance.now();\n\n if (watchMode && !nodeOptions.includes('--watch')) {\n nodeOptions.push('--watch');\n } else if (!watchMode && nodeOptions.includes('--watch')) {\n nodeOptions.splice(nodeOptions.indexOf('--watch'), 1);\n }\n\n if (!nodeOptions.includes('--enable-source-maps')) {\n nodeOptions.push('--enable-source-maps');\n }\n\n erase('.commandkit');\n\n try {\n await build({\n clean: true,\n format: ['esm'],\n dts: false,\n skipNodeModulesBundle: true,\n minify: false,\n shims: true,\n sourcemap: 'inline',\n keepNames: true,\n outDir: '.commandkit',\n silent: true,\n entry: [src, '!dist', '!.commandkit', `!${outDir}`].filter(Boolean),\n watch: watchMode,\n cjsInterop: true,\n splitting: false,\n jsxFactory: 'CommandKit.createElement',\n jsxFragment: 'CommandKit.Fragment',\n async onSuccess() {\n await copyLocaleFiles(src, '.commandkit');\n return await injectShims('.commandkit', main, false, requirePolyfill);\n },\n esbuildPlugins: [\n commandkitPlugin({\n 'use-macro': false\n })]\n\n });\n\n status.succeed(\n Colors.green(\n `Dev server started in ${(performance.now() - start).toFixed(2)}ms!\\n`\n )\n );\n\n if (watchMode) write(Colors.cyan('Watching for file changes...\\n'));\n\n const processEnv = {};\n\n const env = dotenv({\n path: join(process.cwd(), '.env'),\n processEnv\n });\n\n if (envExtra) {\n parseEnv(processEnv);\n }\n\n if (env.error) {\n write(Colors.yellow(`[DOTENV] Warning: ${env.error.message}`));\n }\n\n if (env.parsed) {\n write(Colors.blue('[DOTENV] Loaded .env file!'));\n }\n\n const ps: child_process.ChildProcessWithoutNullStreams =\n child_process.spawn(\n 'node',\n [...nodeOptions, join(process.cwd(), '.commandkit', main)],\n {\n env: {\n ...process.env,\n ...processEnv,\n NODE_ENV: 'development',\n // @ts-expect-error\n COMMANDKIT_DEV: true,\n // @ts-expect-error\n COMMANDKIT_PRODUCTION: false\n },\n cwd: process.cwd()\n }\n );\n\n let isLastLogRestarting = false,\n hasStarted = false;\n\n ps.stdout.on('data', (data) => {\n const message = data.toString();\n\n if (FAILED_RUNNING_PATTERN.test(message)) {\n write(Colors.cyan('Failed running the bot, waiting for changes...'));\n isLastLogRestarting = false;\n if (!hasStarted) hasStarted = true;\n return;\n }\n\n if (clearRestartLogs && !RESTARTING_MSG_PATTERN.test(message)) {\n write(message);\n isLastLogRestarting = false;\n } else {\n if (isLastLogRestarting || !hasStarted) {\n if (!hasStarted) hasStarted = true;\n return;\n }\n write(Colors.cyan('⌀ Restarting the bot...'));\n isLastLogRestarting = true;\n }\n\n if (!hasStarted) hasStarted = true;\n });\n\n ps.stderr.on('data', (data) => {\n const message = data.toString();\n\n if (\n message.includes(\n 'ExperimentalWarning: Watch mode is an experimental feature and might change at any time'\n ))\n\n return;\n\n write(Colors.red(message));\n });\n\n ps.on('close', (code) => {\n write('\\n');\n process.exit(code ?? 0);\n });\n\n ps.on('error', (err) => {\n panic(err);\n });\n } catch (e) {\n status.fail(\n `Error occurred after ${(performance.now() - start).toFixed(2)}ms!\\n`\n );\n panic(e instanceof Error ? e.stack : e);\n }\n}","// @ts-check\nimport { config as dotenv } from 'dotenv';\nimport { existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { Colors, findCommandKitConfig, panic, write } from './common';\nimport { parseEnv } from './parse-env';\nimport child_process from 'node:child_process';\n\nexport async function bootstrapProductionServer(config: any) {\n const {\n main,\n outDir = 'dist',\n envExtra = true,\n sourcemap\n } = await findCommandKitConfig(config);\n\n if (!existsSync(join(process.cwd(), outDir, main))) {\n panic(\n 'Could not find production build, maybe run `commandkit build` first?'\n );\n }\n\n try {\n const processEnv = {};\n\n const env = dotenv({\n path: join(process.cwd(), '.env'),\n processEnv\n });\n\n if (envExtra) {\n parseEnv(processEnv);\n }\n\n if (env.error) {\n write(Colors.yellow(`[DOTENV] Warning: ${env.error.message}`));\n }\n\n if (env.parsed) {\n write(Colors.blue('[DOTENV] Loaded .env file!'));\n }\n\n const ps: child_process.ChildProcessWithoutNullStreams =\n child_process.spawn(\n 'node',\n [\n sourcemap ? '--enable-source-maps' : '',\n join(process.cwd(), outDir, main)].\n filter(Boolean),\n {\n env: {\n ...process.env,\n ...processEnv,\n NODE_ENV: 'production',\n // @ts-expect-error\n COMMANDKIT_DEV: false,\n // @ts-expect-error\n COMMANDKIT_PROD: true\n },\n cwd: process.cwd()\n }\n );\n\n ps.stdout.on('data', (data) => {\n write(data.toString());\n });\n\n ps.stderr.on('data', (data) => {\n write(Colors.red(data.toString()));\n });\n\n ps.on('close', (code) => {\n write('\\n');\n process.exit(code ?? 0);\n });\n\n ps.on('error', (err) => {\n panic(err);\n });\n } catch (e) {\n panic(e);\n }\n}","import { CommandKit } from './CommandKit';\n\nexport default CommandKit;\n\nexport * from './CommandKit';\nexport * from './components';\nexport * from './config';\nexport * from './context/async-context';\nexport * from './context/environment';\nexport * from './cache/index';\nexport * from './app/index';\nexport type * from './types';\n\n\n\n\n\n\n/**\n * The current version of CommandKit.\n */\nexport const version = /* @__MACRO__ $version */\"0.1.11-dev.20250214040728\";\n\n// cli\nexport { bootstrapCommandkitCLI } from './cli/init';","import EventEmitter from 'node:events';\nimport {\n CommandHandler,\n EventHandler,\n ValidationHandler } from\n'./legacy/handlers';\nimport type {\n CommandKitData,\n CommandKitOptions,\n CommandObject,\n ReloadOptions } from\n'./types';\nimport colors from './utils/colors';\nimport { CacheProvider } from './cache/CacheProvider';\nimport { MemoryCache } from './cache/MemoryCache';\nimport { createElement, Fragment } from './components';\nimport { EventInterceptor } from './components/common/EventInterceptor';\nimport { Awaitable, Locale, Message } from 'discord.js';\nimport { DefaultLocalizationStrategy } from './app/i18n/DefaultLocalizationStrategy';\nimport { findAppDirectory } from './utils/utilities';\nimport { join } from 'node:path';\nimport { AppCommandHandler } from './app/command-handler/AppCommandHandler';\nimport { LocalizationStrategy } from './app/i18n/LocalizationStrategy';\nimport { CommandsRouter, EventsRouter } from './app/router';\n\nexport interface CommandKitConfiguration {\n defaultLocale: Locale;\n localizationStrategy: LocalizationStrategy;\n getMessageCommandPrefix: (message: Message) => Awaitable<string | string[]>;\n}\n\nexport class CommandKit extends EventEmitter {\n #data: CommandKitData;\n public readonly eventInterceptor: EventInterceptor;\n\n public static readonly createElement = createElement;\n public static readonly Fragment = Fragment;\n\n public readonly config: CommandKitConfiguration = {\n defaultLocale: Locale.EnglishUS,\n localizationStrategy: new DefaultLocalizationStrategy(this),\n getMessageCommandPrefix: () => '!'\n };\n\n public commandsRouter!: CommandsRouter;\n public eventsRouter!: EventsRouter;\n public appCommandsHandler = new AppCommandHandler(this);\n\n static instance: CommandKit | undefined = undefined;\n\n /**\n * Create a new command and event handler with CommandKit.\n *\n * @param options - The default CommandKit configuration.\n * @see {@link https://commandkit.js.org/docs/guide/commandkit-setup}\n */\n constructor(options: CommandKitOptions) {\n if (CommandKit.instance) {\n process.emitWarning(\n 'CommandKit instance already exists. Having multiple instance in same project is discouraged and it may lead to unexpected behavior.',\n {\n code: 'MultiInstanceWarning'\n }\n );\n }\n\n if (!options.client) {\n throw new Error(\n colors.red('\"client\" is required when instantiating CommandKit.')\n );\n }\n\n if (options.validationsPath && !options.commandsPath) {\n throw new Error(\n colors.red('\"commandsPath\" is required when \"validationsPath\" is set.')\n );\n }\n\n super();\n\n options.debugCommands ??= process.env.NODE_ENV !== 'production';\n\n if (\n options.cacheProvider !== null && (\n !options.cacheProvider ||\n !(options.cacheProvider instanceof CacheProvider)))\n {\n options.cacheProvider = new MemoryCache();\n }\n\n this.eventInterceptor = new EventInterceptor(options.client);\n\n this.#data = options;\n\n this.#init().then(() => {\n // Increment client listeners count, as commandkit registers internal event listeners.\n this.incrementClientListenersCount();\n });\n\n if (!CommandKit.instance) {\n CommandKit.instance = this;\n }\n }\n\n /**\n * Sets the prefix resolver for the command handler.\n * @param resolver The resolver function.\n */\n setPrefixResolver(\n resolver: (message: Message) => Awaitable<string | string[]>)\n {\n this.config.getMessageCommandPrefix = resolver;\n return this;\n }\n\n /**\n * Sets the default locale for the command handler.\n * @param locale The default locale.\n */\n setDefaultLocale(locale: Locale) {\n this.config.defaultLocale = locale;\n return this;\n }\n\n /**\n * Sets the localization strategy for the command handler.\n * @param strategy The localization strategy.\n */\n setLocalizationStrategy(strategy: LocalizationStrategy) {\n this.config.localizationStrategy = strategy;\n return this;\n }\n\n /**\n * Resolves the current cache provider.\n */\n getCacheProvider(): CacheProvider | null {\n const provider = this.#data.cacheProvider;\n return provider ?? null;\n }\n\n /**\n * Whether or not to debug the command handler.\n */\n isDebuggingCommands() {\n return this.#data.debugCommands || false;\n }\n\n /**\n * Get the client attached to this CommandKit instance.\n */\n get client() {\n return this.#data.client;\n }\n\n /**\n * Get command handler instance.\n */\n get commandHandler() {\n return this.#data.commandHandler;\n }\n\n /**\n * (Private) Initialize CommandKit.\n */\n async #init() {\n // <!-- Setup event handler -->\n if (this.#data.eventsPath) {\n const eventHandler = new EventHandler({\n client: this.#data.client,\n eventsPath: this.#data.eventsPath,\n commandKitInstance: this\n });\n\n await eventHandler.init();\n\n this.#data.eventHandler = eventHandler;\n }\n\n // <!-- Setup validation handler -->\n if (this.#data.validationsPath) {\n const validationHandler = new ValidationHandler({\n validationsPath: this.#data.validationsPath\n });\n\n await validationHandler.init();\n\n this.#data.validationHandler = validationHandler;\n }\n\n // <!-- Setup command handler -->\n if (this.#data.commandsPath) {\n const commandHandler = new CommandHandler({\n client: this.#data.client,\n commandsPath: this.#data.commandsPath,\n devGuildIds: this.#data.devGuildIds || [],\n devUserIds: this.#data.devUserIds || [],\n devRoleIds: this.#data.devRoleIds || [],\n validationHandler: this.#data.validationHandler,\n skipBuiltInValidations: this.#data.skipBuiltInValidations || false,\n commandkitInstance: this,\n bulkRegister: this.#data.bulkRegister || false\n });\n\n this.#data.commandHandler = commandHandler;\n\n await this.#initApp();\n await commandHandler.init();\n }\n }\n\n async #initApp() {\n const appDir = this.getAppDirectory();\n if (!appDir) return;\n\n const commandsPath = this.getPath('commands')!;\n const events = this.getPath('events')!;\n\n this.commandsRouter = new CommandsRouter({\n entrypoint: commandsPath\n });\n\n this.eventsRouter = new EventsRouter({\n entrypoint: events\n });\n\n await this.#initEvents();\n await this.#initCommands();\n }\n\n async #initCommands() {\n if (this.commandsRouter.isValidPath()) {\n await this.commandsRouter.scan();\n }\n\n await this.appCommandsHandler.loadCommands();\n }\n\n async #initEvents() {\n if (this.eventsRouter.isValidPath()) {\n await this.eventsRouter.scan();\n }\n\n if (!this.#data.eventHandler) return;\n\n for (const event of Object.values(this.eventsRouter.toJSON())) {\n this.#data.eventHandler.registerExternal(event);\n }\n\n this.#data.eventHandler.resyncListeners();\n }\n\n /**\n * Updates application commands with the latest from \"commandsPath\".\n */\n async reloadCommands(type?: ReloadOptions) {\n if (!this.#data.commandHandler) return;\n await this.#data.commandHandler.reloadCommands(type);\n }\n\n /**\n * Updates application events with the latest from \"eventsPath\".\n */\n async reloadEvents() {\n if (!this.#data.eventHandler) return;\n await this.#data.eventHandler.reloadEvents(this.#data.commandHandler);\n }\n\n /**\n * Updates application command validations with the latest from \"validationsPath\".\n */\n async reloadValidations() {\n if (!this.#data.validationHandler) return;\n await this.#data.validationHandler.reloadValidations();\n }\n\n /**\n * @returns An array of objects of all the commands that CommandKit is handling.\n */\n get commands(): CommandObject[] {\n if (!this.#data.commandHandler) {\n return [];\n }\n\n const commands = this.#data.commandHandler.commands.map((cmd) => {\n const { run, autocomplete, ...command } = cmd;\n return command;\n });\n\n return commands;\n }\n\n /**\n * @returns The path to the commands folder which was set when instantiating CommandKit.\n */\n get commandsPath(): string | undefined {\n return this.#data.commandsPath;\n }\n\n /**\n * @returns The path to the events folder which was set when instantiating CommandKit.\n */\n get eventsPath(): string | undefined {\n return this.#data.eventsPath;\n }\n\n /**\n * @returns The path to the validations folder which was set when instantiating CommandKit.\n */\n get validationsPath(): string | undefined {\n return this.#data.validationsPath;\n }\n\n /**\n * @returns An array of all the developer user IDs which was set when instantiating CommandKit.\n */\n get devUserIds(): string[] {\n return this.#data.devUserIds || [];\n }\n\n /**\n * @returns An array of all the developer guild IDs which was set when instantiating CommandKit.\n */\n get devGuildIds(): string[] {\n return this.#data.devGuildIds || [];\n }\n\n /**\n * @returns An array of all the developer role IDs which was set when instantiating CommandKit.\n */\n get devRoleIds(): string[] {\n return this.#data.devRoleIds || [];\n }\n\n /**\n * Increment the client listeners count.\n */\n incrementClientListenersCount() {\n this.#data.client.setMaxListeners(this.#data.client.getMaxListeners() + 1);\n }\n\n /**\n * Decrement the client listeners count.\n */\n decrementClientListenersCount() {\n this.#data.client.setMaxListeners(this.#data.client.getMaxListeners() - 1);\n }\n\n /**\n * Path to the app directory. Returns `null` if not found.\n * The lookup order is:\n * - `./app`\n * - `./src/app`\n */\n getAppDirectory() {\n return findAppDirectory();\n }\n\n getPath(to: 'locales' | 'commands' | 'events') {\n const appDir = this.getAppDirectory();\n if (!appDir) return null;\n\n switch (to) {\n case 'locales':\n return join(appDir, 'locales');\n case 'commands':\n return join(appDir, 'commands');\n case 'events':\n return join(appDir, 'events');\n default:\n return to satisfies never;\n }\n }\n}","export * from './command-handler/CommandHandler';\nexport * from './event-handler/EventHandler';\nexport * from './validation-handler/ValidationHandler';","import { CacheType, Events, Interaction, Message } from 'discord.js';\nimport type {\n CommandData,\n CommandFileObject,\n ReloadOptions } from\n'../../../types';\nimport { clone } from '../../../utils/clone';\nimport colors from '../../../utils/colors';\nimport { getFilePaths } from '../../../utils/get-paths';\nimport { toFileURL } from '../../../utils/resolve-file-url';\nimport loadCommandsWithRest from './functions/loadCommandsWithRest';\nimport registerCommands from './functions/registerCommands';\nimport type {\n CommandHandlerData,\n CommandHandlerOptions,\n CommandKitInteraction } from\n'./typings';\nimport builtInValidationsFunctions from './validations';\nimport {\n makeContextAwareFunction,\n useEnvironment } from\n'../../../context/async-context';\nimport {\n afterCommand,\n CommandKitEnvironment,\n CommandKitEnvironmentType } from\n'../../../context/environment';\nimport {\n CommandExecutionMode,\n MiddlewareContext } from\n'../../../app/commands/Context';\nimport { CommandKitErrorCodes, isErrorType } from '../../../utils/error-codes';\n\nexport interface hCommandContext {\n interaction: CommandKitInteraction;\n command: CommandData;\n}\n\nenum CommandIndication {\n Continue,\n Stop,\n}\n\n/**\n * A handler for client application commands.\n */\nexport class CommandHandler {\n #data: CommandHandlerData;\n\n constructor({ ...options }: CommandHandlerOptions) {\n this.#data = {\n ...options,\n builtInValidations: [],\n commands: []\n };\n }\n\n async init() {\n await this.#buildCommands();\n\n this.#buildBuiltInValidations();\n\n const devOnlyCommands = this.#data.commands.filter(\n (cmd) => cmd.options?.devOnly\n );\n\n if (devOnlyCommands.length && !this.#data.devGuildIds.length) {\n process.emitWarning(\n colors.yellow(\n 'You have commands marked as \"devOnly\", but \"devGuildIds\" have not been set.'\n )\n );\n }\n\n if (\n devOnlyCommands.length &&\n !this.#data.devUserIds.length &&\n !this.#data.devRoleIds.length)\n {\n process.emitWarning(\n colors.yellow(\n 'You have commands marked as \"devOnly\", but \"devUserIds\" or \"devRoleIds\" have not been set.'\n )\n );\n }\n\n if (this.#data.bulkRegister) {\n await loadCommandsWithRest({\n client: this.#data.client,\n devGuildIds: this.#data.devGuildIds,\n commands: this.#data.commands\n });\n } else {\n await registerCommands({\n client: this.#data.client,\n devGuildIds: this.#data.devGuildIds,\n commands: this.#data.commands\n });\n }\n\n this.handleCommands();\n }\n\n async #buildCommands() {\n const allowedExtensions = /\\.(js|mjs|cjs|ts)$/i;\n const paths = await getFilePaths(this.#data.commandsPath, true);\n\n const commandFilePaths = paths.filter((path) =>\n allowedExtensions.test(path)\n );\n\n for (const commandFilePath of commandFilePaths) {\n const modulePath = toFileURL(commandFilePath);\n\n const importedObj = await import(`${modulePath}?t=${Date.now()}`);\n let commandObj: CommandFileObject = clone(importedObj); // Make commandObj extensible\n\n // If it's CommonJS, invalidate the import cache\n if (typeof module !== 'undefined' && typeof require !== 'undefined') {\n delete require.cache[require.resolve(commandFilePath)];\n }\n\n const compactFilePath =\n commandFilePath.split(process.cwd())[1] || commandFilePath;\n\n if (commandObj.default)\n commandObj = commandObj.default as CommandFileObject;\n\n // Ensure builder properties\n if (importedObj.default) {\n commandObj.data = importedObj.default.data;\n } else {\n commandObj.data = importedObj.data;\n }\n\n if (!commandObj.data) {\n process.emitWarning(\n colors.yellow(\n `Ignoring: Command file ${compactFilePath} does not export \"data\".`\n )\n );\n continue;\n }\n\n if (!commandObj.data.name) {\n process.emitWarning(\n colors.yellow(\n `Ignoring: Command file ${compactFilePath} does not export \"data.name\".`\n )\n );\n continue;\n }\n\n if (!commandObj.run) {\n process.emitWarning(\n colors.yellow(\n `Ignoring: Command file ${commandObj.data.name} does not export \"run\".`\n )\n );\n continue;\n }\n\n if (typeof commandObj.run !== 'function') {\n process.emitWarning(\n colors.yellow(\n `Ignoring: Command file ${commandObj.data.name} does not export \"run\" as a function.`\n )\n );\n continue;\n }\n\n commandObj.filePath = commandFilePath;\n\n let commandCategory =\n commandFilePath.\n split(this.#data.commandsPath)[1]?.\n replace(/\\\\\\\\|\\\\/g, '/').\n split('/')[1] || null;\n\n if (commandCategory && allowedExtensions.test(commandCategory)) {\n commandObj.category = null;\n } else {\n commandObj.category = commandCategory;\n }\n\n this.#data.commands.push(commandObj);\n }\n\n if (this.#data.commandkitInstance.appCommandsHandler) {\n const handler = this.#data.commandkitInstance.appCommandsHandler;\n\n const commands = handler.getCommandsArray();\n\n // this.#data.commands.push(...commands);\n\n for (const cmd of commands) {\n const idx = this.#data.commands.findIndex(\n (c) => c.data.name === cmd.name\n );\n\n if (idx !== -1) {\n // @ts-ignore\n this.#data.commands[idx] = { data: cmd };\n } else {\n // @ts-ignore\n this.#data.commands.push({ data: cmd });\n }\n }\n }\n }\n\n #buildBuiltInValidations() {\n for (const builtInValidationFunction of builtInValidationsFunctions) {\n this.#data.builtInValidations.push(builtInValidationFunction);\n }\n }\n\n async #commandFinalizer() {\n const env = useEnvironment();\n\n await env.runDeferredFunctions();\n\n // Clear all deferred functions if we somehow missed them\n env.clearAllDeferredFunctions();\n }\n\n async #requestExternalHandler(\n interaction: Interaction<CacheType> | Message)\n : Promise<CommandIndication> {\n const handler = this.#data.commandkitInstance.appCommandsHandler;\n if (!handler) return CommandIndication.Continue;\n\n if (\n !(interaction instanceof Message) &&\n !(interaction.isCommand() || interaction.isAutocomplete()))\n {\n return CommandIndication.Continue;\n }\n\n const targetCommand = await handler.prepareCommandRun(interaction);\n\n if (!targetCommand) return CommandIndication.Continue;\n\n const environment = useEnvironment();\n\n environment.variables.set('commandHandlerType', 'app');\n\n const { command, middlewares, messageCommandParser } = targetCommand;\n\n const context = new MiddlewareContext(this.#data.commandkitInstance, {\n executionMode:\n interaction instanceof Message ?\n CommandExecutionMode.Message :\n interaction.isChatInputCommand() ?\n CommandExecutionMode.SlashCommand :\n interaction.isUserContextMenuCommand() ?\n CommandExecutionMode.UserContextMenu :\n interaction.isMessageContextMenuCommand() ?\n CommandExecutionMode.MessageContextMenu :\n interaction.isAutocomplete() ?\n CommandExecutionMode.Autocomplete :\n null as never,\n interaction: interaction instanceof Message ? <never> null : interaction,\n message: interaction instanceof Message ? interaction : <never> null,\n messageCommandParser\n });\n\n const exec = async () => {\n if (middlewares.length > 0) {\n for (const middleware of middlewares) {\n // command was cancelled by middleware\n if (context.cancelled) return CommandIndication.Stop;\n\n try {\n await middleware.data.beforeExecute(context);\n } catch (e) {\n if (isErrorType(e, CommandKitErrorCodes.ExitMiddleware)) {\n break;\n } else if (\n isErrorType(e, [\n CommandKitErrorCodes.DMOnlyException,\n CommandKitErrorCodes.GuildOnlyException,\n CommandKitErrorCodes.ForwardedCommand]\n ))\n {\n // do nothing\n return;\n }\n throw e;\n }\n }\n }\n\n // command was cancelled by middleware\n if (context.cancelled) return CommandIndication.Stop;\n\n let postStageRunner = true;\n\n try {\n const commandContext = context.clone({\n environment\n });\n\n if (interaction instanceof Message) {\n environment.variables.set('execHandlerKind', 'message');\n await command.data.message?.(commandContext);\n } else {\n switch (true) {\n case interaction.isChatInputCommand():\n {\n environment.variables.set('execHandlerKind', 'chatInput');\n await command.data.chatInput?.(commandContext);\n }\n break;\n case interaction.isUserContextMenuCommand():\n {\n environment.variables.set('execHandlerKind', 'userContextMenu');\n await command.data.userContextMenu?.(commandContext);\n }\n break;\n case interaction.isMessageContextMenuCommand():\n {\n environment.variables.set(\n 'execHandlerKind',\n 'messageContextMenu'\n );\n await command.data.messageContextMenu?.(commandContext);\n }\n break;\n case interaction.isAutocomplete():\n {\n environment.variables.set('execHandlerKind', 'autocomplete');\n await command.data.autocomplete?.(commandContext);\n }\n break;\n default:\n break;\n }\n }\n } catch (e) {\n console.log(e);\n if (isErrorType(e, CommandKitErrorCodes.ExitMiddleware)) {\n postStageRunner = false;\n } else if (\n isErrorType(e, [\n CommandKitErrorCodes.DMOnlyException,\n CommandKitErrorCodes.GuildOnlyException,\n CommandKitErrorCodes.ForwardedCommand]\n ))\n {\n // do nothing\n return;\n } else {\n throw e;\n }\n }\n\n if (postStageRunner && middlewares.length > 0) {\n for (const middleware of middlewares) {\n try {\n await middleware.data.afterExecute(context);\n } catch (e) {\n if (isErrorType(e, CommandKitErrorCodes.ExitMiddleware)) {\n break;\n } else if (\n isErrorType(e, [\n CommandKitErrorCodes.DMOnlyException,\n CommandKitErrorCodes.GuildOnlyException,\n CommandKitErrorCodes.ForwardedCommand]\n ))\n {\n // do nothing\n return;\n }\n throw e;\n }\n }\n }\n };\n\n const shouldDebug = this.#data.commandkitInstance.isDebuggingCommands();\n\n if (!shouldDebug) {\n await exec();\n return CommandIndication.Stop;\n }\n\n afterCommand((env) => {\n const error = env.getExecutionError();\n const marker = env.getMarker();\n const time = `${env.getExecutionTime().toFixed(2)}ms`;\n\n if (error) {\n console.error(\n colors.red(\n `[${marker} - ${time}] Error executing command: ${error.stack || error}`\n )\n );\n return;\n }\n\n console.log(\n colors.cyan('(app ✨)') +\n colors.reset(' ') +\n colors.green(`[${marker} - ${time}] Command executed successfully`)\n );\n });\n\n try {\n environment.markStart(`${command.data.command.name}`);\n await exec();\n return CommandIndication.Stop;\n } finally {\n environment.markEnd();\n }\n }\n\n async #interactionHandler(interaction: Interaction<CacheType>) {\n // check if external handler can handle the interaction\n try {\n const result = await this.#requestExternalHandler(interaction);\n\n if (result === CommandIndication.Stop) return;\n } catch (e) {\n console.error(e);\n return;\n }\n\n if (\n !interaction.isChatInputCommand() &&\n !interaction.isContextMenuCommand() &&\n !interaction.isAutocomplete())\n\n return;\n\n const isAutocomplete = interaction.isAutocomplete();\n\n const targetCommand = this.#data.commands.find(\n (cmd) => cmd.data.name === interaction.commandName\n );\n\n if (!targetCommand) return;\n\n const env = useEnvironment();\n\n env.variables.set('commandHandlerType', 'legacy');\n env.variables.set('interaction', interaction);\n\n const { data, options, run, autocomplete, ...rest } = targetCommand;\n\n // Skip if autocomplete handler is not defined\n if (isAutocomplete && !autocomplete) return;\n\n const executor = async () => {\n const commandObj = {\n data: targetCommand.data,\n options: targetCommand.options,\n ...rest\n };\n\n if (this.#data.validationHandler) {\n let canRun = true;\n\n for (const validationFunction of this.#data.validationHandler.\n validations) {\n const stopValidationLoop = await validationFunction({\n interaction,\n commandObj,\n client: this.#data.client,\n handler: this.#data.commandkitInstance\n });\n\n if (stopValidationLoop) {\n canRun = false;\n break;\n }\n }\n\n if (!canRun) return;\n }\n\n let canRun = true;\n\n // If custom validations pass and !skipBuiltInValidations, run built-in CommandKit validation functions\n if (!this.#data.skipBuiltInValidations) {\n for (const validation of this.#data.builtInValidations) {\n const stopValidationLoop = validation({\n targetCommand,\n interaction,\n handlerData: this.#data\n });\n\n if (stopValidationLoop) {\n canRun = false;\n break;\n }\n }\n }\n\n if (!canRun) return;\n\n const command = targetCommand[isAutocomplete ? 'autocomplete' : 'run']!;\n\n if (!command) return;\n\n const context = {\n interaction,\n client: this.#data.client,\n handler: this.#data.commandkitInstance\n };\n\n const shouldDebug = this.#data.commandkitInstance.isDebuggingCommands();\n\n if (!shouldDebug) {\n return command(context);\n }\n\n afterCommand((env) => {\n const error = env.getExecutionError();\n const marker = env.getMarker();\n const time = `${env.getExecutionTime().toFixed(2)}ms`;\n\n if (error) {\n console.error(\n colors.red(\n `[${marker} - ${time}] Error executing command: ${error.stack || error}`\n )\n );\n return;\n }\n\n console.log(\n colors.green(`[${marker} - ${time}] Command executed successfully`)\n );\n });\n\n try {\n env.markStart(interaction.commandName);\n const res = await command(context);\n\n return res;\n } finally {\n env.markEnd();\n }\n };\n\n return executor();\n }\n\n handleCommands() {\n this.#data.client.on(Events.InteractionCreate, (interaction) => {\n const env = new CommandKitEnvironment(this.#data.commandkitInstance);\n env.setType(CommandKitEnvironmentType.CommandHandler);\n\n return makeContextAwareFunction(\n env,\n this.#interactionHandler.bind(this),\n this.#commandFinalizer.bind(this)\n )(interaction);\n });\n\n this.#data.client.on(Events.MessageCreate, (message) => {\n const env = new CommandKitEnvironment(this.#data.commandkitInstance);\n env.setType(CommandKitEnvironmentType.CommandHandler);\n\n return makeContextAwareFunction(\n env,\n this.#requestExternalHandler.bind(this),\n this.#commandFinalizer.bind(this)\n )(message);\n });\n }\n\n get commands() {\n return this.#data.commands;\n }\n\n async reloadCommands(type?: ReloadOptions) {\n if (!this.#data.commandsPath) {\n throw new Error(\n colors.red(\n 'Cannot reload commands as \"commandsPath\" was not provided when instantiating CommandKit.'\n )\n );\n }\n\n this.#data.commands = [];\n\n // Re-build commands tree\n await this.#buildCommands();\n\n if (this.#data.bulkRegister) {\n await loadCommandsWithRest({\n client: this.#data.client,\n devGuildIds: this.#data.devGuildIds,\n commands: this.#data.commands,\n reloading: true,\n type\n });\n } else {\n await registerCommands({\n client: this.#data.client,\n devGuildIds: this.#data.devGuildIds,\n commands: this.#data.commands,\n reloading: true,\n type\n });\n }\n }\n}","import rfdc from 'rfdc';\n\nexport const clone = rfdc();","const resetColor = '\\x1b[0m';\n\nexport default {\n reset: (text: string) => `${text}${resetColor}`,\n bright: (text: string) => `\\x1b[1m${text}${resetColor}`,\n dim: (text: string) => `\\x1b[2m${text}${resetColor}`,\n underscore: (text: string) => `\\x1b[4m${text}${resetColor}`,\n blink: (text: string) => `\\x1b[5m${text}${resetColor}`,\n reverse: (text: string) => `\\x1b[7m${text}${resetColor}`,\n hidden: (text: string) => `\\x1b[8m${text}${resetColor}`,\n\n black: (text: string) => `\\x1b[30m${text}${resetColor}`,\n red: (text: string) => `\\x1b[31m${text}${resetColor}`,\n green: (text: string) => `\\x1b[32m${text}${resetColor}`,\n yellow: (text: string) => `\\x1b[33m${text}${resetColor}`,\n blue: (text: string) => `\\x1b[34m${text}${resetColor}`,\n magenta: (text: string) => `\\x1b[35m${text}${resetColor}`,\n cyan: (text: string) => `\\x1b[36m${text}${resetColor}`,\n white: (text: string) => `\\x1b[37m${text}${resetColor}`,\n\n bgBlack: (text: string) => `\\x1b[40m${text}${resetColor}`,\n bgRed: (text: string) => `\\x1b[41m${text}${resetColor}`,\n bgGreen: (text: string) => `\\x1b[42m${text}${resetColor}`,\n bgYellow: (text: string) => `\\x1b[43m${text}${resetColor}`,\n bgBlue: (text: string) => `\\x1b[44m${text}${resetColor}`,\n bgMagenta: (text: string) => `\\x1b[45m${text}${resetColor}`,\n bgCyan: (text: string) => `\\x1b[46m${text}${resetColor}`,\n bgWhite: (text: string) => `\\x1b[47m${text}${resetColor}`\n};","import path from 'path';\nimport fs from 'fs/promises';\n\nexport async function getFilePaths(\ndirectory: string,\nnesting?: boolean)\n: Promise<string[]> {\n let filePaths: string[] = [];\n\n if (!directory) return filePaths;\n\n const files = await fs.readdir(directory, { withFileTypes: true });\n\n for (const file of files) {\n const filePath = path.join(directory, file.name);\n\n if (file.isFile()) {\n filePaths.push(filePath);\n }\n\n if (nesting && file.isDirectory()) {\n filePaths = [...filePaths, ...(await getFilePaths(filePath, true))];\n }\n }\n\n return filePaths;\n}\n\nexport async function getFolderPaths(\ndirectory: string,\nnesting?: boolean)\n: Promise<string[]> {\n let folderPaths: string[] = [];\n\n if (!directory) return folderPaths;\n\n const folders = await fs.readdir(directory, { withFileTypes: true });\n\n for (const folder of folders) {\n const folderPath = path.join(directory, folder.name);\n\n if (folder.isDirectory()) {\n folderPaths.push(folderPath);\n\n if (nesting) {\n folderPaths = [\n ...folderPaths,\n ...(await getFolderPaths(folderPath, true))];\n\n }\n }\n }\n\n return folderPaths;\n}","import path from 'path';\n\n/**\n * Convert a local file path to a file URL.\n * @param filePath - The local file's path.\n * @returns - The converted file URL.\n */\nexport function toFileURL(filePath: string) {\n const resolvedPath = path.resolve(filePath);\n return 'file://' + resolvedPath.replace(/\\\\\\\\|\\\\/g, '/');\n}","import type { ApplicationCommandDataResolvable, Client } from 'discord.js';\nimport type { CommandFileObject, ReloadOptions } from '../../../../types';\n\nimport colors from '../../../../utils/colors';\n\ntype LoadCommandsWithRestProps = {\n /**\n * The main client.\n */\n client: Client;\n\n /**\n * An array of command objects.\n */\n commands: CommandFileObject[];\n\n /**\n * An array of developer guild IDs.\n */\n devGuildIds: string[];\n\n /**\n * A boolean indicating whether these commands are reloading.\n */\n reloading?: boolean;\n\n /**\n * A type for reloading the commands (if this is reloading).\n */\n type?: ReloadOptions;\n};\n\n/**\n * Use REST to load commands.\n * @param props - Options for loading commands.\n */\nexport default async function loadCommandsWithRest(\nprops: LoadCommandsWithRestProps)\n{\n if (props.reloading) {\n if (props.client.isReady()) {\n await handleLoading(\n props.client,\n props.commands,\n props.devGuildIds,\n props.reloading,\n props.type\n );\n } else {\n throw new Error(\n colors.red(`Cannot reload commands when client is not ready.`)\n );\n }\n } else {\n props.client.once('ready', async (c) => {\n await handleLoading(\n c,\n props.commands,\n props.devGuildIds,\n props.reloading,\n props.type\n );\n });\n }\n}\n\n/**\n * Handles loading commands.\n * @param client - The discord.js client instance.\n * @param commands - An array of command file objects.\n * @param devGuildIds - An array of developer guild IDs.\n * @param reloading - A boolean indicating whether this is reloading.\n * @param type - A type for reloading the commands (if this is reloading).\n */\nasync function handleLoading(\nclient: Client<true>,\ncommands: CommandFileObject[],\ndevGuildIds: string[],\nreloading?: boolean,\ntype?: ReloadOptions)\n{\n commands = commands.filter((cmd) => !cmd.options?.deleted);\n const devOnlyCommands = commands.filter((cmd) => cmd.options?.devOnly);\n const globalCommands = commands.filter((cmd) => !cmd.options?.devOnly);\n\n if (type === 'dev') {\n await loadDevCommands(client, devOnlyCommands, devGuildIds, reloading);\n } else if (type === 'global') {\n await loadGlobalCommands(client, globalCommands, reloading);\n } else {\n await loadDevCommands(client, devOnlyCommands, devGuildIds, reloading);\n await loadGlobalCommands(client, globalCommands, reloading);\n }\n}\n\n/**\n * Load commands globally.\n * @param client - The discord.js client instance.\n * @param commands - An array of command file objects.\n * @param reloading - A boolean indicating whether the commands are reloading.\n */\nasync function loadGlobalCommands(\nclient: Client<true>,\ncommands: CommandFileObject[],\nreloading?: boolean)\n{\n const requestBody = commands.map((cmd) => cmd.data);\n\n await client.application.commands.\n set(requestBody as ApplicationCommandDataResolvable[]).\n catch((error) => {\n throw new Error(\n colors.red(\n `Error ${\n reloading ? 'reloading' : 'loading'} global application commands.\\n`\n\n ),\n error\n );\n });\n\n console.log(\n colors.green(\n `${reloading ? 'Reloaded' : 'Loaded'} ${\n requestBody.length} global commands.`\n\n )\n );\n}\n\n/**\n * Load commands for dev guilds.\n * @param client - The discord.js client instance.\n * @param commands - An array of command file objects.\n * @param guildIds - An array of developer guild IDs.\n * @param reloading - A boolean indicating whether the commands are reloading.\n */\nasync function loadDevCommands(\nclient: Client<true>,\ncommands: CommandFileObject[],\nguildIds: string[],\nreloading?: boolean)\n{\n const requestBody = commands.map((cmd) => cmd.data);\n\n for (const guildId of guildIds) {\n const targetGuild =\n client.guilds.cache.get(guildId) || (await client.guilds.fetch(guildId));\n\n if (!targetGuild) {\n process.emitWarning(\n `Cannot ${\n reloading ? 'reload' : 'load'} commands in guild \"${\n guildId}\" - guild doesn't exist or client isn't part of the guild.`\n );\n\n continue;\n }\n\n await targetGuild.commands.\n set(requestBody as ApplicationCommandDataResolvable[]).\n catch((error) => {\n throw new Error(\n colors.red(\n `Error ${\n reloading ? 'reloading' : 'loading'} developer application commands in guild \"${\n\n targetGuild?.name || guildId}\".\\n`\n\n ),\n error\n );\n });\n\n console.log(\n colors.green(\n `${reloading ? 'Reloaded' : 'Loaded'} ${\n requestBody.length} developer commands in guild \"${\n targetGuild.name}\".`\n )\n );\n }\n}","import type {\n Guild,\n Client,\n ApplicationCommandData,\n GuildApplicationCommandManager,\n ApplicationCommandDataResolvable } from\n'discord.js';\nimport type { CommandFileObject, ReloadOptions } from '../../../../types';\n\nimport areSlashCommandsDifferent from '../utils/areSlashCommandsDifferent';\n\nimport colors from '../../../../utils/colors';\n\ntype RegisterCommandProps = {\n client: Client;\n commands: CommandFileObject[];\n devGuildIds: string[];\n reloading?: boolean;\n type?: ReloadOptions;\n};\n\n/**\n * Register client commands to Discord.\n * @param props\n */\nexport default async function registerCommands(props: RegisterCommandProps) {\n if (props.reloading) {\n if (props.client.isReady()) {\n await handleRegistration(\n props.client,\n props.commands,\n props.devGuildIds,\n props.type\n );\n } else {\n throw new Error(\n colors.red(`Cannot reload commands when client is not ready.`)\n );\n }\n } else {\n props.client.once('ready', async (c) => {\n await handleRegistration(\n c,\n props.commands,\n props.devGuildIds,\n props.type\n );\n });\n }\n}\n\nasync function handleRegistration(\nclient: Client<true>,\ncommands: CommandFileObject[],\ndevGuildIds: string[],\ntype?: ReloadOptions)\n{\n const devOnlyCommands = commands.filter((cmd) => cmd.options?.devOnly);\n const globalCommands = commands.filter((cmd) => !cmd.options?.devOnly);\n\n if (type === 'dev') {\n await registerDevCommands(client, devOnlyCommands, devGuildIds);\n } else if (type === 'global') {\n await registerGlobalCommands(client, globalCommands);\n } else {\n await registerDevCommands(client, devOnlyCommands, devGuildIds);\n await registerGlobalCommands(client, globalCommands);\n }\n}\n\nasync function registerGlobalCommands(\nclient: Client<true>,\ncommands: CommandFileObject[])\n{\n const appCommandsManager = client.application.commands;\n await appCommandsManager.fetch();\n\n for (const command of commands) {\n const targetCommand = appCommandsManager.cache.find(\n (cmd) => cmd.name === command.data.name\n );\n\n // <!-- Delete global command -->\n if (command.options?.deleted) {\n if (!targetCommand) {\n process.emitWarning(\n colors.yellow(\n `Ignoring: Command \"${command.data.name}\" is globally marked as deleted.`\n )\n );\n } else {\n await targetCommand.delete().catch((error) => {\n throw new Error(\n colors.red(\n `Failed to delete command \"${command.data.name}\" globally.\\n`\n ),\n error\n );\n });\n\n console.log(\n colors.green(`Deleted command \"${command.data.name}\" globally.`)\n );\n }\n\n continue;\n }\n\n // <!-- Edit global command -->\n if (targetCommand) {\n const commandsAreDifferent = areSlashCommandsDifferent(\n targetCommand,\n command.data\n );\n\n if (commandsAreDifferent) {\n await targetCommand.\n edit(command.data as Partial<ApplicationCommandData>).\n catch((error) => {\n throw new Error(\n colors.red(\n `Failed to edit command \"${command.data.name}\" globally.\\n`\n ),\n error\n );\n });\n\n console.log(\n colors.green(`Edited command \"${command.data.name}\" globally.`)\n );\n\n continue;\n }\n }\n\n // <!-- Register global command -->\n if (targetCommand) continue;\n\n await appCommandsManager.\n create(command.data as ApplicationCommandDataResolvable).\n catch((error) => {\n throw new Error(\n colors.red(\n `Failed to register command \"${command.data.name}\" globally.\\n`\n ),\n error\n );\n });\n\n console.log(\n colors.green(`Registered command \"${command.data.name}\" globally.`)\n );\n }\n}\n\nasync function registerDevCommands(\nclient: Client<true>,\ncommands: CommandFileObject[],\nguildIds: string[])\n{\n const devGuilds: Guild[] = [];\n\n for (const guildId of guildIds) {\n const guild =\n client.guilds.cache.get(guildId) || (await client.guilds.fetch(guildId));\n\n if (!guild) {\n process.emitWarning(\n colors.yellow(\n `Ignoring: Guild ${guildId} doesn't exist or client isn't part of the guild.`\n )\n );\n continue;\n }\n\n devGuilds.push(guild);\n }\n\n const guildCommandsManagers: GuildApplicationCommandManager[] = [];\n\n for (const guild of devGuilds) {\n const guildCommandsManager = guild.commands;\n await guildCommandsManager.fetch();\n\n guildCommandsManagers.push(guildCommandsManager);\n }\n\n for (const command of commands) {\n for (const guildCommands of guildCommandsManagers) {\n const targetCommand = guildCommands.cache.find(\n (cmd) => cmd.name === command.data.name\n );\n\n // <!-- Delete dev command -->\n if (command.options?.deleted) {\n if (!targetCommand) {\n process.emitWarning(\n colors.yellow(\n `Ignoring: Command \"${command.data.name}\" is marked as deleted in ${guildCommands.guild.name}.`\n )\n );\n } else {\n await targetCommand.delete().catch((error) => {\n throw new Error(\n colors.red(\n `Failed to delete command \"${command.data.name}\" in ${guildCommands.guild.name}.`\n ),\n error\n );\n });\n\n console.log(\n colors.green(\n `Deleted command \"${command.data.name}\" in ${guildCommands.guild.name}.`\n )\n );\n }\n\n continue;\n }\n\n // <!-- Edit dev command -->\n if (targetCommand) {\n const commandsAreDifferent = areSlashCommandsDifferent(\n targetCommand,\n command.data\n );\n\n if (commandsAreDifferent) {\n await targetCommand.\n edit(command.data as Partial<ApplicationCommandData>).\n catch((error) => {\n throw new Error(\n colors.red(\n `Failed to edit command \"${command.data.name}\" in ${guildCommands.guild.name}.\\n`\n ),\n error\n );\n });\n\n console.log(\n colors.green(\n `Edited command \"${command.data.name}\" in ${guildCommands.guild.name}.`\n )\n );\n\n continue;\n }\n }\n\n // <!-- Register guild command -->\n if (targetCommand) continue;\n\n await guildCommands.\n create(command.data as ApplicationCommandDataResolvable).\n catch((error) => {\n throw new Error(\n colors.red(\n `Failed to register command \"${command.data.name}\" in ${guildCommands.guild.name}.\\n`\n ),\n error\n );\n });\n\n console.log(\n colors.green(\n `Registered command \"${command.data.name}\" in ${guildCommands.guild.name}.`\n )\n );\n }\n }\n}","function compareLocalizations(\nfirst: Record<string, string> | undefined,\nsecond: Record<string, string> | undefined)\n: boolean {\n if (!first && !second) return true;\n if (!first || !second) return false;\n\n const keys1 = Object.keys(first);\n const keys2 = Object.keys(second);\n if (keys1.length !== keys2.length) return false;\n\n return keys1.every((key) => first[key] === second[key]);\n}\n\nfunction compareArrays(\narr1: any[] | undefined,\narr2: any[] | undefined)\n: boolean {\n if (!arr1 && !arr2) return true;\n if (!arr1 || !arr2) return false;\n if (arr1.length !== arr2.length) return false;\n\n return arr1.every((item, index) => {\n const item2 = arr2[index];\n return Object.keys(item).every((key) => {\n if (Array.isArray(item[key])) {\n return compareArrays(item[key], item2[key]);\n }\n if (key.endsWith('_localizations')) {\n return compareLocalizations(item[key], item2[key]);\n }\n return item[key] === item2[key];\n });\n });\n}\n\nexport default function areSlashCommandsDifferent(\nappCommand: any,\nlocalCommand: any)\n{\n if (!appCommand.options) appCommand.options = [];\n if (!localCommand.options) localCommand.options = [];\n\n if (!appCommand.description) appCommand.description = '';\n if (!localCommand.description) localCommand.description = '';\n\n // Check basic properties\n if (\n localCommand.description !== appCommand.description ||\n localCommand.options?.length !== appCommand.options?.length ||\n !compareLocalizations(\n localCommand.name_localizations,\n appCommand.name_localizations\n ) ||\n !compareLocalizations(\n localCommand.description_localizations,\n appCommand.description_localizations\n ))\n {\n return true;\n }\n\n // Check options in detail\n return !compareArrays(localCommand.options, appCommand.options);\n}","import devOnly from './devOnly';\nimport permissions from './permissions';\n\nexport default [devOnly, permissions];","import type { BuiltInValidationParams } from '../typings';\nimport { MessageFlags } from 'discord.js';\n\nexport default function ({\n interaction,\n targetCommand,\n handlerData\n}: BuiltInValidationParams) {\n if (interaction.isAutocomplete()) return;\n\n if (targetCommand.options?.devOnly) {\n if (\n interaction.inGuild() &&\n !handlerData.devGuildIds.includes(interaction.guildId))\n {\n interaction.reply({\n content: '❌ This command can only be used inside development servers.',\n flags: MessageFlags.Ephemeral\n });\n\n return true;\n }\n\n const guildMember = interaction.guild?.members.cache.get(\n interaction.user.id\n );\n const memberRoles = guildMember?.roles.cache;\n\n let hasDevRole = false;\n\n memberRoles?.forEach((role) => {\n if (handlerData.devRoleIds.includes(role.id)) {\n hasDevRole = true;\n }\n });\n\n const isDevUser =\n handlerData.devUserIds.includes(interaction.user.id) || hasDevRole;\n\n if (!isDevUser) {\n interaction.reply({\n content: '❌ This command can only be used by developers.',\n flags: MessageFlags.Ephemeral\n });\n\n return true;\n }\n }\n}","import type { BuiltInValidationParams } from '../typings';\nimport { EmbedBuilder, MessageFlags } from 'discord.js';\n\nexport default function ({\n interaction,\n targetCommand\n}: BuiltInValidationParams) {\n if (interaction.isAutocomplete()) return;\n const userPermissions = interaction.memberPermissions;\n let userPermissionsRequired = targetCommand.options?.userPermissions;\n let missingUserPermissions: string[] = [];\n\n if (typeof userPermissionsRequired === 'string') {\n userPermissionsRequired = [userPermissionsRequired];\n }\n\n const botPermissions = interaction.guild?.members.me?.permissions;\n let botPermissionsRequired = targetCommand.options?.botPermissions;\n let missingBotPermissions: string[] = [];\n\n if (typeof botPermissionsRequired === 'string') {\n botPermissionsRequired = [botPermissionsRequired];\n }\n\n if (!userPermissionsRequired?.length && !botPermissionsRequired?.length) {\n return;\n }\n\n if (userPermissions && userPermissionsRequired) {\n for (const permission of userPermissionsRequired) {\n const hasPermission = userPermissions.has(permission);\n\n if (!hasPermission) {\n missingUserPermissions.push(permission);\n }\n }\n }\n\n if (botPermissions && botPermissionsRequired) {\n for (const permission of botPermissionsRequired) {\n const hasPermission = botPermissions.has(permission);\n\n if (!hasPermission) {\n missingBotPermissions.push(permission);\n }\n }\n }\n\n if (!missingUserPermissions.length && !missingBotPermissions.length) {\n return;\n }\n\n // Fix casing. e.g. KickMembers -> Kick Members\n const pattern = /([a-z])([A-Z])|([A-Z]+)([A-Z][a-z])/g;\n\n missingUserPermissions = missingUserPermissions.map((str) =>\n str.replace(pattern, '$1$3 $2$4')\n );\n missingBotPermissions = missingBotPermissions.map((str) =>\n str.replace(pattern, '$1$3 $2$4')\n );\n\n let embedDescription = '';\n\n const formatter = new Intl.ListFormat('en', {\n style: 'long',\n type: 'conjunction'\n });\n\n const getPermissionWord = (permissions: string[]) =>\n permissions.length === 1 ? 'permission' : 'permissions';\n\n if (missingUserPermissions.length) {\n const formattedPermissions = missingUserPermissions.map((p) => `\\`${p}\\``);\n const permissionsString = formatter.format(formattedPermissions);\n\n embedDescription += `- You must have the ${permissionsString} ${getPermissionWord(\n missingUserPermissions\n )} to be able to run this command.\\n`;\n }\n\n if (missingBotPermissions.length) {\n const formattedPermissions = missingBotPermissions.map((p) => `\\`${p}\\``);\n const permissionsString = formatter.format(formattedPermissions);\n\n embedDescription += `- I must have the ${permissionsString} ${getPermissionWord(\n missingBotPermissions\n )} to be able to execute this command.\\n`;\n }\n\n const embed = new EmbedBuilder().\n setTitle(`:x: Missing permissions!`).\n setDescription(embedDescription).\n setColor('Red');\n\n interaction.reply({ embeds: [embed], flags: MessageFlags.Ephemeral });\n return true;\n}","import { AsyncLocalStorage } from 'node:async_hooks';\nimport { CommandKitEnvironment } from './environment';\nimport { CommandKitErrorCodes, isCommandKitError } from '../utils/error-codes';\nimport { Interaction, MessageFlags } from 'discord.js';\nimport { CommandKit } from '../CommandKit';\n\nconst context = new AsyncLocalStorage<CommandKitEnvironment>();\n\nexport type GenericFunction<A extends any[] = any[]> = (...args: A) => any;\n\nexport function exitContext<T>(fn: () => T): T {\n return context.exit(fn);\n}\n\n/**\n * Returns a context-aware version of the given function.\n * @param env - The commandkit environment data.\n * @param fn - The target function.\n * @param finalizer - An optional finalizer function to run after the target function. This function will be context-aware.\n * @internal\n */\nexport function makeContextAwareFunction<\n R extends GenericFunction,\n F extends GenericFunction>(\nenv: CommandKitEnvironment, fn: R, finalizer?: F): R {\n const _fn = (...args: any[]) => {\n return context.run(env, async () => {\n try {\n // execute the target function\n const result = await fn(...args);\n\n return result;\n } catch (e) {\n // set the error in the environment data\n if (isCommandKitError(e)) {\n const code = Reflect.get(e, 'code');\n const interaction = env.variables.get('interaction') as Interaction;\n if (!interaction) return;\n\n switch (code) {\n case CommandKitErrorCodes.GuildOnlyException:{\n if (interaction.isRepliable()) {\n await interaction.reply({\n content: 'This command is only available in guilds.',\n flags: MessageFlags.Ephemeral\n });\n }\n return;\n }\n case CommandKitErrorCodes.DMOnlyException:{\n if (interaction.isRepliable()) {\n await interaction.reply({\n content: 'This command is only available in DMs.',\n flags: MessageFlags.Ephemeral\n });\n }\n return;\n }\n }\n\n return;\n }\n\n env.setExecutionError(e as Error);\n } finally {\n if (typeof finalizer === 'function') {\n // execute the finalizer function\n try {\n await finalizer(...args);\n } catch {\n\n // no-op\n }}\n }\n });\n };\n\n return _fn as R;\n}\n\n/**\n * Retrieves commandkit\n * @private\n * @internal\n */\nexport function getCommandKit(): CommandKit | undefined;\nexport function getCommandKit(strict: true): CommandKit;\nexport function getCommandKit(strict: false): CommandKit | undefined;\nexport function getCommandKit(strict = false): CommandKit | undefined {\n const kit = context.getStore()?.commandkit ?? CommandKit.instance;\n\n if (!kit && strict) {\n throw new Error('CommandKit instance not found.');\n }\n\n return kit;\n}\n\n/**\n * Get the current commandkit context.\n * @internal\n */\nexport function getContext(): CommandKitEnvironment | undefined {\n const ctx = context.getStore();\n return ctx;\n}\n\n/**\n * Use current commandkit context. Throws an error if no context is found.\n */\nexport function useEnvironment(): CommandKitEnvironment {\n const ctx = context.getStore();\n if (!ctx) {\n throw new Error(\n 'No commandkit environment found. Please make sure you are inside commandkit handler.'\n );\n }\n\n return ctx;\n}\n\n/**\n * Ensures the command is only available in guilds.\n * Note: do not wrap this function in a try/catch block.\n */\nexport function guildOnly() {\n const env = useEnvironment();\n const interaction: Interaction = env.variables.get('interaction');\n\n if (!interaction) {\n throw new Error('No interaction found in environment.');\n }\n\n if (!interaction.guild) {\n const error = new Error('This command is only available in guilds.');\n Reflect.set(error, 'code', CommandKitErrorCodes.GuildOnlyException);\n\n throw error;\n }\n}\n\n/**\n * Ensures the command is only available in DMs.\n * Note: do not wrap this function in a try/catch block.\n */\nexport function dmOnly() {\n const env = useEnvironment();\n const interaction: Interaction = env.variables.get('interaction');\n\n if (!interaction) {\n throw new Error('No interaction found in environment.');\n }\n\n if (interaction.guild) {\n const error = new Error('This command is only available in DMs.');\n Reflect.set(error, 'code', CommandKitErrorCodes.DMOnlyException);\n\n throw error;\n }\n}","export const CommandKitErrorCodes = {\n GuildOnlyException: Symbol('kGuildOnlyException'),\n DMOnlyException: Symbol('kDMOnlyException'),\n ExitMiddleware: Symbol('kExitMiddleware'),\n ForwardedCommand: Symbol('kForwardedCommand'),\n InvalidCommandPrefix: Symbol('kInvalidCommandPrefix')\n} as const;\n\nexport type CommandKitError = Error & {code: symbol;};\n\nexport function createCommandKitError(code: symbol): CommandKitError {\n const error = new Error() as CommandKitError;\n\n Reflect.set(error, 'code', code);\n\n return error;\n}\n\nexport function isCommandKitError(error: unknown): error is CommandKitError {\n if (!(error instanceof Error)) return false;\n const code = Reflect.get(error, 'code');\n\n for (const key in CommandKitErrorCodes) {\n if (CommandKitErrorCodes[key as keyof typeof CommandKitErrorCodes] === code)\n return true;\n }\n\n return false;\n}\n\nexport function isErrorType(error: unknown, code: symbol | symbol[]): boolean {\n if (!isCommandKitError(error)) return false;\n const errorCode = Reflect.get(error, 'code');\n\n if (!errorCode) return false;\n\n if (Array.isArray(code)) return code.includes(errorCode);\n\n return errorCode === code;\n}","import { randomUUID } from 'node:crypto';\nimport { CommandKit } from '../CommandKit';\nimport { GenericFunction, getContext } from './async-context';\n\nexport interface CommandKitEnvironmentInternalData {\n executionError: Error | null;\n type: CommandKitEnvironmentType | null;\n variables: Map<string, any>;\n deferredFunctions: Map<string, GenericFunction<[CommandKitEnvironment]>>;\n marker: string;\n markStart: number;\n markEnd: number;\n}\n\nexport class CommandKitEnvironment {\n #data: CommandKitEnvironmentInternalData = {\n executionError: null,\n type: null,\n variables: new Map(),\n deferredFunctions: new Map(),\n marker: '',\n markStart: 0,\n markEnd: 0\n };\n\n /**\n * Creates the commandkit execution environment.\n * @param commandkit - The commandkit instance.\n */\n public constructor(public readonly commandkit: CommandKit) {}\n\n /**\n * Get the execution error.\n * @internal\n */\n public getExecutionError(): Error | null {\n return this.#data.executionError;\n }\n\n /**\n * Set the execution error.\n * @param error - The error to set.\n * @internal\n */\n public setExecutionError(error: Error): void {\n if (this.#data.executionError) {\n throw new Error('Execution error already set.');\n }\n\n this.#data.executionError = error;\n }\n\n /**\n * Get the environment type.\n */\n public getType(): CommandKitEnvironmentType {\n const type = this.#data.type;\n\n if (!type) {\n throw new Error('Environment type not set.');\n }\n\n return type;\n }\n\n /**\n * Set the environment type.\n * @param type - The environment type to set.\n * @internal\n */\n public setType(type: CommandKitEnvironmentType): void {\n this.#data.type = type;\n }\n\n /**\n * The variables store for this environment.\n */\n public get variables(): Map<string, any> {\n return this.#data.variables;\n }\n\n /**\n * Register a deferred function.\n * @param fn - The deferred function to register.\n * @returns The deferred function id.\n * @internal\n */\n public registerDeferredFunction(\n fn: GenericFunction<[CommandKitEnvironment]>)\n : string {\n const id = randomUUID();\n this.#data.deferredFunctions.set(id, fn);\n return id;\n }\n\n /**\n * Clear a deferred function by id.\n * @param id - The deferred function id to clear.\n * @internal\n */\n public clearDeferredFunction(id: string): void {\n this.#data.deferredFunctions.delete(id);\n }\n\n /**\n * Run all deferred functions sequentially.\n * @internal\n */\n public async runDeferredFunctions(): Promise<void> {\n for (const [id, fn] of this.#data.deferredFunctions) {\n try {\n await fn(this);\n } catch (e) {\n this.commandkit.emit('unhandledDeferredFunctionRejection', e);\n } finally {\n this.clearDeferredFunction(id);\n }\n }\n }\n\n /**\n * Clear all deferred functions.\n * @internal\n */\n public clearAllDeferredFunctions(): void {\n this.#data.deferredFunctions.clear();\n }\n\n /**\n * Mark the start of a command execution.\n * @param marker - The marker to set.\n * @internal\n */\n public markStart(marker: string): void {\n this.#data.marker = marker;\n this.#data.markStart = performance.now();\n }\n\n /**\n * Mark the end of a command execution.\n * @internal\n */\n public markEnd(): void {\n if (!this.#data.markEnd) this.#data.markEnd = performance.now();\n }\n\n /**\n * Get the marker.\n * @internal\n */\n public getMarker(): string {\n return this.#data.marker;\n }\n\n /**\n * Get the execution time in milliseconds.\n * @internal\n */\n public getExecutionTime(): number {\n return Math.abs(this.#data.markEnd - this.#data.markStart);\n }\n}\n\nexport enum CommandKitEnvironmentType {\n CommandHandler = 'COMMAND_HANDLER',\n}\n\n/**\n * Runs the given function after the current command has finished executing.\n * @param fn The function to run after the current command.\n * @returns The deferred function id. This can be used to cancel the deferred function.\n */\nexport function afterCommand(\nfn: GenericFunction<[CommandKitEnvironment]>)\n: string {\n const env = getContext();\n\n if (!env) {\n throw new Error('after must be called inside commandkit handler.');\n }\n\n return env.registerDeferredFunction(fn);\n}\n\n/**\n * Cancels a deferred function registered with `afterCommand`.\n * @param id The deferred function id to cancel.\n */\nexport function cancelAfterCommand(id: string): void {\n const env = getContext();\n\n if (!env) {\n throw new Error('cancelAfter must be called inside commandkit handler.');\n }\n\n env.clearDeferredFunction(id);\n}","import {\n AutocompleteInteraction,\n ChatInputCommandInteraction,\n MessageContextMenuCommandInteraction,\n Message,\n Locale,\n Interaction,\n UserContextMenuCommandInteraction } from\n'discord.js';\nimport { CommandKit } from '../../CommandKit';\nimport { Localization } from '../i18n/Localization';\nimport {\n MessageCommandOptions,\n MessageCommandParser } from\n'./MessageCommandParser';\nimport {\n CommandKitErrorCodes,\n createCommandKitError } from\n'../../utils/error-codes';\nimport { CommandKitEnvironment } from '../../context/environment';\nimport { getContext } from '../../context/async-context';\n\nexport const CommandExecutionMode = {\n SlashCommand: 'chatInput',\n MessageContextMenu: 'messageContextMenu',\n UserContextMenu: 'userContextMenu',\n Autocomplete: 'autocomplete',\n Message: 'message'\n} as const;\n\nexport type CommandExecutionMode =\n(typeof CommandExecutionMode)[keyof typeof CommandExecutionMode];\n\nexport interface ContextParameters<T extends CommandExecutionMode> {\n environment?: CommandKitEnvironment;\n executionMode: T;\n // interaction: T extends 'interaction'\n // ?\n // | ChatInputCommandInteraction\n // | ContextMenuCommandInteraction\n // | MessageContextMenuCommandInteraction\n // : never;\n interaction: T extends 'chatInput' ?\n ChatInputCommandInteraction :\n T extends 'messageContextMenu' ?\n MessageContextMenuCommandInteraction :\n T extends 'userContextMenu' ?\n UserContextMenuCommandInteraction :\n T extends 'autocomplete' ?\n AutocompleteInteraction :\n never;\n message: T extends 'message' ? Message : never;\n forwarded?: boolean;\n messageCommandParser?: T extends 'message' ? MessageCommandParser : never;\n}\n\nexport type MessageCommandContext = Context<'message'>;\nexport type InteractionCommandContext = Context<\n 'autocomplete' | 'chatInput' | 'messageContextMenu' | 'userContextMenu'>;\n\nexport type MessageCommandMiddlewareContext = MiddlewareContext<'message'>;\nexport type InteractionCommandMiddlewareContext = MiddlewareContext<\n 'autocomplete' | 'chatInput' | 'messageContextMenu' | 'userContextMenu'>;\n\nexport type SlashCommandContext = Context<'chatInput'>;\nexport type SlashCommandMiddlewareContext = MiddlewareContext<'chatInput'>;\nexport type AutocompleteCommandContext = Context<'autocomplete'>;\nexport type AutocompleteCommandMiddlewareContext =\nMiddlewareContext<'autocomplete'>;\nexport type MessageContextMenuCommandContext = Context<'messageContextMenu'>;\nexport type MessageContextMenuCommandMiddlewareContext =\nMiddlewareContext<'messageContextMenu'>;\nexport type UserContextMenuCommandContext = Context<'userContextMenu'>;\nexport type UserContextMenuCommandMiddlewareContext =\nMiddlewareContext<'userContextMenu'>;\n\nexport type CommandContextOptions<T extends CommandExecutionMode> =\nT extends 'message' ?\nMessageCommandOptions :\nT extends 'chatInput' ?\nChatInputCommandInteraction['options'] :\nT extends 'autocomplete' ?\nAutocompleteInteraction['options'] :\nT extends 'messageContextMenu' ?\nMessageContextMenuCommandInteraction['options'] :\nT extends 'userContextMenu' ?\nUserContextMenuCommandInteraction['options'] :\nnever;\n\nexport class Context<\n ExecutionMode extends CommandExecutionMode = CommandExecutionMode>\n{\n /**\n * The interaction that triggered the command.\n */\n public readonly interaction: ContextParameters<ExecutionMode>['interaction'];\n /**\n * The message that triggered the command.\n */\n public readonly message: ContextParameters<ExecutionMode>['message'];\n\n private _locale: Locale | null = null;\n\n /**\n * Creates a new command context.\n * @param commandkit The command kit instance.\n * @param config The context parameters.\n */\n public constructor(\n public readonly commandkit: CommandKit,\n private readonly config: ContextParameters<ExecutionMode>)\n {\n // these are assigned to readonly properties to make them accessible via object destructuring\n this.interaction = config.interaction;\n this.message = config.message;\n }\n\n public get commandName(): string {\n if (this.isInteraction()) {\n return this.interaction.commandName;\n } else {\n return this.config.messageCommandParser!.getCommand();\n }\n }\n\n public get options(): CommandContextOptions<ExecutionMode> {\n if (this.isMessage()) {\n const parser = this.config.messageCommandParser!;\n // @ts-expect-error\n return parser.options;\n } else {\n const interaction = (<InteractionCommandContext> this).interaction;\n // @ts-expect-error\n return interaction.options;\n }\n }\n\n /**\n * Whether this context was forwarded from another context. This happens when a command forwards its context to another command.\n */\n public get forwarded(): boolean {\n return this.config.forwarded ?? false;\n }\n\n /**\n * Forwards the context to another command. The target handler will be the same as current handler.\n * @param command The command to forward to.\n */\n public async forwardCommand(command: string): Promise<never> {\n const target = await this.commandkit.appCommandsHandler.prepareCommandRun(\n (this.isInteraction() ? this.interaction : this.message) as Interaction\n );\n\n if (!target) {\n throw new Error(\n `Command ${command} not found! If you are trying to forward to a legacy command, ctx.forwardCommand is not compatible with legacy commands.`\n );\n }\n\n const env = this.config.environment ?? getContext();\n\n if (!env) {\n throw new Error('No commandkit environment found.');\n }\n\n const handlers = {\n chatInput: target.command.data.chatInput,\n autocomplete: target.command.data.autocomplete,\n message: target.command.data.message,\n messageContextMenu: target.command.data.messageContextMenu,\n userContextMenu: target.command.data.userContextMenu\n };\n\n const handlerKind = env.variables.get(\n 'execHandlerKind'\n ) as keyof typeof handlers;\n\n if (!handlerKind) {\n throw new Error('No execution handler kind found.');\n }\n\n const handler = handlers[handlerKind];\n\n if (!handler) {\n throw new Error(`No handler found for ${handlerKind}`);\n }\n\n await handler(this.clone({ forwarded: true }));\n\n throw createCommandKitError(CommandKitErrorCodes.ForwardedCommand);\n }\n\n /**\n * The execution mode of the command.\n */\n public get executionMode(): ExecutionMode {\n return this.config.executionMode;\n }\n\n /**\n * Whether the command was triggered by an interaction.\n */\n public isInteraction(): this is InteractionCommandContext {\n return (\n this.executionMode === CommandExecutionMode.SlashCommand ||\n this.executionMode === CommandExecutionMode.Autocomplete ||\n this.executionMode === CommandExecutionMode.MessageContextMenu ||\n this.executionMode === CommandExecutionMode.UserContextMenu);\n\n }\n\n /**\n * Whether the command was triggered by a slash command interaction.\n */\n public isSlashCommand(): this is SlashCommandContext {\n return this.executionMode === CommandExecutionMode.SlashCommand;\n }\n\n /**\n * Whether the command was triggered by an autocomplete interaction.\n */\n public isAutocomplete(): this is AutocompleteCommandContext {\n return this.executionMode === CommandExecutionMode.Autocomplete;\n }\n\n /**\n * Whether the command was triggered by a message context menu interaction.\n */\n public isMessageContextMenu(): this is MessageContextMenuCommandContext {\n return this.executionMode === CommandExecutionMode.MessageContextMenu;\n }\n\n /**\n * Whether the command was triggered by a user context menu interaction.\n */\n public isUserContextMenu(): this is UserContextMenuCommandContext {\n return this.executionMode === CommandExecutionMode.UserContextMenu;\n }\n\n /**\n * Whether the command was triggered by a message.\n */\n public isMessage(): this is Context<'message'> {\n return this.executionMode === CommandExecutionMode.Message;\n }\n\n /**\n * Returns the command identifier.\n */\n public getCommandIdentifier(): string {\n if (this.isInteraction()) {\n return this.interaction.commandName;\n } else {\n return this.message.content.split(' ')[0].slice(1);\n }\n }\n\n /**\n * Returns the locale of the guild where this command was triggered.\n */\n public getGuildLocale(): Locale | null {\n if (this.isInteraction()) {\n return this.interaction.guildLocale;\n } else {\n return this.message.guild?.preferredLocale ?? null;\n }\n }\n\n /**\n * Returns the locale of the user who triggered this command.\n */\n public getUserLocale(): Locale | null {\n if (this.isInteraction()) {\n return this.interaction.locale;\n } else {\n return null;\n }\n }\n\n /**\n * Returns the locale for this command.\n * @param preferUser Whether to prefer the user's locale over the guild's locale.\n * @returns The locale for this command. If no locale is found, the default locale is returned.\n */\n public getLocale(preferUser = false): Locale {\n if (this._locale) return this._locale;\n\n const locale = preferUser ? this.getUserLocale() : this.getGuildLocale();\n\n if (!locale) {\n return this.commandkit.config.defaultLocale;\n }\n\n return locale;\n }\n\n /**\n * Sets the locale for this command.\n * @param locale The locale to set.\n */\n public setLocale(locale: Locale | null): void {\n this._locale = locale;\n }\n\n /**\n * Returns the i18n api for this command.\n * @param locale The locale to use for the i18n api.\n */\n public locale(locale?: Locale) {\n const selectedLocale = locale ?? this.getLocale();\n\n return new Localization(this.commandkit, {\n locale: selectedLocale,\n target: this.getCommandIdentifier()\n });\n }\n\n /**\n * Creates a clone of this context\n */\n public clone(\n config?: Partial<ContextParameters<ExecutionMode>>)\n : Context<ExecutionMode> {\n if (!config) return new Context(this.commandkit, this.config);\n\n return new Context(this.commandkit, { ...this.config, ...config });\n }\n\n public isMiddleware(): this is MiddlewareContext<ExecutionMode> {\n return this instanceof MiddlewareContext;\n }\n\n public args(): string[] {\n if (this.isMessage()) {\n return this.config.messageCommandParser!.getArgs();\n }\n\n return [];\n }\n}\n\nexport class MiddlewareContext<\n T extends CommandExecutionMode = CommandExecutionMode> extends\nContext<T> {\n #cancel = false;\n\n /**\n * Whether the command execution was cancelled.\n */\n public get cancelled(): boolean {\n return this.#cancel;\n }\n\n /**\n * Cancels the command execution.\n */\n public cancel(): void {\n this.#cancel = true;\n }\n}","import { Locale } from 'discord.js';\nimport { CommandKit } from '../../CommandKit';\nimport {\n LocalizationTranslationRequest,\n TranslationResult } from\n'./LocalizationStrategy';\nimport { TranslatableArguments } from './Translation';\n\nexport interface LocalizationConfig {\n /**\n * The locale to use for localization.\n */\n locale: Locale;\n /**\n * The internalization data target.\n */\n target: string;\n}\n\nexport type Translator = (\ntranslatable: string,\nargs?: TranslatableArguments | undefined)\n=> Promise<TranslationResult>;\n\nexport class Localization {\n /**\n * Translates the given translatable object.\n * @param translatable The translatable object to translate.\n */\n public readonly t: Translator;\n\n /**\n * Creates a new localization instance.\n * @param commandkit The command kit instance.\n * @param config The localization configuration.\n */\n public constructor(\n private readonly commandkit: CommandKit,\n private readonly config: LocalizationConfig)\n {\n const strategy = this.commandkit.config.localizationStrategy;\n const { locale, target } = this.config;\n\n // we are doing this so that it can be destructured\n // eg: const { t } = ctx.locale()\n this.t = (translatable, args) => {\n return strategy.translate({\n args,\n key: translatable,\n locale,\n scope: target\n });\n };\n }\n\n /**\n * Get the localization strategy.\n */\n public getStrategy() {\n return this.commandkit.config.localizationStrategy;\n }\n\n /**\n * Get the default locale\n */\n public getDefaultLocale() {\n return this.commandkit.config.defaultLocale;\n }\n\n /**\n * Get the current locale\n */\n public getLocale() {\n return this.config.locale;\n }\n\n /**\n * Get the localization target\n */\n public getTarget() {\n return this.config.target;\n }\n}","import type { EventHandlerOptions, EventHandlerData } from './typings';\nimport type { CommandHandler } from '../command-handler/CommandHandler';\nimport { getFilePaths, getFolderPaths } from '../../../utils/get-paths';\nimport { toFileURL } from '../../../utils/resolve-file-url';\nimport { clone } from '../../../utils/clone';\nimport colors from '../../../utils/colors';\nimport { ParsedEvent } from '../../../app/router';\n\n/**\n * A handler for client events.\n */\nexport class EventHandler {\n #data: EventHandlerData;\n #listening = new Set<string>();\n\n constructor({ ...options }: EventHandlerOptions) {\n this.#data = {\n ...options,\n events: []\n };\n }\n\n async init() {\n await this.#buildEvents();\n this.#registerEvents();\n }\n\n async #buildEvents() {\n const eventFolderPaths = await getFolderPaths(this.#data.eventsPath);\n\n for (const eventFolderPath of eventFolderPaths) {\n const eventName = eventFolderPath.\n replace(/\\\\\\\\|\\\\/g, '/').\n split('/').\n pop() as string;\n\n const allowedExtensions = /\\.(js|mjs|cjs|ts)$/i;\n const eventPaths = await getFilePaths(eventFolderPath, true);\n\n const eventFilePaths = eventPaths.filter((path) =>\n allowedExtensions.test(path)\n );\n\n // const eventObj = {\n // name: eventName,\n // functions: [] as Function[],\n // };\n\n // this.#data.events.push(eventObj);\n\n let eventObj = this.#data.events.find((e) => e.name === eventName);\n\n if (!eventObj) {\n eventObj = {\n name: eventName,\n functions: []\n };\n\n this.#data.events.push(eventObj);\n }\n\n for (const eventFilePath of eventFilePaths) {\n const modulePath = toFileURL(eventFilePath);\n\n let importedFunction = (await import(`${modulePath}?t=${Date.now()}`)).\n default;\n let eventFunction = clone(importedFunction);\n\n // If it's CommonJS, invalidate the import cache\n if (typeof module !== 'undefined' && typeof require !== 'undefined') {\n delete require.cache[require.resolve(eventFilePath)];\n }\n\n if (eventFunction?.default) {\n eventFunction = eventFunction.default;\n }\n\n const compactFilePath =\n eventFilePath.split(process.cwd())[1] || eventFilePath;\n\n if (typeof eventFunction !== 'function') {\n process.emitWarning(\n colors.yellow(\n `Ignoring: Event file ${compactFilePath} does not export a function.`\n )\n );\n continue;\n }\n\n eventObj.functions.push(eventFunction);\n }\n }\n }\n\n async registerExternal(entry: ParsedEvent) {\n const { event, listeners } = entry;\n\n const functions = await Promise.all(\n listeners.map(async (l) =>\n import(`${toFileURL(l)}?t=${Date.now()}`).then((m) => m.default)\n )\n );\n\n const existing = this.#data.events.find((e) => e.name === event);\n\n if (existing) {\n existing.functions.unshift(...functions);\n } else {\n this.#data.events.unshift({\n name: event,\n functions\n });\n }\n }\n\n resyncListeners() {\n const client = this.#data.client;\n const handler = this.#data.commandKitInstance;\n\n for (const eventObj of this.#data.events) {\n if (this.#listening.has(eventObj.name)) continue;\n\n client.on(eventObj.name, async (...params) => {\n for (const eventFunction of eventObj.functions) {\n const stopEventLoop = await eventFunction(...params, client, handler);\n\n if (stopEventLoop) {\n break;\n }\n }\n });\n\n this.#listening.add(eventObj.name);\n }\n }\n\n #registerEvents() {\n const client = this.#data.client;\n const handler = this.#data.commandKitInstance;\n\n for (const eventObj of this.#data.events) {\n client.on(eventObj.name, async (...params) => {\n for (const eventFunction of eventObj.functions) {\n const stopEventLoop = await eventFunction(...params, client, handler);\n\n if (stopEventLoop) {\n break;\n }\n }\n });\n\n this.#listening.add(eventObj.name);\n }\n }\n\n get events() {\n return this.#data.events;\n }\n\n async reloadEvents(commandHandler?: CommandHandler) {\n if (!this.#data.eventsPath) {\n throw new Error(\n colors.red(\n 'Cannot reload events as \"eventsPath\" was not provided when instantiating CommandKit.'\n )\n );\n }\n\n this.#data.events = [];\n\n await this.#buildEvents();\n\n this.#listening.clear();\n this.#data.client.removeAllListeners();\n\n this.#registerEvents();\n\n // Re-register \"interactionCreate\" event for application commands.\n commandHandler?.handleCommands();\n }\n}","import type {\n ValidationHandlerData,\n ValidationHandlerOptions } from\n'./typings';\nimport { toFileURL } from '../../../utils/resolve-file-url';\nimport { getFilePaths } from '../../../utils/get-paths';\nimport { clone } from '../../../utils/clone';\nimport colors from '../../../utils/colors';\n\n/**\n * A handler for command validations.\n */\nexport class ValidationHandler {\n #data: ValidationHandlerData;\n\n constructor({ ...options }: ValidationHandlerOptions) {\n this.#data = {\n ...options,\n validations: []\n };\n }\n\n async init() {\n this.#data.validations = await this.#buildValidations();\n }\n\n async #buildValidations() {\n const allowedExtensions = /\\.(js|mjs|cjs|ts)$/i;\n\n const validationPaths = await getFilePaths(\n this.#data.validationsPath,\n true\n );\n const validationFilePaths = validationPaths.filter((path) =>\n allowedExtensions.test(path)\n );\n\n const validationFunctions: Function[] = [];\n\n for (const validationFilePath of validationFilePaths) {\n const modulePath = toFileURL(validationFilePath);\n\n let importedFunction = (await import(`${modulePath}?t=${Date.now()}`)).\n default;\n let validationFunction = clone(importedFunction);\n\n // If it's CommonJS, invalidate the import cache\n if (typeof module !== 'undefined' && typeof require !== 'undefined') {\n delete require.cache[require.resolve(validationFilePath)];\n }\n\n if (validationFunction?.default) {\n validationFunction = validationFunction.default;\n }\n\n const compactFilePath =\n validationFilePath.split(process.cwd())[1] || validationFilePath;\n\n if (typeof validationFunction !== 'function') {\n process.emitWarning(\n colors.yellow(\n `Ignoring: Validation file ${compactFilePath} does not export a function.`\n )\n );\n continue;\n }\n\n validationFunctions.push(validationFunction);\n }\n\n return validationFunctions;\n }\n\n get validations() {\n return this.#data.validations;\n }\n\n async reloadValidations() {\n if (!this.#data.validationsPath) {\n throw new Error(\n colors.red(\n 'Cannot reload validations as \"validationsPath\" was not provided when instantiating CommandKit.'\n )\n );\n }\n\n const newValidations = await this.#buildValidations();\n\n this.#data.validations = newValidations;\n }\n}","export interface CacheEntry<T = unknown> {\n value: T;\n ttl?: number;\n}\n\nexport abstract class CacheProvider {\n abstract get<T>(key: string): Promise<CacheEntry<T> | undefined>;\n abstract set<T>(key: string, value: T, ttl?: number): Promise<void>;\n abstract exists(key: string): Promise<boolean>;\n abstract delete(key: string): Promise<void>;\n abstract clear(): Promise<void>;\n abstract expire(key: string, ttl: number): Promise<void>;\n}","import { CacheEntry, CacheProvider } from './CacheProvider';\n\nexport class MemoryCache extends CacheProvider {\n #cache = new Map<string, CacheEntry>();\n\n public async get<T>(key: string): Promise<CacheEntry<T> | undefined> {\n const entry = this.#cache.get(key);\n\n if (!entry) {\n return undefined;\n }\n\n if (entry.ttl && Date.now() > entry.ttl) {\n this.#cache.delete(key);\n return undefined;\n }\n\n return entry as CacheEntry<T>;\n }\n\n public async set<T>(key: string, value: T, ttl?: number): Promise<void> {\n const entry: CacheEntry<T> = {\n value,\n ttl: ttl != null ? Date.now() + ttl : undefined\n };\n\n this.#cache.set(key, entry);\n }\n\n public async exists(key: string): Promise<boolean> {\n return this.#cache.has(key);\n }\n\n public async delete(key: string): Promise<void> {\n this.#cache.delete(key);\n }\n\n public async clear(): Promise<void> {\n this.#cache.clear();\n }\n\n public async expire(key: string, ttl: number): Promise<void> {\n const entry = this.#cache.get(key);\n\n if (!entry) return;\n\n const _ttl = Date.now() + ttl;\n\n // delete if _ttl is in the past\n if (_ttl < Date.now()) {\n this.#cache.delete(key);\n return;\n }\n\n entry.ttl = _ttl;\n }\n}","// action row\nexport * from './action-row/ActionRow';\n\n// buttons\nexport * from './button/ButtonKit';\nexport * from './button/Button';\n\n// modals\nexport * from './modal/ModalKit';\nexport * from './modal/Modal';\n\n// common\nexport * from './common/element';\nexport * from './common/types';\nexport * from './common/EventInterceptor';","import { ActionRowBuilder } from 'discord.js';\nimport { AnyCommandKitElement, CommandKitElement } from '../common/element';\n\nexport interface ActionRowProps {\n children?: AnyCommandKitElement[] | AnyCommandKitElement;\n}\n\n/**\n * The action row component.\n * @param props The action row properties.\n * @returns The commandkit element.\n * @example <ActionRow><Button label=\"Click me\" style={ButtonStyle.Primary} customId=\"click_me\" /></ActionRow>\n */\nexport function ActionRow(\nprops: ActionRowProps)\n: CommandKitElement<'action-row'> {\n const row = new ActionRowBuilder();\n\n if (Array.isArray(props.children)) {\n // @ts-ignore\n row.setComponents(...props.children);\n } else if (props.children) {\n // @ts-ignore\n row.setComponents(props.children);\n }\n\n return row;\n}","import {\n type Awaitable,\n type ButtonInteraction,\n ButtonStyle,\n ButtonBuilder,\n Events } from\n'discord.js';\nimport {\n exitContext,\n getCommandKit,\n getContext } from\n'../../context/async-context';\nimport {\n EventInterceptorContextData,\n EventInterceptorErrorHandler } from\n'../common/EventInterceptor';\n\nexport type ButtonKitPredicate = (\ninteraction: ButtonInteraction)\n=> Awaitable<boolean>;\n\n/**\n * The handler to run when a button is clicked. This handler is called with the interaction as the first argument.\n * If the first argument is null, it means that the interaction collector has been destroyed.\n */\nexport type OnButtonKitClick =\nCommandKitButtonBuilderInteractionCollectorDispatch;\n\n/**\n * The handler to run when the interaction collector ends. This handler is called with the reason as the first argument.\n * If the first argument is null, it means that the interaction collector has been destroyed.\n */\nexport type OnButtonKitEnd = CommandKitButtonBuilderOnEnd;\n\n/**\n * The handler to run when a button is clicked. This handler is called with the interaction as the first argument.\n * If the first argument is null, it means that the interaction collector has been destroyed.\n */\nexport type CommandKitButtonBuilderInteractionCollectorDispatch = (\ninteraction: ButtonInteraction,\ncontext: ButtonKit)\n=> Awaitable<void>;\n\nexport type CommandKitButtonBuilderOnEnd = (reason: string) => Awaitable<void>;\n\nexport type CommandKitButtonBuilderInteractionCollectorDispatchContextData =\nEventInterceptorContextData<Events.InteractionCreate>;\n\nexport class ButtonKit extends ButtonBuilder {\n #onClickHandler: CommandKitButtonBuilderInteractionCollectorDispatch | null =\n null;\n #contextData: CommandKitButtonBuilderInteractionCollectorDispatchContextData | null =\n {\n autoReset: true,\n time: 5 * 60 * 1000,\n once: false\n };\n #unsub: (() => void) | null = null;\n\n #getEventInterceptor() {\n const ctx = getContext();\n if (!ctx) return getCommandKit(true).eventInterceptor;\n\n return exitContext(() => ctx.commandkit.eventInterceptor);\n }\n\n /**\n * Sets up an inline interaction collector for this button. This collector by default allows as many interactions as possible if it is actively used.\n * If unused, this expires after 24 hours or custom time if specified.\n * @param handler The handler to run when the button is clicked\n * @param data The context data to use for the interaction collector\n * @returns This button\n * @example\n * ```ts\n * const button = new ButtonKit()\n * .setLabel('Click me')\n * .setStyle(ButtonStyle.Primary)\n * .setCustomId('click_me')\n * .filter((interaction) => interaction.user.id === '1234567890')\n * .onClick(async (interaction) => {\n * await interaction.reply('You clicked me!');\n * });\n *\n * const row = new ActionRowBuilder().addComponents(button);\n *\n * const message = await channel.send({ content: 'Click the button', components: [row] });\n *\n * // Remove onClick handler and destroy the interaction collector\n * button.onClick(null);\n * ```\n */\n public onClick(\n handler: CommandKitButtonBuilderInteractionCollectorDispatch,\n data?: CommandKitButtonBuilderInteractionCollectorDispatchContextData)\n : this {\n if (this.data.style === ButtonStyle.Link) {\n throw new TypeError('Cannot setup \"onClick\" handler on link buttons.');\n }\n\n if (!handler) {\n throw new TypeError(\n 'Cannot setup \"onClick\" without a handler function parameter.'\n );\n }\n\n if (this.#onClickHandler) {\n this.#destroyCollector();\n }\n\n this.#onClickHandler = handler;\n if (data) {\n this.#contextData = {\n autoReset: data.autoReset ?? this.#contextData?.autoReset ?? true,\n time: data.time ?? this.#contextData?.time ?? 5 * 60 * 1000,\n filter: data.filter ?? this.#contextData?.filter,\n onEnd: data.onEnd ?? this.#contextData?.onEnd\n };\n }\n\n this.#setupInteractionCollector();\n\n return this;\n }\n\n public onEnd(handler: CommandKitButtonBuilderOnEnd): this {\n if (this.data.style === ButtonStyle.Link) {\n throw new TypeError('Cannot setup \"onEnd\" handler on link buttons.');\n }\n\n if (!handler) {\n throw new TypeError(\n 'Cannot setup \"onEnd\" without a handler function parameter.'\n );\n }\n\n this.#contextData ??= {};\n this.#contextData.onEnd = handler;\n\n return this;\n }\n\n /**\n * Sets the handler to run when the interaction collector ends.\n * @param handler - The handler to run when the interaction collector ends.\n * @returns This instance of the modal builder.\n */\n public onError(handler: EventInterceptorErrorHandler): this {\n if (!handler) {\n throw new TypeError(\n 'Cannot setup \"onError\" without a handler function parameter.'\n );\n }\n\n this.#contextData ??= {};\n this.#contextData.onError = handler;\n\n return this;\n }\n\n /**\n * Sets a filter for the interaction collector.\n * @param predicate The filter to use for the interaction collector\n */\n public filter(predicate: ButtonKitPredicate): this {\n this.#contextData ??= {\n autoReset: true,\n time: 5 * 60 * 1000\n };\n // @ts-ignore\n this.#contextData.filter = predicate;\n\n return this;\n }\n\n private get customId() {\n // @ts-ignore\n return this.data.custom_id ?? this.data.customId;\n }\n\n #setupInteractionCollector() {\n if (\n this.data.style === ButtonStyle.Link ||\n !this.#contextData ||\n !this.#onClickHandler)\n\n return;\n\n const myCustomId = this.customId ?? null;\n\n if (myCustomId === null) {\n throw new TypeError(\n 'Cannot setup \"onClick\" handler on a button without a custom id.'\n );\n }\n\n const interceptor = this.#getEventInterceptor();\n\n this.#unsub = interceptor.subscribe(\n Events.InteractionCreate,\n async (interaction) => {\n if (!interaction.isButton()) return;\n\n const myCustomId = this.customId ?? null;\n const interactionCustomId = interaction.customId;\n\n if (myCustomId && interactionCustomId !== myCustomId) return;\n\n const filter = this.#contextData?.filter;\n\n if (filter && !(await filter(interaction))) return;\n\n const handler = this.#onClickHandler;\n\n if (!handler) return this.#unsub?.();\n\n return handler(interaction, this);\n },\n this.#contextData\n );\n }\n\n public dispose() {\n this.#destroyCollector();\n return this;\n }\n\n #destroyCollector() {\n this.#unsub?.();\n this.#unsub = null;\n this.#contextData = null;\n this.#onClickHandler = null;\n }\n}","import { ButtonStyle, ComponentEmojiResolvable } from 'discord.js';\nimport {\n ButtonKit,\n CommandKitButtonBuilderOnEnd,\n type CommandKitButtonBuilderInteractionCollectorDispatch,\n type CommandKitButtonBuilderInteractionCollectorDispatchContextData } from\n'./ButtonKit';\nimport { CommandKitElement } from '../common/element';\nimport { MaybeArray } from '../common/types';\nimport { EventInterceptorErrorHandler } from '../common/EventInterceptor';\n\nexport type ButtonChildrenLike = string | number | boolean;\n\nexport interface ButtonProps {\n label?: string;\n style?: ButtonStyle;\n emoji?: ComponentEmojiResolvable;\n disabled?: boolean;\n customId?: string;\n url?: string;\n skuId?: string;\n onClick?: CommandKitButtonBuilderInteractionCollectorDispatch;\n onError?: EventInterceptorErrorHandler;\n options?: CommandKitButtonBuilderInteractionCollectorDispatchContextData;\n onEnd?: CommandKitButtonBuilderOnEnd;\n children?: MaybeArray<ButtonChildrenLike>;\n}\n\n/**\n * The button component.\n * @param props The button properties.\n * @returns The commandkit element.\n * @example <Button style={ButtonStyle.Primary} customId=\"click_me\">Click Me</Button>\n */\nexport function Button(props: ButtonProps): CommandKitElement<'button-kit'> {\n const button = new ButtonKit();\n\n props.style ??= ButtonStyle.Primary;\n\n // auto-generate customId if not provided (only if onClick is set)\n if (props.onClick) {\n props.customId ??= `buttonkit::${crypto.randomUUID()}`;\n }\n\n if (props.customId) {\n button.setCustomId(props.customId);\n }\n\n if (props.onClick) {\n button.onClick(props.onClick, props.options);\n }\n\n if (props.disabled) {\n button.setDisabled(props.disabled);\n }\n\n if (props.emoji) {\n button.setEmoji(props.emoji);\n }\n\n if (props.skuId) {\n button.setSKUId(props.skuId);\n }\n\n if (props.url) {\n button.setURL(props.url);\n }\n\n if (props.style) {\n button.setStyle(props.style);\n }\n\n const label = props.label || props.children;\n\n if (label) {\n button.setLabel(\n Array.isArray(label) ?\n label.join(' ') :\n typeof label === 'string' ?\n label :\n String(label)\n );\n }\n\n if (props.onEnd) {\n button.onEnd(props.onEnd);\n }\n\n if (props.onError) {\n button.onError(props.onError);\n }\n\n return button;\n}","import {\n Awaitable,\n Events,\n ModalBuilder,\n ModalSubmitInteraction } from\n'discord.js';\nimport {\n exitContext,\n getCommandKit,\n getContext } from\n'../../context/async-context';\nimport {\n EventInterceptorContextData,\n EventInterceptorErrorHandler } from\n'../common/EventInterceptor';\n\nexport type ModalKitPredicate = (\ninteraction: ModalSubmitInteraction)\n=> Awaitable<boolean>;\n\n/**\n * The handler to run when a modal is submitted. This handler is called with the interaction as the first argument.\n * If the first argument is null, it means that the interaction collector has been destroyed.\n */\nexport type OnModalKitSubmit =\nCommandKitModalBuilderInteractionCollectorDispatch;\n\n/**\n * The handler to run when the interaction collector ends. This handler is called with the reason as the first argument.\n * If the first argument is null, it means that the interaction collector has been destroyed.\n */\nexport type OnModalKitEnd = CommandKitModalBuilderOnEnd;\n\n/**\n * The handler to run when a modal is submitted. This handler is called with the interaction as the first argument.\n * If the first argument is null, it means that the interaction collector has been destroyed.\n */\nexport type CommandKitModalBuilderInteractionCollectorDispatch = (\ninteraction: ModalSubmitInteraction,\ncontext: ModalKit)\n=> Awaitable<void>;\n\nexport type CommandKitModalBuilderOnEnd = (reason: string) => Awaitable<void>;\n\nexport type CommandKitModalBuilderInteractionCollectorDispatchContextData =\nEventInterceptorContextData<Events.InteractionCreate>;\n\nexport class ModalKit extends ModalBuilder {\n #onSubmitHandler: CommandKitModalBuilderInteractionCollectorDispatch | null =\n null;\n #contextData: CommandKitModalBuilderInteractionCollectorDispatchContextData | null =\n {\n autoReset: false,\n time: 5 * 60 * 1000,\n once: true\n };\n #unsub: (() => void) | null = null;\n\n #getEventInterceptor() {\n const ctx = getContext();\n if (!ctx) return getCommandKit(true).eventInterceptor;\n\n return exitContext(() => ctx.commandkit.eventInterceptor);\n }\n\n /**\n * Sets the handler to run when the modal is submitted.\n * @param handler - The handler to run when the modal is submitted.\n * @param data - The context data for the interaction collector.\n * @returns This instance of the modal builder.\n * @example\n * ```ts\n * const modal = new ModalKit()\n * .setTitle('My Modal')\n * .setCustomId('my-modal')\n * .filter((interaction) => interaction.user.id === '1234567890')\n * .onSubmit(async (interaction) => {\n * await interaction.reply('You submitted the modal!');\n * })\n * .addComponents(actionRow1, actionRow2);\n * ```\n */\n public onSubmit(\n handler: CommandKitModalBuilderInteractionCollectorDispatch,\n data?: CommandKitModalBuilderInteractionCollectorDispatchContextData)\n : this {\n if (!handler) {\n throw new TypeError(\n 'Cannot setup \"onClick\" without a handler function parameter.'\n );\n }\n\n if (this.#onSubmitHandler) {\n this.#destroyCollector();\n }\n\n this.#onSubmitHandler = handler;\n\n if (data) {\n this.#contextData = {\n autoReset: data.autoReset ?? this.#contextData?.autoReset ?? true,\n time: data.time ?? this.#contextData?.time ?? 5 * 60 * 1000,\n filter: data.filter ?? this.#contextData?.filter,\n onEnd: data.onEnd ?? this.#contextData?.onEnd\n };\n }\n\n this.#setupCollector();\n\n return this;\n }\n\n /**\n * Sets the handler to run when the interaction collector ends.\n * @param handler - The handler to run when the interaction collector ends.\n * @returns This instance of the modal builder.\n */\n public onEnd(handler: CommandKitModalBuilderOnEnd): this {\n if (!handler) {\n throw new TypeError(\n 'Cannot setup \"onEnd\" without a handler function parameter.'\n );\n }\n\n this.#contextData ??= {};\n this.#contextData.onEnd = handler;\n\n return this;\n }\n\n /**\n * Sets the handler to run when the interaction collector ends.\n * @param handler - The handler to run when the interaction collector ends.\n * @returns This instance of the modal builder.\n */\n public onError(handler: EventInterceptorErrorHandler): this {\n if (!handler) {\n throw new TypeError(\n 'Cannot setup \"onError\" without a handler function parameter.'\n );\n }\n\n this.#contextData ??= {};\n this.#contextData.onError = handler;\n\n return this;\n }\n\n /**\n * Sets a filter for the interaction collector.\n * @param predicate - The filter to use for the interaction collector.\n * @returns This instance of the modal builder.\n */\n public filter(predicate: ModalKitPredicate): this {\n this.#contextData ??= {\n autoReset: true,\n time: 5 * 60 * 1000\n };\n // @ts-ignore\n this.#contextData.filter = predicate;\n\n return this;\n }\n\n private get customId() {\n // @ts-ignore\n return this.data.custom_id ?? this.data.customId;\n }\n\n #setupCollector() {\n if (!this.#contextData) return;\n\n if (!this.customId) {\n throw new TypeError(\n 'Cannot setup an modal collector without a custom ID.'\n );\n }\n\n const interceptor = this.#getEventInterceptor();\n if (!interceptor) return;\n\n this.#unsub = interceptor.subscribe(\n Events.InteractionCreate,\n async (interaction) => {\n if (!interaction.isModalSubmit()) return;\n\n const myCustomId = this.customId ?? null;\n const interactionCustomId = interaction.customId;\n\n if (myCustomId && interactionCustomId !== myCustomId) return;\n\n const filter = this.#contextData?.filter;\n\n if (filter && !(await filter(interaction))) return;\n\n const handler = this.#onSubmitHandler;\n\n if (!handler) return this.#unsub?.();\n\n return handler(interaction, this);\n },\n this.#contextData\n );\n }\n\n public dispose() {\n this.#destroyCollector();\n return this;\n }\n\n #destroyCollector() {\n this.#unsub?.();\n this.#unsub = null;\n this.#onSubmitHandler = null;\n this.#contextData = null;\n }\n}","import { ActionRowBuilder, TextInputBuilder, TextInputStyle } from 'discord.js';\nimport { MaybeArray } from '../common/types';\nimport { CommandKitElement } from '../common/element';\nimport {\n CommandKitModalBuilderInteractionCollectorDispatchContextData,\n ModalKit,\n OnModalKitEnd,\n OnModalKitSubmit } from\n'./ModalKit';\nimport { EventInterceptorErrorHandler } from '../common/EventInterceptor';\n\nexport interface ModalProps {\n customId?: string;\n title: string;\n children?: MaybeArray<TextInputBuilder | ActionRowBuilder>;\n onSubmit?: OnModalKitSubmit;\n onEnd?: OnModalKitEnd;\n onError?: EventInterceptorErrorHandler;\n options?: CommandKitModalBuilderInteractionCollectorDispatchContextData;\n}\n\n/**\n * The modal component.\n * @param props The modal properties.\n * @returns The commandkit element.\n * @example <Modal title=\"My Modal\" onSubmit={onSubmit}>...</Modal>\n */\nexport function Modal(props: ModalProps): CommandKitElement<'modal'> {\n const modal = new ModalKit();\n\n if (props.title) {\n modal.setTitle(props.title);\n }\n\n if (props.onSubmit) {\n props.customId ??= `modalkit::${crypto.randomUUID()}`;\n }\n\n if (props.customId) {\n modal.setCustomId(props.customId);\n }\n\n if (props.onSubmit) {\n modal.onSubmit(props.onSubmit, props.options);\n }\n\n if (props.children) {\n const childs = (\n Array.isArray(props.children) ? props.children : [props.children]).\n\n map((c) => {\n if (c instanceof ActionRowBuilder) return c;\n if (c instanceof TextInputBuilder)\n return new ActionRowBuilder().addComponents(c);\n }).\n filter((c): c is ActionRowBuilder<TextInputBuilder> => c != null);\n\n modal.addComponents(childs);\n }\n\n if (props.onEnd) {\n modal.onEnd(props.onEnd);\n }\n\n if (props.onError) {\n modal.onError(props.onError);\n }\n\n return modal;\n}\n\nexport interface TextInputProps {\n customId: string;\n label: string;\n placeholder?: string;\n maxLength?: number;\n minLength?: number;\n value?: string;\n required?: boolean;\n}\n\n/**\n * The text input component.\n * @param props The text input properties.\n * @returns The commandkit element.\n * @example <TextInput customId=\"input\" label=\"Input\" style={TextInputStyle.Short} />\n */\nexport function TextInput(\nprops: TextInputProps & {style: TextInputStyle;})\n: CommandKitElement<'text-input'> {\n const input = new TextInputBuilder().setStyle(props.style);\n\n if (props.customId) {\n input.setCustomId(props.customId);\n }\n\n if (props.label) {\n input.setLabel(props.label);\n }\n\n if (props.placeholder) {\n input.setPlaceholder(props.placeholder);\n }\n\n if (props.maxLength) {\n input.setMaxLength(props.maxLength);\n }\n\n if (props.minLength) {\n input.setMinLength(props.minLength);\n }\n\n if (props.value) {\n input.setValue(props.value);\n }\n\n if (props.required) {\n input.setRequired(props.required);\n }\n\n return input;\n}\n\n/**\n * The short text input component.\n * @param props The text input properties.\n * @returns The commandkit element.\n * @example <ShortInput customId=\"input\" label=\"Input\" />\n */\nexport function ShortInput(\nprops: TextInputProps)\n: CommandKitElement<'text-input'> {\n return TextInput({ ...props, style: TextInputStyle.Short });\n}\n\n/**\n * The paragraph text input component.\n * @param props The text input properties.\n * @returns The commandkit element.\n * @example <ParagraphInput customId=\"input\" label=\"Input\" />\n */\nexport function ParagraphInput(\nprops: TextInputProps)\n: CommandKitElement<'text-input'> {\n return TextInput({ ...props, style: TextInputStyle.Paragraph });\n}","import { ActionRowBuilder, TextInputBuilder } from 'discord.js';\nimport type { ButtonKit } from '../button/ButtonKit';\nimport { warnUnstable } from '../../utils/warn-unstable';\nimport { ModalKit } from '../modal/ModalKit';\n\nexport const ElementType = {\n ActionRow: 'action-row',\n Button: 'button-kit',\n Modal: 'modal',\n TextInput: 'text-input'\n} as const;\n\nexport type ElementType = (typeof ElementType)[keyof typeof ElementType];\n\nexport interface CommandKitElementData {\n [ElementType.ActionRow]: ActionRowBuilder;\n [ElementType.Button]: ButtonKit;\n [ElementType.Modal]: ModalKit;\n [ElementType.TextInput]: TextInputBuilder;\n}\n\nexport type CommandKitElement<Type extends ElementType> =\nCommandKitElementData[Type];\n\nexport type AnyCommandKitElement = CommandKitElement<ElementType>;\n\nexport function isCommandKitElement(\nelement: unknown)\n: element is CommandKitElement<ElementType> {\n if (typeof element !== 'object' || element === null) return false;\n if (!Reflect.has(element, 'type')) return false;\n if (!Reflect.has(element, 'data')) return false;\n\n return true;\n}\n\nexport function getElement<\n T extends ElementType,\n E extends CommandKitElement<T>>(\nelement: E): CommandKitElementData[T] {\n return element.data as CommandKitElementData[T];\n}\n\nexport interface FragmentElementProps {\n children: [];\n}\n\nexport function Fragment(\nprops: FragmentElementProps)\n: CommandKitElementData[ElementType][] {\n warnUnstable('CommandKit JSX');\n return Array.isArray(props.children) ? props.children.flat() : props.children;\n}\n\nexport function createElement(\ntype: Function,\nprops: Record<string, unknown>,\n...children: any[])\n: CommandKitElement<ElementType> {\n warnUnstable('CommandKit JSX');\n return type({ ...props, children });\n}","const WARNED_KEYS = new Set<string>();\n\nexport function emitWarning(message: string, code = 'CommandKitWarning') {\n process.emitWarning(message, { code });\n}\n\nexport function warnUnstable(name: string) {\n if (WARNED_KEYS.has(name)) return;\n\n WARNED_KEYS.add(name);\n\n emitWarning(\n `${name} is unstable and may change in future versions.`,\n 'CommandKitUnstableWarning'\n );\n}","export type MaybeArray<T> = T | T[];","import { Awaitable, Client, ClientEvents, Events } from 'discord.js';\n\nexport interface EventInterceptorContextData<E extends keyof ClientEvents> {\n /**\n * The filter to use for the collector.\n */\n filter?: (...args: ClientEvents[E]) => Awaitable<boolean>;\n /**\n * The duration (in ms) that the collector should run for.\n */\n time?: number;\n /**\n * If the collector should automatically reset the timer when a button is clicked.\n */\n autoReset?: boolean;\n /**\n * Whether the collector should run only once.\n */\n once?: boolean;\n /**\n * The handler to run when the collector ends.\n */\n onEnd?: (reason: string) => Awaitable<void>;\n /**\n * The handler to run upon an error.\n */\n onError?: EventInterceptorErrorHandler;\n}\n\nexport type EventInterceptorErrorHandler = (error: Error) => Awaitable<void>;\n\nexport class EventInterceptor {\n private subscribers = new Map<\n keyof ClientEvents,\n Set<(...args: any[]) => void>>(\n );\n private globalHandlers = new Map<\n keyof ClientEvents,\n (...args: any[]) => void>(\n );\n private cleanupTimer: NodeJS.Timeout | null = null;\n\n /**\n * Creates the event interceptor.\n */\n public constructor(public readonly client: Client) {\n this.#cleanupLoop();\n }\n\n #cleanupLoop() {\n if (this.cleanupTimer) clearInterval(this.cleanupTimer);\n\n this.cleanupTimer = setInterval(() => {\n for (const [event, handlers] of this.subscribers) {\n for (const handler of handlers) {\n const options = Reflect.get(\n handler,\n 'options'\n ) as EventInterceptorContextData<keyof ClientEvents> & {\n registeredAt: number;\n };\n\n const isExpired =\n options.time && Date.now() - options.registeredAt > options.time;\n\n if (isExpired) {\n this.unsubscribe(event, handler, 'time');\n }\n }\n }\n }, 60_000).unref();\n }\n\n /**\n * Destroys the event interceptor.\n */\n public destroy(): void {\n if (this.cleanupTimer) {\n clearInterval(this.cleanupTimer);\n this.cleanupTimer = null;\n }\n\n for (const [event, handlers] of this.subscribers) {\n for (const handler of handlers) {\n this.unsubscribe(event, handler, 'destroy');\n }\n }\n\n this.subscribers.clear();\n this.globalHandlers.clear();\n }\n\n /**\n * Whether the event has subscribers.\n * @param event The event to check.\n */\n public hasSubscribers(event: keyof ClientEvents): boolean {\n return this.subscribers.has(event);\n }\n\n /**\n * Returns the number of subscribers for the event.\n * @param event The event to check.\n */\n public getSubscriberCount(event: keyof ClientEvents): number {\n const handlers = this.subscribers.get(event);\n return handlers?.size ?? 0;\n }\n\n /**\n * Whether the event has global handlers.\n */\n public hasGlobalHandlers(): boolean {\n return this.globalHandlers.size > 0;\n }\n\n /**\n * Returns the number of global handlers.\n */\n public getGlobalHandlersCount(): number {\n return this.subscribers.size;\n }\n\n /**\n * Subscribes to an event.\n * @param event The event to subscribe to.\n * @param listener The listener to call when the event is emitted.\n * @returns A function to unsubscribe from the event.\n */\n public subscribe<Event extends keyof ClientEvents>(\n event: Event,\n listener: (...args: ClientEvents[Event]) => void,\n options?: EventInterceptorContextData<Event>)\n : () => void {\n if (!this.subscribers.has(event)) {\n this.subscribers.set(event, new Set());\n this.client.on(event, this.createGlobalHandler(event));\n this.client.setMaxListeners(this.client.getMaxListeners() + 1);\n }\n\n options ??= {};\n\n // @ts-ignore\n options.registeredAt = Date.now();\n\n Reflect.set(listener, 'options', options);\n\n this.subscribers.get(event)!.add(listener);\n\n return () => {\n this.unsubscribe(event, listener);\n };\n }\n\n /**\n * Unsubscribes from an event.\n * @param event The event to unsubscribe from.\n */\n public unsubscribe<Event extends keyof ClientEvents>(\n event: Event,\n listener: (...args: ClientEvents[Event]) => void,\n reason?: string)\n : void {\n const handlers = this.subscribers.get(event);\n if (!handlers) return;\n\n handlers.delete(listener);\n\n if (handlers.size < 1) {\n this.subscribers.delete(event);\n this.client.removeListener(event, this.globalHandlers.get(event)!);\n this.globalHandlers.delete(event);\n this.client.setMaxListeners(\n Math.max(this.client.getMaxListeners() - 1, 0)\n );\n }\n\n Reflect.get(listener, 'options').onEnd?.(reason ?? 'unsubscribe');\n }\n\n /**\n * Creates a global handler for the event.\n * @param event The event to create a global handler for.\n * @returns The global handler.\n */\n private createGlobalHandler<Event extends keyof ClientEvents>(\n event: Event)\n : (...args: ClientEvents[Event]) => void {\n if (this.globalHandlers.has(event)) {\n return this.globalHandlers.get(event)!;\n }\n\n const handler = async (...args: ClientEvents[Event]) => {\n const subscribers = this.subscribers.get(event);\n if (subscribers && subscribers.size > 0) {\n for (const subscriber of subscribers) {\n const options = Reflect.get(\n subscriber,\n 'options'\n ) as EventInterceptorContextData<Event> & {registeredAt: number;};\n\n const isExpired =\n options.time && Date.now() - options.registeredAt > options.time;\n\n if (isExpired) {\n this.unsubscribe(event, subscriber, 'time');\n continue;\n }\n\n if (options.autoReset) {\n options.registeredAt = Date.now();\n }\n\n if (options.filter && !(await options.filter(...args))) {\n continue;\n }\n\n try {\n await subscriber(...args);\n } catch (e) {\n if (options.onError) {\n await options.onError(<Error> e);\n } else {\n throw e;\n }\n } finally {\n if (options.once) {\n this.unsubscribe(event, subscriber, 'once');\n }\n }\n }\n }\n };\n\n this.globalHandlers.set(event, handler);\n\n return handler;\n }\n}","import { Locale } from 'discord.js';\nimport { CommandKit } from '../../CommandKit';\nimport {\n LocalizationStrategy,\n LocalizationTranslationRequest,\n TranslationResult } from\n'./LocalizationStrategy';\nimport { Translation } from './Translation';\nimport { readFile } from 'node:fs/promises';\nimport { join } from 'node:path';\n\nexport class DefaultLocalizationStrategy implements LocalizationStrategy {\n private translations: Map<string, Translation> = new Map();\n\n public constructor(private readonly commandkit: CommandKit) {}\n\n public async locateTranslation(scope: string, locale: Locale) {\n const localesPath = this.commandkit.getPath('locales');\n\n if (!localesPath) return null;\n\n const path = join(localesPath, locale, `${scope}.json`);\n\n try {\n const data = await readFile(path, 'utf-8');\n\n return JSON.parse(data) as Translation;\n } catch {\n return null;\n }\n }\n\n public async getTranslationStrict(scope: string, locale: Locale) {\n const key = `${scope}:${locale}`;\n if (!this.translations.has(key)) {\n const translation = await this.locateTranslation(scope, locale);\n\n if (!translation) {\n throw new Error(`Translation not found for ${key}`);\n }\n\n this.translations.set(key, translation);\n\n return translation;\n }\n\n return this.translations.get(key)!;\n }\n\n public async getTranslation(\n scope: string,\n locale: Locale)\n : Promise<Translation | null> {\n try {\n return this.getTranslationStrict(scope, locale);\n } catch (e) {\n return null;\n }\n }\n\n public async translate(\n request: LocalizationTranslationRequest)\n : Promise<TranslationResult> {\n const { scope, key, args, locale } = request;\n\n const translation = await this.getTranslation(scope, locale);\n\n if (!translation) return `${scope}.${key}`;\n\n const value = translation.translations[key];\n\n const translated = this.applyTranslation(value, args);\n\n return translated || `${scope}.${key}`;\n }\n\n private applyTranslation(\n translation: string,\n args?: Record<string, any>)\n : string {\n if (!translation || !args) return translation;\n\n return translation.replace(/{([^}]+)}/g, (_, key) => {\n return String(args[key] ?? `{${key}}`);\n });\n }\n}","import { existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { COMMANDKIT_IS_DEV } from './constants';\n\nlet appDir: string | null = null;\n\n/**\n * Returns the path to the app directory.\n * @returns The path to the app directory or `null` if not found.\n */\nexport function findAppDirectory(): string | null {\n if (appDir) return appDir;\n\n let root = join(process.cwd(), COMMANDKIT_IS_DEV ? '.commandkit' : 'dist');\n\n if (!existsSync(root)) root = process.cwd();\n\n const dirs = ['app', 'src/app'].map((dir) => join(root, dir));\n\n for (const dir of dirs) {\n if (existsSync(dir)) {\n appDir = dir;\n return dir;\n }\n }\n\n return null;\n}","export const COMMANDKIT_CACHE_TAG = Symbol('kCommandKitCacheTag');\n\nexport const COMMANDKIT_IS_DEV = !!process.env.COMMANDKIT_DEV;","import type { CommandKit } from '../../CommandKit';\nimport {\n Awaitable,\n Collection,\n ContextMenuCommandBuilder,\n Interaction,\n Locale,\n Message,\n SlashCommandBuilder } from\n'discord.js';\nimport { Context } from '../commands/Context';\nimport { toFileURL } from '../../utils/resolve-file-url';\nimport { TranslatableCommandOptions } from '../i18n/Translation';\nimport { MessageCommandParser } from '../commands/MessageCommandParser';\nimport { CommandKitErrorCodes, isErrorType } from '../../utils/error-codes';\nimport { ParsedCommand, ParsedMiddleware } from '../router';\n\ninterface AppCommand {\n command: SlashCommandBuilder | Record<string, any>;\n chatInput?: (ctx: Context) => Awaitable<unknown>;\n autocomplete?: (ctx: Context) => Awaitable<unknown>;\n message?: (ctx: Context) => Awaitable<unknown>;\n messageContextMenu?: (ctx: Context) => Awaitable<unknown>;\n userContextMenu?: (ctx: Context) => Awaitable<unknown>;\n}\n\ninterface AppCommandMiddleware {\n beforeExecute: (ctx: Context) => Awaitable<unknown>;\n afterExecute: (ctx: Context) => Awaitable<unknown>;\n}\n\ninterface LoadedCommand {\n command: ParsedCommand;\n data: AppCommand;\n}\n\ninterface LoadedMiddleware {\n middleware: ParsedMiddleware;\n data: AppCommandMiddleware;\n}\n\nexport interface PreparedAppCommandExecution {\n command: LoadedCommand;\n middlewares: LoadedMiddleware[];\n messageCommandParser?: MessageCommandParser;\n}\n\ntype CommandBuilderLike =\nSlashCommandBuilder |\nContextMenuCommandBuilder |\nRecord<string, any>;\n\nconst commandDataSchema = {\n command: (c: unknown) =>\n c instanceof SlashCommandBuilder ||\n c instanceof ContextMenuCommandBuilder ||\n c && typeof c === 'object',\n chatInput: (c: unknown) => typeof c === 'function',\n autocomplete: (c: unknown) => typeof c === 'function',\n message: (c: unknown) => typeof c === 'function',\n messageContextMenu: (c: unknown) => typeof c === 'function',\n userContextMenu: (c: unknown) => typeof c === 'function'\n};\n\nconst middlewareDataSchema = {\n beforeExecute: (c: unknown) => typeof c === 'function',\n afterExecute: (c: unknown) => typeof c === 'function'\n};\n\nexport class AppCommandHandler {\n private loadedCommands = new Collection<string, LoadedCommand>();\n private loadedMiddlewares = new Collection<string, LoadedMiddleware>();\n\n public constructor(public readonly commandkit: CommandKit) {}\n\n public getCommandsArray() {\n return Array.from(this.loadedCommands.values()).map((v) => {\n if ('toJSON' in v && typeof v.toJSON === 'function') return v.toJSON();\n return v.data.command;\n });\n }\n\n public async prepareCommandRun(\n source: Interaction | Message)\n : Promise<PreparedAppCommandExecution | null> {\n let cmd: string;\n let parser: MessageCommandParser | undefined;\n\n if (source instanceof Message) {\n if (source.author.bot) return null;\n\n const prefix =\n await this.commandkit.config.getMessageCommandPrefix(source);\n\n parser = new MessageCommandParser(\n source,\n Array.isArray(prefix) ? prefix : [prefix],\n (command: string) => {\n const loadedCommand = this.loadedCommands.find((c) => {\n return c.data.command.name === command;\n });\n\n if (!loadedCommand) return null;\n\n const json =\n 'toJSON' in loadedCommand.data.command ?\n loadedCommand.data.command.toJSON() :\n loadedCommand.data.command;\n\n return (\n json.options?.reduce(\n (acc: Record<string, unknown>, opt: Record<string, any>) => {\n acc[opt.name] = opt.type;\n return acc;\n },\n {} as Record<string, unknown>\n ) ?? {});\n\n }\n );\n\n try {\n cmd = parser.getFullCommand();\n } catch (e) {\n if (isErrorType(e, CommandKitErrorCodes.InvalidCommandPrefix)) {\n return null;\n }\n\n console.error(e);\n return null;\n }\n } else {\n if (!source.isCommand()) return null;\n\n cmd = source.commandName;\n\n if (source.isChatInputCommand()) {\n const subcommandGroup = source.options.getSubcommandGroup(false);\n const subcommand = source.options.getSubcommand(false);\n\n if (subcommandGroup) {\n cmd += ` ${subcommandGroup}`;\n }\n\n if (subcommand) {\n cmd += ` ${subcommand}`;\n }\n }\n }\n\n const loadedCommand = this.loadedCommands.find((c) => {\n return c.data.command.name === cmd;\n });\n\n if (!loadedCommand) return null;\n\n return {\n command: loadedCommand,\n middlewares: loadedCommand.command.middlewares.\n map((m) => this.loadedMiddlewares.get(m)).\n filter((m): m is LoadedMiddleware => !!m),\n messageCommandParser: parser\n };\n }\n\n public async loadCommands() {\n const commandsRouter = this.commandkit.commandsRouter;\n\n if (!commandsRouter) {\n throw new Error('Commands router has not yet initialized');\n }\n\n const { commands, middleware } = commandsRouter.getData();\n\n for (const [id, md] of middleware) {\n const data = await import(`${toFileURL(md.fullPath)}?t=${Date.now()}`);\n\n let handlerCount = 0;\n for (const [key, validator] of Object.entries(middlewareDataSchema)) {\n if (data[key] && !(await validator(data[key]))) {\n throw new Error(\n `Invalid export for middleware ${id}: ${key} does not match expected value`\n );\n }\n\n if (data[key]) handlerCount++;\n }\n\n if (handlerCount === 0) {\n throw new Error(\n `Invalid export for middleware ${id}: at least one handler function must be provided`\n );\n }\n\n this.loadedMiddlewares.set(id, { middleware: md, data });\n }\n\n for (const [name, command] of commands) {\n const data = await import(\n `${toFileURL(command.fullPath)}?t=${Date.now()}`\n );\n\n if (!data.command) {\n throw new Error(\n `Invalid export for command ${name}: no command definition found`\n );\n }\n\n let handlerCount = 0;\n\n for (const [key, validator] of Object.entries(commandDataSchema)) {\n if (key !== 'command' && data[key]) handlerCount++;\n if (data[key] && !(await validator(data[key]))) {\n throw new Error(\n `Invalid export for command ${name}: ${key} does not match expected value`\n );\n }\n }\n\n if (handlerCount === 0) {\n throw new Error(\n `Invalid export for command ${name}: at least one handler function must be provided`\n );\n }\n\n const localizedCommand = await this.applyLocalizations({\n ...data.command\n });\n\n this.loadedCommands.set(name, {\n command,\n data: {\n ...data,\n command: localizedCommand\n }\n });\n }\n }\n\n public async applyLocalizations(command: CommandBuilderLike) {\n const localization = this.commandkit.config.localizationStrategy;\n\n const validLocales = Object.values(Locale).filter(\n (v) => typeof v === 'string'\n );\n\n for (const locale of validLocales) {\n const translation = await localization.locateTranslation(\n command.name,\n locale\n );\n\n if (!translation?.command) continue;\n\n if (command instanceof SlashCommandBuilder) {\n if (translation.command.name) {\n command.setNameLocalization(locale, translation.command.name);\n }\n\n if (translation.command.description) {\n command.setDescriptionLocalization(\n locale,\n translation.command.description\n );\n }\n\n const raw = command.toJSON();\n\n if (raw.options?.length && translation.command.options?.length) {\n const opt = translation.command.options.slice();\n let o: TranslatableCommandOptions;\n\n while (o = opt.shift()!) {\n raw.options?.forEach((option) => {\n if (option.name === o.ref) {\n if (option.name) {\n option.name_localizations ??= {};\n option.name_localizations[locale] = o.name;\n }\n\n if (option.description) {\n option.description_localizations ??= {};\n option.description_localizations[locale] = o.description;\n }\n }\n });\n }\n }\n } else if (command instanceof ContextMenuCommandBuilder) {\n if (translation.command.name) {\n command.setNameLocalization(locale, translation.command.name);\n }\n\n const raw = command.toJSON();\n\n return raw;\n } else {\n command.name_localizations ??= {};\n command.name_localizations[locale] = translation.command.name;\n\n if (command.description) {\n command.description_localizations ??= {};\n command.description_localizations[locale] =\n translation.command.description;\n }\n\n if (command.options?.length && translation.command.options?.length) {\n const opt = translation.command.options.slice();\n let o: TranslatableCommandOptions;\n\n while (o = opt.shift()!) {\n command.options.forEach((option: any) => {\n if (option.name === o.ref) {\n if (option.name) {\n option.name_localizations ??= {};\n option.name_localizations[locale] = o.name;\n }\n\n if (option.description) {\n option.description_localizations ??= {};\n option.description_localizations[locale] = o.description;\n }\n }\n });\n }\n }\n }\n }\n\n return command;\n }\n}","import { Channel } from 'diagnostics_channel';\nimport {\n Message,\n ApplicationCommandOptionType,\n GuildMember,\n Attachment,\n User,\n Role,\n CommandInteractionOption } from\n'discord.js';\nimport {\n CommandKitErrorCodes,\n createCommandKitError } from\n'../../utils/error-codes';\n\nexport interface ParsedMessageCommand {\n command: string;\n options: {name: string;value: unknown;}[];\n subcommand?: string;\n subcommandGroup?: string;\n}\n\nexport type MessageCommandOptionsSchema = Record<\n string,\n ApplicationCommandOptionType>;\n\n\nexport class MessageCommandParser {\n #parsed: ParsedMessageCommand | null = null;\n #options: MessageCommandOptions | null = null;\n #args: string[] = [];\n\n public constructor(\n public message: Message,\n private prefix: string[],\n private schema: (command: string) => MessageCommandOptionsSchema)\n {}\n\n public getArgs() {\n void this.parse();\n return this.#args;\n }\n\n public get options() {\n if (!this.#options) {\n this.#options = new MessageCommandOptions(this);\n }\n\n return this.#options;\n }\n\n public getOption<T>(name: string): T | undefined {\n return this.parse().options.find((o) => o.name === name)?.value as T;\n }\n\n public getCommand(): string {\n return this.parse().command;\n }\n\n public getSubcommand(): string | undefined {\n return this.parse().subcommand;\n }\n\n public getSubcommandGroup(): string | undefined {\n return this.parse().subcommandGroup;\n }\n\n public getPrefix() {\n for (const p of this.prefix) {\n if (this.message.content.startsWith(p)) {\n return p;\n }\n }\n }\n\n public getFullCommand() {\n return [this.getCommand(), this.getSubcommandGroup(), this.getSubcommand()].\n filter((v) => v).\n join(' ');\n }\n\n public parse(): ParsedMessageCommand {\n if (this.#parsed) {\n return this.#parsed;\n }\n\n const content = this.message.content;\n\n const prefix = this.getPrefix();\n\n if (!prefix) {\n throw createCommandKitError(CommandKitErrorCodes.InvalidCommandPrefix);\n }\n\n const parts = content.slice(prefix.length).trim().split(' ');\n const command = parts.shift();\n\n this.#args = parts;\n\n let subcommandGroup: string | undefined;\n let subcommand: string | undefined;\n\n if (command?.includes(':')) {\n const [, group, cmd] = command.split(':');\n\n if (!cmd && group) {\n subcommand = group;\n } else if (cmd && group) {\n subcommandGroup = group;\n subcommand = cmd;\n }\n }\n\n const schema = this.schema(\n [command, subcommandGroup, subcommand].filter(Boolean).join(' ').trim()\n );\n\n const options = parts.\n map((part) => {\n try {\n const [name, value] = part.split(':');\n\n if (!(name in schema)) return null;\n\n switch (schema[name]) {\n case ApplicationCommandOptionType.Boolean:\n return { name, value: value === 'true' };\n case ApplicationCommandOptionType.Integer:\n return { name, value: parseInt(value, 10) };\n case ApplicationCommandOptionType.Number:\n return { name, value: parseFloat(value) };\n case ApplicationCommandOptionType.String:\n return { name, value };\n case ApplicationCommandOptionType.User:\n return {\n name,\n value: this.message.mentions.users.find((u) => {\n return u.id === value.replace(/[<@!>]/g, '');\n })\n };\n case ApplicationCommandOptionType.Channel:\n return {\n name,\n value: this.message.mentions.channels.find((c) => {\n return c.id === value.replace(/[<#>]/g, '');\n })\n };\n case ApplicationCommandOptionType.Role:\n return {\n name,\n value: this.message.mentions.roles.find((r) => {\n return r.id === value.replace(/[<@&>]/g, '');\n })\n };\n case ApplicationCommandOptionType.Attachment:\n return {\n name,\n value: this.message.attachments.find((a) => {\n return a.name === value;\n })\n };\n default:\n return null;\n }\n } catch {\n // Invalid option\n return null;\n }\n }).\n filter((v) => v !== null);\n\n this.#parsed = {\n command: command!,\n options,\n subcommand,\n subcommandGroup\n };\n\n return this.#parsed;\n }\n}\n\nexport class MessageCommandOptions {\n public constructor(private parser: MessageCommandParser) {}\n\n private assertOption<T>(name: string, required = false) {\n const option = this.parser.getOption<T>(name);\n\n if (required && option === undefined) {\n throw new Error(`Option \"${name}\" is required.`);\n }\n\n return option ?? null;\n }\n\n getMember(name: string): GuildMember | null;\n getMember(name: string, required: true): GuildMember;\n getMember(name: string, required = false) {\n const user = this.assertOption<User>(name, required);\n const member = this.parser.message.guild?.members.cache.get(user?.id!);\n\n if (required && !member) {\n throw new Error(`Member \"${name}\" is required.`);\n }\n\n return member ?? null;\n }\n\n getAttachment(name: string): Attachment | null;\n getAttachment(name: string, required: true): Attachment;\n getAttachment(name: string, required = false) {\n return this.assertOption<Attachment>(name, required);\n }\n\n getBoolean(name: string): boolean | null;\n getBoolean(name: string, required: true): boolean;\n getBoolean(name: string, required = false) {\n return this.assertOption<boolean>(name, required);\n }\n\n getNumber(name: string): number | null;\n getNumber(name: string, required: true): number;\n getNumber(name: string, required = false) {\n return this.assertOption<number>(name, required);\n }\n\n getString(name: string): string | null;\n getString(name: string, required: true): string;\n getString(name: string, required = false) {\n return this.assertOption<string>(name, required);\n }\n\n getInteger(name: string): number | null;\n getInteger(name: string, required: true): number;\n getInteger(name: string, required = false) {\n return this.assertOption<number>(name, required);\n }\n\n getUser(name: string): User | null;\n getUser(name: string, required: true): User;\n getUser(name: string, required = false) {\n return this.assertOption<User>(name, required);\n }\n\n getChannel(name: string): Channel | null;\n getChannel(name: string, required: true): Channel;\n getChannel(name: string, required = false) {\n return this.assertOption<Channel>(name, required);\n }\n\n getRole(name: string): Role | null;\n getRole(name: string, required: true): Role;\n getRole(name: string, required = false) {\n return this.assertOption<Role>(name, required);\n }\n\n getMentionable(\n name: string)\n : NonNullable<CommandInteractionOption['member' | 'role' | 'user']> | null;\n getMentionable(\n name: string,\n required: true)\n : NonNullable<CommandInteractionOption['member' | 'role' | 'user']>;\n getMentionable(\n name: string,\n required = false)\n : NonNullable<CommandInteractionOption['member' | 'role' | 'user']> | null {\n const target = this.assertOption(name, required);\n\n if (\n target instanceof GuildMember ||\n target instanceof User ||\n target instanceof Role)\n {\n return target;\n }\n\n if (required) {\n throw new Error(`Mentionable \"${name}\" is required.`);\n }\n\n return null;\n }\n\n getSubcommand(): string | null;\n getSubcommand(required: true): string;\n getSubcommand(required = false) {\n const sub = this.parser.getSubcommand();\n\n if (required && sub === undefined) {\n throw new Error('Subcommand is required.');\n }\n\n return sub ?? null;\n }\n\n getSubcommandGroup(): string | null;\n getSubcommandGroup(required: true): string;\n getSubcommandGroup(required = false) {\n const sub = this.parser.getSubcommandGroup();\n\n if (required && sub === undefined) {\n throw new Error('Subcommand group is required.');\n }\n\n return sub ?? null;\n }\n}","export * from './CommandsRouter';\nexport * from './EventsRouter';","import { existsSync } from 'node:fs';\nimport { readdir } from 'node:fs/promises';\nimport path, { join } from 'node:path';\n\n/**\n * Matcher type for identifying command and middleware files.\n * Can be a string suffix (e.g. '.cmd.js'), RegExp pattern, or custom matcher function.\n */\nexport type CommandsRouterMatcher =\nstring |\nRegExp |\n((path: string) => boolean);\n\n/**\n * Maps file type identifiers to their respective matchers.\n * Used to identify command and middleware files in the directory structure.\n */\nexport type CommandsRouterMatchersMap = Record<\n 'command' | 'middleware',\n CommandsRouterMatcher>;\n\n\n/**\n * Configuration options for the CommandsRouter\n */\nexport interface CommandsRouterOptions {\n /**\n * The path to the directory containing the command files.\n */\n entrypoint: string;\n /**\n * The path to the directory containing the middleware files.\n */\n matcher?: Partial<CommandsRouterMatchersMap>;\n}\n\n/**\n * Represents a parsed command with its metadata\n * @interface ParsedCommand\n */\nexport interface ParsedCommand {\n /** Command name derived from the file name without extension */\n name: string;\n /** Absolute file system path to the command file */\n path: string;\n /** Parent command name for nested commands, or null if root-level command */\n parent: string | null;\n /** Array of command segments representing the command hierarchy */\n parentSegments: string[];\n /** Array of middleware IDs that apply to this command */\n middlewares: string[];\n /** Absolute path to this command */\n fullPath: string;\n}\n\n/**\n * Represents a parsed middleware with its metadata\n * @interface ParsedMiddleware\n */\nexport interface ParsedMiddleware {\n /** Unique identifier used to reference this middleware */\n id: string;\n /** Middleware name derived from the file path */\n name: string;\n /** Path to the middleware file, relative to the entrypoint */\n path: string;\n /** Absolute path to the middleware file */\n fullPath: string;\n}\n\n/**\n * Complete tree structure of all commands and middleware\n * @interface CommandsTree\n */\nexport interface CommandsTree {\n /** Map of command names to their parsed metadata */\n commands: Record<string, ParsedCommand>;\n /** Map of middleware IDs to their parsed metadata */\n middleware: Record<string, ParsedMiddleware>;\n}\n\n/**\n * Result of a successful command match operation\n * @interface CommandMatchResult\n */\nexport interface CommandMatchResult {\n /** The matched command metadata */\n command: ParsedCommand;\n /** Array of middleware that apply to the matched command */\n middlewares: ParsedMiddleware[];\n}\n\n/**\n * CommandsRouter handles the discovery and routing of commands and middleware files\n * in a directory structure. It supports nested commands and middleware inheritance.\n */\nexport class CommandsRouter {\n private commands = new Map<string, ParsedCommand>();\n private middlewares = new Map<string, ParsedMiddleware>();\n\n /**\n * Creates a new CommandsRouter instance\n * @param options - Configuration options for the router\n */\n public constructor(private readonly options: CommandsRouterOptions) {\n if (!options.entrypoint) {\n throw new Error('Entrypoint directory must be provided');\n }\n\n options.matcher ??= {};\n options.matcher.command ??= /command\\.(m|c)?(j|t)sx?$/;\n options.matcher.middleware ??= /middleware\\.(m|c)?(j|t)sx?$/;\n }\n\n /**\n * Gets the configured entrypoint directory\n */\n public get entrypoint(): string {\n return this.options.entrypoint;\n }\n\n /**\n * Gets the configured matchers for command and middleware files\n */\n public get matchers(): CommandsRouterMatchersMap {\n return this.options.matcher as CommandsRouterMatchersMap;\n }\n\n /**\n * Returns the cached data of the commands and middleware\n */\n public getData() {\n return {\n commands: this.commands,\n middleware: this.middlewares\n };\n }\n\n /**\n * Checks if the entrypoint path is valid\n */\n public isValidPath() {\n return existsSync(this.entrypoint);\n }\n\n /**\n * Executes a matcher against a file path\n * @param matcher - The matcher to use\n * @param path - The file path to test\n * @returns boolean indicating if the path matches\n */\n private execMatcher(matcher: CommandsRouterMatcher, path: string): boolean {\n if (typeof matcher === 'string') {\n return path.endsWith(matcher);\n }\n\n if (matcher instanceof RegExp) {\n return matcher.test(path);\n }\n\n return matcher(path);\n }\n\n /**\n * Converts an absolute path to a path relative to the entrypoint\n * @param path - The absolute path to convert\n */\n private resolveRelativePath(path: string): string {\n const regex = new RegExp(`^${this.entrypoint}`);\n return path.replace(regex, '');\n }\n\n /**\n * Matches a command by name or path segments\n * @param commandOrSegment - Command name or array of path segments\n * @returns Matched command and its middlewares, or null if no match\n */\n public match(commandOrSegment: string | string[]): CommandMatchResult | null {\n if (!commandOrSegment?.length) return null;\n\n if (Array.isArray(commandOrSegment) && commandOrSegment.length === 1) {\n commandOrSegment = commandOrSegment[0];\n }\n\n if (!Array.isArray(commandOrSegment) && !commandOrSegment.includes(' ')) {\n const command = this.commands.get(commandOrSegment);\n if (!command) return null;\n\n const middlewares = command.middlewares.\n map((id) => this.middlewares.get(id)).\n filter((m): m is ParsedMiddleware => !!m);\n\n return {\n command,\n middlewares\n };\n }\n\n const segments = Array.isArray(commandOrSegment) ?\n commandOrSegment :\n commandOrSegment.split(' ');\n\n const command = Array.from(this.commands.values()).find((cmd) => {\n const commandSegments = cmd.parentSegments;\n\n if (commandSegments.length !== segments.length) return false;\n\n return commandSegments.every((segment, index) => {\n if (segment === '[name]') return true;\n return segment === segments[index];\n });\n });\n\n if (!command) return null;\n\n const middlewares = command.middlewares.\n map((id) => this.middlewares.get(id)).\n filter((m): m is ParsedMiddleware => !!m);\n\n return {\n command,\n middlewares\n };\n }\n\n /**\n * Reloads the commands tree by re-scanning the entrypoint directory\n */\n public async reload(): Promise<CommandsTree> {\n this.clear();\n return this.scan();\n }\n\n /**\n * Clears the internal commands and middleware maps\n */\n public clear(): void {\n this.commands.clear();\n this.middlewares.clear();\n }\n\n /**\n * Scans the entrypoint directory for commands and middleware\n * @returns Promise resolving to the complete commands tree\n */\n public async scan(): Promise<CommandsTree> {\n const files = await this.scanDirectory(this.entrypoint, []);\n\n for (const file of files) {\n if (this.execMatcher(this.matchers.command, file)) {\n const location = this.resolveRelativePath(file);\n const parts = location.split(path.sep);\n\n const parentSegments: string[] = [];\n\n parts.forEach((part, index, arr) => {\n const isLast = index === arr.length - 1;\n\n // ignore last because it's definitely a command source file\n if (isLast) return;\n\n // we ignore groups\n if (!/\\(.+\\)/.test(part)) {\n parentSegments.push(part.trim());\n }\n });\n\n const parent = parentSegments.join(' ');\n const name = parts[parts.length - 1].replace(/\\.(m|c)?(j|t)sx?$/, '');\n\n const command: ParsedCommand = {\n name,\n middlewares: [],\n parent: parent || null,\n path: location,\n fullPath: file,\n parentSegments\n };\n\n this.commands.set(name, command);\n }\n\n if (this.execMatcher(this.matchers.middleware, file)) {\n const location = this.resolveRelativePath(file);\n const name = location.replace(/\\.(m|c)?(j|t)sx?$/, '');\n const middlewareDir = path.dirname(location);\n\n const command = Array.from(this.commands.values()).filter((command) => {\n const commandDir = path.dirname(command.path);\n return (\n commandDir === middlewareDir || commandDir.startsWith(middlewareDir));\n\n });\n\n const id = crypto.randomUUID();\n\n const middleware: ParsedMiddleware = {\n id,\n name,\n path: location,\n fullPath: file\n };\n\n this.middlewares.set(id, middleware);\n\n command.forEach((cmd) => {\n cmd.middlewares.push(id);\n });\n }\n }\n\n return this.toJSON();\n }\n\n /**\n * Converts the internal maps to a serializable object\n * @returns CommandsTree containing all commands and middleware\n */\n public toJSON(): CommandsTree {\n return {\n commands: Object.fromEntries(this.commands),\n middleware: Object.fromEntries(this.middlewares)\n };\n }\n\n /**\n * Recursively scans a directory for files\n * @param dir - Directory to scan\n * @param entries - Accumulator for found files\n * @returns Promise resolving to array of file paths\n */\n private async scanDirectory(\n dir: string,\n entries: string[])\n : Promise<string[]> {\n const files = await readdir(dir, {\n withFileTypes: true\n });\n\n for (const file of files) {\n // for whatever reason\n if (\n file.name === 'node_modules' ||\n file.parentPath.includes('node_modules'))\n {\n continue;\n }\n\n if (file.isDirectory()) {\n const next = join(dir, file.name);\n await this.scanDirectory(next, entries);\n continue;\n }\n\n entries.push(join(dir, file.name));\n }\n\n return entries;\n }\n}","import { 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 entrypoint: 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}\n\n/** Map 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 Map<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.entrypoint) {\n throw new Error('Entrypoint directory must be provided');\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 entrypoint(): string {\n return this.options.entrypoint;\n }\n\n /**\n * Checks if the entrypoint path is valid\n */\n public isValidPath() {\n return existsSync(this.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 const dirs = await readdir(this.entrypoint, { withFileTypes: true });\n\n for (const dir of dirs) {\n if (dir.isDirectory()) {\n const path = join(this.entrypoint, dir.name);\n const event = await this.scanEvent(dir.name, path);\n this.events.set(event.event, event);\n }\n }\n\n return Object.fromEntries(this.events);\n }\n\n /**\n * Convert the internal events map 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 listeners: string[] = [])\n : Promise<ParsedEvent> {\n const files = await readdir(path, { withFileTypes: true });\n\n for (const file of files) {\n if (/node_modules/.test(file.name)) continue;\n\n if (file.isDirectory()) {\n const nextPath = join(path, file.name);\n await this.scanEvent(event, nextPath, 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 return { event, path, listeners };\n }\n}","export interface CommandKitConfig {\n /**\n * The source directory of the project.\n */\n src: string;\n /**\n * The main \"javascript\" file of the project.\n */\n main: string;\n /**\n * Whether or not to use the watch mode. Defaults to `true`.\n */\n watch: boolean;\n /**\n * The output directory of the project. Defaults to `dist`.\n */\n outDir: string;\n /**\n * Whether or not to include extra env utilities. Defaults to `true`.\n */\n envExtra: boolean;\n /**\n * Node.js cli options.\n */\n nodeOptions: string[];\n /**\n * Whether or not to clear default restart logs. Defaults to `true`.\n */\n clearRestartLogs: boolean;\n /**\n * Whether or not to minify the output. Defaults to `false`.\n */\n minify: boolean;\n /**\n * Whether or not to include sourcemaps in production build. Defaults to `false`.\n */\n sourcemap: boolean | 'inline';\n /**\n * Whether or not to include anti-crash handler in production. Defaults to `true`.\n */\n antiCrash: boolean;\n /**\n * Whether or not to polyfill `require` function. Defaults to `true`.\n */\n requirePolyfill: boolean;\n}\n\nlet globalConfig: Partial<CommandKitConfig> = {\n envExtra: true,\n outDir: 'dist',\n watch: true,\n clearRestartLogs: true,\n minify: false,\n sourcemap: false,\n nodeOptions: [],\n antiCrash: true,\n requirePolyfill: true\n};\n\nexport function getConfig(): CommandKitConfig {\n return globalConfig as CommandKitConfig;\n}\n\nconst requiredProps = ['src', 'main'] as const;\n\ntype R = (typeof requiredProps)[number];\n\ntype PartialConfig<T extends CommandKitConfig> = Partial<Omit<T, R>> &\nPick<T, R>;\n\nexport function defineConfig(config: PartialConfig<CommandKitConfig>) {\n for (const prop of requiredProps) {\n if (!config[prop]) {\n throw new Error(\n `[CommandKit Config] Missing required config property: ${prop}`\n );\n }\n }\n\n globalConfig = {\n ...globalConfig,\n ...config\n };\n\n return globalConfig;\n}","export * from './CacheProvider';\nexport * from './MemoryCache';\nexport * from './cache';","import { AsyncLocalStorage } from 'node:async_hooks';\nimport ms from 'ms';\nimport { GenericFunction, getCommandKit } from '../context/async-context';\nimport { randomUUID } from 'node:crypto';\n\nexport type AsyncFunction<R extends any[] = any[], T = any> = (\n...args: R)\n=> Promise<T>;\n\nexport interface CacheTag {\n tag: string;\n ttl: number | string;\n}\n\nexport interface CacheParams extends CacheTag {\n target: GenericFunction;\n memo: GenericFunction;\n}\n\ninterface CacheContext {\n target: GenericFunction;\n params: CacheTag;\n memo?: GenericFunction;\n}\n\nconst CACHED_FUNCTIONS_STORE = new WeakMap<Function, CacheParams>();\nconst TAG_FUNCTION_MAP = new Map<string, Function>();\nconst DEFAULT_TTL = ms('15m');\n\nconst cacheContext = new AsyncLocalStorage<CacheContext>();\n\nconst __identificationKey = `__cache_identification_key_${Date.now()}__${Math.random()}__`;\n\nconst getDefaultCacheTag = (): CacheTag => {\n return {\n tag: randomUUID(),\n ttl: DEFAULT_TTL\n };\n};\n\n/**\n * Cache a function with a specific tag and time-to-live.\n * @param fn The function to cache.\n * @param params The cache tag and time-to-live.\n * @returns The memoized function.\n */\nfunction cache<R extends any[], F extends AsyncFunction<R>>(\nfn: F,\nparams?: Partial<CacheTag>)\n: F {\n params = Object.assign({}, getDefaultCacheTag(), params);\n\n return useCache(fn, __identificationKey, params as CacheTag);\n}\n\n/**\n * **DO NOT USE THIS FUNCTION DIRECTLY**\n * @internal\n * @private\n */\nfunction useCache<R extends any[], F extends AsyncFunction<R>>(\nfn: F,\nid?: string,\ntag?: CacheTag)\n: F {\n if (id !== undefined && id !== __identificationKey) {\n throw new TypeError('useCache may not be called directly.');\n }\n\n const isLocal = id === __identificationKey;\n\n const memoized = (async (...args) => {\n const commandkit = getCommandKit(true);\n const cache = commandkit.getCacheProvider();\n\n if (!cache) {\n throw new Error(\n 'CacheProvider was not found, please provide a cache provider to the CommandKit instance.'\n );\n }\n\n const context = cacheContext.getStore();\n\n if (context === undefined) {\n throw new Error(\n 'useCache must be called inside a function decorated with \"use cache\" directive.'\n );\n }\n\n const entryKey = context.params.tag;\n const entry = await cache.get(entryKey);\n\n // cache hit\n if (entry !== undefined) {\n return entry.value;\n }\n\n const ttl =\n typeof context.params.ttl === 'string' ?\n ms(context.params.ttl) :\n context.params.ttl;\n\n const writeCache = async (...args: any) => {\n const result = await fn(...args);\n\n CACHED_FUNCTIONS_STORE.set(fn, {\n ...context.params,\n target: fn,\n memo: cacheContext.exit(() => wrapper)\n });\n\n if (entryKey !== context.params.tag) {\n TAG_FUNCTION_MAP.delete(entryKey);\n }\n\n TAG_FUNCTION_MAP.set(context.params.tag, fn);\n\n await cache.set(entryKey, result, ttl);\n\n return result;\n };\n\n CACHED_FUNCTIONS_STORE.set(fn, {\n ...context.params,\n target: fn,\n memo: cacheContext.exit(() => wrapper)\n });\n\n TAG_FUNCTION_MAP.set(entryKey, fn);\n\n return writeCache(...args);\n }) as F;\n\n const wrapper = (async (...args: any) => {\n const params =\n CACHED_FUNCTIONS_STORE.get(fn) ?? (\n (isLocal ? tag : null) || getDefaultCacheTag());\n\n return cacheContext.run(\n {\n params,\n target: fn\n },\n () => memoized(...args)\n );\n }) as F;\n\n return wrapper;\n}\n\n/**\n * Tags the current function with the given cache tag name\n * @param tag The cache tag name.\n */\nfunction cacheTag(tag: string): void;\n/**\n * Tags the current function with the given cache tag parameters.\n * @param tag The cache tag parameters.\n */\nfunction cacheTag(tag: CacheTag): void;\n/**\n * Tags the current function with the given cache tag name or parameters.\n * @param tag The cache tag name or parameters.\n */\nfunction cacheTag(tag: CacheTag | string): void {\n if (!tag) {\n throw new TypeError('cacheTag must be called with a tag.');\n }\n\n const context = cacheContext.getStore();\n\n if (context === undefined) {\n throw new Error(\n 'cacheTag must be called inside cache() or a function decorated with \"use cache\" directive.'\n );\n }\n\n let tagObj: CacheTag;\n\n if (typeof tag === 'string') {\n tagObj = {\n tag,\n ttl: context.params?.ttl ?? DEFAULT_TTL\n };\n } else {\n tagObj = tag;\n }\n\n context.params = tagObj;\n}\n\n/**\n * Sets the time-to-live for the current cache tag.\n * @param life The time-to-live value in milliseconds or a string.\n */\nfunction cacheLife(life: string): void;\nfunction cacheLife(life: number): void;\nfunction cacheLife(life: string | number) {\n if (life == null) {\n throw new TypeError('cacheLife must be called with a time-to-live value.');\n }\n\n const context = cacheContext.getStore();\n\n if (context === undefined) {\n throw new Error(\n 'cacheLife must be called inside cache() or a function decorated with \"use cache\" directive.'\n );\n }\n\n if (typeof life === 'string') {\n context.params.ttl = ms(life);\n } else {\n context.params.ttl = life;\n }\n}\n\n/**\n * Invalidates the cache with the given tag.\n * This will immediately remove the cache entry. The next time cache is requested, it will be re-fetched.\n * @param tag The cache tag to invalidate.\n */\nasync function invalidate(tag: string) {\n const commandkit = getCommandKit(true);\n const cache = commandkit.getCacheProvider();\n\n if (!cache) {\n throw new Error(\n 'CacheProvider was not found, please provide a cache provider to the CommandKit instance.'\n );\n }\n\n await cache.delete(tag);\n}\n\n/**\n * Revalidates the cache with the given tag.\n * This will immediately remove the cache entry and re-fetch the value.\n * @param tag The cache tag to revalidate.\n * @param args The arguments to pass to the memoized function (if any).\n * @returns The new value of the cache.\n */\nasync function revalidate<R = any>(\ntag: string,\n...args: any[])\n: Promise<R | undefined> {\n const commandkit = getCommandKit(true);\n const cache = commandkit.getCacheProvider();\n\n if (!cache) {\n throw new Error(\n 'CacheProvider was not found, please provide a cache provider to the CommandKit instance.'\n );\n }\n\n await cache.delete(tag);\n\n const tagFn = TAG_FUNCTION_MAP.get(tag);\n if (!tagFn) return undefined;\n\n const ctx = CACHED_FUNCTIONS_STORE.get(tagFn);\n if (!ctx) return undefined;\n\n return ctx.memo(...args) as R;\n}\n\nexport {\n cache,\n useCache as super_duper_secret_internal_for_use_cache_directive_of_commandkit_cli_do_not_use_it_directly_or_you_will_be_fired_from_your_job_kthxbai,\n cacheTag,\n cacheLife,\n invalidate,\n revalidate };","export * from './command-handler/AppCommandHandler';\nexport * from './commands/Context';\nexport * from './commands/MessageCommandParser';\nexport * from './i18n/DefaultLocalizationStrategy';\nexport * from './i18n/Localization';\nexport * from './i18n/LocalizationStrategy';\nexport * from './i18n/Translation';\nexport * from './middleware/signals';","import type { Locale } from 'discord.js';\nimport type { Translation } from './Translation';\n\nexport interface LocalizationTranslationRequest {\n locale: Locale;\n scope: string;\n key: string;\n args?: Record<string, any> | undefined;\n}\n\nexport type TranslationResult = string;\n\nexport interface LocalizationStrategy {\n locateTranslation(scope: string, locale: Locale): Promise<Translation | null>;\n getTranslation(scope: string, locale: Locale): Promise<Translation | null>;\n getTranslationStrict(scope: string, locale: Locale): Promise<Translation>;\n translate(\n request: LocalizationTranslationRequest)\n : Promise<TranslationResult>;\n}","export interface TranslatableCommand {\n name?: string;\n description?: string;\n options?: TranslatableCommandOptions[];\n}\n\nexport interface TranslatableCommandOptions {\n ref: string;\n name?: string;\n description?: string;\n}\n\nexport interface Translation {\n command: TranslatableCommand;\n translations: TranslatableArguments;\n}\n\nexport type TranslatableArguments = Record<string, string>;","import {\n CommandKitErrorCodes,\n createCommandKitError,\n isCommandKitError } from\n'../../utils/error-codes';\n\n/**\n * Cancel upcoming middleware execution.\n * If this is called inside pre-stage middleware, the next run will be the actual command, skipping all other pre-stage middlewares.\n * If this is called inside a command itself, it will skip all post-stage middlewares.\n * If this is called inside post-stage middleware, it will skip all other post-stage middlewares.\n */\nexport function exitMiddleware(): never {\n throw createCommandKitError(CommandKitErrorCodes.ExitMiddleware);\n}\n\n/**\n * Rethrow the error if it is a CommandKit error.\n * @param error The error to rethrow.\n */\nexport function rethrow(error: unknown): void {\n if (isCommandKitError(error)) throw error;\n}","/**\n * Creates a command line interface for CommandKit.\n * @param argv The arguments passed to the CLI.\n * @param options The options passed to the CLI.\n */\nexport async function bootstrapCommandkitCLI(\nargv: string[],\noptions?: import('commander').ParseOptions | undefined)\n{\n const { Command } = await import('commander');\n const { bootstrapDevelopmentServer } = await import('./development');\n const { bootstrapProductionServer } = await import('./production');\n const { bootstrapProductionBuild } = await import('./build');\n\n const program = new Command('commandkit');\n\n program.\n command('dev').\n description('Start your bot in development mode.').\n option(\n '-c, --config <path>',\n 'Path to your commandkit config file.',\n './commandkit.js'\n ).\n action(() => {\n const options = program.opts();\n bootstrapDevelopmentServer(options);\n });\n\n program.\n command('start').\n description(\n 'Start your bot in production mode after running the build command.'\n ).\n option(\n '-c, --config <path>',\n 'Path to your commandkit.json file.',\n './commandkit.js'\n ).\n action(() => {\n const options = program.opts();\n bootstrapProductionServer(options.config);\n });\n\n program.\n command('build').\n description('Build your project for production usage.').\n option(\n '-c, --config <path>',\n 'Path to your commandkit.json file.',\n './commandkit.json'\n ).\n action(() => {\n const options = program.opts();\n bootstrapProductionBuild(options.config);\n });\n\n await program.parseAsync(argv, options);\n}"],"mappings":"w8DAAA,0LCoCO,SAAS,MAAM,QAAc,CAClC,QAAQ,OAAO,MAAM,OAAO,EAC5B,QAAQ,OAAO,MAAM;AAAA,CAAI,CAC3B,CAKO,SAAS,MAAM,QAAc,CAClC,MAAM,OAAO,IAAI,UAAU,OAAO,EAAE,CAAC,EACrC,QAAQ,KAAK,CAAC,CAChB,CA2BA,eAAsB,qBAAqB,IAAa,CACtD,IAAM,IAAM,QAAQ,IAAI,EAClB,UAAY,IAClB,IAAC,wBAAK,IAAK,GAAG,CAAC,EACf,kBAAkB,IAAK,SAAS,wBAAK,IAAK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AQ,KAAK,EAC7BD,0BAAyBC,SAAQ,MAAM,CACzC,CAAC,EAED,MAAM,QAAQ,WAAW,KAAM,OAAO,CACxC,CArDsB,wDhDHtB,IAAO,cAAQ,WAmBF,QAAmC","names":["fs","path","import_node_path","import_node_fs","resetColor","import_node_crypto","_traverse","_generate","path","import_promises","build","ora","path","import_promises","import_node_path","ora","dotenv","child_process","import_node_path","import_tsup","import_ora","dotenv","child_process","import_dotenv","import_node_fs","import_node_path","import_node_child_process","import_discord","rfdc","fs","path","import_path","path","import_discord","import_discord","CommandKitEnvironmentType","_data","path","context","canRun","env","_data","path","_data","path","import_discord","import_discord","myCustomId","import_discord","import_discord","_contextData","_unsub","getEventInterceptor_fn","destroyCollector_fn","import_discord","import_discord","import_promises","path","import_node_path","import_node_path","import_discord","import_discord","parser","parser","loadedCommand","import_node_fs","import_promises","import_node_path","path","command","middlewares","import_node_fs","import_promises","import_node_path","path","_data","EventEmitter","appDir","import_node_async_hooks","import_node_crypto","ms","cache","context","args","bootstrapDevelopmentServer","bootstrapProductionServer","bootstrapProductionBuild","options"]}