commandkit 0.1.11-dev.20250113184412 → 0.1.11-dev.20250127160127

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.
Files changed (60) hide show
  1. package/bin/build.mjs +2 -3
  2. package/bin/development.mjs +6 -2
  3. package/bin/esbuild-plugins/plugin.mjs +74 -0
  4. package/bin/esbuild-plugins/use-cache.mjs +126 -143
  5. package/dist/CommandKit.js +1 -1
  6. package/dist/CommandKit.js.map +1 -1
  7. package/dist/CommandKit.mjs +1 -1
  8. package/dist/cache/CacheProvider.d.mts +4 -5
  9. package/dist/cache/CacheProvider.d.ts +4 -5
  10. package/dist/cache/CacheProvider.js.map +1 -1
  11. package/dist/cache/CacheProvider.mjs +1 -1
  12. package/dist/cache/MemoryCache.d.mts +2 -2
  13. package/dist/cache/MemoryCache.d.ts +2 -2
  14. package/dist/cache/MemoryCache.js +1 -1
  15. package/dist/cache/MemoryCache.js.map +1 -1
  16. package/dist/cache/MemoryCache.mjs +1 -1
  17. package/dist/cache/index.d.mts +23 -44
  18. package/dist/cache/index.d.ts +23 -44
  19. package/dist/cache/index.js +2 -2
  20. package/dist/cache/index.js.map +1 -1
  21. package/dist/cache/index.mjs +1 -1
  22. package/dist/chunk-CO2EZ53K.mjs +2 -0
  23. package/dist/chunk-CO2EZ53K.mjs.map +1 -0
  24. package/dist/chunk-GIQCBDID.mjs +2 -0
  25. package/dist/chunk-GIQCBDID.mjs.map +1 -0
  26. package/dist/chunk-JJTJBXV2.mjs +2 -0
  27. package/dist/chunk-JJTJBXV2.mjs.map +1 -0
  28. package/dist/{chunk-3TRGTPDU.mjs → chunk-NRRM7DKC.mjs} +2 -2
  29. package/dist/{chunk-3TRGTPDU.mjs.map → chunk-NRRM7DKC.mjs.map} +1 -1
  30. package/dist/{chunk-47FOQCN7.mjs → chunk-UPJYI5Q6.mjs} +1 -1
  31. package/dist/chunk-UPJYI5Q6.mjs.map +1 -0
  32. package/dist/context/async-context.js +1 -1
  33. package/dist/context/async-context.js.map +1 -1
  34. package/dist/context/async-context.mjs +1 -1
  35. package/dist/context/environment.mjs +1 -1
  36. package/dist/handlers/command-handler/CommandHandler.js +1 -1
  37. package/dist/handlers/command-handler/CommandHandler.js.map +1 -1
  38. package/dist/handlers/command-handler/CommandHandler.mjs +1 -1
  39. package/dist/handlers/index.js +1 -1
  40. package/dist/handlers/index.js.map +1 -1
  41. package/dist/handlers/index.mjs +1 -1
  42. package/dist/index.d.mts +2 -3
  43. package/dist/index.d.ts +2 -3
  44. package/dist/index.js +2 -2
  45. package/dist/index.js.map +1 -1
  46. package/dist/index.mjs +1 -1
  47. package/dist/index.mjs.map +1 -1
  48. package/dist/utils/warn-unstable.d.mts +2 -1
  49. package/dist/utils/warn-unstable.d.ts +2 -1
  50. package/dist/utils/warn-unstable.js +1 -1
  51. package/dist/utils/warn-unstable.js.map +1 -1
  52. package/dist/utils/warn-unstable.mjs +1 -1
  53. package/package.json +2 -2
  54. package/dist/chunk-47FOQCN7.mjs.map +0 -1
  55. package/dist/chunk-GSYRGHXQ.mjs +0 -2
  56. package/dist/chunk-GSYRGHXQ.mjs.map +0 -1
  57. package/dist/chunk-MVPNDXHU.mjs +0 -2
  58. package/dist/chunk-MVPNDXHU.mjs.map +0 -1
  59. package/dist/chunk-YLJX7MMA.mjs +0 -2
  60. package/dist/chunk-YLJX7MMA.mjs.map +0 -1
package/bin/build.mjs CHANGED
@@ -11,8 +11,7 @@ import {
11
11
  write,
12
12
  } from './common.mjs';
13
13
  import ora from 'ora';
14
- import { esbuildPluginUseMacro } from 'use-macro';
15
- import { cacheDirectivePlugin } from './esbuild-plugins/use-cache.mjs';
14
+ import { commandkitPlugin } from './esbuild-plugins/plugin.mjs';
16
15
 
17
16
  export async function bootstrapProductionBuild(config) {
18
17
  const {
@@ -48,7 +47,7 @@ export async function bootstrapProductionBuild(config) {
48
47
  watch: false,
49
48
  cjsInterop: true,
50
49
  entry: [src, '!dist', '!.commandkit', `!${outDir}`],
51
- esbuildPlugins: [cacheDirectivePlugin()],
50
+ esbuildPlugins: [commandkitPlugin()],
52
51
  });
53
52
 
54
53
  await injectShims(outDir, main, antiCrash, polyfillRequire);
@@ -13,7 +13,7 @@ import { parseEnv } from './parse-env.mjs';
13
13
  import child_process from 'node:child_process';
14
14
  import ora from 'ora';
15
15
  import { injectShims } from './build.mjs';
16
- import { cacheDirectivePlugin } from './esbuild-plugins/use-cache.mjs';
16
+ import { commandkitPlugin } from './esbuild-plugins/plugin.mjs';
17
17
 
18
18
  const RESTARTING_MSG_PATTERN = /^Restarting '|".+'|"\n?$/;
19
19
  const FAILED_RUNNING_PATTERN = /^Failed running '.+'|"\n?$/;
@@ -74,7 +74,11 @@ export async function bootstrapDevelopmentServer(opts) {
74
74
  async onSuccess() {
75
75
  return await injectShims('.commandkit', main, false, requirePolyfill);
76
76
  },
77
- esbuildPlugins: [cacheDirectivePlugin()],
77
+ esbuildPlugins: [
78
+ commandkitPlugin({
79
+ 'use-macro': false,
80
+ }),
81
+ ],
78
82
  });
79
83
 
