commandkit 0.1.10 → 0.1.11-dev.20240202064607

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js DELETED
@@ -1,1122 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
-
30
- // src/index.ts
31
- var src_exports = {};
32
- __export(src_exports, {
33
- ButtonKit: () => ButtonKit,
34
- CommandKit: () => CommandKit,
35
- createEffect: () => createEffect,
36
- createSignal: () => createSignal,
37
- defineConfig: () => defineConfig,
38
- getConfig: () => getConfig
39
- });
40
- module.exports = __toCommonJS(src_exports);
41
-
42
- // src/utils/resolve-file-url.ts
43
- var import_path = __toESM(require("path"));
44
- function toFileURL(filePath) {
45
- const resolvedPath = import_path.default.resolve(filePath);
46
- return "file://" + resolvedPath.replace(/\\\\|\\/g, "/");
47
- }
48
-
49
- // src/utils/get-paths.ts
50
- var import_path2 = __toESM(require("path"));
51
- var import_promises = __toESM(require("fs/promises"));
52
- async function getFilePaths(directory, nesting) {
53
- let filePaths = [];
54
- if (!directory)
55
- return filePaths;
56
- const files = await import_promises.default.readdir(directory, { withFileTypes: true });
57
- for (const file of files) {
58
- const filePath = import_path2.default.join(directory, file.name);
59
- if (file.isFile()) {
60
- filePaths.push(filePath);
61
- }
62
- if (nesting && file.isDirectory()) {
63
- filePaths = [...filePaths, ...await getFilePaths(filePath, true)];
64
- }
65
- }
66
- return filePaths;
67
- }
68
- async function getFolderPaths(directory, nesting) {
69
- let folderPaths = [];
70
- if (!directory)
71
- return folderPaths;
72
- const folders = await import_promises.default.readdir(directory, { withFileTypes: true });
73
- for (const folder of folders) {
74
- const folderPath = import_path2.default.join(directory, folder.name);
75
- if (folder.isDirectory()) {
76
- folderPaths.push(folderPath);
77
- if (nesting) {
78
- folderPaths = [...folderPaths, ...await getFolderPaths(folderPath, true)];
79
- }
80
- }
81
- }
82
- return folderPaths;
83
- }
84
-
85
- // src/utils/clone.ts
86
- var import_rfdc = __toESM(require("rfdc"));
87
- var clone = (0, import_rfdc.default)();
88
-
89
- // src/utils/colors.ts
90
- var resetColor = "\x1B[0m";
91
- var colors_default = {
92
- reset: (text) => `${text}${resetColor}`,
93
- bright: (text) => `\x1B[1m${text}${resetColor}`,
94
- dim: (text) => `\x1B[2m${text}${resetColor}`,
95
- underscore: (text) => `\x1B[4m${text}${resetColor}`,
96
- blink: (text) => `\x1B[5m${text}${resetColor}`,
97
- reverse: (text) => `\x1B[7m${text}${resetColor}`,
98
- hidden: (text) => `\x1B[8m${text}${resetColor}`,
99
- black: (text) => `\x1B[30m${text}${resetColor}`,
100
- red: (text) => `\x1B[31m${text}${resetColor}`,
101
- green: (text) => `\x1B[32m${text}${resetColor}`,
102
- yellow: (text) => `\x1B[33m${text}${resetColor}`,
103
- blue: (text) => `\x1B[34m${text}${resetColor}`,
104
- magenta: (text) => `\x1B[35m${text}${resetColor}`,
105
- cyan: (text) => `\x1B[36m${text}${resetColor}`,
106
- white: (text) => `\x1B[37m${text}${resetColor}`,
107
- bgBlack: (text) => `\x1B[40m${text}${resetColor}`,
108
- bgRed: (text) => `\x1B[41m${text}${resetColor}`,
109
- bgGreen: (text) => `\x1B[42m${text}${resetColor}`,
110
- bgYellow: (text) => `\x1B[43m${text}${resetColor}`,
111
- bgBlue: (text) => `\x1B[44m${text}${resetColor}`,
112
- bgMagenta: (text) => `\x1B[45m${text}${resetColor}`,
113
- bgCyan: (text) => `\x1B[46m${text}${resetColor}`,
114
- bgWhite: (text) => `\x1B[47m${text}${resetColor}`
115
- };
116
-
117
- // src/handlers/command-handler/functions/loadCommandsWithRest.ts
118
- async function loadCommandsWithRest(props) {
119
- if (props.reloading) {
120
- if (props.client.isReady()) {
121
- await handleLoading(
122
- props.client,
123
- props.commands,
124
- props.devGuildIds,
125
- props.reloading,
126
- props.type
127
- );
128
- } else {
129
- throw new Error(colors_default.red(`\u274C Cannot reload commands when client is not ready.`));
130
- }
131
- } else {
132
- props.client.once("ready", async (c) => {
133
- await handleLoading(c, props.commands, props.devGuildIds, props.reloading, props.type);
134
- });
135
- }
136
- }
137
- async function handleLoading(client, commands, devGuildIds, reloading, type) {
138
- commands = commands.filter((cmd) => !cmd.options?.deleted);
139
- const devOnlyCommands = commands.filter((cmd) => cmd.options?.devOnly);
140
- const globalCommands = commands.filter((cmd) => !cmd.options?.devOnly);
141
- if (type === "dev") {
142
- await loadDevCommands(client, devOnlyCommands, devGuildIds, reloading);
143
- } else if (type === "global") {
144
- await loadGlobalCommands(client, globalCommands, reloading);
145
- } else {
146
- await loadDevCommands(client, devOnlyCommands, devGuildIds, reloading);
147
- await loadGlobalCommands(client, globalCommands, reloading);
148
- }
149
- }
150
- async function loadGlobalCommands(client, commands, reloading) {
151
- const requestBody = commands.map((cmd) => cmd.data);
152
- await client.application.commands.set(requestBody).catch((error) => {
153
- console.log(
154
- colors_default.red(
155
- `\u274C Error ${reloading ? "reloading" : "loading"} global application commands.
156
- `
157
- )
158
- );
159
- throw new Error(error);
160
- });
161
- console.log(
162
- colors_default.green(
163
- `\u2705 ${reloading ? "Reloaded" : "Loaded"} ${requestBody.length} global commands.`
164
- )
165
- );
166
- }
167
- async function loadDevCommands(client, commands, guildIds, reloading) {
168
- const requestBody = commands.map((cmd) => cmd.data);
169
- for (const guildId of guildIds) {
170
- const targetGuild = client.guilds.cache.get(guildId) || await client.guilds.fetch(guildId);
171
- if (!targetGuild) {
172
- console.log(
173
- `Couldn't ${reloading ? "reloading" : "loading"} commands in guild "${targetGuild}" - guild doesn't exist or client isn't part of the guild.`
174
- );
175
- continue;
176
- }
177
- await targetGuild.commands.set(requestBody).catch((error) => {
178
- console.log(
179
- colors_default.red(
180
- `\u274C Error ${reloading ? "reloading" : "loading"} developer application commands in guild "${targetGuild?.name || guildId}".
181
- `
182
- )
183
- );
184
- throw new Error(error);
185
- });
186
- console.log(
187
- colors_default.green(
188
- `\u2705 ${reloading ? "Reloaded" : "Loaded"} ${requestBody.length} developer commands in guild "${targetGuild.name}".`
189
- )
190
- );
191
- }
192
- }
193
-
194
- // src/handlers/command-handler/utils/areSlashCommandsDifferent.ts
195
- function areSlashCommandsDifferent(appCommand, localCommand) {
196
- if (!appCommand.options)
197
- appCommand.options = [];
198
- if (!localCommand.options)
199
- localCommand.options = [];
200
- if (!appCommand.description)
201
- appCommand.description = "";
202
- if (!localCommand.description)
203
- localCommand.description = "";
204
- if (localCommand.description !== appCommand.description || localCommand.options.length !== appCommand.options.length) {
205
- return true;
206
- }
207
- }
208
-
209
- // src/handlers/command-handler/functions/registerCommands.ts
210
- async function registerCommands(props) {
211
- if (props.reloading) {
212
- if (props.client.isReady()) {
213
- await handleRegistration(props.client, props.commands, props.devGuildIds, props.type);
214
- } else {
215
- throw new Error(colors_default.red(`\u274C Cannot reload commands when client is not ready.`));
216
- }
217
- } else {
218
- props.client.once("ready", async (c) => {
219
- await handleRegistration(c, props.commands, props.devGuildIds, props.type);
220
- });
221
- }
222
- }
223
- async function handleRegistration(client, commands, devGuildIds, type) {
224
- const devOnlyCommands = commands.filter((cmd) => cmd.options?.devOnly);
225
- const globalCommands = commands.filter((cmd) => !cmd.options?.devOnly);
226
- if (type === "dev") {
227
- await registerDevCommands(client, devOnlyCommands, devGuildIds);
228
- } else if (type === "global") {
229
- await registerGlobalCommands(client, globalCommands);
230
- } else {
231
- await registerDevCommands(client, devOnlyCommands, devGuildIds);
232
- await registerGlobalCommands(client, globalCommands);
233
- }
234
- }
235
- async function registerGlobalCommands(client, commands) {
236
- const appCommandsManager = client.application.commands;
237
- await appCommandsManager.fetch();
238
- for (const command of commands) {
239
- const targetCommand = appCommandsManager.cache.find(
240
- (cmd) => cmd.name === command.data.name
241
- );
242
- if (command.options?.deleted) {
243
- if (!targetCommand) {
244
- console.log(
245
- colors_default.yellow(
246
- `\u23E9 Ignoring: Command "${command.data.name}" is globally marked as deleted.`
247
- )
248
- );
249
- } else {
250
- await targetCommand.delete().catch((error) => {
251
- console.log(
252
- colors_default.red(`\u274C Failed to delete command "${command.data.name}" globally.`)
253
- );
254
- console.error(error);
255
- });
256
- console.log(colors_default.green(`\u{1F6AE} Deleted command "${command.data.name}" globally.`));
257
- }
258
- continue;
259
- }
260
- if (targetCommand) {
261
- const commandsAreDifferent = areSlashCommandsDifferent(targetCommand, command.data);
262
- if (commandsAreDifferent) {
263
- await targetCommand.edit(command.data).catch((error) => {
264
- console.log(
265
- colors_default.red(
266
- `\u274C Failed to edit command "${command.data.name}" globally.`
267
- )
268
- );
269
- console.error(error);
270
- });
271
- console.log(colors_default.green(`\u2705 Edited command "${command.data.name}" globally.`));
272
- continue;
273
- }
274
- }
275
- if (targetCommand)
276
- continue;
277
- await appCommandsManager.create(command.data).catch((error) => {
278
- console.log(
279
- colors_default.red(`\u274C Failed to register command "${command.data.name}" globally.`)
280
- );
281
- console.error(error);
282
- });
283
- console.log(colors_default.green(`\u2705 Registered command "${command.data.name}" globally.`));
284
- }
285
- }
286
- async function registerDevCommands(client, commands, guildIds) {
287
- const devGuilds = [];
288
- for (const guildId of guildIds) {
289
- const guild = client.guilds.cache.get(guildId) || await client.guilds.fetch(guildId);
290
- if (!guild) {
291
- console.log(
292
- colors_default.yellow(
293
- `\u23E9 Ignoring: Guild ${guildId} does not exist or client isn't in this guild.`
294
- )
295
- );
296
- continue;
297
- }
298
- devGuilds.push(guild);
299
- }
300
- const guildCommandsManagers = [];
301
- for (const guild of devGuilds) {
302
- const guildCommandsManager = guild.commands;
303
- await guildCommandsManager.fetch();
304
- guildCommandsManagers.push(guildCommandsManager);
305
- }
306
- for (const command of commands) {
307
- for (const guildCommands of guildCommandsManagers) {
308
- const targetCommand = guildCommands.cache.find((cmd) => cmd.name === command.data.name);
309
- if (command.options?.deleted) {
310
- if (!targetCommand) {
311
- console.log(
312
- colors_default.yellow(
313
- `\u23E9 Ignoring: Command "${command.data.name}" is marked as deleted for ${guildCommands.guild.name}.`
314
- )
315
- );
316
- } else {
317
- await targetCommand.delete().catch((error) => {
318
- console.log(
319
- colors_default.red(
320
- `\u274C Failed to delete command "${command.data.name}" in ${guildCommands.guild.name}.`
321
- )
322
- );
323
- console.error(error);
324
- });
325
- console.log(
326
- colors_default.green(
327
- `\u{1F6AE} Deleted command "${command.data.name}" in ${guildCommands.guild.name}.`
328
- )
329
- );
330
- }
331
- continue;
332
- }
333
- if (targetCommand) {
334
- const commandsAreDifferent = areSlashCommandsDifferent(targetCommand, command.data);
335
- if (commandsAreDifferent) {
336
- await targetCommand.edit(command.data).catch((error) => {
337
- console.log(
338
- colors_default.red(
339
- `\u274C Failed to edit command "${command.data.name}" in ${guildCommands.guild.name}.`
340
- )
341
- );
342
- console.error(error);
343
- });
344
- console.log(
345
- colors_default.green(
346
- `\u2705 Edited command "${command.data.name}" in ${guildCommands.guild.name}.`
347
- )
348
- );
349
- continue;
350
- }
351
- }
352
- if (targetCommand)
353
- continue;
354
- await guildCommands.create(command.data).catch((error) => {
355
- console.log(
356
- colors_default.red(
357
- `\u274C Failed to register command "${command.data.name}" in ${guildCommands.guild.name}.`
358
- )
359
- );
360
- console.error(error);
361
- });
362
- console.log(
363
- colors_default.green(
364
- `\u2705 Registered command "${command.data.name}" in ${guildCommands.guild.name}.`
365
- )
366
- );
367
- }
368
- }
369
- }
370
-
371
- // src/handlers/command-handler/validations/devOnly.ts
372
- function devOnly_default({ interaction, targetCommand, handlerData }) {
373
- if (interaction.isAutocomplete())
374
- return;
375
- if (targetCommand.options?.devOnly) {
376
- if (interaction.inGuild() && !handlerData.devGuildIds.includes(interaction.guildId)) {
377
- interaction.reply({
378
- content: "\u274C This command can only be used inside development servers.",
379
- ephemeral: true
380
- });
381
- return true;
382
- }
383
- const guildMember = interaction.guild?.members.cache.get(interaction.user.id);
384
- const memberRoles = guildMember?.roles.cache;
385
- let hasDevRole = false;
386
- memberRoles?.forEach((role) => {
387
- if (handlerData.devRoleIds.includes(role.id)) {
388
- hasDevRole = true;
389
- }
390
- });
391
- const isDevUser = handlerData.devUserIds.includes(interaction.user.id) || hasDevRole;
392
- if (!isDevUser) {
393
- interaction.reply({
394
- content: "\u274C This command can only be used by developers.",
395
- ephemeral: true
396
- });
397
- return true;
398
- }
399
- }
400
- }
401
-
402
- // src/handlers/command-handler/validations/permissions.ts
403
- var import_discord = require("discord.js");
404
- function permissions_default({ interaction, targetCommand }) {
405
- if (interaction.isAutocomplete())
406
- return;
407
- const userPermissions = interaction.memberPermissions;
408
- let userPermissionsRequired = targetCommand.options?.userPermissions;
409
- let missingUserPermissions = [];
410
- if (typeof userPermissionsRequired === "string") {
411
- userPermissionsRequired = [userPermissionsRequired];
412
- }
413
- const botPermissions = interaction.guild?.members.me?.permissions;
414
- let botPermissionsRequired = targetCommand.options?.botPermissions;
415
- let missingBotPermissions = [];
416
- if (typeof botPermissionsRequired === "string") {
417
- botPermissionsRequired = [botPermissionsRequired];
418
- }
419
- if (!userPermissionsRequired?.length && !botPermissionsRequired?.length) {
420
- return;
421
- }
422
- if (userPermissions && userPermissionsRequired) {
423
- for (const permission of userPermissionsRequired) {
424
- const hasPermission = userPermissions.has(permission);
425
- if (!hasPermission) {
426
- missingUserPermissions.push(permission);
427
- }
428
- }
429
- }
430
- if (botPermissions && botPermissionsRequired) {
431
- for (const permission of botPermissionsRequired) {
432
- const hasPermission = botPermissions.has(permission);
433
- if (!hasPermission) {
434
- missingBotPermissions.push(permission);
435
- }
436
- }
437
- }
438
- if (!missingUserPermissions.length && !missingBotPermissions.length) {
439
- return;
440
- }
441
- const pattern = /([a-z])([A-Z])|([A-Z]+)([A-Z][a-z])/g;
442
- missingUserPermissions = missingUserPermissions.map((str) => str.replace(pattern, "$1$3 $2$4"));
443
- missingBotPermissions = missingBotPermissions.map((str) => str.replace(pattern, "$1$3 $2$4"));
444
- let embedDescription = "";
445
- const formatter = new Intl.ListFormat("en", { style: "long", type: "conjunction" });
446
- const getPermissionWord = (permissions) => permissions.length === 1 ? "permission" : "permissions";
447
- if (missingUserPermissions.length) {
448
- const formattedPermissions = missingUserPermissions.map((p) => `\`${p}\``);
449
- const permissionsString = formatter.format(formattedPermissions);
450
- embedDescription += `- You must have the ${permissionsString} ${getPermissionWord(
451
- missingUserPermissions
452
- )} to be able to run this command.
453
- `;
454
- }
455
- if (missingBotPermissions.length) {
456
- const formattedPermissions = missingBotPermissions.map((p) => `\`${p}\``);
457
- const permissionsString = formatter.format(formattedPermissions);
458
- embedDescription += `- I must have the ${permissionsString} ${getPermissionWord(
459
- missingBotPermissions
460
- )} to be able to execute this command.
461
- `;
462
- }
463
- const embed = new import_discord.EmbedBuilder().setTitle(`:x: Missing permissions!`).setDescription(embedDescription).setColor("Red");
464
- interaction.reply({ embeds: [embed], ephemeral: true });
465
- return true;
466
- }
467
-
468
- // src/handlers/command-handler/validations/index.ts
469
- var validations_default = [devOnly_default, permissions_default];
470
-
471
- // src/handlers/command-handler/CommandHandler.ts
472
- var CommandHandler = class {
473
- #data;
474
- constructor({ ...options }) {
475
- this.#data = {
476
- ...options,
477
- builtInValidations: [],
478
- commands: []
479
- };
480
- }
481
- async init() {
482
- await this.#buildCommands();
483
- this.#buildBuiltInValidations();
484
- const devOnlyCommands = this.#data.commands.filter((cmd) => cmd.options?.devOnly);
485
- if (devOnlyCommands.length && !this.#data.devGuildIds.length) {
486
- console.log(
487
- colors_default.yellow(
488
- '\u2139\uFE0F Warning: You have commands marked as "devOnly", but "devGuildIds" have not been set.'
489
- )
490
- );
491
- }
492
- if (devOnlyCommands.length && !this.#data.devUserIds.length && !this.#data.devRoleIds.length) {
493
- console.log(
494
- colors_default.yellow(
495
- '\u2139\uFE0F Warning: You have commands marked as "devOnly", but "devUserIds" or "devRoleIds" have not been set.'
496
- )
497
- );
498
- }
499
- if (this.#data.bulkRegister) {
500
- await loadCommandsWithRest({
501
- client: this.#data.client,
502
- devGuildIds: this.#data.devGuildIds,
503
- commands: this.#data.commands
504
- });
505
- } else {
506
- await registerCommands({
507
- client: this.#data.client,
508
- devGuildIds: this.#data.devGuildIds,
509
- commands: this.#data.commands
510
- });
511
- }
512
- this.handleCommands();
513
- }
514
- async #buildCommands() {
515
- const allowedExtensions = /\.(js|mjs|cjs|ts)$/i;
516
- const paths = await getFilePaths(this.#data.commandsPath, true);
517
- const commandFilePaths = paths.filter((path3) => allowedExtensions.test(path3));
518
- for (const commandFilePath of commandFilePaths) {
519
- const modulePath = toFileURL(commandFilePath);
520
- const importedObj = await import(`${modulePath}?t=${Date.now()}`);
521
- let commandObj = clone(importedObj);
522
- if (typeof module !== "undefined" && typeof require !== "undefined") {
523
- delete require.cache[require.resolve(commandFilePath)];
524
- }
525
- const compactFilePath = commandFilePath.split(process.cwd())[1] || commandFilePath;
526
- if (commandObj.default)
527
- commandObj = commandObj.default;
528
- if (importedObj.default) {
529
- commandObj.data = importedObj.default.data;
530
- } else {
531
- commandObj.data = importedObj.data;
532
- }
533
- if (!commandObj.data) {
534
- console.log(
535
- colors_default.yellow(
536
- `\u23E9 Ignoring: Command ${compactFilePath} does not export "data".`
537
- )
538
- );
539
- continue;
540
- }
541
- if (!commandObj.data.name) {
542
- console.log(
543
- colors_default.yellow(
544
- `\u23E9 Ignoring: Command ${compactFilePath} does not export "data.name".`
545
- )
546
- );
547
- continue;
548
- }
549
- if (!commandObj.run) {
550
- console.log(
551
- colors_default.yellow(
552
- `\u23E9 Ignoring: Command ${commandObj.data.name} does not export "run".`
553
- )
554
- );
555
- continue;
556
- }
557
- if (typeof commandObj.run !== "function") {
558
- console.log(
559
- colors_default.yellow(
560
- `\u23E9 Ignoring: Command ${commandObj.data.name} does not export "run" as a function.`
561
- )
562
- );
563
- continue;
564
- }
565
- commandObj.filePath = commandFilePath;
566
- let commandCategory = commandFilePath.split(this.#data.commandsPath)[1]?.replace(/\\\\|\\/g, "/").split("/")[1] || null;
567
- if (commandCategory && allowedExtensions.test(commandCategory)) {
568
- commandObj.category = null;
569
- } else {
570
- commandObj.category = commandCategory;
571
- }
572
- if (commandObj.options?.guildOnly) {
573
- console.log(
574
- colors_default.yellow(
575
- `\u2139\uFE0F Deprecation warning: The command "${commandObj.data.name}" uses "options.guildOnly", which will be deprecated soon. Use "data.dm_permission" instead.`
576
- )
577
- );
578
- }
579
- this.#data.commands.push(commandObj);
580
- }
581
- }
582
- #buildBuiltInValidations() {
583
- for (const builtInValidationFunction of validations_default) {
584
- this.#data.builtInValidations.push(builtInValidationFunction);
585
- }
586
- }
587
- handleCommands() {
588
- this.#data.client.on("interactionCreate", async (interaction) => {
589
- if (!interaction.isChatInputCommand() && !interaction.isContextMenuCommand() && !interaction.isAutocomplete())
590
- return;
591
- const isAutocomplete = interaction.isAutocomplete();
592
- const targetCommand = this.#data.commands.find(
593
- (cmd) => cmd.data.name === interaction.commandName
594
- );
595
- if (!targetCommand)
596
- return;
597
- const { data, options, run, autocomplete, ...rest } = targetCommand;
598
- if (isAutocomplete && !autocomplete)
599
- return;
600
- const commandObj = {
601
- data: targetCommand.data,
602
- options: targetCommand.options,
603
- ...rest
604
- };
605
- if (this.#data.validationHandler) {
606
- let canRun2 = true;
607
- for (const validationFunction of this.#data.validationHandler.validations) {
608
- const stopValidationLoop = await validationFunction({
609
- interaction,
610
- commandObj,
611
- client: this.#data.client,
612
- handler: this.#data.commandkitInstance
613
- });
614
- if (stopValidationLoop) {
615
- canRun2 = false;
616
- break;
617
- }
618
- }
619
- if (!canRun2)
620
- return;
621
- }
622
- let canRun = true;
623
- if (!this.#data.skipBuiltInValidations) {
624
- for (const validation of this.#data.builtInValidations) {
625
- const stopValidationLoop = validation({
626
- targetCommand,
627
- interaction,
628
- handlerData: this.#data
629
- });
630
- if (stopValidationLoop) {
631
- canRun = false;
632
- break;
633
- }
634
- }
635
- }
636
- if (!canRun)
637
- return;
638
- const context2 = {
639
- interaction,
640
- client: this.#data.client,
641
- handler: this.#data.commandkitInstance
642
- };
643
- await targetCommand[isAutocomplete ? "autocomplete" : "run"](context2);
644
- });
645
- }
646
- get commands() {
647
- return this.#data.commands;
648
- }
649
- async reloadCommands(type) {
650
- if (!this.#data.commandsPath) {
651
- throw new Error(
652
- 'Cannot reload commands as "commandsPath" was not provided when instantiating CommandKit.'
653
- );
654
- }
655
- this.#data.commands = [];
656
- await this.#buildCommands();
657
- if (this.#data.bulkRegister) {
658
- await loadCommandsWithRest({
659
- client: this.#data.client,
660
- devGuildIds: this.#data.devGuildIds,
661
- commands: this.#data.commands,
662
- reloading: true,
663
- type
664
- });
665
- } else {
666
- await registerCommands({
667
- client: this.#data.client,
668
- devGuildIds: this.#data.devGuildIds,
669
- commands: this.#data.commands,
670
- reloading: true,
671
- type
672
- });
673
- }
674
- }
675
- };
676
-
677
- // src/handlers/event-handler/EventHandler.ts
678
- var EventHandler = class {
679
- #data;
680
- constructor({ ...options }) {
681
- this.#data = {
682
- ...options,
683
- events: []
684
- };
685
- }
686
- async init() {
687
- await this.#buildEvents();
688
- this.#registerEvents();
689
- }
690
- async #buildEvents() {
691
- const eventFolderPaths = await getFolderPaths(this.#data.eventsPath);
692
- for (const eventFolderPath of eventFolderPaths) {
693
- const eventName = eventFolderPath.replace(/\\\\|\\/g, "/").split("/").pop();
694
- const allowedExtensions = /\.(js|mjs|cjs|ts)$/i;
695
- const eventPaths = await getFilePaths(eventFolderPath, true);
696
- const eventFilePaths = eventPaths.filter((path3) => allowedExtensions.test(path3));
697
- const eventObj = {
698
- name: eventName,
699
- functions: []
700
- };
701
- this.#data.events.push(eventObj);
702
- for (const eventFilePath of eventFilePaths) {
703
- const modulePath = toFileURL(eventFilePath);
704
- let importedFunction = (await import(`${modulePath}?t=${Date.now()}`)).default;
705
- let eventFunction = clone(importedFunction);
706
- if (typeof module !== "undefined" && typeof require !== "undefined") {
707
- delete require.cache[require.resolve(eventFilePath)];
708
- }
709
- if (eventFunction?.default) {
710
- eventFunction = eventFunction.default;
711
- }
712
- const compactFilePath = eventFilePath.split(process.cwd())[1] || eventFilePath;
713
- if (typeof eventFunction !== "function") {
714
- console.log(
715
- colors_default.yellow(
716
- `\u23E9 Ignoring: Event ${compactFilePath} does not export a function.`
717
- )
718
- );
719
- continue;
720
- }
721
- eventObj.functions.push(eventFunction);
722
- }
723
- }
724
- }
725
- #registerEvents() {
726
- const client = this.#data.client;
727
- const handler = this.#data.commandKitInstance;
728
- for (const eventObj of this.#data.events) {
729
- client.on(eventObj.name, async (...params) => {
730
- for (const eventFunction of eventObj.functions) {
731
- const stopEventLoop = await eventFunction(...params, client, handler);
732
- if (stopEventLoop) {
733
- break;
734
- }
735
- }
736
- });
737
- }
738
- }
739
- get events() {
740
- return this.#data.events;
741
- }
742
- async reloadEvents(commandHandler) {
743
- if (!this.#data.eventsPath) {
744
- throw new Error(
745
- 'Cannot reload events as "eventsPath" was not provided when instantiating CommandKit.'
746
- );
747
- }
748
- this.#data.events = [];
749
- await this.#buildEvents();
750
- this.#data.client.removeAllListeners();
751
- this.#registerEvents();
752
- commandHandler?.handleCommands();
753
- }
754
- };
755
-
756
- // src/handlers/validation-handler/ValidationHandler.ts
757
- var ValidationHandler = class {
758
- #data;
759
- constructor({ ...options }) {
760
- this.#data = {
761
- ...options,
762
- validations: []
763
- };
764
- }
765
- async init() {
766
- this.#data.validations = await this.#buildValidations();
767
- }
768
- async #buildValidations() {
769
- const allowedExtensions = /\.(js|mjs|cjs|ts)$/i;
770
- const validationPaths = await getFilePaths(this.#data.validationsPath, true);
771
- const validationFilePaths = validationPaths.filter((path3) => allowedExtensions.test(path3));
772
- const validationFunctions = [];
773
- for (const validationFilePath of validationFilePaths) {
774
- const modulePath = toFileURL(validationFilePath);
775
- let importedFunction = (await import(`${modulePath}?t=${Date.now()}`)).default;
776
- let validationFunction = clone(importedFunction);
777
- if (typeof module !== "undefined" && typeof require !== "undefined") {
778
- delete require.cache[require.resolve(validationFilePath)];
779
- }
780
- if (validationFunction?.default) {
781
- validationFunction = validationFunction.default;
782
- }
783
- const compactFilePath = validationFilePath.split(process.cwd())[1] || validationFilePath;
784
- if (typeof validationFunction !== "function") {
785
- console.log(
786
- colors_default.yellow(
787
- `\u23E9 Ignoring: Validation ${compactFilePath} does not export a function.`
788
- )
789
- );
790
- continue;
791
- }
792
- validationFunctions.push(validationFunction);
793
- }
794
- return validationFunctions;
795
- }
796
- get validations() {
797
- return this.#data.validations;
798
- }
799
- async reloadValidations() {
800
- if (!this.#data.validationsPath) {
801
- throw new Error(
802
- 'Cannot reload validations as "validationsPath" was not provided when instantiating CommandKit.'
803
- );
804
- }
805
- const newValidations = await this.#buildValidations();
806
- this.#data.validations = newValidations;
807
- }
808
- };
809
-
810
- // src/CommandKit.ts
811
- var CommandKit = class {
812
- #data;
813
- /**
814
- * Create a new command and event handler with CommandKit.
815
- *
816
- * @param options - The default CommandKit configuration.
817
- * @see {@link https://commandkit.js.org/docs/commandkit-setup}
818
- */
819
- constructor(options) {
820
- if (!options.client) {
821
- throw new Error(colors_default.red('"client" is required when instantiating CommandKit.'));
822
- }
823
- if (options.validationsPath && !options.commandsPath) {
824
- throw new Error(
825
- colors_default.red('"commandsPath" is required when "validationsPath" is set.')
826
- );
827
- }
828
- this.#data = options;
829
- this.#init();
830
- }
831
- /**
832
- * (Private) Initialize CommandKit.
833
- */
834
- async #init() {
835
- if (this.#data.eventsPath) {
836
- const eventHandler = new EventHandler({
837
- client: this.#data.client,
838
- eventsPath: this.#data.eventsPath,
839
- commandKitInstance: this
840
- });
841
- await eventHandler.init();
842
- this.#data.eventHandler = eventHandler;
843
- }
844
- if (this.#data.validationsPath) {
845
- const validationHandler = new ValidationHandler({
846
- validationsPath: this.#data.validationsPath
847
- });
848
- await validationHandler.init();
849
- this.#data.validationHandler = validationHandler;
850
- }
851
- if (this.#data.commandsPath) {
852
- const commandHandler = new CommandHandler({
853
- client: this.#data.client,
854
- commandsPath: this.#data.commandsPath,
855
- devGuildIds: this.#data.devGuildIds || [],
856
- devUserIds: this.#data.devUserIds || [],
857
- devRoleIds: this.#data.devRoleIds || [],
858
- validationHandler: this.#data.validationHandler,
859
- skipBuiltInValidations: this.#data.skipBuiltInValidations || false,
860
- commandkitInstance: this,
861
- bulkRegister: this.#data.bulkRegister || false
862
- });
863
- await commandHandler.init();
864
- this.#data.commandHandler = commandHandler;
865
- }
866
- }
867
- /**
868
- * Updates application commands with the latest from "commandsPath".
869
- */
870
- async reloadCommands(type) {
871
- if (!this.#data.commandHandler)
872
- return;
873
- await this.#data.commandHandler.reloadCommands(type);
874
- }
875
- /**
876
- * Updates application events with the latest from "eventsPath".
877
- */
878
- async reloadEvents() {
879
- if (!this.#data.eventHandler)
880
- return;
881
- await this.#data.eventHandler.reloadEvents(this.#data.commandHandler);
882
- }
883
- /**
884
- * Updates application command validations with the latest from "validationsPath".
885
- */
886
- async reloadValidations() {
887
- if (!this.#data.validationHandler)
888
- return;
889
- await this.#data.validationHandler.reloadValidations();
890
- }
891
- /**
892
- * @returns An array of objects of all the commands that CommandKit is handling.
893
- */
894
- get commands() {
895
- if (!this.#data.commandHandler) {
896
- return [];
897
- }
898
- const commands = this.#data.commandHandler.commands.map((cmd) => {
899
- const { run, autocomplete, ...command } = cmd;
900
- return command;
901
- });
902
- return commands;
903
- }
904
- /**
905
- * @returns The path to the commands folder which was set when instantiating CommandKit.
906
- */
907
- get commandsPath() {
908
- return this.#data.commandsPath;
909
- }
910
- /**
911
- * @returns The path to the events folder which was set when instantiating CommandKit.
912
- */
913
- get eventsPath() {
914
- return this.#data.eventsPath;
915
- }
916
- /**
917
- * @returns The path to the validations folder which was set when instantiating CommandKit.
918
- */
919
- get validationsPath() {
920
- return this.#data.validationsPath;
921
- }
922
- /**
923
- * @returns An array of all the developer user IDs which was set when instantiating CommandKit.
924
- */
925
- get devUserIds() {
926
- return this.#data.devUserIds || [];
927
- }
928
- /**
929
- * @returns An array of all the developer guild IDs which was set when instantiating CommandKit.
930
- */
931
- get devGuildIds() {
932
- return this.#data.devGuildIds || [];
933
- }
934
- /**
935
- * @returns An array of all the developer role IDs which was set when instantiating CommandKit.
936
- */
937
- get devRoleIds() {
938
- return this.#data.devRoleIds || [];
939
- }
940
- };
941
-
942
- // src/components/ButtonKit.ts
943
- var import_discord2 = require("discord.js");
944
- var ButtonKit = class extends import_discord2.ButtonBuilder {
945
- #onClickHandler = null;
946
- #onEndHandler = null;
947
- #contextData = null;
948
- #collector = null;
949
- /**
950
- * Sets up an inline interaction collector for this button. This collector by default allows as many interactions as possible if it is actively used.
951
- * If unused, this expires after 24 hours or custom time if specified.
952
- * @param handler The handler to run when the button is clicked
953
- * @param data The context data to use for the interaction collector
954
- * @returns This button
955
- * @example
956
- * ```ts
957
- * const button = new ButtonKit()
958
- * .setLabel('Click me')
959
- * .setStyle(ButtonStyle.Primary)
960
- * .setCustomId('click_me');
961
- *
962
- * const row = new ActionRowBuilder().addComponents(button);
963
- *
964
- * const message = await channel.send({ content: 'Click the button', components: [row] });
965
- *
966
- * button.onClick(async (interaction) => {
967
- * await interaction.reply('You clicked me!');
968
- * }, { message });
969
- *
970
- * // Remove onClick handler and destroy the interaction collector
971
- * button.onClick(null);
972
- * ```
973
- */
974
- onClick(handler, data) {
975
- if (this.data.style === import_discord2.ButtonStyle.Link) {
976
- throw new TypeError('Cannot setup "onClick" handler on link buttons.');
977
- }
978
- if (!handler) {
979
- throw new TypeError('Cannot setup "onClick" without a handler function parameter.');
980
- }
981
- this.#destroyCollector();
982
- this.#onClickHandler = handler;
983
- if (data)
984
- this.#contextData = data;
985
- this.#setupInteractionCollector();
986
- return this;
987
- }
988
- onEnd(handler) {
989
- if (!handler) {
990
- throw new TypeError('Cannot setup "onEnd" without a handler function parameter.');
991
- }
992
- this.#onEndHandler = handler;
993
- return this;
994
- }
995
- #setupInteractionCollector() {
996
- if (!this.#contextData || !this.#onClickHandler)
997
- return;
998
- const message = this.#contextData.message;
999
- if (!message) {
1000
- throw new TypeError(
1001
- 'Cannot setup "onClick" handler without a message in the context data.'
1002
- );
1003
- }
1004
- if ("customId" in this.data && !this.data.customId) {
1005
- throw new TypeError('Cannot setup "onClick" handler on a button without a custom id.');
1006
- }
1007
- const data = {
1008
- time: 864e5,
1009
- autoReset: true,
1010
- ...this.#contextData
1011
- };
1012
- const collector = this.#collector = message.createMessageComponentCollector({
1013
- filter: (interaction) => interaction.customId === this.data.custom_id && interaction.message.id === message.id,
1014
- componentType: import_discord2.ComponentType.Button,
1015
- ...data
1016
- });
1017
- this.#collector.on("collect", (interaction) => {
1018
- const handler = this.#onClickHandler;
1019
- if (!handler)
1020
- return this.#destroyCollector();
1021
- if (!this.#collector) {
1022
- return collector.stop("destroyed");
1023
- }
1024
- if (data.autoReset) {
1025
- this.#collector.resetTimer();
1026
- }
1027
- return handler(interaction);
1028
- });
1029
- this.#collector.on("end", () => {
1030
- this.#destroyCollector();
1031
- this.#onEndHandler?.();
1032
- });
1033
- }
1034
- #destroyCollector() {
1035
- this.#collector?.stop("end");
1036
- this.#collector?.removeAllListeners();
1037
- this.#collector = null;
1038
- this.#contextData = null;
1039
- this.#onClickHandler = null;
1040
- }
1041
- };
1042
-
1043
- // src/config.ts
1044
- var globalConfig = {
1045
- envExtra: true,
1046
- outDir: "dist",
1047
- watch: true,
1048
- clearRestartLogs: true,
1049
- minify: false,
1050
- sourcemap: false,
1051
- nodeOptions: [],
1052
- antiCrash: true,
1053
- requirePolyfill: true
1054
- };
1055
- function getConfig() {
1056
- return globalConfig;
1057
- }
1058
- var requiredProps = ["src", "main"];
1059
- function defineConfig(config) {
1060
- for (const prop of requiredProps) {
1061
- if (!config[prop]) {
1062
- throw new Error(`[CommandKit Config] Missing required config property: ${prop}`);
1063
- }
1064
- }
1065
- globalConfig = {
1066
- ...globalConfig,
1067
- ...config
1068
- };
1069
- return globalConfig;
1070
- }
1071
-
1072
- // src/utils/signal.ts
1073
- var context = [];
1074
- function createSignal(value) {
1075
- const subscribers = /* @__PURE__ */ new Set();
1076
- let disposed = false;
1077
- let val = value instanceof Function ? value() : value;
1078
- const getter = () => {
1079
- if (!disposed) {
1080
- const running = getCurrentObserver();
1081
- if (running)
1082
- subscribers.add(running);
1083
- }
1084
- return val;
1085
- };
1086
- const setter = (newValue) => {
1087
- if (disposed)
1088
- return;
1089
- val = newValue instanceof Function ? newValue(val) : newValue;
1090
- for (const subscriber of subscribers) {
1091
- subscriber();
1092
- }
1093
- };
1094
- const dispose = () => {
1095
- subscribers.clear();
1096
- disposed = true;
1097
- };
1098
- return [getter, setter, dispose];
1099
- }
1100
- function createEffect(callback) {
1101
- const execute = () => {
1102
- context.push(execute);
1103
- try {
1104
- callback();
1105
- } finally {
1106
- context.pop();
1107
- }
1108
- };
1109
- execute();
1110
- }
1111
- function getCurrentObserver() {
1112
- return context[context.length - 1];
1113
- }
1114
- // Annotate the CommonJS export names for ESM import in node:
1115
- 0 && (module.exports = {
1116
- ButtonKit,
1117
- CommandKit,
1118
- createEffect,
1119
- createSignal,
1120
- defineConfig,
1121
- getConfig
1122
- });