commandkit 0.1.11-dev.20250128162628 → 0.1.11-dev.20250208064131
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/{CommandKit-B3EDajLJ.d.mts → CommandKit-BRxmnywX.d.mts} +5 -0
- package/dist/{CommandKit-BO77LFI2.d.ts → CommandKit-BhFmurtb.d.ts} +5 -0
- package/dist/CommandKit.d.mts +5 -1
- package/dist/CommandKit.d.ts +5 -1
- package/dist/CommandKit.js +1 -1
- package/dist/CommandKit.js.map +1 -1
- package/dist/CommandKit.mjs +1 -1
- package/dist/{async-context-DnJSN785.d.ts → async-context-B5Gze_ie.d.mts} +3 -2
- package/dist/{async-context-C5FJOAIU.d.mts → async-context-BW1JD1Dt.d.ts} +3 -2
- package/dist/cache/cache.d.mts +6 -2
- package/dist/cache/cache.d.ts +6 -2
- package/dist/cache/cache.js +1 -1
- package/dist/cache/cache.js.map +1 -1
- package/dist/cache/cache.mjs +1 -1
- package/dist/cache/index.d.mts +6 -2
- package/dist/cache/index.d.ts +6 -2
- package/dist/cache/index.js +1 -1
- package/dist/cache/index.js.map +1 -1
- package/dist/cache/index.mjs +1 -1
- package/dist/chunk-2F6IEOYN.mjs +1 -0
- package/dist/chunk-52E3USJK.mjs +2 -0
- package/dist/chunk-52E3USJK.mjs.map +1 -0
- package/dist/chunk-5CQ732SA.mjs +2 -0
- package/dist/chunk-5CQ732SA.mjs.map +1 -0
- package/dist/chunk-6EE35LXH.mjs +2 -0
- package/dist/chunk-6EE35LXH.mjs.map +1 -0
- package/dist/{chunk-UP6ACDGE.mjs → chunk-6OSC45ZN.mjs} +2 -2
- package/dist/chunk-75Q5UTDQ.mjs +2 -0
- package/dist/chunk-75Q5UTDQ.mjs.map +1 -0
- package/dist/{chunk-ULPF2QCW.mjs → chunk-D4IIOMFB.mjs} +1 -1
- package/dist/{chunk-B5T552SB.mjs → chunk-DMNZASZO.mjs} +2 -2
- package/dist/chunk-HFOCTXRX.mjs +2 -0
- package/dist/chunk-HFOCTXRX.mjs.map +1 -0
- package/dist/chunk-HN3WQT6R.mjs +2 -0
- package/dist/chunk-HN3WQT6R.mjs.map +1 -0
- package/dist/{chunk-LQPVE73I.mjs → chunk-JPMIJRUL.mjs} +2 -2
- package/dist/{chunk-WZU7OSUV.mjs → chunk-P7PNFSAC.mjs} +3 -3
- package/dist/chunk-P7PNFSAC.mjs.map +1 -0
- package/dist/cli/build.js +2 -2
- package/dist/cli/build.js.map +1 -1
- package/dist/cli/build.mjs +1 -1
- package/dist/cli/development.js +2 -2
- package/dist/cli/development.js.map +1 -1
- package/dist/cli/development.mjs +2 -2
- package/dist/cli/development.mjs.map +1 -1
- package/dist/cli/esbuild-plugins/plugin.d.mts +1 -0
- package/dist/cli/esbuild-plugins/plugin.d.ts +1 -0
- package/dist/cli/esbuild-plugins/plugin.js +1 -1
- package/dist/cli/esbuild-plugins/plugin.js.map +1 -1
- package/dist/cli/esbuild-plugins/plugin.mjs +1 -1
- package/dist/cli/init.js +3 -3
- package/dist/cli/init.js.map +1 -1
- package/dist/cli/init.mjs +1 -1
- package/dist/components/action-row/ActionRow.d.mts +18 -0
- package/dist/components/action-row/ActionRow.d.ts +18 -0
- package/dist/components/action-row/ActionRow.js +2 -0
- package/dist/components/action-row/ActionRow.js.map +1 -0
- package/dist/components/action-row/ActionRow.mjs +2 -0
- package/dist/components/button/Button.d.mts +30 -0
- package/dist/components/button/Button.d.ts +30 -0
- package/dist/components/button/Button.js +11 -0
- package/dist/components/button/Button.js.map +1 -0
- package/dist/components/button/Button.mjs +2 -0
- package/dist/components/button/Button.mjs.map +1 -0
- package/dist/components/{ButtonKit.d.mts → button/ButtonKit.d.mts} +26 -21
- package/dist/components/{ButtonKit.d.ts → button/ButtonKit.d.ts} +26 -21
- package/dist/components/button/ButtonKit.js +11 -0
- package/dist/components/button/ButtonKit.js.map +1 -0
- package/dist/components/button/ButtonKit.mjs +2 -0
- package/dist/components/button/ButtonKit.mjs.map +1 -0
- package/dist/components/common/EventInterceptor.d.mts +73 -0
- package/dist/components/common/EventInterceptor.d.ts +73 -0
- package/dist/components/common/EventInterceptor.js +2 -0
- package/dist/components/common/EventInterceptor.js.map +1 -0
- package/dist/components/common/EventInterceptor.mjs +2 -0
- package/dist/components/common/EventInterceptor.mjs.map +1 -0
- package/dist/components/common/element.d.mts +29 -0
- package/dist/components/common/element.d.ts +29 -0
- package/dist/components/common/element.js +2 -0
- package/dist/components/common/element.js.map +1 -0
- package/dist/components/common/element.mjs +2 -0
- package/dist/components/common/element.mjs.map +1 -0
- package/dist/components/common/types.d.mts +3 -0
- package/dist/components/common/types.d.ts +3 -0
- package/dist/components/common/types.js +2 -0
- package/dist/components/common/types.js.map +1 -0
- package/dist/components/common/types.mjs +2 -0
- package/dist/components/common/types.mjs.map +1 -0
- package/dist/components/index.d.mts +8 -1
- package/dist/components/index.d.ts +8 -1
- package/dist/components/index.js +10 -1
- package/dist/components/index.js.map +1 -1
- package/dist/components/index.mjs +1 -1
- package/dist/components/modal/Modal.d.mts +56 -0
- package/dist/components/modal/Modal.d.ts +56 -0
- package/dist/components/modal/Modal.js +11 -0
- package/dist/components/modal/Modal.js.map +1 -0
- package/dist/components/modal/Modal.mjs +2 -0
- package/dist/components/modal/Modal.mjs.map +1 -0
- package/dist/components/modal/ModalKit.d.mts +58 -0
- package/dist/components/modal/ModalKit.d.ts +58 -0
- package/dist/components/modal/ModalKit.js +11 -0
- package/dist/components/modal/ModalKit.js.map +1 -0
- package/dist/components/modal/ModalKit.mjs +2 -0
- package/dist/components/modal/ModalKit.mjs.map +1 -0
- package/dist/context/async-context.d.mts +6 -2
- package/dist/context/async-context.d.ts +6 -2
- package/dist/context/async-context.js +2 -2
- package/dist/context/async-context.js.map +1 -1
- package/dist/context/async-context.mjs +1 -1
- package/dist/context/environment.d.mts +6 -2
- package/dist/context/environment.d.ts +6 -2
- package/dist/context/environment.js +1 -1
- package/dist/context/environment.js.map +1 -1
- package/dist/context/environment.mjs +1 -1
- package/dist/handlers/command-handler/CommandHandler.d.mts +5 -1
- package/dist/handlers/command-handler/CommandHandler.d.ts +5 -1
- package/dist/handlers/command-handler/CommandHandler.js +1 -1
- package/dist/handlers/command-handler/CommandHandler.js.map +1 -1
- package/dist/handlers/command-handler/CommandHandler.mjs +1 -1
- package/dist/handlers/command-handler/functions/loadCommandsWithRest.d.mts +5 -1
- package/dist/handlers/command-handler/functions/loadCommandsWithRest.d.ts +5 -1
- package/dist/handlers/command-handler/functions/registerCommands.d.mts +5 -1
- package/dist/handlers/command-handler/functions/registerCommands.d.ts +5 -1
- package/dist/handlers/command-handler/typings.d.mts +5 -1
- package/dist/handlers/command-handler/typings.d.ts +5 -1
- package/dist/handlers/command-handler/validations/devOnly.d.mts +5 -1
- package/dist/handlers/command-handler/validations/devOnly.d.ts +5 -1
- package/dist/handlers/command-handler/validations/index.d.mts +5 -1
- package/dist/handlers/command-handler/validations/index.d.ts +5 -1
- package/dist/handlers/command-handler/validations/permissions.d.mts +5 -1
- package/dist/handlers/command-handler/validations/permissions.d.ts +5 -1
- package/dist/handlers/event-handler/EventHandler.d.mts +5 -1
- package/dist/handlers/event-handler/EventHandler.d.ts +5 -1
- package/dist/handlers/event-handler/EventHandler.mjs +1 -1
- package/dist/handlers/event-handler/typings.d.mts +5 -1
- package/dist/handlers/event-handler/typings.d.ts +5 -1
- package/dist/handlers/index.d.mts +5 -1
- package/dist/handlers/index.d.ts +5 -1
- package/dist/handlers/index.js +1 -1
- package/dist/handlers/index.js.map +1 -1
- package/dist/handlers/index.mjs +1 -1
- package/dist/handlers/validation-handler/ValidationHandler.mjs +1 -1
- package/dist/index.d.mts +12 -4
- package/dist/index.d.ts +12 -4
- package/dist/index.js +5 -5
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/types.d.mts +5 -1
- package/dist/types.d.ts +5 -1
- package/dist/utils/warn-unstable.mjs +1 -1
- package/dist/utils/warn-unstable.mjs.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-KAJRRZVI.mjs +0 -2
- package/dist/chunk-KAJRRZVI.mjs.map +0 -1
- package/dist/chunk-M5FMJETI.mjs +0 -1
- package/dist/chunk-TEL2J6LT.mjs +0 -2
- package/dist/chunk-TEL2J6LT.mjs.map +0 -1
- package/dist/chunk-WZU7OSUV.mjs.map +0 -1
- package/dist/chunk-ZCUZ5ENB.mjs +0 -2
- package/dist/chunk-ZCUZ5ENB.mjs.map +0 -1
- package/dist/components/ButtonKit.js +0 -2
- package/dist/components/ButtonKit.js.map +0 -1
- package/dist/components/ButtonKit.mjs +0 -2
- /package/dist/{chunk-M5FMJETI.mjs.map → chunk-2F6IEOYN.mjs.map} +0 -0
- /package/dist/{chunk-UP6ACDGE.mjs.map → chunk-6OSC45ZN.mjs.map} +0 -0
- /package/dist/{chunk-ULPF2QCW.mjs.map → chunk-D4IIOMFB.mjs.map} +0 -0
- /package/dist/{chunk-B5T552SB.mjs.map → chunk-DMNZASZO.mjs.map} +0 -0
- /package/dist/{chunk-LQPVE73I.mjs.map → chunk-JPMIJRUL.mjs.map} +0 -0
- /package/dist/components/{ButtonKit.mjs.map → action-row/ActionRow.mjs.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/context/async-context.ts","../src/CommandKit.ts","../src/context/environment.ts","../src/handlers/command-handler/CommandHandler.ts","../src/components/button/ButtonKit.ts","../src/components/button/Button.ts","../src/components/modal/ModalKit.ts","../src/components/modal/Modal.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks';\nimport { CommandKitEnvironment } from './environment';\nimport { CommandKitErrorCodes, isCommandKitError } from '../utils/error-codes';\nimport { Interaction } 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 ephemeral: true\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 ephemeral: true\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 | void {\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}","import EventEmitter from 'node:events';\nimport { CommandHandler, EventHandler, ValidationHandler } from './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';\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 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.dev/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 * 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 await commandHandler.init();\n\n this.#data.commandHandler = commandHandler;\n }\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}","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 handler has finished executing.\n * @param fn The function to run after the current handler.\n * @returns The deferred function id. This can be used to cancel the deferred function.\n */\nexport function after(fn: GenericFunction<[CommandKitEnvironment]>): 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 `after`.\n * @param id The deferred function id to cancel.\n */\nexport function cancelAfter(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 { CacheType, Interaction } 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 after,\n CommandKitEnvironment,\n CommandKitEnvironmentType } from\n'../../context/environment';\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\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 #interactionHandler(interaction: Interaction<CacheType>) {\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('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 after((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('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\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 {\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 { EventInterceptorContextData } from '../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)\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 };\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 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);\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';\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 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 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 { EventInterceptorContextData } from '../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)\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: true,\n time: 5 * 60 * 1000\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 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);\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';\n\nexport interface ModalProps {\n customId?: string;\n title: string;\n children?: MaybeArray<TextInputBuilder | ActionRowBuilder>;\n onSubmit?: OnModalKitSubmit;\n onEnd?: OnModalKitEnd;\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 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}"],"mappings":"k0BAAA,OAAS,sBAAyB,mBCAlC,OAAO,iBAAkB,cCAzB,OAAS,eAAkB,cAA3B,UAca,uBAAN,MAAM,sBAAsB,CAe1B,YAA4B,WAAwB,CAAxB,2BAdnC,wBAA2C,CACzC,eAAgB,KAChB,KAAM,KACN,UAAW,IAAI,IACf,kBAAmB,IAAI,IACvB,OAAQ,GACR,UAAW,EACX,QAAS,CACX,EAM4D,CAMrD,mBAAkC,CACvC,OAAO,kBAAK,OAAM,cACpB,CAOO,kBAAkB,MAAoB,CAC3C,GAAI,kBAAK,OAAM,eACb,MAAM,IAAI,MAAM,8BAA8B,EAGhD,kBAAK,OAAM,eAAiB,KAC9B,CAKO,SAAqC,CAC1C,IAAM,KAAO,kBAAK,OAAM,KAExB,GAAI,CAAC,KACH,MAAM,IAAI,MAAM,2BAA2B,EAG7C,OAAO,IACT,CAOO,QAAQ,KAAuC,CACpD,kBAAK,OAAM,KAAO,IACpB,CAKA,IAAW,WAA8B,CACvC,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BAAkB,EAE5D,KACR,CACF,CAdgB,8BAoBT,SAAS,QAAS,CAEvB,IAAM,YADM,eAAe,EACU,UAAU,IAAI,aAAa,EAEhE,GAAI,CAAC,YACH,MAAM,IAAI,MAAM,sCAAsC,EAGxD,GAAI,YAAY,MAAO,CACrB,IAAM,MAAQ,IAAI,MAAM,wCAAwC,EAChE,cAAQ,IAAI,MAAO,OAAQ,qBAAqB,eAAe,EAEzD,KACR,CACF,CAdgB","names":["CommandKitEnvironmentType","_data","canRun","context","env","myCustomId","ButtonStyle","ButtonStyle","Events","_contextData","_unsub","getEventInterceptor_fn","destroyCollector_fn","Events","_data"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{warnUnstable}from"./chunk-75Q5UTDQ.mjs";import{__name}from"./chunk-35OSBS47.mjs";var ElementType={ActionRow:"action-row",Button:"button-kit",Modal:"modal",TextInput:"text-input"};function isCommandKitElement(element){return!(typeof element!="object"||element===null||!Reflect.has(element,"type")||!Reflect.has(element,"data"))}__name(isCommandKitElement,"isCommandKitElement");function getElement(element){return element.data}__name(getElement,"getElement");function Fragment(props){return warnUnstable("CommandKit JSX"),Array.isArray(props.children)?props.children.flat():props.children}__name(Fragment,"Fragment");function createElement(type,props,...children){return warnUnstable("CommandKit JSX"),type({...props,children})}__name(createElement,"createElement");export{ElementType,isCommandKitElement,getElement,Fragment,createElement};
|
|
2
|
+
//# sourceMappingURL=chunk-5CQ732SA.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/components/common/element.ts"],"sourcesContent":["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}"],"mappings":"wFAKO,IAAM,YAAc,CACzB,UAAW,aACX,OAAQ,aACR,MAAO,QACP,UAAW,YACb,EAgBO,SAAS,oBAChB,QAC4C,CAG1C,MAFI,SAAO,SAAY,UAAY,UAAY,MAC3C,CAAC,QAAQ,IAAI,QAAS,MAAM,GAC5B,CAAC,QAAQ,IAAI,QAAS,MAAM,EAGlC,CARgB,kDAUT,SAAS,WAGhB,QAAsC,CACpC,OAAO,QAAQ,IACjB,CALgB,gCAWT,SAAS,SAChB,MACuC,CACrC,oBAAa,gBAAgB,EACtB,MAAM,QAAQ,MAAM,QAAQ,EAAI,MAAM,SAAS,KAAK,EAAI,MAAM,QACvE,CALgB,4BAOT,SAAS,cAChB,KACA,SACG,SAC8B,CAC/B,oBAAa,gBAAgB,EACtB,KAAK,CAAE,GAAG,MAAO,QAAS,CAAC,CACpC,CAPgB","names":[]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{__name,__privateAdd,__privateMethod,__publicField}from"./chunk-35OSBS47.mjs";var _EventInterceptor_instances,cleanupLoop_fn,_EventInterceptor=class _EventInterceptor{constructor(client){this.client=client;__privateAdd(this,_EventInterceptor_instances);__publicField(this,"subscribers",new Map);__publicField(this,"globalHandlers",new Map);__publicField(this,"cleanupTimer",null);__privateMethod(this,_EventInterceptor_instances,cleanupLoop_fn).call(this)}destroy(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=null);for(let[event,handlers]of this.subscribers)for(let handler of handlers)this.unsubscribe(event,handler,"destroy");this.subscribers.clear(),this.globalHandlers.clear()}hasSubscribers(event){return this.subscribers.has(event)}getSubscriberCount(event){let handlers=this.subscribers.get(event);return(handlers==null?void 0:handlers.size)??0}hasGlobalHandlers(){return this.globalHandlers.size>0}getGlobalHandlersCount(){return this.subscribers.size}subscribe(event,listener,options){return this.subscribers.has(event)||(this.subscribers.set(event,new Set),this.client.on(event,this.createGlobalHandler(event)),this.client.setMaxListeners(this.client.getMaxListeners()+1)),options??={},options.registeredAt=Date.now(),Reflect.set(listener,"options",options),this.subscribers.get(event).add(listener),()=>{this.unsubscribe(event,listener)}}unsubscribe(event,listener,reason){var _a,_b;let handlers=this.subscribers.get(event);handlers&&(handlers.delete(listener),handlers.size<1&&(this.subscribers.delete(event),this.client.removeListener(event,this.globalHandlers.get(event)),this.globalHandlers.delete(event),this.client.setMaxListeners(Math.max(this.client.getMaxListeners()-1,0))),(_b=(_a=Reflect.get(listener,"options")).onEnd)==null||_b.call(_a,reason??"unsubscribe"))}createGlobalHandler(event){if(this.globalHandlers.has(event))return this.globalHandlers.get(event);let handler=__name(async(...args)=>{let subscribers=this.subscribers.get(event);if(subscribers&&subscribers.size>0)for(let subscriber of subscribers){let options=Reflect.get(subscriber,"options");if(options.time&&Date.now()-options.registeredAt>options.time){this.unsubscribe(event,subscriber,"time");continue}options.autoReset&&(options.registeredAt=Date.now()),!(options.filter&&!await options.filter(...args))&&await subscriber(...args)}},"handler");return this.globalHandlers.set(event,handler),handler}};_EventInterceptor_instances=new WeakSet,cleanupLoop_fn=__name(function(){this.cleanupTimer&&clearInterval(this.cleanupTimer),this.cleanupTimer=setInterval(()=>{for(let[event,handlers]of this.subscribers)for(let handler of handlers){let options=Reflect.get(handler,"options");options.time&&Date.now()-options.registeredAt>options.time&&this.unsubscribe(event,handler,"time")}},6e4).unref()},"#cleanupLoop"),__name(_EventInterceptor,"EventInterceptor");var EventInterceptor=_EventInterceptor;export{EventInterceptor};
|
|
2
|
+
//# sourceMappingURL=chunk-6EE35LXH.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/components/common/EventInterceptor.ts"],"sourcesContent":["import { Awaitable, Client, ClientEvents } 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 * The handler to run when the collector ends.\n */\n onEnd?: (reason: string) => Awaitable<void>;\n}\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 await subscriber(...args);\n }\n }\n };\n\n this.globalHandlers.set(event, handler);\n\n return handler;\n }\n}"],"mappings":"oFAAA,+CAqBa,kBAAN,MAAM,iBAAiB,CAcrB,YAA4B,OAAgB,CAAhB,mBAd9B,+CACL,mBAAQ,cAAc,IAAI,KAI1B,mBAAQ,iBAAiB,IAAI,KAI7B,mBAAQ,eAAsC,MAM5C,qBAAK,4CAAL,UACF,CA6BO,SAAgB,CACjB,KAAK,eACP,cAAc,KAAK,YAAY,EAC/B,KAAK,aAAe,MAGtB,OAAW,CAAC,MAAO,QAAQ,IAAK,KAAK,YACnC,QAAW,WAAW,SACpB,KAAK,YAAY,MAAO,QAAS,SAAS,EAI9C,KAAK,YAAY,MAAM,EACvB,KAAK,eAAe,MAAM,CAC5B,CAMO,eAAe,MAAoC,CACxD,OAAO,K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pC,QAAW,cAAc,YAAa,CACpC,IAAM,QAAU,QAAQ,IACtB,WACA,SACF,EAKA,GAFA,QAAQ,MAAQ,KAAK,IAAI,EAAI,QAAQ,aAAe,QAAQ,KAE7C,CACb,KAAK,YAAY,MAAO,WAAY,MAAM,EAC1C,QACF,CAEI,QAAQ,YACV,QAAQ,aAAe,KAAK,IAAI,GAG9B,UAAQ,QAAU,CAAE,MAAM,QAAQ,OAAO,GAAG,IAAI,IAIpD,MAAM,WAAW,GAAG,IAAI,CAC1B,CAEJ,EA5BgB,WA8BhB,YAAK,eAAe,IAAI,MAAO,OAAO,EAE/B,OACT,CACF,EAnMO,wCAkBL,eAAY,iBAAG,CACT,KAAK,cAAc,cAAc,KAAK,YAAY,EAEtD,KAAK,aAAe,YAAY,IAAM,CACpC,OAAW,CAAC,MAAO,QAAQ,IAAK,KAAK,YACnC,QAAW,WAAW,SAAU,CAC9B,IAAM,QAAU,QAAQ,IACtB,QACA,SACF,EAKA,QAAQ,MAAQ,KAAK,IAAI,EAAI,QAAQ,aAAe,QAAQ,MAG1D,KAAK,YAAY,MAAO,QAAS,MAAM,CAE3C,CAEJ,EAAG,GAAM,EAAE,MAAM,CACnB,EAtBY,gBAlBgB,6CAAvB,IAAM,iBAAN","names":[]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{getCommandKit}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{getCommandKit}from"./chunk-52E3USJK.mjs";import{__name}from"./chunk-35OSBS47.mjs";import{AsyncLocalStorage}from"node:async_hooks";import ms from"ms";import{randomUUID}from"node:crypto";var CACHED_FUNCTIONS_STORE=new WeakMap,TAG_FUNCTION_MAP=new Map,DEFAULT_TTL=ms("15m"),cacheContext=new AsyncLocalStorage,__identificationKey=`__cache_identification_key_${Date.now()}__${Math.random()}__`,getDefaultCacheTag=__name(()=>({tag:randomUUID(),ttl:DEFAULT_TTL}),"getDefaultCacheTag");function cache(fn,params){return params=Object.assign({},getDefaultCacheTag(),params),useCache(fn,__identificationKey,params)}__name(cache,"cache");function useCache(fn,id,tag){if(id!==void 0&&id!==__identificationKey)throw new TypeError("useCache may not be called directly.");let isLocal=id===__identificationKey,memoized=__name(async(...args)=>{let cache2=getCommandKit(!0).getCacheProvider();if(!cache2)throw new Error("CacheProvider was not found, please provide a cache provider to the CommandKit instance.");let context=cacheContext.getStore();if(context===void 0)throw new Error('useCache must be called inside a function decorated with "use cache" directive.');let entryKey=context.params.tag,entry=await cache2.get(entryKey);if(entry!==void 0)return entry.value;let ttl=typeof context.params.ttl=="string"?ms(context.params.ttl):context.params.ttl,writeCache=__name(async(...args2)=>{let result=await fn(...args2);return CACHED_FUNCTIONS_STORE.set(fn,{...context.params,target:fn,memo:cacheContext.exit(()=>wrapper)}),entryKey!==context.params.tag&&TAG_FUNCTION_MAP.delete(entryKey),TAG_FUNCTION_MAP.set(context.params.tag,fn),await cache2.set(entryKey,result,ttl),result},"writeCache");return CACHED_FUNCTIONS_STORE.set(fn,{...context.params,target:fn,memo:cacheContext.exit(()=>wrapper)}),TAG_FUNCTION_MAP.set(entryKey,fn),writeCache(...args)},"memoized"),wrapper=__name(async(...args)=>{let params=CACHED_FUNCTIONS_STORE.get(fn)??((isLocal?tag:null)||getDefaultCacheTag());return cacheContext.run({params,target:fn},()=>memoized(...args))},"wrapper");return wrapper}__name(useCache,"useCache");function cacheTag(tag){var _a;if(!tag)throw new TypeError("cacheTag must be called with a tag.");let context=cacheContext.getStore();if(context===void 0)throw new Error('cacheTag must be called inside cache() or a function decorated with "use cache" directive.');let tagObj;typeof tag=="string"?tagObj={tag,ttl:((_a=context.params)==null?void 0:_a.ttl)??DEFAULT_TTL}:tagObj=tag,context.params=tagObj}__name(cacheTag,"cacheTag");function cacheLife(life){if(life==null)throw new TypeError("cacheLife must be called with a time-to-live value.");let context=cacheContext.getStore();if(context===void 0)throw new Error('cacheLife must be called inside cache() or a function decorated with "use cache" directive.');typeof life=="string"?context.params.ttl=ms(life):context.params.ttl=life}__name(cacheLife,"cacheLife");async function invalidate(tag){let cache2=getCommandKit(!0).getCacheProvider();if(!cache2)throw new Error("CacheProvider was not found, please provide a cache provider to the CommandKit instance.");await cache2.delete(tag)}__name(invalidate,"invalidate");async function revalidate(tag,...args){let cache2=getCommandKit(!0).getCacheProvider();if(!cache2)throw new Error("CacheProvider was not found, please provide a cache provider to the CommandKit instance.");await cache2.delete(tag);let tagFn=TAG_FUNCTION_MAP.get(tag);if(!tagFn)return;let ctx=CACHED_FUNCTIONS_STORE.get(tagFn);if(ctx)return ctx.memo(...args)}__name(revalidate,"revalidate");export{cache,useCache,cacheTag,cacheLife,invalidate,revalidate};
|
|
2
|
+
//# sourceMappingURL=chunk-6OSC45ZN.mjs.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{__name}from"./chunk-35OSBS47.mjs";var WARNED_KEYS=new Set;function emitWarning(message,code="CommandKitWarning"){process.emitWarning(message,{code})}__name(emitWarning,"emitWarning");function warnUnstable(name){WARNED_KEYS.has(name)||(WARNED_KEYS.add(name),emitWarning(`${name} is unstable and may change in future versions.`,"CommandKitUnstableWarning"))}__name(warnUnstable,"warnUnstable");export{emitWarning,warnUnstable};
|
|
2
|
+
//# sourceMappingURL=chunk-75Q5UTDQ.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/utils/warn-unstable.ts"],"sourcesContent":["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}"],"mappings":"yCAAA,IAAM,YAAc,IAAI,IAEjB,SAAS,YAAY,QAAiB,KAAO,oBAAqB,CACvE,QAAQ,YAAY,QAAS,CAAE,IAAK,CAAC,CACvC,CAFgB,kCAIT,SAAS,aAAa,KAAc,CACrC,YAAY,IAAI,IAAI,IAExB,YAAY,IAAI,IAAI,EAEpB,YACE,GAAG,IAAI,kDACP,2BACF,EACF,CATgB","names":[]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{__name}from"./chunk-35OSBS47.mjs";async function bootstrapCommandkitCLI(argv,options){let{Command}=await import("commander"),{bootstrapDevelopmentServer}=await import("./cli/development.mjs"),{bootstrapProductionServer}=await import("./cli/production.mjs"),{bootstrapProductionBuild}=await import("./cli/build.mjs"),program=new Command("commandkit");program.command("dev").description("Start your bot in development mode.").option("-c, --config <path>","Path to your commandkit config file.","./commandkit.js").action(()=>{let options2=program.opts();bootstrapDevelopmentServer(options2)}),program.command("start").description("Start your bot in production mode after running the build command.").option("-c, --config <path>","Path to your commandkit.json file.","./commandkit.js").action(()=>{let options2=program.opts();bootstrapProductionServer(options2.config)}),program.command("build").description("Build your project for production usage.").option("-c, --config <path>","Path to your commandkit.json file.","./commandkit.json").action(()=>{let options2=program.opts();bootstrapProductionBuild(options2.config)}),await program.parseAsync(argv,options)}__name(bootstrapCommandkitCLI,"bootstrapCommandkitCLI");export{bootstrapCommandkitCLI};
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
2
|
+
//# sourceMappingURL=chunk-D4IIOMFB.mjs.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{clone}from"./chunk-MNPCM4QU.mjs";import{colors_default}from"./chunk-QXMWKQIO.mjs";import{getFilePaths}from"./chunk-RVGLG66X.mjs";import{toFileURL}from"./chunk-ICJ4BBWI.mjs";import{__name,__privateAdd,__privateGet,__privateMethod,__privateSet,__require}from"./chunk-35OSBS47.mjs";var _data,_ValidationHandler_instances,buildValidations_fn,_ValidationHandler=class _ValidationHandler{constructor({...options}){__privateAdd(this,_ValidationHandler_instances);__privateAdd(this,_data);__privateSet(this,_data,{...options,validations:[]})}async init(){__privateGet(this,_data).validations=await __privateMethod(this,_ValidationHandler_instances,buildValidations_fn).call(this)}get validations(){return __privateGet(this,_data).validations}async reloadValidations(){if(!__privateGet(this,_data).validationsPath)throw new Error(colors_default.red('Cannot reload validations as "validationsPath" was not provided when instantiating CommandKit.'));let newValidations=await __privateMethod(this,_ValidationHandler_instances,buildValidations_fn).call(this);__privateGet(this,_data).validations=newValidations}};_data=new WeakMap,_ValidationHandler_instances=new WeakSet,buildValidations_fn=__name(async function(){let allowedExtensions=/\.(js|mjs|cjs|ts)$/i,validationFilePaths=(await getFilePaths(__privateGet(this,_data).validationsPath,!0)).filter(path=>allowedExtensions.test(path)),validationFunctions=[];for(let validationFilePath of validationFilePaths){let importedFunction=(await import(`${toFileURL(validationFilePath)}?t=${Date.now()}`)).default,validationFunction=clone(importedFunction);typeof module<"u"&&typeof __require<"u"&&delete __require.cache[__require.resolve(validationFilePath)],validationFunction!=null&&validationFunction.default&&(validationFunction=validationFunction.default);let compactFilePath=validationFilePath.split(process.cwd())[1]||validationFilePath;if(typeof validationFunction!="function"){process.emitWarning(colors_default.yellow(`Ignoring: Validation file ${compactFilePath} does not export a function.`));continue}validationFunctions.push(validationFunction)}return validationFunctions},"#buildValidations"),__name(_ValidationHandler,"ValidationHandler");var ValidationHandler=_ValidationHandler;export{ValidationHandler};
|
|
2
|
+
//# sourceMappingURL=chunk-DMNZASZO.mjs.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{cacheDirectivePlugin}from"./chunk-Y522NY4J.mjs";import{__name}from"./chunk-35OSBS47.mjs";import{MacroTransformer}from"use-macro";import{readFile}from"node:fs/promises";var defaultConfig={"use-macro":!0,"use-cache":!0,"jsx-importsource":!0},commandkitPlugin=__name(config=>{config=Object.assign({},defaultConfig,config);let plugins=[{name:"use-macro",plugin:__name(async(content,args)=>{let transformer=new MacroTransformer,{contents}=await transformer.transform(content,args.path);return contents},"plugin")},{name:"use-cache",plugin:__name(async(content,args)=>{let{contents}=await cacheDirectivePlugin(content,args);return contents},"plugin")}].filter(p=>!!config[p.name]);return{name:"commandkit-transformer-plugin",setup(build){if(!plugins.length)return;let fileFilter=/\.(c|m)?(t|j)sx?$/;build.onLoad({filter:fileFilter},async args=>{let source=await readFile(args.path,"utf8"),loader=args.path.split(".").pop(),contents=source;for(let _plugin of plugins){let{plugin,name}=_plugin;try{contents=await plugin(contents,args)}catch(e){let err=new Error(`Plugin ${name} failed with ${e}`);throw err.stack=e instanceof Error?e.stack:"",err}}return{contents,loader}})}}},"commandkitPlugin");export{commandkitPlugin};
|
|
2
|
+
//# sourceMappingURL=chunk-HFOCTXRX.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/cli/esbuild-plugins/plugin.ts"],"sourcesContent":["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};"],"mappings":"gGAAA,OAAS,qBAAwB,YAEjC,OAAS,aAAgB,mBAEzB,IAAM,cAAgB,CACpB,YAAa,GACb,YAAa,GACb,mBAAoB,EACtB,EAQa,iBAAmB,OAAC,QAA2C,CAC1E,OAAS,OAAO,OAAO,CAAC,EAAG,cAAe,MAAM,EAEhD,IAAM,QAAU,CAChB,CACE,KAAM,YACN,OAAQ,aAAO,QAAiB,OAAc,CAC5C,IAAM,YAAc,IAAI,iBAClB,CAAE,QAAS,EAAI,MAAM,YAAY,UAAU,QAAS,KAAK,IAAI,EACnE,OAAO,QACT,EAJQ,SAKV,EACA,CACE,KAAM,YACN,OAAQ,aAAO,QAAiB,OAAc,CAC5C,GAAM,CAAE,QAAS,EAAI,MAAM,qBAAqB,QAAS,IAAI,EAC7D,OAAO,QACT,EAHQ,SAIV,CAAC,EACD,OAAQ,GACC,CAAC,CAAC,OAAO,EAAE,IAA2C,CAC9D,EAED,MAAO,CACL,KAAM,gCACN,MAAM,MAAY,CAChB,GAAI,CAAC,QAAQ,OAAQ,OAErB,IAAM,WAAa,oBAEnB,MAAM,OAAO,CAAE,OAAQ,UAAW,EAAG,MAAO,MAAc,CACxD,IAAM,OAAS,MAAM,SAAS,KAAK,KAAM,MAAM,EACzC,OAAS,KAAK,KAAK,MAAM,GAAG,EAAE,IAAI,EAEpC,SAAW,OAEf,QAAW,WAAW,QAAS,CAC7B,GAAM,CAAE,OAAQ,IAAK,EAAI,QACzB,GAAI,CACF,SAAW,MAAM,OAAO,SAAU,IAAI,CACxC,OAAS,EAAG,CACV,IAAM,IAAM,IAAI,MAAM,UAAU,IAAI,gBAAgB,CAAC,EAAE,EACvD,UAAI,MAAQ,aAAa,MAAQ,EAAE,MAAQ,GAErC,GACR,CACF,CAEA,MAAO,CACL,SACA,MACF,CACF,CAAC,CACH,CACF,CACF,EAvDgC","names":[]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{__name}from"./chunk-35OSBS47.mjs";import{ActionRowBuilder}from"discord.js";function ActionRow(props){let row=new ActionRowBuilder;return Array.isArray(props.children)?row.setComponents(...props.children):props.children&&row.setComponents(props.children),row}__name(ActionRow,"ActionRow");export{ActionRow};
|
|
2
|
+
//# sourceMappingURL=chunk-HN3WQT6R.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/components/action-row/ActionRow.ts"],"sourcesContent":["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}"],"mappings":"yCAAA,OAAS,qBAAwB,aAa1B,SAAS,UAChB,MACkC,CAChC,IAAM,IAAM,IAAI,iBAEhB,OAAI,MAAM,QAAQ,MAAM,QAAQ,EAE9B,IAAI,cAAc,GAAG,MAAM,QAAQ,EAC1B,MAAM,UAEf,IAAI,cAAc,MAAM,QAAQ,EAG3B,GACT,CAdgB","names":[]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{clone}from"./chunk-MNPCM4QU.mjs";import{colors_default}from"./chunk-QXMWKQIO.mjs";import{getFilePaths,getFolderPaths}from"./chunk-RVGLG66X.mjs";import{toFileURL}from"./chunk-ICJ4BBWI.mjs";import{__name,__privateAdd,__privateGet,__privateMethod,__privateSet,__require}from"./chunk-35OSBS47.mjs";var _data,_EventHandler_instances,buildEvents_fn,registerEvents_fn,_EventHandler=class _EventHandler{constructor({...options}){__privateAdd(this,_EventHandler_instances);__privateAdd(this,_data);__privateSet(this,_data,{...options,events:[]})}async init(){await __privateMethod(this,_EventHandler_instances,buildEvents_fn).call(this),__privateMethod(this,_EventHandler_instances,registerEvents_fn).call(this)}get events(){return __privateGet(this,_data).events}async reloadEvents(commandHandler){if(!__privateGet(this,_data).eventsPath)throw new Error(colors_default.red('Cannot reload events as "eventsPath" was not provided when instantiating CommandKit.'));__privateGet(this,_data).events=[],await __privateMethod(this,_EventHandler_instances,buildEvents_fn).call(this),__privateGet(this,_data).client.removeAllListeners(),__privateMethod(this,_EventHandler_instances,registerEvents_fn).call(this),commandHandler==null||commandHandler.handleCommands()}};_data=new WeakMap,_EventHandler_instances=new WeakSet,buildEvents_fn=__name(async function(){let eventFolderPaths=await getFolderPaths(__privateGet(this,_data).eventsPath);for(let eventFolderPath of eventFolderPaths){let eventName=eventFolderPath.replace(/\\\\|\\/g,"/").split("/").pop(),allowedExtensions=/\.(js|mjs|cjs|ts)$/i,eventFilePaths=(await getFilePaths(eventFolderPath,!0)).filter(path=>allowedExtensions.test(path)),eventObj={name:eventName,functions:[]};__privateGet(this,_data).events.push(eventObj);for(let eventFilePath of eventFilePaths){let importedFunction=(await import(`${toFileURL(eventFilePath)}?t=${Date.now()}`)).default,eventFunction=clone(importedFunction);typeof module<"u"&&typeof __require<"u"&&delete __require.cache[__require.resolve(eventFilePath)],eventFunction!=null&&eventFunction.default&&(eventFunction=eventFunction.default);let compactFilePath=eventFilePath.split(process.cwd())[1]||eventFilePath;if(typeof eventFunction!="function"){process.emitWarning(colors_default.yellow(`Ignoring: Event file ${compactFilePath} does not export a function.`));continue}eventObj.functions.push(eventFunction)}}},"#buildEvents"),registerEvents_fn=__name(function(){let client=__privateGet(this,_data).client,handler=__privateGet(this,_data).commandKitInstance;for(let eventObj of __privateGet(this,_data).events)client.on(eventObj.name,async(...params)=>{for(let eventFunction of eventObj.functions)if(await eventFunction(...params,client,handler))break})},"#registerEvents"),__name(_EventHandler,"EventHandler");var EventHandler=_EventHandler;export{EventHandler};
|
|
2
|
+
//# sourceMappingURL=chunk-JPMIJRUL.mjs.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{commandkitPlugin}from"./chunk-
|
|
2
|
-
`).start(),start=performance.now();erase(outDir);try{await build({clean:!0,format:["esm"],dts:!1,skipNodeModulesBundle:!0,minify,shims:!0,banner:{js:"/* Optimized production build generated by CommandKit */"},sourcemap,keepNames:!0,outDir,silent:!0,watch:!1,cjsInterop:!0,entry:[src,"!dist","!.commandkit",`!${outDir}`],esbuildPlugins:[commandkitPlugin()]}),await injectShims(outDir,main,antiCrash,polyfillRequire),status.succeed(Colors.green(`Build completed in ${(performance.now()-start).toFixed(2)}ms!`)),write(Colors.green(`
|
|
1
|
+
import{commandkitPlugin}from"./chunk-HFOCTXRX.mjs";import{Colors,erase,findCommandKitConfig,panic,write}from"./chunk-FC5WQLBI.mjs";import{__name}from"./chunk-35OSBS47.mjs";import{readFile,writeFile}from"node:fs/promises";import{join}from"node:path";import{build}from"tsup";import ora from"ora";async function bootstrapProductionBuild(config){let{sourcemap=!1,minify=!1,outDir="dist",antiCrash=!0,src,main,requirePolyfill:polyfillRequire}=await findCommandKitConfig(config),status=ora(`Creating optimized production build...
|
|
2
|
+
`).start(),start=performance.now();erase(outDir);try{await build({clean:!0,format:["esm"],dts:!1,skipNodeModulesBundle:!0,minify,shims:!0,banner:{js:"/* Optimized production build generated by CommandKit */"},sourcemap,keepNames:!0,outDir,silent:!0,watch:!1,cjsInterop:!0,entry:[src,"!dist","!.commandkit",`!${outDir}`],esbuildPlugins:[commandkitPlugin()],jsxFactory:"CommandKit.createElement",jsxFragment:"CommandKit.Fragment"}),await injectShims(outDir,main,antiCrash,polyfillRequire),status.succeed(Colors.green(`Build completed in ${(performance.now()-start).toFixed(2)}ms!`)),write(Colors.green(`
|
|
3
3
|
Run ${Colors.magenta("commandkit start")} ${Colors.green("to start your bot.")}`))}catch(e){status.fail(`Build failed after ${(performance.now()-start).toFixed(2)}ms!`),panic(e)}}__name(bootstrapProductionBuild,"bootstrapProductionBuild");async function injectShims(outDir,main,antiCrash,polyfillRequire){let path=join(process.cwd(),outDir,main),head=[`
|
|
4
4
|
|
|
5
5
|
;await (async()=>{`," 'use strict';"].join(`
|
|
@@ -10,4 +10,4 @@ Run ${Colors.magenta("commandkit start")} ${Colors.green("to start your bot.")}`
|
|
|
10
10
|
|
|
11
11
|
`,contents].join(`
|
|
12
12
|
`);return writeFile(path,finalScript)}__name(injectShims,"injectShims");export{bootstrapProductionBuild,injectShims};
|
|
13
|
-
//# sourceMappingURL=chunk-
|
|
13
|
+
//# sourceMappingURL=chunk-P7PNFSAC.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/cli/build.ts"],"sourcesContent":["// @ts-check\n\nimport { readFile, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { build } from 'tsup';\nimport { Colors, erase, findCommandKitConfig, panic, write } from './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 entry: [src, '!dist', '!.commandkit', `!${outDir}`],\n esbuildPlugins: [commandkitPlugin()],\n jsxFactory: 'CommandKit.createElement',\n jsxFragment: 'CommandKit.Fragment'\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}"],"mappings":"4KAEA,OAAS,SAAU,cAAiB,mBACpC,OAAS,SAAY,YACrB,OAAS,UAAa,OAEtB,OAAO,QAAS,MAGhB,eAAsB,yBAAyB,OAAa,CAC1D,GAAM,CACJ,UAAY,GACZ,OAAS,GACT,OAAS,OACT,UAAY,GACZ,IACA,KACA,gBAAiB,eACnB,EAAI,MAAM,qBAAqB,MAAM,EAE/B,OAAS,IAAI;AAAA,CAA0C,EAAE,MAAM,EAC/D,MAAQ,YAAY,IAAI,EAE9B,MAAM,MAAM,EAEZ,GAAI,CACF,MAAM,MAAM,CACV,MAAO,GACP,OAAQ,CAAC,KAAK,EACd,IAAK,GACL,sBAAuB,GACvB,OACA,MAAO,GACP,OAAQ,CACN,GAAI,0DACN,EACA,UACA,UAAW,GACX,OACA,OAAQ,GACR,MAAO,GACP,WAAY,GACZ,MAAO,CAAC,IAAK,QAAS,eAAgB,IAAI,MAAM,EAAE,EAClD,eAAgB,CAAC,iBAAiB,CAAC,EACnC,WAAY,2BACZ,YAAa,qBACf,CAAC,EAED,MAAM,YAAY,OAAQ,KAAM,UAAW,eAAe,EAE1D,OAAO,QACL,OAAO,MACL,uBAAuB,YAAY,IAAI,EAAI,OAAO,QAAQ,CAAC,CAAC,KAC9D,CACF,EACA,MACE,OAAO,MACL;AAAA,MAAS,OAAO,QAAQ,kBAAkB,CAAC,IAAI,OAAO,MACpD,oBACF,CAAC,EACH,CACF,CACF,OAAS,EAAG,CACV,OAAO,KACL,uBAAuB,YAAY,IAAI,EAAI,OAAO,QAAQ,CAAC,CAAC,KAC9D,EACA,MAAM,CAAC,CACT,CACF,CA3DsB,4DA6DtB,eAAsB,YACtB,OACA,KACA,UACA,gBACA,CACE,IAAM,KAAO,KAAK,QAAQ,IAAI,EAAG,OAAQ,IAAI,EAEvC,KAAO,CAAC;AAAA;AAAA,oBAA0B,iBAAiB,EAAE,KAAK;AAAA,CAAI,EAC9D,KAAO;AAAA,OACP,cAAgB,gBACtB,CACA,2CACA,0CACA,6DACA,wDACA,qDACA,yBACA,gCACA,WACA,4BACA,2BACA,wBACA,UACA,MACA,0CAA0C,EAC1C,KAAK;AAAA,CAAI,EACT,GAEM,gBAAkB,UACxB,CACA,2CACA,wHACA,2DACA,mFACA,2JACA,6EACA,8BACA,mEACA,SACA,6EACA,8BACA,gFACA,UACA,0CAA0C,EAC1C,KAAK;AAAA,CAAI,EACT,GAEM,SAAW,MAAM,SAAS,KAAM,OAAO,EACvC,YAAc,CACpB,KACA,cACA,gBACA,KACA;AAAA;AAAA,EACA,QAAQ,EACR,KAAK;AAAA,CAAI,EAET,OAAO,UAAU,KAAM,WAAW,CACpC,CA3DsB","names":[]}
|
package/dist/cli/build.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty;var __name=(target,value)=>__defProp(target,"name",{value,configurable:!0});var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target,mod)),__toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod);var build_exports={};__export(build_exports,{bootstrapProductionBuild:()=>bootstrapProductionBuild,injectShims:()=>injectShims});module.exports=__toCommonJS(build_exports);var import_promises2=require("fs/promises"),import_node_path2=require("path"),import_tsup=require("tsup");var import_rimraf=require("rimraf"),import_node_path=require("path"),import_node_fs=__toESM(require("fs"));var resetColor="\x1B[0m",Colors={reset:__name(text=>`${text}${resetColor}`,"reset"),bright:__name(text=>`\x1B[1m${text}${resetColor}`,"bright"),dim:__name(text=>`\x1B[2m${text}${resetColor}`,"dim"),underscore:__name(text=>`\x1B[4m${text}${resetColor}`,"underscore"),blink:__name(text=>`\x1B[5m${text}${resetColor}`,"blink"),reverse:__name(text=>`\x1B[7m${text}${resetColor}`,"reverse"),hidden:__name(text=>`\x1B[8m${text}${resetColor}`,"hidden"),black:__name(text=>`\x1B[30m${text}${resetColor}`,"black"),red:__name(text=>`\x1B[31m${text}${resetColor}`,"red"),green:__name(text=>`\x1B[32m${text}${resetColor}`,"green"),yellow:__name(text=>`\x1B[33m${text}${resetColor}`,"yellow"),blue:__name(text=>`\x1B[34m${text}${resetColor}`,"blue"),magenta:__name(text=>`\x1B[35m${text}${resetColor}`,"magenta"),cyan:__name(text=>`\x1B[36m${text}${resetColor}`,"cyan"),white:__name(text=>`\x1B[37m${text}${resetColor}`,"white"),bgBlack:__name(text=>`\x1B[40m${text}${resetColor}`,"bgBlack"),bgRed:__name(text=>`\x1B[41m${text}${resetColor}`,"bgRed"),bgGreen:__name(text=>`\x1B[42m${text}${resetColor}`,"bgGreen"),bgYellow:__name(text=>`\x1B[43m${text}${resetColor}`,"bgYellow"),bgBlue:__name(text=>`\x1B[44m${text}${resetColor}`,"bgBlue"),bgMagenta:__name(text=>`\x1B[45m${text}${resetColor}`,"bgMagenta"),bgCyan:__name(text=>`\x1B[46m${text}${resetColor}`,"bgCyan"),bgWhite:__name(text=>`\x1B[47m${text}${resetColor}`,"bgWhite")};function write(message){process.stdout.write(message),process.stdout.write(`
|
|
2
|
-
`)}__name(write,"write");function panic(message){write(Colors.red(`Error: ${message}`)),process.exit(1)}__name(panic,"panic");var possibleFileNames=["commandkit.json","commandkit.config.json","commandkit.js","commandkit.config.js","commandkit.mjs","commandkit.config.mjs","commandkit.cjs","commandkit.config.cjs","commandkit.ts","commandkit.mts","commandkit.cts"];async function findCommandKitConfig(src){let cwd=process.cwd(),locations=src?[(0,import_node_path.join)(cwd,src)]:possibleFileNames.map(name=>(0,import_node_path.join)(cwd,name));for(let location of locations)try{return await loadConfigInner(location)}catch{continue}panic(`Could not locate commandkit config from ${cwd}`)}__name(findCommandKitConfig,"findCommandKitConfig");function ensureTypeScript(target){/\.(c|m)tsx?$/.test(target)&&!process.features.typescript&&panic("You are trying to load commandkit config file that is written in typescript. The current Node.js version does not have TypeScript feature enabled.")}__name(ensureTypeScript,"ensureTypeScript");async function loadConfigInner(target){let isJSON=target.endsWith(".json");return await ensureExists(target),ensureTypeScript(target),await import(`file://${target}`).then(conf=>conf.default||conf)}__name(loadConfigInner,"loadConfigInner");async function ensureExists(loc){await import_node_fs.default.promises.access(loc,import_node_fs.default.constants.F_OK)}__name(ensureExists,"ensureExists");function erase(dir){(0,import_rimraf.rimrafSync)(dir)}__name(erase,"erase");var import_ora=__toESM(require("ora"));var import_use_macro=require("use-macro");var parser=__toESM(require("@babel/parser")),import_traverse=__toESM(require("@babel/traverse")),import_generator=__toESM(require("@babel/generator")),t=__toESM(require("@babel/types"));var traverse=import_traverse.default.default||import_traverse.default,generate=import_generator.default.default||import_generator.default,IMPORT_PATH="commandkit",DIRECTIVE="use cache",CACHE_IDENTIFIER="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",generateRandomString=__name((length=6)=>{let chars="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";return Array.from({length},()=>chars[Math.floor(Math.random()*chars.length)]).join("")},"generateRandomString"),cacheDirectivePlugin=__name(async(source,args)=>{let ast=parser.parse(source,{sourceType:"module",plugins:["typescript","jsx"]}),state={needsImport:!1,hasExistingImport:!1,cacheIdentifierName:CACHE_IDENTIFIER,modifications:[]};traverse(ast,{Program:{enter(path){path.scope.getBinding(CACHE_IDENTIFIER)&&(state.cacheIdentifierName=`${CACHE_IDENTIFIER}_${generateRandomString()}`)}},ImportDeclaration(path){path.node.source.value===IMPORT_PATH&&path.node.specifiers.some(spec=>t.isImportSpecifier(spec)&&spec.imported.name===CACHE_IDENTIFIER)&&(state.hasExistingImport=!0,state.cacheIdentifierName!==CACHE_IDENTIFIER&&state.modifications.push(()=>{path.node.specifiers.forEach(spec=>{t.isImportSpecifier(spec)&&spec.imported.name===CACHE_IDENTIFIER&&(spec.local.name=state.cacheIdentifierName)})}))},"FunctionDeclaration|FunctionExpression|ArrowFunctionExpression"(path){var _a,_b,_c;let body=t.isBlockStatement(path.node.body)?path.node.body:null,hasUseCache=(_a=body==null?void 0:body.directives)==null?void 0:_a.some(d=>d.value.value===DIRECTIVE);if(!hasUseCache&&!t.isBlockStatement(path.node.body)){let parentFunction=path.findParent(p=>(p.isFunction()||p.isProgram())&&"directives"in p.node);if(!((_b=parentFunction==null?void 0:parentFunction.node.directives)!=null&&_b.some(d=>d.value.value===DIRECTIVE)))return}if(hasUseCache||!t.isBlockStatement(path.node.body)){if(!path.node.async)throw new Error(`"${DIRECTIVE}" directive may only be used in async functions at ${args.path}`);state.needsImport=!0;let name=t.isFunctionDeclaration(path.node)?(_c=path.node.id)==null?void 0:_c.name:void 0,newBody=t.isBlockStatement(path.node.body)?t.blockStatement(path.node.body.body,path.node.body.directives.filter(d=>d.value.value!==DIRECTIVE)):path.node.body,wrapped=t.callExpression(t.identifier(state.cacheIdentifierName),[t.arrowFunctionExpression(path.node.params,newBody,!0)]);state.modifications.push(()=>{name?path.replaceWith(t.variableDeclaration("const",[t.variableDeclarator(t.identifier(name),wrapped)])):t.isVariableDeclarator(path.parent)?path.parent.init=wrapped:path.replaceWith(wrapped)})}}}),state.modifications.length>0&&(state.needsImport&&!state.hasExistingImport&&ast.program.body.unshift(t.importDeclaration([t.importSpecifier(t.identifier(state.cacheIdentifierName),t.identifier(CACHE_IDENTIFIER))],t.stringLiteral(IMPORT_PATH))),state.modifications.forEach(modify=>modify()));let{code}=generate(ast);return{contents:code,loader:args.path.split(".").pop()}},"cacheDirectivePlugin");var import_promises=require("fs/promises");var defaultConfig={"use-macro":!0,"use-cache":!0},commandkitPlugin=__name(config=>{config=Object.assign({},defaultConfig,config);let plugins=[{name:"use-macro",plugin:__name(async(content,args)=>{let transformer=new import_use_macro.MacroTransformer,{contents}=await transformer.transform(content,args.path);return contents},"plugin")},{name:"use-cache",plugin:__name(async(content,args)=>{let{contents}=await cacheDirectivePlugin(content,args);return contents},"plugin")}].filter(p=>!!config[p.name]);return{name:"commandkit-transformer-plugin",setup(build2){if(!plugins.length)return;let fileFilter=/\.(c|m)?(t|j)sx?$/;build2.onLoad({filter:fileFilter},async args=>{let source=await(0,import_promises.readFile)(args.path,"utf8"),loader=args.path.split(".").pop(),contents=source;for(let _plugin of plugins){let{plugin,name}=_plugin;try{contents=await plugin(contents,args)}catch(e){let err=new Error(`Plugin ${name} failed with ${e}`);throw err.stack=e instanceof Error?e.stack:"",err}}return{contents,loader}})}}},"commandkitPlugin");async function bootstrapProductionBuild(config){let{sourcemap=!1,minify=!1,outDir="dist",antiCrash=!0,src,main,requirePolyfill:polyfillRequire}=await findCommandKitConfig(config),status=(0,import_ora.default)(`Creating optimized production build...
|
|
3
|
-
`).start(),start=performance.now();erase(outDir);try{await(0,import_tsup.build)({clean:!0,format:["esm"],dts:!1,skipNodeModulesBundle:!0,minify,shims:!0,banner:{js:"/* Optimized production build generated by CommandKit */"},sourcemap,keepNames:!0,outDir,silent:!0,watch:!1,cjsInterop:!0,entry:[src,"!dist","!.commandkit",`!${outDir}`],esbuildPlugins:[commandkitPlugin()]}),await injectShims(outDir,main,antiCrash,polyfillRequire),status.succeed(Colors.green(`Build completed in ${(performance.now()-start).toFixed(2)}ms!`)),write(Colors.green(`
|
|
2
|
+
`)}__name(write,"write");function panic(message){write(Colors.red(`Error: ${message}`)),process.exit(1)}__name(panic,"panic");var possibleFileNames=["commandkit.json","commandkit.config.json","commandkit.js","commandkit.config.js","commandkit.mjs","commandkit.config.mjs","commandkit.cjs","commandkit.config.cjs","commandkit.ts","commandkit.mts","commandkit.cts"];async function findCommandKitConfig(src){let cwd=process.cwd(),locations=src?[(0,import_node_path.join)(cwd,src)]:possibleFileNames.map(name=>(0,import_node_path.join)(cwd,name));for(let location of locations)try{return await loadConfigInner(location)}catch{continue}panic(`Could not locate commandkit config from ${cwd}`)}__name(findCommandKitConfig,"findCommandKitConfig");function ensureTypeScript(target){/\.(c|m)tsx?$/.test(target)&&!process.features.typescript&&panic("You are trying to load commandkit config file that is written in typescript. The current Node.js version does not have TypeScript feature enabled.")}__name(ensureTypeScript,"ensureTypeScript");async function loadConfigInner(target){let isJSON=target.endsWith(".json");return await ensureExists(target),ensureTypeScript(target),await import(`file://${target}`).then(conf=>conf.default||conf)}__name(loadConfigInner,"loadConfigInner");async function ensureExists(loc){await import_node_fs.default.promises.access(loc,import_node_fs.default.constants.F_OK)}__name(ensureExists,"ensureExists");function erase(dir){(0,import_rimraf.rimrafSync)(dir)}__name(erase,"erase");var import_ora=__toESM(require("ora"));var import_use_macro=require("use-macro");var parser=__toESM(require("@babel/parser")),import_traverse=__toESM(require("@babel/traverse")),import_generator=__toESM(require("@babel/generator")),t=__toESM(require("@babel/types"));var traverse=import_traverse.default.default||import_traverse.default,generate=import_generator.default.default||import_generator.default,IMPORT_PATH="commandkit",DIRECTIVE="use cache",CACHE_IDENTIFIER="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",generateRandomString=__name((length=6)=>{let chars="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";return Array.from({length},()=>chars[Math.floor(Math.random()*chars.length)]).join("")},"generateRandomString"),cacheDirectivePlugin=__name(async(source,args)=>{let ast=parser.parse(source,{sourceType:"module",plugins:["typescript","jsx"]}),state={needsImport:!1,hasExistingImport:!1,cacheIdentifierName:CACHE_IDENTIFIER,modifications:[]};traverse(ast,{Program:{enter(path){path.scope.getBinding(CACHE_IDENTIFIER)&&(state.cacheIdentifierName=`${CACHE_IDENTIFIER}_${generateRandomString()}`)}},ImportDeclaration(path){path.node.source.value===IMPORT_PATH&&path.node.specifiers.some(spec=>t.isImportSpecifier(spec)&&spec.imported.name===CACHE_IDENTIFIER)&&(state.hasExistingImport=!0,state.cacheIdentifierName!==CACHE_IDENTIFIER&&state.modifications.push(()=>{path.node.specifiers.forEach(spec=>{t.isImportSpecifier(spec)&&spec.imported.name===CACHE_IDENTIFIER&&(spec.local.name=state.cacheIdentifierName)})}))},"FunctionDeclaration|FunctionExpression|ArrowFunctionExpression"(path){var _a,_b,_c;let body=t.isBlockStatement(path.node.body)?path.node.body:null,hasUseCache=(_a=body==null?void 0:body.directives)==null?void 0:_a.some(d=>d.value.value===DIRECTIVE);if(!hasUseCache&&!t.isBlockStatement(path.node.body)){let parentFunction=path.findParent(p=>(p.isFunction()||p.isProgram())&&"directives"in p.node);if(!((_b=parentFunction==null?void 0:parentFunction.node.directives)!=null&&_b.some(d=>d.value.value===DIRECTIVE)))return}if(hasUseCache||!t.isBlockStatement(path.node.body)){if(!path.node.async)throw new Error(`"${DIRECTIVE}" directive may only be used in async functions at ${args.path}`);state.needsImport=!0;let name=t.isFunctionDeclaration(path.node)?(_c=path.node.id)==null?void 0:_c.name:void 0,newBody=t.isBlockStatement(path.node.body)?t.blockStatement(path.node.body.body,path.node.body.directives.filter(d=>d.value.value!==DIRECTIVE)):path.node.body,wrapped=t.callExpression(t.identifier(state.cacheIdentifierName),[t.arrowFunctionExpression(path.node.params,newBody,!0)]);state.modifications.push(()=>{name?path.replaceWith(t.variableDeclaration("const",[t.variableDeclarator(t.identifier(name),wrapped)])):t.isVariableDeclarator(path.parent)?path.parent.init=wrapped:path.replaceWith(wrapped)})}}}),state.modifications.length>0&&(state.needsImport&&!state.hasExistingImport&&ast.program.body.unshift(t.importDeclaration([t.importSpecifier(t.identifier(state.cacheIdentifierName),t.identifier(CACHE_IDENTIFIER))],t.stringLiteral(IMPORT_PATH))),state.modifications.forEach(modify=>modify()));let{code}=generate(ast);return{contents:code,loader:args.path.split(".").pop()}},"cacheDirectivePlugin");var import_promises=require("fs/promises");var defaultConfig={"use-macro":!0,"use-cache":!0,"jsx-importsource":!0},commandkitPlugin=__name(config=>{config=Object.assign({},defaultConfig,config);let plugins=[{name:"use-macro",plugin:__name(async(content,args)=>{let transformer=new import_use_macro.MacroTransformer,{contents}=await transformer.transform(content,args.path);return contents},"plugin")},{name:"use-cache",plugin:__name(async(content,args)=>{let{contents}=await cacheDirectivePlugin(content,args);return contents},"plugin")}].filter(p=>!!config[p.name]);return{name:"commandkit-transformer-plugin",setup(build2){if(!plugins.length)return;let fileFilter=/\.(c|m)?(t|j)sx?$/;build2.onLoad({filter:fileFilter},async args=>{let source=await(0,import_promises.readFile)(args.path,"utf8"),loader=args.path.split(".").pop(),contents=source;for(let _plugin of plugins){let{plugin,name}=_plugin;try{contents=await plugin(contents,args)}catch(e){let err=new Error(`Plugin ${name} failed with ${e}`);throw err.stack=e instanceof Error?e.stack:"",err}}return{contents,loader}})}}},"commandkitPlugin");async function bootstrapProductionBuild(config){let{sourcemap=!1,minify=!1,outDir="dist",antiCrash=!0,src,main,requirePolyfill:polyfillRequire}=await findCommandKitConfig(config),status=(0,import_ora.default)(`Creating optimized production build...
|
|
3
|
+
`).start(),start=performance.now();erase(outDir);try{await(0,import_tsup.build)({clean:!0,format:["esm"],dts:!1,skipNodeModulesBundle:!0,minify,shims:!0,banner:{js:"/* Optimized production build generated by CommandKit */"},sourcemap,keepNames:!0,outDir,silent:!0,watch:!1,cjsInterop:!0,entry:[src,"!dist","!.commandkit",`!${outDir}`],esbuildPlugins:[commandkitPlugin()],jsxFactory:"CommandKit.createElement",jsxFragment:"CommandKit.Fragment"}),await injectShims(outDir,main,antiCrash,polyfillRequire),status.succeed(Colors.green(`Build completed in ${(performance.now()-start).toFixed(2)}ms!`)),write(Colors.green(`
|
|
4
4
|
Run ${Colors.magenta("commandkit start")} ${Colors.green("to start your bot.")}`))}catch(e){status.fail(`Build failed after ${(performance.now()-start).toFixed(2)}ms!`),panic(e)}}__name(bootstrapProductionBuild,"bootstrapProductionBuild");async function injectShims(outDir,main,antiCrash,polyfillRequire){let path=(0,import_node_path2.join)(process.cwd(),outDir,main),head=[`
|
|
5
5
|
|
|
6
6
|
;await (async()=>{`," 'use strict';"].join(`
|
package/dist/cli/build.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/cli/build.ts","../../src/cli/common.ts","../../src/cli/esbuild-plugins/plugin.ts","../../src/cli/esbuild-plugins/use-cache.ts"],"sourcesContent":["// @ts-check\n\nimport { readFile, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { build } from 'tsup';\nimport { Colors, erase, findCommandKitConfig, panic, write } from './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 entry: [src, '!dist', '!.commandkit', `!${outDir}`],\n esbuildPlugins: [commandkitPlugin()]\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\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 assert: 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}","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};\n\ninterface CommandKitEsbuildPluginConfig {\n 'use-macro'?: 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};","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};"],"mappings":"q+BAAA,4KAEA,IAAAA,iBAAoC,uBACpCC,kBAAqB,gBACrB,YAAsB,gBCFtB,kBAA2B,kBAC3B,iBAAqB,gBACrB,eAAe,uBAEf,IAAM,WAAa,UAEN,OAAS,CACpB,MAAO,OAAC,MAAiB,GAAG,IAAI,GAAG,UAAU,GAAtC,SACP,OAAQ,OAAC,MAAiB,UAAU,IAAI,GAAG,UAAU,GAA7C,UACR,IAAK,OAAC,MAAiB,UAAU,IAAI,GAAG,UAAU,GAA7C,OACL,WAAY,OAAC,MAAiB,UAAU,IAAI,GAAG,UAAU,GAA7C,cACZ,MAAO,OAAC,MAAiB,UAAU,IAAI,GAAG,UAAU,GAA7C,SACP,QAAS,OAAC,MAAiB,UAAU,IAAI,GAAG,UAAU,GAA7C,WACT,OAAQ,OAAC,MAAiB,UAAU,IAAI,GAAG,UAAU,GAA7C,UAER,MAAO,OAAC,MAAiB,WAAW,IAAI,GAAG,UAAU,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,CAAC,CACrC,CAAC,EAED,MAAM,YAAY,OAAQ,KAAM,UAAW,eAAe,EAE1D,OAAO,QACL,OAAO,MACL,uBAAuB,YAAY,IAAI,EAAI,OAAO,QAAQ,CAAC,CAAC,KAC9D,CACF,EACA,MACE,OAAO,MACL;AAAA,MAAS,OAAO,QAAQ,kBAAkB,CAAC,IAAI,OAAO,MACpD,oBACF,CAAC,EACH,CACF,CACF,OAAS,EAAG,CACV,OAAO,KACL,uBAAuB,YAAY,IAAI,EAAI,OAAO,QAAQ,CAAC,CAAC,KAC9D,EACA,MAAM,CAAC,CACT,CACF,CAzDsB,4DA2DtB,eAAsB,YACtB,OACA,KACA,UACA,gBACA,CACE,IAAM,QAAO,wBAAK,QAAQ,IAAI,EAAG,OAAQ,IAAI,EAEvC,KAAO,CAAC;AAAA;AAAA,oBAA0B,iBAAiB,EAAE,KAAK;AAAA,CAAI,EAC9D,KAAO;AAAA,OACP,cAAgB,gBACtB,CACA,2CACA,0CACA,6DACA,wDACA,qDACA,yBACA,gCACA,WACA,4BACA,2BACA,wBACA,UACA,MACA,0CAA0C,EAC1C,KAAK;AAAA,CAAI,EACT,GAEM,gBAAkB,UACxB,CACA,2CACA,wHACA,2DACA,mFACA,2JACA,6EACA,8BACA,mEACA,SACA,6EACA,8BACA,gFACA,UACA,0CAA0C,EAC1C,KAAK;AAAA,CAAI,EACT,GAEM,SAAW,QAAM,2BAAS,KAAM,OAAO,EACvC,YAAc,CACpB,KACA,cACA,gBACA,KACA;AAAA;AAAA,EACA,QAAQ,EACR,KAAK;AAAA,CAAI,EAET,SAAO,4BAAU,KAAM,WAAW,CACpC,CA3DsB","names":["import_promises","import_node_path","fs","_traverse","_generate","build","ora"]}
|
|
1
|
+
{"version":3,"sources":["../../src/cli/build.ts","../../src/cli/common.ts","../../src/cli/esbuild-plugins/plugin.ts","../../src/cli/esbuild-plugins/use-cache.ts"],"sourcesContent":["// @ts-check\n\nimport { readFile, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { build } from 'tsup';\nimport { Colors, erase, findCommandKitConfig, panic, write } from './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 entry: [src, '!dist', '!.commandkit', `!${outDir}`],\n esbuildPlugins: [commandkitPlugin()],\n jsxFactory: 'CommandKit.createElement',\n jsxFragment: 'CommandKit.Fragment'\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\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 assert: 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}","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};","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(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KAAO;AAAA,OACP,cAAgB,gBACtB,CACA,2CACA,0CACA,6DACA,wDACA,qDACA,yBACA,gCACA,WACA,4BACA,2BACA,wBACA,UACA,MACA,0CAA0C,EAC1C,KAAK;AAAA,CAAI,EACT,GAEM,gBAAkB,UACxB,CACA,2CACA,wHACA,2DACA,mFACA,2JACA,6EACA,8BACA,mEACA,SACA,6EACA,8BACA,gFACA,UACA,0CAA0C,EAC1C,KAAK;AAAA,CAAI,EACT,GAEM,SAAW,QAAM,2BAAS,KAAM,OAAO,EACvC,YAAc,CACpB,KACA,cACA,gBACA,KACA;AAAA;AAAA,EACA,QAAQ,EACR,KAAK;AAAA,CAAI,EAET,SAAO,4BAAU,KAAM,WAAW,CACpC,CA3DsB","names":["import_promises","import_node_path","fs","_traverse","_generate","build","ora"]}
|
package/dist/cli/build.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{bootstrapProductionBuild,injectShims}from"../chunk-
|
|
1
|
+
import{bootstrapProductionBuild,injectShims}from"../chunk-P7PNFSAC.mjs";import"../chunk-HFOCTXRX.mjs";import"../chunk-Y522NY4J.mjs";import"../chunk-FC5WQLBI.mjs";import"../chunk-35OSBS47.mjs";export{bootstrapProductionBuild,injectShims};
|
|
2
2
|
//# sourceMappingURL=build.mjs.map
|
package/dist/cli/development.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
"use strict";var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty;var __name=(target,value)=>__defProp(target,"name",{value,configurable:!0});var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target,mod)),__toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod);var development_exports={};__export(development_exports,{bootstrapDevelopmentServer:()=>bootstrapDevelopmentServer});module.exports=__toCommonJS(development_exports);var import_dotenv=require("dotenv"),import_node_path3=require("path"),import_tsup2=require("tsup");var import_rimraf=require("rimraf"),import_node_path=require("path"),import_node_fs=__toESM(require("fs"));var resetColor="\x1B[0m",Colors={reset:__name(text=>`${text}${resetColor}`,"reset"),bright:__name(text=>`\x1B[1m${text}${resetColor}`,"bright"),dim:__name(text=>`\x1B[2m${text}${resetColor}`,"dim"),underscore:__name(text=>`\x1B[4m${text}${resetColor}`,"underscore"),blink:__name(text=>`\x1B[5m${text}${resetColor}`,"blink"),reverse:__name(text=>`\x1B[7m${text}${resetColor}`,"reverse"),hidden:__name(text=>`\x1B[8m${text}${resetColor}`,"hidden"),black:__name(text=>`\x1B[30m${text}${resetColor}`,"black"),red:__name(text=>`\x1B[31m${text}${resetColor}`,"red"),green:__name(text=>`\x1B[32m${text}${resetColor}`,"green"),yellow:__name(text=>`\x1B[33m${text}${resetColor}`,"yellow"),blue:__name(text=>`\x1B[34m${text}${resetColor}`,"blue"),magenta:__name(text=>`\x1B[35m${text}${resetColor}`,"magenta"),cyan:__name(text=>`\x1B[36m${text}${resetColor}`,"cyan"),white:__name(text=>`\x1B[37m${text}${resetColor}`,"white"),bgBlack:__name(text=>`\x1B[40m${text}${resetColor}`,"bgBlack"),bgRed:__name(text=>`\x1B[41m${text}${resetColor}`,"bgRed"),bgGreen:__name(text=>`\x1B[42m${text}${resetColor}`,"bgGreen"),bgYellow:__name(text=>`\x1B[43m${text}${resetColor}`,"bgYellow"),bgBlue:__name(text=>`\x1B[44m${text}${resetColor}`,"bgBlue"),bgMagenta:__name(text=>`\x1B[45m${text}${resetColor}`,"bgMagenta"),bgCyan:__name(text=>`\x1B[46m${text}${resetColor}`,"bgCyan"),bgWhite:__name(text=>`\x1B[47m${text}${resetColor}`,"bgWhite")};function write(message){process.stdout.write(message),process.stdout.write(`
|
|
2
|
-
`)}__name(write,"write");function panic(message){write(Colors.red(`Error: ${message}`)),process.exit(1)}__name(panic,"panic");var possibleFileNames=["commandkit.json","commandkit.config.json","commandkit.js","commandkit.config.js","commandkit.mjs","commandkit.config.mjs","commandkit.cjs","commandkit.config.cjs","commandkit.ts","commandkit.mts","commandkit.cts"];async function findCommandKitConfig(src){let cwd=process.cwd(),locations=src?[(0,import_node_path.join)(cwd,src)]:possibleFileNames.map(name=>(0,import_node_path.join)(cwd,name));for(let location of locations)try{return await loadConfigInner(location)}catch{continue}panic(`Could not locate commandkit config from ${cwd}`)}__name(findCommandKitConfig,"findCommandKitConfig");function ensureTypeScript(target){/\.(c|m)tsx?$/.test(target)&&!process.features.typescript&&panic("You are trying to load commandkit config file that is written in typescript. The current Node.js version does not have TypeScript feature enabled.")}__name(ensureTypeScript,"ensureTypeScript");async function loadConfigInner(target){let isJSON=target.endsWith(".json");return await ensureExists(target),ensureTypeScript(target),await import(`file://${target}`).then(conf=>conf.default||conf)}__name(loadConfigInner,"loadConfigInner");async function ensureExists(loc){await import_node_fs.default.promises.access(loc,import_node_fs.default.constants.F_OK)}__name(ensureExists,"ensureExists");function erase(dir){(0,import_rimraf.rimrafSync)(dir)}__name(erase,"erase");var import_node_crypto=require("crypto");var valuesMap={true:!0,false:!1,null:null,undefined:void 0,__UUIDv4__:__name(()=>(0,import_node_crypto.randomUUID)(),"__UUIDv4__")},VALUE_PREFIXES={JSON:"JSON::",DATE:"DATE::"};function catcher(fn){try{return fn(),!0}catch{return!1}}__name(catcher,"catcher");function parseEnv(src){for(let key in src){let value=src[key];if(typeof value=="string"){if(value.startsWith(VALUE_PREFIXES.JSON)){catcher(()=>src[key]=JSON.parse(value.replace(VALUE_PREFIXES.JSON,"")));continue}if(value.startsWith(VALUE_PREFIXES.DATE)){src[key]=new Date(value.replace(VALUE_PREFIXES.DATE,""));continue}if(value.includes(",")){src[key]=value.split(",").map(v=>v.trim());continue}if(/^[0-9]+n$/.test(value)){src[key]=BigInt(value);continue}if(value in valuesMap){src[key]=typeof valuesMap[value]=="function"?valuesMap[value]():valuesMap[value];continue}}}return src}__name(parseEnv,"parseEnv");var import_node_child_process=__toESM(require("child_process")),import_ora2=__toESM(require("ora"));var import_promises2=require("fs/promises"),import_node_path2=require("path"),import_tsup=require("tsup");var import_ora=__toESM(require("ora"));var import_use_macro=require("use-macro");var parser=__toESM(require("@babel/parser")),import_traverse=__toESM(require("@babel/traverse")),import_generator=__toESM(require("@babel/generator")),t=__toESM(require("@babel/types"));var traverse=import_traverse.default.default||import_traverse.default,generate=import_generator.default.default||import_generator.default,IMPORT_PATH="commandkit",DIRECTIVE="use cache",CACHE_IDENTIFIER="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",generateRandomString=__name((length=6)=>{let chars="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";return Array.from({length},()=>chars[Math.floor(Math.random()*chars.length)]).join("")},"generateRandomString"),cacheDirectivePlugin=__name(async(source,args)=>{let ast=parser.parse(source,{sourceType:"module",plugins:["typescript","jsx"]}),state={needsImport:!1,hasExistingImport:!1,cacheIdentifierName:CACHE_IDENTIFIER,modifications:[]};traverse(ast,{Program:{enter(path){path.scope.getBinding(CACHE_IDENTIFIER)&&(state.cacheIdentifierName=`${CACHE_IDENTIFIER}_${generateRandomString()}`)}},ImportDeclaration(path){path.node.source.value===IMPORT_PATH&&path.node.specifiers.some(spec=>t.isImportSpecifier(spec)&&spec.imported.name===CACHE_IDENTIFIER)&&(state.hasExistingImport=!0,state.cacheIdentifierName!==CACHE_IDENTIFIER&&state.modifications.push(()=>{path.node.specifiers.forEach(spec=>{t.isImportSpecifier(spec)&&spec.imported.name===CACHE_IDENTIFIER&&(spec.local.name=state.cacheIdentifierName)})}))},"FunctionDeclaration|FunctionExpression|ArrowFunctionExpression"(path){var _a,_b,_c;let body=t.isBlockStatement(path.node.body)?path.node.body:null,hasUseCache=(_a=body==null?void 0:body.directives)==null?void 0:_a.some(d=>d.value.value===DIRECTIVE);if(!hasUseCache&&!t.isBlockStatement(path.node.body)){let parentFunction=path.findParent(p=>(p.isFunction()||p.isProgram())&&"directives"in p.node);if(!((_b=parentFunction==null?void 0:parentFunction.node.directives)!=null&&_b.some(d=>d.value.value===DIRECTIVE)))return}if(hasUseCache||!t.isBlockStatement(path.node.body)){if(!path.node.async)throw new Error(`"${DIRECTIVE}" directive may only be used in async functions at ${args.path}`);state.needsImport=!0;let name=t.isFunctionDeclaration(path.node)?(_c=path.node.id)==null?void 0:_c.name:void 0,newBody=t.isBlockStatement(path.node.body)?t.blockStatement(path.node.body.body,path.node.body.directives.filter(d=>d.value.value!==DIRECTIVE)):path.node.body,wrapped=t.callExpression(t.identifier(state.cacheIdentifierName),[t.arrowFunctionExpression(path.node.params,newBody,!0)]);state.modifications.push(()=>{name?path.replaceWith(t.variableDeclaration("const",[t.variableDeclarator(t.identifier(name),wrapped)])):t.isVariableDeclarator(path.parent)?path.parent.init=wrapped:path.replaceWith(wrapped)})}}}),state.modifications.length>0&&(state.needsImport&&!state.hasExistingImport&&ast.program.body.unshift(t.importDeclaration([t.importSpecifier(t.identifier(state.cacheIdentifierName),t.identifier(CACHE_IDENTIFIER))],t.stringLiteral(IMPORT_PATH))),state.modifications.forEach(modify=>modify()));let{code}=generate(ast);return{contents:code,loader:args.path.split(".").pop()}},"cacheDirectivePlugin");var import_promises=require("fs/promises");var defaultConfig={"use-macro":!0,"use-cache":!0},commandkitPlugin=__name(config=>{config=Object.assign({},defaultConfig,config);let plugins=[{name:"use-macro",plugin:__name(async(content,args)=>{let transformer=new import_use_macro.MacroTransformer,{contents}=await transformer.transform(content,args.path);return contents},"plugin")},{name:"use-cache",plugin:__name(async(content,args)=>{let{contents}=await cacheDirectivePlugin(content,args);return contents},"plugin")}].filter(p=>!!config[p.name]);return{name:"commandkit-transformer-plugin",setup(build3){if(!plugins.length)return;let fileFilter=/\.(c|m)?(t|j)sx?$/;build3.onLoad({filter:fileFilter},async args=>{let source=await(0,import_promises.readFile)(args.path,"utf8"),loader=args.path.split(".").pop(),contents=source;for(let _plugin of plugins){let{plugin,name}=_plugin;try{contents=await plugin(contents,args)}catch(e){let err=new Error(`Plugin ${name} failed with ${e}`);throw err.stack=e instanceof Error?e.stack:"",err}}return{contents,loader}})}}},"commandkitPlugin");async function injectShims(outDir,main,antiCrash,polyfillRequire){let path=(0,import_node_path2.join)(process.cwd(),outDir,main),head=[`
|
|
2
|
+
`)}__name(write,"write");function panic(message){write(Colors.red(`Error: ${message}`)),process.exit(1)}__name(panic,"panic");var possibleFileNames=["commandkit.json","commandkit.config.json","commandkit.js","commandkit.config.js","commandkit.mjs","commandkit.config.mjs","commandkit.cjs","commandkit.config.cjs","commandkit.ts","commandkit.mts","commandkit.cts"];async function findCommandKitConfig(src){let cwd=process.cwd(),locations=src?[(0,import_node_path.join)(cwd,src)]:possibleFileNames.map(name=>(0,import_node_path.join)(cwd,name));for(let location of locations)try{return await loadConfigInner(location)}catch{continue}panic(`Could not locate commandkit config from ${cwd}`)}__name(findCommandKitConfig,"findCommandKitConfig");function ensureTypeScript(target){/\.(c|m)tsx?$/.test(target)&&!process.features.typescript&&panic("You are trying to load commandkit config file that is written in typescript. The current Node.js version does not have TypeScript feature enabled.")}__name(ensureTypeScript,"ensureTypeScript");async function loadConfigInner(target){let isJSON=target.endsWith(".json");return await ensureExists(target),ensureTypeScript(target),await import(`file://${target}`).then(conf=>conf.default||conf)}__name(loadConfigInner,"loadConfigInner");async function ensureExists(loc){await import_node_fs.default.promises.access(loc,import_node_fs.default.constants.F_OK)}__name(ensureExists,"ensureExists");function erase(dir){(0,import_rimraf.rimrafSync)(dir)}__name(erase,"erase");var import_node_crypto=require("crypto");var valuesMap={true:!0,false:!1,null:null,undefined:void 0,__UUIDv4__:__name(()=>(0,import_node_crypto.randomUUID)(),"__UUIDv4__")},VALUE_PREFIXES={JSON:"JSON::",DATE:"DATE::"};function catcher(fn){try{return fn(),!0}catch{return!1}}__name(catcher,"catcher");function parseEnv(src){for(let key in src){let value=src[key];if(typeof value=="string"){if(value.startsWith(VALUE_PREFIXES.JSON)){catcher(()=>src[key]=JSON.parse(value.replace(VALUE_PREFIXES.JSON,"")));continue}if(value.startsWith(VALUE_PREFIXES.DATE)){src[key]=new Date(value.replace(VALUE_PREFIXES.DATE,""));continue}if(value.includes(",")){src[key]=value.split(",").map(v=>v.trim());continue}if(/^[0-9]+n$/.test(value)){src[key]=BigInt(value);continue}if(value in valuesMap){src[key]=typeof valuesMap[value]=="function"?valuesMap[value]():valuesMap[value];continue}}}return src}__name(parseEnv,"parseEnv");var import_node_child_process=__toESM(require("child_process")),import_ora2=__toESM(require("ora"));var import_promises2=require("fs/promises"),import_node_path2=require("path"),import_tsup=require("tsup");var import_ora=__toESM(require("ora"));var import_use_macro=require("use-macro");var parser=__toESM(require("@babel/parser")),import_traverse=__toESM(require("@babel/traverse")),import_generator=__toESM(require("@babel/generator")),t=__toESM(require("@babel/types"));var traverse=import_traverse.default.default||import_traverse.default,generate=import_generator.default.default||import_generator.default,IMPORT_PATH="commandkit",DIRECTIVE="use cache",CACHE_IDENTIFIER="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",generateRandomString=__name((length=6)=>{let chars="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";return Array.from({length},()=>chars[Math.floor(Math.random()*chars.length)]).join("")},"generateRandomString"),cacheDirectivePlugin=__name(async(source,args)=>{let ast=parser.parse(source,{sourceType:"module",plugins:["typescript","jsx"]}),state={needsImport:!1,hasExistingImport:!1,cacheIdentifierName:CACHE_IDENTIFIER,modifications:[]};traverse(ast,{Program:{enter(path){path.scope.getBinding(CACHE_IDENTIFIER)&&(state.cacheIdentifierName=`${CACHE_IDENTIFIER}_${generateRandomString()}`)}},ImportDeclaration(path){path.node.source.value===IMPORT_PATH&&path.node.specifiers.some(spec=>t.isImportSpecifier(spec)&&spec.imported.name===CACHE_IDENTIFIER)&&(state.hasExistingImport=!0,state.cacheIdentifierName!==CACHE_IDENTIFIER&&state.modifications.push(()=>{path.node.specifiers.forEach(spec=>{t.isImportSpecifier(spec)&&spec.imported.name===CACHE_IDENTIFIER&&(spec.local.name=state.cacheIdentifierName)})}))},"FunctionDeclaration|FunctionExpression|ArrowFunctionExpression"(path){var _a,_b,_c;let body=t.isBlockStatement(path.node.body)?path.node.body:null,hasUseCache=(_a=body==null?void 0:body.directives)==null?void 0:_a.some(d=>d.value.value===DIRECTIVE);if(!hasUseCache&&!t.isBlockStatement(path.node.body)){let parentFunction=path.findParent(p=>(p.isFunction()||p.isProgram())&&"directives"in p.node);if(!((_b=parentFunction==null?void 0:parentFunction.node.directives)!=null&&_b.some(d=>d.value.value===DIRECTIVE)))return}if(hasUseCache||!t.isBlockStatement(path.node.body)){if(!path.node.async)throw new Error(`"${DIRECTIVE}" directive may only be used in async functions at ${args.path}`);state.needsImport=!0;let name=t.isFunctionDeclaration(path.node)?(_c=path.node.id)==null?void 0:_c.name:void 0,newBody=t.isBlockStatement(path.node.body)?t.blockStatement(path.node.body.body,path.node.body.directives.filter(d=>d.value.value!==DIRECTIVE)):path.node.body,wrapped=t.callExpression(t.identifier(state.cacheIdentifierName),[t.arrowFunctionExpression(path.node.params,newBody,!0)]);state.modifications.push(()=>{name?path.replaceWith(t.variableDeclaration("const",[t.variableDeclarator(t.identifier(name),wrapped)])):t.isVariableDeclarator(path.parent)?path.parent.init=wrapped:path.replaceWith(wrapped)})}}}),state.modifications.length>0&&(state.needsImport&&!state.hasExistingImport&&ast.program.body.unshift(t.importDeclaration([t.importSpecifier(t.identifier(state.cacheIdentifierName),t.identifier(CACHE_IDENTIFIER))],t.stringLiteral(IMPORT_PATH))),state.modifications.forEach(modify=>modify()));let{code}=generate(ast);return{contents:code,loader:args.path.split(".").pop()}},"cacheDirectivePlugin");var import_promises=require("fs/promises");var defaultConfig={"use-macro":!0,"use-cache":!0,"jsx-importsource":!0},commandkitPlugin=__name(config=>{config=Object.assign({},defaultConfig,config);let plugins=[{name:"use-macro",plugin:__name(async(content,args)=>{let transformer=new import_use_macro.MacroTransformer,{contents}=await transformer.transform(content,args.path);return contents},"plugin")},{name:"use-cache",plugin:__name(async(content,args)=>{let{contents}=await cacheDirectivePlugin(content,args);return contents},"plugin")}].filter(p=>!!config[p.name]);return{name:"commandkit-transformer-plugin",setup(build3){if(!plugins.length)return;let fileFilter=/\.(c|m)?(t|j)sx?$/;build3.onLoad({filter:fileFilter},async args=>{let source=await(0,import_promises.readFile)(args.path,"utf8"),loader=args.path.split(".").pop(),contents=source;for(let _plugin of plugins){let{plugin,name}=_plugin;try{contents=await plugin(contents,args)}catch(e){let err=new Error(`Plugin ${name} failed with ${e}`);throw err.stack=e instanceof Error?e.stack:"",err}}return{contents,loader}})}}},"commandkitPlugin");async function injectShims(outDir,main,antiCrash,polyfillRequire){let path=(0,import_node_path2.join)(process.cwd(),outDir,main),head=[`
|
|
3
3
|
|
|
4
4
|
;await (async()=>{`," 'use strict';"].join(`
|
|
5
5
|
`),tail=`
|
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
|
|
10
10
|
`,contents].join(`
|
|
11
11
|
`);return(0,import_promises2.writeFile)(path,finalScript)}__name(injectShims,"injectShims");var RESTARTING_MSG_PATTERN=/^Restarting '|".+'|"\n?$/,FAILED_RUNNING_PATTERN=/^Failed running '.+'|"\n?$/;async function bootstrapDevelopmentServer(opts){let{src,main,watch=!!opts.noWatch,nodeOptions=[],envExtra=!0,clearRestartLogs=!0,outDir,requirePolyfill}=await findCommandKitConfig(opts.config);src||panic("Could not find src in commandkit.json"),main||panic("Could not find main in commandkit.json");let watchMode=watch,status=(0,import_ora2.default)(Colors.green(`Starting a development server...
|
|
12
|
-
`)).start(),start=performance.now();watchMode&&!nodeOptions.includes("--watch")?nodeOptions.push("--watch"):!watchMode&&nodeOptions.includes("--watch")&&nodeOptions.splice(nodeOptions.indexOf("--watch"),1),nodeOptions.includes("--enable-source-maps")||nodeOptions.push("--enable-source-maps"),erase(".commandkit");try{await(0,import_tsup2.build)({clean:!0,format:["esm"],dts:!1,skipNodeModulesBundle:!0,minify:!1,shims:!0,sourcemap:"inline",keepNames:!0,outDir:".commandkit",silent:!0,entry:[src,"!dist","!.commandkit",`!${outDir}`].filter(Boolean),watch:watchMode,cjsInterop:!0,async onSuccess(){return await injectShims(".commandkit",main,!1,requirePolyfill)},esbuildPlugins:[commandkitPlugin({"use-macro":!1})]}),status.succeed(Colors.green(`Dev server started in ${(performance.now()-start).toFixed(2)}ms!
|
|
12
|
+
`)).start(),start=performance.now();watchMode&&!nodeOptions.includes("--watch")?nodeOptions.push("--watch"):!watchMode&&nodeOptions.includes("--watch")&&nodeOptions.splice(nodeOptions.indexOf("--watch"),1),nodeOptions.includes("--enable-source-maps")||nodeOptions.push("--enable-source-maps"),erase(".commandkit");try{await(0,import_tsup2.build)({clean:!0,format:["esm"],dts:!1,skipNodeModulesBundle:!0,minify:!1,shims:!0,sourcemap:"inline",keepNames:!0,outDir:".commandkit",silent:!0,entry:[src,"!dist","!.commandkit",`!${outDir}`].filter(Boolean),watch:watchMode,cjsInterop:!0,jsxFactory:"CommandKit.createElement",jsxFragment:"CommandKit.Fragment",async onSuccess(){return await injectShims(".commandkit",main,!1,requirePolyfill)},esbuildPlugins:[commandkitPlugin({"use-macro":!1})]}),status.succeed(Colors.green(`Dev server started in ${(performance.now()-start).toFixed(2)}ms!
|
|
13
13
|
`)),watchMode&&write(Colors.cyan(`Watching for file changes...
|
|
14
14
|
`));let processEnv={},env=(0,import_dotenv.config)({path:(0,import_node_path3.join)(process.cwd(),".env"),processEnv});envExtra&&parseEnv(processEnv),env.error&&write(Colors.yellow(`[DOTENV] Warning: ${env.error.message}`)),env.parsed&&write(Colors.blue("[DOTENV] Loaded .env file!"));let ps=import_node_child_process.default.spawn("node",[...nodeOptions,(0,import_node_path3.join)(process.cwd(),".commandkit",main)],{env:{...process.env,...processEnv,NODE_ENV:"development",COMMANDKIT_DEV:!0,COMMANDKIT_PRODUCTION:!1},cwd:process.cwd()}),isLastLogRestarting=!1,hasStarted=!1;ps.stdout.on("data",data=>{let message=data.toString();if(FAILED_RUNNING_PATTERN.test(message)){write(Colors.cyan("Failed running the bot, waiting for changes...")),isLastLogRestarting=!1,hasStarted||(hasStarted=!0);return}if(clearRestartLogs&&!RESTARTING_MSG_PATTERN.test(message))write(message),isLastLogRestarting=!1;else{if(isLastLogRestarting||!hasStarted){hasStarted||(hasStarted=!0);return}write(Colors.cyan("\u2300 Restarting the bot...")),isLastLogRestarting=!0}hasStarted||(hasStarted=!0)}),ps.stderr.on("data",data=>{let message=data.toString();message.includes("ExperimentalWarning: Watch mode is an experimental feature and might change at any time")||write(Colors.red(message))}),ps.on("close",code=>{write(`
|
|
15
15
|
`),process.exit(code??0)}),ps.on("error",err=>{panic(err)})}catch(e){status.fail(`Error occurred after ${(performance.now()-start).toFixed(2)}ms!
|