80
84
  status.succeed(
@@ -0,0 +1,74 @@
1
+ import { MacroTransformer } from 'use-macro';
2
+ import { cacheDirectivePlugin } from './use-cache.mjs';
3
+ import { readFile } from 'node:fs/promises';
4
+
5
+ const defaultConfig = {
6
+ 'use-macro': true,
7
+ 'use-cache': true,
8
+ };
9
+
10
+ /**
11
+ * @typedef {Object} CommandKitEsbuildPluginConfig
12
+ * @property {boolean} [use-macro]
13
+ * @property {boolean} [use-cache]
14
+ */
15
+
16
+ /**
17
+ * @param {CommandKitEsbuildPluginConfig} [config]
18
+ */
19
+ export const commandkitPlugin = (config) => {
20
+ config = Object.assign({}, defaultConfig, config);
21
+
22
+ const plugins = [
23
+ {
24
+ name: 'use-macro',
25
+ plugin: async (content, args) => {
26
+ const transformer = new MacroTransformer();
27
+ const { contents } = await transformer.transform(content, args.path);
28
+ return contents;
29
+ },
30
+ },
31
+ {
32
+ name: 'use-cache',
33
+ plugin: async (content, args) => {
34
+ const { contents } = await cacheDirectivePlugin(content, args);
35
+ return contents;
36
+ },
37
+ },
38
+ ].filter((p) => {
39
+ return !!config[p.name];
40
+ });
41
+
42
+ return {
43
+ name: 'commandkit-transformer-plugin',
44
+ setup(build) {
45
+ if (!plugins.length) return;
46
+
47
+ const fileFilter = /\.(c|m)?(t|j)sx?$/;
48
+
49
+ build.onLoad({ filter: fileFilter }, async (args) => {
50
+ const source = await readFile(args.path, 'utf8');
51
+ const loader = args.path.split('.').pop();
52
+
53
+ let contents = source;
54
+
55
+ for (const _plugin of plugins) {
56
+ const { plugin, name } = _plugin;
57
+ try {
58
+ contents = await plugin(contents, args);
59
+ } catch (e) {
60
+ const err = new Error(`Plugin ${name} failed with ${e}`);
61
+ err.stack = e.stack;
62
+
63
+ throw err;
64
+ }
65
+ }
66
+
67
+ return {
68
+ contents,
69
+ loader,
70
+ };
71
+ });
72
+ },
73
+ };
74
+ };
@@ -19,159 +19,142 @@ const generateRandomString = (length = 6) => {
19
19
  ).join('');
20
20
  };
21
21
 
22
- export const cacheDirectivePlugin = () => {
23
- return {
24
- name: 'cache-directive',
25
- setup(build) {
26
- const fileFilter = /\.(c|m)?(t|j)sx?$/;
27
-
28
- build.onLoad({ filter: fileFilter }, async (args) => {
29
- const { readFile } = await import('fs/promises');
30
- const source = await readFile(args.path, 'utf8');
31
-
32
- const ast = parser.parse(source, {
33
- sourceType: 'module',
34
- plugins: ['typescript', 'jsx'],
35
- });
22
+ export const cacheDirectivePlugin = async (source, args) => {
23
+ const ast = parser.parse(source, {
24
+ sourceType: 'module',
25
+ plugins: ['typescript', 'jsx'],
26
+ });
27
+
28
+ let state = {
29
+ needsImport: false,
30
+ hasExistingImport: false,
31
+ cacheIdentifierName: CACHE_IDENTIFIER,
32
+ modifications: [],
33
+ };
36
34
 
37
- let state = {
38
- needsImport: false,
39
- hasExistingImport: false,
40
- cacheIdentifierName: CACHE_IDENTIFIER,
41
- modifications: [],
42
- };
43
-
44
- // First pass: check for naming collisions and collect modifications
45
- traverse(ast, {
46
- Program: {
47
- enter(path) {
48
- const binding = path.scope.getBinding(CACHE_IDENTIFIER);
49
- if (binding) {
50
- state.cacheIdentifierName = `${CACHE_IDENTIFIER}_${generateRandomString()}`;
51
- }
52
- },
53
- },
54
-
55
- ImportDeclaration(path) {
56
- if (
57
- path.node.source.value === IMPORT_PATH &&
58
- path.node.specifiers.some(
59
- (spec) =>
60
- t.isImportSpecifier(spec) &&
61
- spec.imported.name === CACHE_IDENTIFIER,
62
- )
63
- ) {
64
- state.hasExistingImport = true;
65
- if (state.cacheIdentifierName !== CACHE_IDENTIFIER) {
66
- state.modifications.push(() => {
67
- path.node.specifiers.forEach((spec) => {
68
- if (
69
- t.isImportSpecifier(spec) &&
70
- spec.imported.name === CACHE_IDENTIFIER
71
- ) {
72
- spec.local.name = state.cacheIdentifierName;
73
- }
74
- });
75
- });
76
- }
77
- }
78
- },
79
-
80
- 'FunctionDeclaration|FunctionExpression|ArrowFunctionExpression'(
81
- path,
82
- ) {
83
- const body = t.isBlockStatement(path.node.body)
84
- ? path.node.body
85
- : null;
86
- const hasUseCache = body?.directives?.some(
87
- (d) => d.value.value === DIRECTIVE,
88
- );
35
+ // First pass: check for naming collisions and collect modifications
36
+ traverse(ast, {
37
+ Program: {
38
+ enter(path) {
39
+ const binding = path.scope.getBinding(CACHE_IDENTIFIER);
40
+ if (binding) {
41
+ state.cacheIdentifierName = `${CACHE_IDENTIFIER}_${generateRandomString()}`;
42
+ }
43
+ },
44
+ },
89
45
 
90
- if (!hasUseCache && !t.isBlockStatement(path.node.body)) {
91
- const parentFunction = path.findParent(
92
- (p) =>
93
- (p.isFunction() || p.isProgram()) && 'directives' in p.node,
94
- );
46
+ ImportDeclaration(path) {
47
+ if (
48
+ path.node.source.value === IMPORT_PATH &&
49
+ path.node.specifiers.some(
50
+ (spec) =>
51
+ t.isImportSpecifier(spec) &&
52
+ spec.imported.name === CACHE_IDENTIFIER,
53
+ )
54
+ ) {
55
+ state.hasExistingImport = true;
56
+ if (state.cacheIdentifierName !== CACHE_IDENTIFIER) {
57
+ state.modifications.push(() => {
58
+ path.node.specifiers.forEach((spec) => {
95
59
  if (
96
- !parentFunction?.node.directives?.some(
97
- (d) => d.value.value === DIRECTIVE,
98
- )
60
+ t.isImportSpecifier(spec) &&
61
+ spec.imported.name === CACHE_IDENTIFIER
99
62
  ) {
100
- return;
101
- }
102
- }
103
-
104
- if (hasUseCache || !t.isBlockStatement(path.node.body)) {
105
- // Check if the function is async
106
- if (!path.node.async) {
107
- throw new Error(
108
- `"${DIRECTIVE}" directive may only be used in async functions at ${args.path}`,
109
- );
63
+ spec.local.name = state.cacheIdentifierName;
110
64
  }
65
+ });
66
+ });
67
+ }
68
+ }
69
+ },
111
70
 
112
- state.needsImport = true;
113
- const isDeclaration = t.isFunctionDeclaration(path.node);
114
- const name = isDeclaration ? path.node.id?.name : undefined;
115
-
116
- // Create a new body without the 'use cache' directive
117
- const newBody = t.isBlockStatement(path.node.body)
118
- ? t.blockStatement(
119
- path.node.body.body,
120
- path.node.body.directives.filter(
121
- (d) => d.value.value !== DIRECTIVE,
122
- ),
123
- )
124
- : path.node.body;
125
-
126
- const wrapped = t.callExpression(
127
- t.identifier(state.cacheIdentifierName),
128
- [t.arrowFunctionExpression(path.node.params, newBody, true)],
129
- );
130
-
131
- state.modifications.push(() => {
132
- if (name) {
133
- path.replaceWith(
134
- t.variableDeclaration('const', [
135
- t.variableDeclarator(t.identifier(name), wrapped),
136
- ]),
137
- );
138
- } else if (!t.isVariableDeclarator(path.parent)) {
139
- path.replaceWith(wrapped);
140
- } else {
141
- path.parent.init = wrapped;
142
- }
143
- });
144
- }
145
- },
146
- });
71
+ 'FunctionDeclaration|FunctionExpression|ArrowFunctionExpression'(path) {
72
+ const body = t.isBlockStatement(path.node.body) ? path.node.body : null;
73
+ const hasUseCache = body?.directives?.some(
74
+ (d) => d.value.value === DIRECTIVE,
75
+ );
76
+
77
+ if (!hasUseCache && !t.isBlockStatement(path.node.body)) {
78
+ const parentFunction = path.findParent(
79
+ (p) => (p.isFunction() || p.isProgram()) && 'directives' in p.node,
80
+ );
81
+ if (
82
+ !parentFunction?.node.directives?.some(
83
+ (d) => d.value.value === DIRECTIVE,
84
+ )
85
+ ) {
86
+ return;
87
+ }
88
+ }
89
+
90
+ if (hasUseCache || !t.isBlockStatement(path.node.body)) {
91
+ // Check if the function is async
92
+ if (!path.node.async) {
93
+ throw new Error(
94
+ `"${DIRECTIVE}" directive may only be used in async functions at ${args.path}`,
95
+ );
96
+ }
97
+
98
+ state.needsImport = true;
99
+ const isDeclaration = t.isFunctionDeclaration(path.node);
100
+ const name = isDeclaration ? path.node.id?.name : undefined;
147
101
 
148
- // Apply all collected modifications
149
- if (state.modifications.length > 0) {
150
- // Add import if needed
151
- if (state.needsImport && !state.hasExistingImport) {
152
- ast.program.body.unshift(
153
- t.importDeclaration(
154
- [
155
- t.importSpecifier(
156
- t.identifier(state.cacheIdentifierName),
157
- t.identifier(CACHE_IDENTIFIER),
158
- ),
159
- ],
160
- t.stringLiteral(IMPORT_PATH),
102
+ // Create a new body without the 'use cache' directive
103
+ const newBody = t.isBlockStatement(path.node.body)
104
+ ? t.blockStatement(
105
+ path.node.body.body,
106
+ path.node.body.directives.filter(
107
+ (d) => d.value.value !== DIRECTIVE,
161
108
  ),
109
+ )
110
+ : path.node.body;
111
+
112
+ const wrapped = t.callExpression(
113
+ t.identifier(state.cacheIdentifierName),
114
+ [t.arrowFunctionExpression(path.node.params, newBody, true)],
115
+ );
116
+
117
+ state.modifications.push(() => {
118
+ if (name) {
119
+ path.replaceWith(
120
+ t.variableDeclaration('const', [
121
+ t.variableDeclarator(t.identifier(name), wrapped),
122
+ ]),
162
123
  );
124
+ } else if (!t.isVariableDeclarator(path.parent)) {
125
+ path.replaceWith(wrapped);
126
+ } else {
127
+ path.parent.init = wrapped;
163
128
  }
164
-
165
- // Apply collected modifications
166
- state.modifications.forEach((modify) => modify());
167
- }
168
-
169
- const { code } = generate(ast);
170
- return {
171
- contents: code,
172
- loader: args.path.split('.').pop(),
173
- };
174
- });
129
+ });
130
+ }
175
131
  },
132
+ });
133
+
134
+ // Apply all collected modifications
135
+ if (state.modifications.length > 0) {
136
+ // Add import if needed
137
+ if (state.needsImport && !state.hasExistingImport) {
138
+ ast.program.body.unshift(
139
+ t.importDeclaration(
140
+ [
141
+ t.importSpecifier(
142
+ t.identifier(state.cacheIdentifierName),
143
+ t.identifier(CACHE_IDENTIFIER),
144
+ ),
145
+ ],
146
+ t.stringLiteral(IMPORT_PATH),
147
+ ),
148
+ );
149
+ }
150
+
151
+ // Apply collected modifications
152
+ state.modifications.forEach((modify) => modify());
153
+ }
154
+
155
+ const { code } = generate(ast);
156
+ return {
157
+ contents: code,
158
+ loader: args.path.split('.').pop(),
176
159
  };
177
160
  };
@@ -7,5 +7,5 @@
7
7
  `),error)}),console.log(colors_default.green(`Edited command "${command.data.name}" in ${guildCommands.guild.name}.`));continue}targetCommand||(await guildCommands.create(command.data).catch(error=>{throw new Error(colors_default.red(`Failed to register command "${command.data.name}" in ${guildCommands.guild.name}.
8
8
  `),error)}),console.log(colors_default.green(`Registered command "${command.data.name}" in ${guildCommands.guild.name}.`)))}}__name(registerDevCommands,"registerDevCommands");function devOnly_default({interaction,targetCommand,handlerData}){if(!interaction.isAutocomplete()&&targetCommand.options?.devOnly){if(interaction.inGuild()&&!handlerData.devGuildIds.includes(interaction.guildId))return interaction.reply({content:"\u274C This command can only be used inside development servers.",ephemeral:!0}),!0;let memberRoles=interaction.guild?.members.cache.get(interaction.user.id)?.roles.cache,hasDevRole=!1;if(memberRoles?.forEach(role=>{handlerData.devRoleIds.includes(role.id)&&(hasDevRole=!0)}),!(handlerData.devUserIds.includes(interaction.user.id)||hasDevRole))return interaction.reply({content:"\u274C This command can only be used by developers.",ephemeral:!0}),!0}}__name(devOnly_default,"default");var import_discord=require("discord.js");function permissions_default({interaction,targetCommand}){if(interaction.isAutocomplete())return;let userPermissions=interaction.memberPermissions,userPermissionsRequired=targetCommand.options?.userPermissions,missingUserPermissions=[];typeof userPermissionsRequired=="string"&&(userPermissionsRequired=[userPermissionsRequired]);let botPermissions=interaction.guild?.members.me?.permissions,botPermissionsRequired=targetCommand.options?.botPermissions,missingBotPermissions=[];if(typeof botPermissionsRequired=="string"&&(botPermissionsRequired=[botPermissionsRequired]),!userPermissionsRequired?.length&&!botPermissionsRequired?.length)return;if(userPermissions&&userPermissionsRequired)for(let permission of userPermissionsRequired)userPermissions.has(permission)||missingUserPermissions.push(permission);if(botPermissions&&botPermissionsRequired)for(let permission of botPermissionsRequired)botPermissions.has(permission)||missingBotPermissions.push(permission);if(!missingUserPermissions.length&&!missingBotPermissions.length)return;let pattern=/([a-z])([A-Z])|([A-Z]+)([A-Z][a-z])/g;missingUserPermissions=missingUserPermissions.map(str=>str.replace(pattern,"$1$3 $2$4")),missingBotPermissions=missingBotPermissions.map(str=>str.replace(pattern,"$1$3 $2$4"));let embedDescription="",formatter=new Intl.ListFormat("en",{style:"long",type:"conjunction"}),getPermissionWord=__name(permissions=>permissions.length===1?"permission":"permissions","getPermissionWord");if(missingUserPermissions.length){let formattedPermissions=missingUserPermissions.map(p=>`\`${p}\``),permissionsString=formatter.format(formattedPermissions);embedDescription+=`- You must have the ${permissionsString} ${getPermissionWord(missingUserPermissions)} to be able to run this command.
9
9
  `}if(missingBotPermissions.length){let formattedPermissions=missingBotPermissions.map(p=>`\`${p}\``),permissionsString=formatter.format(formattedPermissions);embedDescription+=`- I must have the ${permissionsString} ${getPermissionWord(missingBotPermissions)} to be able to execute this command.
10
- `}let embed=new import_discord.EmbedBuilder().setTitle(":x: Missing permissions!").setDescription(embedDescription).setColor("Red");return interaction.reply({embeds:[embed],ephemeral:!0}),!0}__name(permissions_default,"default");var validations_default=[devOnly_default,permissions_default];var import_node_async_hooks=require("async_hooks");var CommandKitErrorCodes={GuildOnlyException:Symbol("kGuildOnlyException"),DMOnlyException:Symbol("kDMOnlyException")};function isCommandKitError(error){if(!(error instanceof Error))return!1;let code=Reflect.get(error,"code");for(let key in CommandKitErrorCodes)if(CommandKitErrorCodes[key]===code)return!0;return!1}__name(isCommandKitError,"isCommandKitError");var context=new import_node_async_hooks.AsyncLocalStorage;function makeContextAwareFunction(env,fn,finalizer){return __name((...args)=>context.run(env,async()=>{try{return await fn(...args)}catch(e){if(isCommandKitError(e)){let code=Reflect.get(e,"code"),interaction=env.variables.get("interaction");if(!interaction)return;switch(code){case CommandKitErrorCodes.GuildOnlyException:{interaction.isRepliable()&&await interaction.reply({content:"This command is only available in guilds.",ephemeral:!0});return}case CommandKitErrorCodes.DMOnlyException:{interaction.isRepliable()&&await interaction.reply({content:"This command is only available in DMs.",ephemeral:!0});return}}return}env.setExecutionError(e)}finally{if(typeof finalizer=="function")try{await finalizer(...args)}catch{}}}),"_fn")}__name(makeContextAwareFunction,"makeContextAwareFunction");function getContext(){return context.getStore()}__name(getContext,"getContext");function useEnvironment(){let ctx=context.getStore();if(!ctx)throw new Error("No commandkit environment found. Please make sure you are inside commandkit handler.");return ctx}__name(useEnvironment,"useEnvironment");var import_node_crypto=require("crypto");var CommandKitEnvironment=class{constructor(commandkit){this.commandkit=commandkit}static{__name(this,"CommandKitEnvironment")}#data={executionError:null,type:null,variables:new Map,deferredFunctions:new Map,marker:"",markStart:0,markEnd:0};getExecutionError(){return this.#data.executionError}setExecutionError(error){if(this.#data.executionError)throw new Error("Execution error already set.");this.#data.executionError=error}getType(){let type=this.#data.type;if(!type)throw new Error("Environment type not set.");return type}setType(type){this.#data.type=type}get variables(){return this.#data.variables}registerDeferredFunction(fn){let id=(0,import_node_crypto.randomUUID)();return this.#data.deferredFunctions.set(id,fn),id}clearDeferredFunction(id){this.#data.deferredFunctions.delete(id)}async runDeferredFunctions(){for(let[id,fn]of this.#data.deferredFunctions)try{await fn(this)}catch(e){this.commandkit.emit("unhandledDeferredFunctionRejection",e)}finally{this.clearDeferredFunction(id)}}clearAllDeferredFunctions(){this.#data.deferredFunctions.clear()}markStart(marker){this.#data.marker=marker,this.#data.markStart=performance.now()}markEnd(){this.#data.markEnd||(this.#data.markEnd=performance.now())}getMarker(){return this.#data.marker}getExecutionTime(){return Math.abs(this.#data.markEnd-this.#data.markStart)}};function after(fn){let env=getContext();if(!env)throw new Error("after must be called inside commandkit handler.");return env.registerDeferredFunction(fn)}__name(after,"after");var CommandHandler=class{static{__name(this,"CommandHandler")}#data;constructor({...options}){this.#data={...options,builtInValidations:[],commands:[]}}async init(){await this.#buildCommands(),this.#buildBuiltInValidations();let devOnlyCommands=this.#data.commands.filter(cmd=>cmd.options?.devOnly);devOnlyCommands.length&&!this.#data.devGuildIds.length&&process.emitWarning(colors_default.yellow('You have commands marked as "devOnly", but "devGuildIds" have not been set.')),devOnlyCommands.length&&!this.#data.devUserIds.length&&!this.#data.devRoleIds.length&&process.emitWarning(colors_default.yellow('You have commands marked as "devOnly", but "devUserIds" or "devRoleIds" have not been set.')),this.#data.bulkRegister?await loadCommandsWithRest({client:this.#data.client,devGuildIds:this.#data.devGuildIds,commands:this.#data.commands}):await registerCommands({client:this.#data.client,devGuildIds:this.#data.devGuildIds,commands:this.#data.commands}),this.handleCommands()}async#buildCommands(){let allowedExtensions=/\.(js|mjs|cjs|ts)$/i,commandFilePaths=(await getFilePaths(this.#data.commandsPath,!0)).filter(path3=>allowedExtensions.test(path3));for(let commandFilePath of commandFilePaths){let importedObj=await import(`${toFileURL(commandFilePath)}?t=${Date.now()}`),commandObj=clone(importedObj);typeof module<"u"&&typeof require<"u"&&delete require.cache[require.resolve(commandFilePath)];let compactFilePath=commandFilePath.split(process.cwd())[1]||commandFilePath;if(commandObj.default&&(commandObj=commandObj.default),importedObj.default?commandObj.data=importedObj.default.data:commandObj.data=importedObj.data,!commandObj.data){process.emitWarning(colors_default.yellow(`Ignoring: Command file ${compactFilePath} does not export "data".`));continue}if(!commandObj.data.name){process.emitWarning(colors_default.yellow(`Ignoring: Command file ${compactFilePath} does not export "data.name".`));continue}if(!commandObj.run){process.emitWarning(colors_default.yellow(`Ignoring: Command file ${commandObj.data.name} does not export "run".`));continue}if(typeof commandObj.run!="function"){process.emitWarning(colors_default.yellow(`Ignoring: Command file ${commandObj.data.name} does not export "run" as a function.`));continue}commandObj.filePath=commandFilePath;let commandCategory=commandFilePath.split(this.#data.commandsPath)[1]?.replace(/\\\\|\\/g,"/").split("/")[1]||null;commandCategory&&allowedExtensions.test(commandCategory)?commandObj.category=null:commandObj.category=commandCategory,this.#data.commands.push(commandObj)}}#buildBuiltInValidations(){for(let builtInValidationFunction of validations_default)this.#data.builtInValidations.push(builtInValidationFunction)}async#commandFinalizer(){let env=useEnvironment();await env.runDeferredFunctions(),env.clearAllDeferredFunctions()}async#interactionHandler(interaction){if(!interaction.isChatInputCommand()&&!interaction.isContextMenuCommand()&&!interaction.isAutocomplete())return;let isAutocomplete=interaction.isAutocomplete(),targetCommand=this.#data.commands.find(cmd=>cmd.data.name===interaction.commandName);if(!targetCommand)return;let env=useEnvironment();env.variables.set("interaction",interaction);let{data,options,run,autocomplete,...rest}=targetCommand;return isAutocomplete&&!autocomplete?void 0:__name(async()=>{let commandObj={data:targetCommand.data,options:targetCommand.options,...rest};if(this.#data.validationHandler){let canRun2=!0;for(let validationFunction of this.#data.validationHandler.validations)if(await validationFunction({interaction,commandObj,client:this.#data.client,handler:this.#data.commandkitInstance})){canRun2=!1;break}if(!canRun2)return}let canRun=!0;if(!this.#data.skipBuiltInValidations){for(let validation of this.#data.builtInValidations)if(validation({targetCommand,interaction,handlerData:this.#data})){canRun=!1;break}}if(!canRun)return;let command=targetCommand[isAutocomplete?"autocomplete":"run"],context2={interaction,client:this.#data.client,handler:this.#data.commandkitInstance};if(!this.#data.commandkitInstance.isDebuggingCommands())return command(context2);after(env2=>{let error=env2.getExecutionError(),marker=env2.getMarker(),time=`${env2.getExecutionTime().toFixed(2)}ms`,cachedMarker=!!env2.variables.get("cacheHit")?" (cached)":"";if(error){console.error(colors_default.red(`[${marker} - ${time}]${cachedMarker} Error executing command: ${error}`));return}console.log(colors_default.green(`[${marker} - ${time}]${cachedMarker} Command executed successfully`))});try{return env.markStart(interaction.commandName),await command(context2)}finally{env.markEnd()}},"executor")()}handleCommands(){this.#data.client.on("interactionCreate",interaction=>{let env=new CommandKitEnvironment(this.#data.commandkitInstance);return env.setType("COMMAND_HANDLER"),makeContextAwareFunction(env,this.#interactionHandler.bind(this),this.#commandFinalizer.bind(this))(interaction)})}get commands(){return this.#data.commands}async reloadCommands(type){if(!this.#data.commandsPath)throw new Error(colors_default.red('Cannot reload commands as "commandsPath" was not provided when instantiating CommandKit.'));this.#data.commands=[],await this.#buildCommands(),this.#data.bulkRegister?await loadCommandsWithRest({client:this.#data.client,devGuildIds:this.#data.devGuildIds,commands:this.#data.commands,reloading:!0,type}):await registerCommands({client:this.#data.client,devGuildIds:this.#data.devGuildIds,commands:this.#data.commands,reloading:!0,type})}};var EventHandler=class{static{__name(this,"EventHandler")}#data;constructor({...options}){this.#data={...options,events:[]}}async init(){await this.#buildEvents(),this.#registerEvents()}async#buildEvents(){let eventFolderPaths=await getFolderPaths(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(path3=>allowedExtensions.test(path3)),eventObj={name:eventName,functions:[]};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?.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)}}}#registerEvents(){let client=this.#data.client,handler=this.#data.commandKitInstance;for(let eventObj of this.#data.events)client.on(eventObj.name,async(...params)=>{for(let eventFunction of eventObj.functions)if(await eventFunction(...params,client,handler))break})}get events(){return this.#data.events}async reloadEvents(commandHandler){if(!this.#data.eventsPath)throw new Error(colors_default.red('Cannot reload events as "eventsPath" was not provided when instantiating CommandKit.'));this.#data.events=[],await this.#buildEvents(),this.#data.client.removeAllListeners(),this.#registerEvents(),commandHandler?.handleCommands()}};var ValidationHandler=class{static{__name(this,"ValidationHandler")}#data;constructor({...options}){this.#data={...options,validations:[]}}async init(){this.#data.validations=await this.#buildValidations()}async#buildValidations(){let allowedExtensions=/\.(js|mjs|cjs|ts)$/i,validationFilePaths=(await getFilePaths(this.#data.validationsPath,!0)).filter(path3=>allowedExtensions.test(path3)),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?.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}get validations(){return this.#data.validations}async reloadValidations(){if(!this.#data.validationsPath)throw new Error(colors_default.red('Cannot reload validations as "validationsPath" was not provided when instantiating CommandKit.'));let newValidations=await this.#buildValidations();this.#data.validations=newValidations}};var CacheProvider=class{static{__name(this,"CacheProvider")}};var MemoryCache=class extends CacheProvider{static{__name(this,"MemoryCache")}#cache=new Map;async get(key){let entry=this.#cache.get(key);if(entry){if(entry.ttl&&Date.now()>entry.ttl){this.#cache.delete(key);return}return entry.value}}async set(key,value,ttl){this.#cache.set(key,{key,value,ttl:ttl!=null?Date.now()+ttl:void 0})}async exists(key){return this.#cache.has(key)}async delete(key){this.#cache.delete(key)}async clear(){this.#cache.clear()}async expire(key,ttl){let entry=this.#cache.get(key);if(!entry)return;let _ttl=Date.now()+ttl;if(_ttl<Date.now()){this.#cache.delete(key);return}entry.ttl=_ttl}};var CommandKit=class _CommandKit extends import_node_events.default{static{__name(this,"CommandKit")}#data;static instance=void 0;constructor(options){if(_CommandKit.instance&&process.emitWarning("CommandKit instance already exists. Having multiple instance in same project is discouraged and it may lead to unexpected behavior.",{code:"MultiInstanceWarning"}),!options.client)throw new Error(colors_default.red('"client" is required when instantiating CommandKit.'));if(options.validationsPath&&!options.commandsPath)throw new Error(colors_default.red('"commandsPath" is required when "validationsPath" is set.'));super(),options.debugCommands??=process.env.NODE_ENV!=="production",options.cacheProvider!==null&&(!options.cacheProvider||!(options.cacheProvider instanceof CacheProvider))&&(options.cacheProvider=new MemoryCache),this.#data=options,this.#init().then(()=>{this.incrementClientListenersCount()}),_CommandKit.instance||(_CommandKit.instance=this)}getCacheProvider(){return this.#data.cacheProvider??null}isDebuggingCommands(){return this.#data.debugCommands||!1}get client(){return this.#data.client}get commandHandler(){return this.#data.commandHandler}async#init(){if(this.#data.eventsPath){let eventHandler=new EventHandler({client:this.#data.client,eventsPath:this.#data.eventsPath,commandKitInstance:this});await eventHandler.init(),this.#data.eventHandler=eventHandler}if(this.#data.validationsPath){let validationHandler=new ValidationHandler({validationsPath:this.#data.validationsPath});await validationHandler.init(),this.#data.validationHandler=validationHandler}if(this.#data.commandsPath){let commandHandler=new CommandHandler({client:this.#data.client,commandsPath:this.#data.commandsPath,devGuildIds:this.#data.devGuildIds||[],devUserIds:this.#data.devUserIds||[],devRoleIds:this.#data.devRoleIds||[],validationHandler:this.#data.validationHandler,skipBuiltInValidations:this.#data.skipBuiltInValidations||!1,commandkitInstance:this,bulkRegister:this.#data.bulkRegister||!1});await commandHandler.init(),this.#data.commandHandler=commandHandler}}async reloadCommands(type){this.#data.commandHandler&&await this.#data.commandHandler.reloadCommands(type)}async reloadEvents(){this.#data.eventHandler&&await this.#data.eventHandler.reloadEvents(this.#data.commandHandler)}async reloadValidations(){this.#data.validationHandler&&await this.#data.validationHandler.reloadValidations()}get commands(){return this.#data.commandHandler?this.#data.commandHandler.commands.map(cmd=>{let{run,autocomplete,...command}=cmd;return command}):[]}get commandsPath(){return this.#data.commandsPath}get eventsPath(){return this.#data.eventsPath}get validationsPath(){return this.#data.validationsPath}get devUserIds(){return this.#data.devUserIds||[]}get devGuildIds(){return this.#data.devGuildIds||[]}get devRoleIds(){return this.#data.devRoleIds||[]}incrementClientListenersCount(){this.#data.client.setMaxListeners(this.#data.client.getMaxListeners()+1)}decrementClientListenersCount(){this.#data.client.setMaxListeners(this.#data.client.getMaxListeners()-1)}};0&&(module.exports={CommandKit});
10
+ `}let embed=new import_discord.EmbedBuilder().setTitle(":x: Missing permissions!").setDescription(embedDescription).setColor("Red");return interaction.reply({embeds:[embed],ephemeral:!0}),!0}__name(permissions_default,"default");var validations_default=[devOnly_default,permissions_default];var import_node_async_hooks=require("async_hooks");var CommandKitErrorCodes={GuildOnlyException:Symbol("kGuildOnlyException"),DMOnlyException:Symbol("kDMOnlyException")};function isCommandKitError(error){if(!(error instanceof Error))return!1;let code=Reflect.get(error,"code");for(let key in CommandKitErrorCodes)if(CommandKitErrorCodes[key]===code)return!0;return!1}__name(isCommandKitError,"isCommandKitError");var context=new import_node_async_hooks.AsyncLocalStorage;function makeContextAwareFunction(env,fn,finalizer){return __name((...args)=>context.run(env,async()=>{try{return await fn(...args)}catch(e){if(isCommandKitError(e)){let code=Reflect.get(e,"code"),interaction=env.variables.get("interaction");if(!interaction)return;switch(code){case CommandKitErrorCodes.GuildOnlyException:{interaction.isRepliable()&&await interaction.reply({content:"This command is only available in guilds.",ephemeral:!0});return}case CommandKitErrorCodes.DMOnlyException:{interaction.isRepliable()&&await interaction.reply({content:"This command is only available in DMs.",ephemeral:!0});return}}return}env.setExecutionError(e)}finally{if(typeof finalizer=="function")try{await finalizer(...args)}catch{}}}),"_fn")}__name(makeContextAwareFunction,"makeContextAwareFunction");function getContext(){return context.getStore()}__name(getContext,"getContext");function useEnvironment(){let ctx=context.getStore();if(!ctx)throw new Error("No commandkit environment found. Please make sure you are inside commandkit handler.");return ctx}__name(useEnvironment,"useEnvironment");var import_node_crypto=require("crypto");var CommandKitEnvironment=class{constructor(commandkit){this.commandkit=commandkit}static{__name(this,"CommandKitEnvironment")}#data={executionError:null,type:null,variables:new Map,deferredFunctions:new Map,marker:"",markStart:0,markEnd:0};getExecutionError(){return this.#data.executionError}setExecutionError(error){if(this.#data.executionError)throw new Error("Execution error already set.");this.#data.executionError=error}getType(){let type=this.#data.type;if(!type)throw new Error("Environment type not set.");return type}setType(type){this.#data.type=type}get variables(){return this.#data.variables}registerDeferredFunction(fn){let id=(0,import_node_crypto.randomUUID)();return this.#data.deferredFunctions.set(id,fn),id}clearDeferredFunction(id){this.#data.deferredFunctions.delete(id)}async runDeferredFunctions(){for(let[id,fn]of this.#data.deferredFunctions)try{await fn(this)}catch(e){this.commandkit.emit("unhandledDeferredFunctionRejection",e)}finally{this.clearDeferredFunction(id)}}clearAllDeferredFunctions(){this.#data.deferredFunctions.clear()}markStart(marker){this.#data.marker=marker,this.#data.markStart=performance.now()}markEnd(){this.#data.markEnd||(this.#data.markEnd=performance.now())}getMarker(){return this.#data.marker}getExecutionTime(){return Math.abs(this.#data.markEnd-this.#data.markStart)}};function after(fn){let env=getContext();if(!env)throw new Error("after must be called inside commandkit handler.");return env.registerDeferredFunction(fn)}__name(after,"after");var CommandHandler=class{static{__name(this,"CommandHandler")}#data;constructor({...options}){this.#data={...options,builtInValidations:[],commands:[]}}async init(){await this.#buildCommands(),this.#buildBuiltInValidations();let devOnlyCommands=this.#data.commands.filter(cmd=>cmd.options?.devOnly);devOnlyCommands.length&&!this.#data.devGuildIds.length&&process.emitWarning(colors_default.yellow('You have commands marked as "devOnly", but "devGuildIds" have not been set.')),devOnlyCommands.length&&!this.#data.devUserIds.length&&!this.#data.devRoleIds.length&&process.emitWarning(colors_default.yellow('You have commands marked as "devOnly", but "devUserIds" or "devRoleIds" have not been set.')),this.#data.bulkRegister?await loadCommandsWithRest({client:this.#data.client,devGuildIds:this.#data.devGuildIds,commands:this.#data.commands}):await registerCommands({client:this.#data.client,devGuildIds:this.#data.devGuildIds,commands:this.#data.commands}),this.handleCommands()}async#buildCommands(){let allowedExtensions=/\.(js|mjs|cjs|ts)$/i,commandFilePaths=(await getFilePaths(this.#data.commandsPath,!0)).filter(path3=>allowedExtensions.test(path3));for(let commandFilePath of commandFilePaths){let importedObj=await import(`${toFileURL(commandFilePath)}?t=${Date.now()}`),commandObj=clone(importedObj);typeof module<"u"&&typeof require<"u"&&delete require.cache[require.resolve(commandFilePath)];let compactFilePath=commandFilePath.split(process.cwd())[1]||commandFilePath;if(commandObj.default&&(commandObj=commandObj.default),importedObj.default?commandObj.data=importedObj.default.data:commandObj.data=importedObj.data,!commandObj.data){process.emitWarning(colors_default.yellow(`Ignoring: Command file ${compactFilePath} does not export "data".`));continue}if(!commandObj.data.name){process.emitWarning(colors_default.yellow(`Ignoring: Command file ${compactFilePath} does not export "data.name".`));continue}if(!commandObj.run){process.emitWarning(colors_default.yellow(`Ignoring: Command file ${commandObj.data.name} does not export "run".`));continue}if(typeof commandObj.run!="function"){process.emitWarning(colors_default.yellow(`Ignoring: Command file ${commandObj.data.name} does not export "run" as a function.`));continue}commandObj.filePath=commandFilePath;let commandCategory=commandFilePath.split(this.#data.commandsPath)[1]?.replace(/\\\\|\\/g,"/").split("/")[1]||null;commandCategory&&allowedExtensions.test(commandCategory)?commandObj.category=null:commandObj.category=commandCategory,this.#data.commands.push(commandObj)}}#buildBuiltInValidations(){for(let builtInValidationFunction of validations_default)this.#data.builtInValidations.push(builtInValidationFunction)}async#commandFinalizer(){let env=useEnvironment();await env.runDeferredFunctions(),env.clearAllDeferredFunctions()}async#interactionHandler(interaction){if(!interaction.isChatInputCommand()&&!interaction.isContextMenuCommand()&&!interaction.isAutocomplete())return;let isAutocomplete=interaction.isAutocomplete(),targetCommand=this.#data.commands.find(cmd=>cmd.data.name===interaction.commandName);if(!targetCommand)return;let env=useEnvironment();env.variables.set("interaction",interaction);let{data,options,run,autocomplete,...rest}=targetCommand;return isAutocomplete&&!autocomplete?void 0:__name(async()=>{let commandObj={data:targetCommand.data,options:targetCommand.options,...rest};if(this.#data.validationHandler){let canRun2=!0;for(let validationFunction of this.#data.validationHandler.validations)if(await validationFunction({interaction,commandObj,client:this.#data.client,handler:this.#data.commandkitInstance})){canRun2=!1;break}if(!canRun2)return}let canRun=!0;if(!this.#data.skipBuiltInValidations){for(let validation of this.#data.builtInValidations)if(validation({targetCommand,interaction,handlerData:this.#data})){canRun=!1;break}}if(!canRun)return;let command=targetCommand[isAutocomplete?"autocomplete":"run"],context2={interaction,client:this.#data.client,handler:this.#data.commandkitInstance};if(!this.#data.commandkitInstance.isDebuggingCommands())return command(context2);after(env2=>{let error=env2.getExecutionError(),marker=env2.getMarker(),time=`${env2.getExecutionTime().toFixed(2)}ms`;if(error){console.error(colors_default.red(`[${marker} - ${time}] Error executing command: ${error}`));return}console.log(colors_default.green(`[${marker} - ${time}] Command executed successfully`))});try{return env.markStart(interaction.commandName),await command(context2)}finally{env.markEnd()}},"executor")()}handleCommands(){this.#data.client.on("interactionCreate",interaction=>{let env=new CommandKitEnvironment(this.#data.commandkitInstance);return env.setType("COMMAND_HANDLER"),makeContextAwareFunction(env,this.#interactionHandler.bind(this),this.#commandFinalizer.bind(this))(interaction)})}get commands(){return this.#data.commands}async reloadCommands(type){if(!this.#data.commandsPath)throw new Error(colors_default.red('Cannot reload commands as "commandsPath" was not provided when instantiating CommandKit.'));this.#data.commands=[],await this.#buildCommands(),this.#data.bulkRegister?await loadCommandsWithRest({client:this.#data.client,devGuildIds:this.#data.devGuildIds,commands:this.#data.commands,reloading:!0,type}):await registerCommands({client:this.#data.client,devGuildIds:this.#data.devGuildIds,commands:this.#data.commands,reloading:!0,type})}};var EventHandler=class{static{__name(this,"EventHandler")}#data;constructor({...options}){this.#data={...options,events:[]}}async init(){await this.#buildEvents(),this.#registerEvents()}async#buildEvents(){let eventFolderPaths=await getFolderPaths(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(path3=>allowedExtensions.test(path3)),eventObj={name:eventName,functions:[]};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?.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)}}}#registerEvents(){let client=this.#data.client,handler=this.#data.commandKitInstance;for(let eventObj of this.#data.events)client.on(eventObj.name,async(...params)=>{for(let eventFunction of eventObj.functions)if(await eventFunction(...params,client,handler))break})}get events(){return this.#data.events}async reloadEvents(commandHandler){if(!this.#data.eventsPath)throw new Error(colors_default.red('Cannot reload events as "eventsPath" was not provided when instantiating CommandKit.'));this.#data.events=[],await this.#buildEvents(),this.#data.client.removeAllListeners(),this.#registerEvents(),commandHandler?.handleCommands()}};var ValidationHandler=class{static{__name(this,"ValidationHandler")}#data;constructor({...options}){this.#data={...options,validations:[]}}async init(){this.#data.validations=await this.#buildValidations()}async#buildValidations(){let allowedExtensions=/\.(js|mjs|cjs|ts)$/i,validationFilePaths=(await getFilePaths(this.#data.validationsPath,!0)).filter(path3=>allowedExtensions.test(path3)),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?.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}get validations(){return this.#data.validations}async reloadValidations(){if(!this.#data.validationsPath)throw new Error(colors_default.red('Cannot reload validations as "validationsPath" was not provided when instantiating CommandKit.'));let newValidations=await this.#buildValidations();this.#data.validations=newValidations}};var CacheProvider=class{static{__name(this,"CacheProvider")}};var MemoryCache=class extends CacheProvider{static{__name(this,"MemoryCache")}#cache=new Map;async get(key){let entry=this.#cache.get(key);if(entry){if(entry.ttl&&Date.now()>entry.ttl){this.#cache.delete(key);return}return entry}}async set(key,value,ttl){let entry={value,ttl:ttl!=null?Date.now()+ttl:void 0};this.#cache.set(key,entry)}async exists(key){return this.#cache.has(key)}async delete(key){this.#cache.delete(key)}async clear(){this.#cache.clear()}async expire(key,ttl){let entry=this.#cache.get(key);if(!entry)return;let _ttl=Date.now()+ttl;if(_ttl<Date.now()){this.#cache.delete(key);return}entry.ttl=_ttl}};var CommandKit=class _CommandKit extends import_node_events.default{static{__name(this,"CommandKit")}#data;static instance=void 0;constructor(options){if(_CommandKit.instance&&process.emitWarning("CommandKit instance already exists. Having multiple instance in same project is discouraged and it may lead to unexpected behavior.",{code:"MultiInstanceWarning"}),!options.client)throw new Error(colors_default.red('"client" is required when instantiating CommandKit.'));if(options.validationsPath&&!options.commandsPath)throw new Error(colors_default.red('"commandsPath" is required when "validationsPath" is set.'));super(),options.debugCommands??=process.env.NODE_ENV!=="production",options.cacheProvider!==null&&(!options.cacheProvider||!(options.cacheProvider instanceof CacheProvider))&&(options.cacheProvider=new MemoryCache),this.#data=options,this.#init().then(()=>{this.incrementClientListenersCount()}),_CommandKit.instance||(_CommandKit.instance=this)}getCacheProvider(){return this.#data.cacheProvider??null}isDebuggingCommands(){return this.#data.debugCommands||!1}get client(){return this.#data.client}get commandHandler(){return this.#data.commandHandler}async#init(){if(this.#data.eventsPath){let eventHandler=new EventHandler({client:this.#data.client,eventsPath:this.#data.eventsPath,commandKitInstance:this});await eventHandler.init(),this.#data.eventHandler=eventHandler}if(this.#data.validationsPath){let validationHandler=new ValidationHandler({validationsPath:this.#data.validationsPath});await validationHandler.init(),this.#data.validationHandler=validationHandler}if(this.#data.commandsPath){let commandHandler=new CommandHandler({client:this.#data.client,commandsPath:this.#data.commandsPath,devGuildIds:this.#data.devGuildIds||[],devUserIds:this.#data.devUserIds||[],devRoleIds:this.#data.devRoleIds||[],validationHandler:this.#data.validationHandler,skipBuiltInValidations:this.#data.skipBuiltInValidations||!1,commandkitInstance:this,bulkRegister:this.#data.bulkRegister||!1});await commandHandler.init(),this.#data.commandHandler=commandHandler}}async reloadCommands(type){this.#data.commandHandler&&await this.#data.commandHandler.reloadCommands(type)}async reloadEvents(){this.#data.eventHandler&&await this.#data.eventHandler.reloadEvents(this.#data.commandHandler)}async reloadValidations(){this.#data.validationHandler&&await this.#data.validationHandler.reloadValidations()}get commands(){return this.#data.commandHandler?this.#data.commandHandler.commands.map(cmd=>{let{run,autocomplete,...command}=cmd;return command}):[]}get commandsPath(){return this.#data.commandsPath}get eventsPath(){return this.#data.eventsPath}get validationsPath(){return this.#data.validationsPath}get devUserIds(){return this.#data.devUserIds||[]}get devGuildIds(){return this.#data.devGuildIds||[]}get devRoleIds(){return this.#data.devRoleIds||[]}incrementClientListenersCount(){this.#data.client.setMaxListeners(this.#data.client.getMaxListeners()+1)}decrementClientListenersCount(){this.#data.client.setMaxListeners(this.#data.client.getMaxListeners()-1)}};0&&(module.exports={CommandKit});
11
11
  //# sourceMappingURL=CommandKit.js.map