stoatx 0.2.0 → 0.2.1

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 ADDED
@@ -0,0 +1,697 @@
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 index_exports = {};
32
+ __export(index_exports, {
33
+ CommandRegistry: () => CommandRegistry,
34
+ Guard: () => Guard,
35
+ METADATA_KEYS: () => METADATA_KEYS,
36
+ MallyHandler: () => MallyHandler,
37
+ SimpleCommand: () => SimpleCommand,
38
+ Stoat: () => Stoat,
39
+ buildSimpleCommandMetadata: () => buildSimpleCommandMetadata,
40
+ getGuards: () => getGuards,
41
+ getSimpleCommands: () => getSimpleCommands,
42
+ isStoatClass: () => isStoatClass
43
+ });
44
+ module.exports = __toCommonJS(index_exports);
45
+
46
+ // src/decorators/Stoat.ts
47
+ var import_reflect_metadata = require("reflect-metadata");
48
+
49
+ // src/decorators/keys.ts
50
+ var METADATA_KEYS = {
51
+ IS_STOAT_CLASS: /* @__PURE__ */ Symbol("mally:stoat:isClass"),
52
+ SIMPLE_COMMANDS: /* @__PURE__ */ Symbol("mally:stoat:simpleCommands"),
53
+ GUARDS: "mally:command:guards"
54
+ };
55
+
56
+ // src/decorators/store.ts
57
+ var DecoratorStore = class _DecoratorStore {
58
+ constructor() {
59
+ /** Stoat classes with their SimpleCommand methods */
60
+ this.stoatClasses = /* @__PURE__ */ new Map();
61
+ /** Registered commands from @Stoat/@SimpleCommand decorators */
62
+ this.commands = [];
63
+ /** Whether the store has been initialized */
64
+ this.initialized = false;
65
+ }
66
+ static getInstance() {
67
+ if (!_DecoratorStore.instance) {
68
+ _DecoratorStore.instance = new _DecoratorStore();
69
+ }
70
+ return _DecoratorStore.instance;
71
+ }
72
+ /**
73
+ * Register a @Stoat decorated class
74
+ */
75
+ registerStoatClass(classConstructor) {
76
+ if (!this.stoatClasses.has(classConstructor)) {
77
+ const instance = new classConstructor();
78
+ this.stoatClasses.set(classConstructor, instance);
79
+ }
80
+ }
81
+ /**
82
+ * Get all registered Stoat classes with their instances
83
+ */
84
+ getStoatClasses() {
85
+ return this.stoatClasses;
86
+ }
87
+ /**
88
+ * Add a registered command
89
+ */
90
+ addCommand(command) {
91
+ this.commands.push(command);
92
+ }
93
+ /**
94
+ * Get all registered commands
95
+ */
96
+ getCommands() {
97
+ return this.commands;
98
+ }
99
+ /**
100
+ * Clear all registered classes (useful for testing)
101
+ */
102
+ clear() {
103
+ this.stoatClasses.clear();
104
+ this.commands = [];
105
+ this.initialized = false;
106
+ }
107
+ /**
108
+ * Mark as initialized
109
+ */
110
+ markInitialized() {
111
+ this.initialized = true;
112
+ }
113
+ /**
114
+ * Check if initialized
115
+ */
116
+ isInitialized() {
117
+ return this.initialized;
118
+ }
119
+ };
120
+ var decoratorStore = DecoratorStore.getInstance();
121
+
122
+ // src/decorators/Stoat.ts
123
+ function Stoat() {
124
+ return (target) => {
125
+ Reflect.defineMetadata(METADATA_KEYS.IS_STOAT_CLASS, true, target);
126
+ decoratorStore.registerStoatClass(target);
127
+ };
128
+ }
129
+ function isStoatClass(target) {
130
+ return Reflect.getMetadata(METADATA_KEYS.IS_STOAT_CLASS, target) === true;
131
+ }
132
+
133
+ // src/decorators/SimpleCommand.ts
134
+ var import_reflect_metadata2 = require("reflect-metadata");
135
+ function SimpleCommand(options = {}) {
136
+ return (target, propertyKey, descriptor) => {
137
+ const constructor = target.constructor;
138
+ const existingCommands = Reflect.getMetadata(METADATA_KEYS.SIMPLE_COMMANDS, constructor) || [];
139
+ existingCommands.push({
140
+ methodName: String(propertyKey),
141
+ options
142
+ });
143
+ Reflect.defineMetadata(METADATA_KEYS.SIMPLE_COMMANDS, existingCommands, constructor);
144
+ return descriptor;
145
+ };
146
+ }
147
+ function getSimpleCommands(target) {
148
+ return Reflect.getMetadata(METADATA_KEYS.SIMPLE_COMMANDS, target) || [];
149
+ }
150
+
151
+ // src/decorators/Guard.ts
152
+ var import_reflect_metadata3 = require("reflect-metadata");
153
+ function Guard(guardClass) {
154
+ return (target) => {
155
+ const existingGuards = Reflect.getMetadata(METADATA_KEYS.GUARDS, target) || [];
156
+ existingGuards.push(guardClass);
157
+ Reflect.defineMetadata(METADATA_KEYS.GUARDS, existingGuards, target);
158
+ };
159
+ }
160
+ function getGuards(target) {
161
+ return Reflect.getMetadata(METADATA_KEYS.GUARDS, target) || [];
162
+ }
163
+
164
+ // src/decorators/utils.ts
165
+ function buildSimpleCommandMetadata(options, methodName, category) {
166
+ return {
167
+ name: options.name ?? methodName.toLowerCase(),
168
+ description: options.description ?? "No description provided",
169
+ aliases: options.aliases ?? [],
170
+ permissions: options.permissions ?? [],
171
+ category: options.category ?? category ?? "uncategorized",
172
+ cooldown: options.cooldown ?? 0,
173
+ nsfw: options.nsfw ?? false,
174
+ ownerOnly: options.ownerOnly ?? false
175
+ };
176
+ }
177
+
178
+ // src/registry.ts
179
+ var path = __toESM(require("path"));
180
+ var fs = __toESM(require("fs/promises"));
181
+ var import_node_url = require("url");
182
+ var import_tinyglobby = require("tinyglobby");
183
+ var _CommandRegistry = class _CommandRegistry {
184
+ constructor(extensions = [".js", ".mjs", ".cjs"]) {
185
+ this.commands = /* @__PURE__ */ new Map();
186
+ this.aliases = /* @__PURE__ */ new Map();
187
+ this.processedStoatClasses = /* @__PURE__ */ new Set();
188
+ this.extensions = extensions;
189
+ }
190
+ /**
191
+ * Get the number of registered commands
192
+ */
193
+ get size() {
194
+ return this.commands.size;
195
+ }
196
+ /**
197
+ * Load commands from a directory using glob pattern matching
198
+ */
199
+ async loadFromDirectory(directory) {
200
+ const patterns = this.extensions.map((ext) => path.join(directory, "**", `*${ext}`).replace(/\\/g, "/"));
201
+ for (const pattern of patterns) {
202
+ const files = await (0, import_tinyglobby.glob)(pattern, {
203
+ ignore: ["**/*.d.ts", "**/*.test.ts", "**/*.spec.ts"],
204
+ absolute: true
205
+ });
206
+ for (const file of files) {
207
+ await this.loadFile(file, directory);
208
+ }
209
+ }
210
+ console.log(`[Mally] Loaded ${this.commands.size} command(s)`);
211
+ }
212
+ /**
213
+ * Auto-discover command files across one or more roots.
214
+ */
215
+ async autoDiscover(options = {}) {
216
+ const roots = options.roots?.length ? options.roots : [process.cwd()];
217
+ const includePatterns = options.include?.length ? options.include : this.getDefaultAutoDiscoveryPatterns();
218
+ const patterns = roots.flatMap(
219
+ (root) => includePatterns.map((pattern) => path.join(root, pattern).replace(/\\/g, "/"))
220
+ );
221
+ const files = await (0, import_tinyglobby.glob)(patterns, {
222
+ ignore: [..._CommandRegistry.DEFAULT_AUTO_DISCOVERY_IGNORES, ...options.ignore ?? []],
223
+ absolute: true
224
+ });
225
+ const uniqueFiles = [...new Set(files)];
226
+ let candidateFiles = 0;
227
+ for (const file of uniqueFiles) {
228
+ if (!await this.isLikelyCommandModule(file)) {
229
+ continue;
230
+ }
231
+ candidateFiles++;
232
+ const baseDir = roots.find((root) => {
233
+ const relative2 = path.relative(root, file);
234
+ return relative2 && !relative2.startsWith("..") && !path.isAbsolute(relative2);
235
+ }) ?? roots[0];
236
+ await this.loadFile(file, baseDir);
237
+ }
238
+ console.log(`[Mally] Auto-discovered ${candidateFiles} candidate file(s), loaded ${this.commands.size} command(s)`);
239
+ }
240
+ getDefaultAutoDiscoveryPatterns() {
241
+ return this.extensions.map((ext) => `**/*${ext}`);
242
+ }
243
+ async isLikelyCommandModule(filePath) {
244
+ try {
245
+ const source = await fs.readFile(filePath, "utf8");
246
+ return source.includes("Stoat") || source.includes("SimpleCommand") || source.includes("Command") || source.includes("mally:command");
247
+ } catch {
248
+ return true;
249
+ }
250
+ }
251
+ /**
252
+ * Register a command instance
253
+ */
254
+ register(instance, metadata, classConstructor, methodName) {
255
+ const name = metadata.name.toLowerCase();
256
+ if (this.commands.has(name)) {
257
+ console.warn(`[Mally] Duplicate command name: ${name}. Skipping...`);
258
+ return;
259
+ }
260
+ this.validateGuards(classConstructor, metadata.name);
261
+ this.commands.set(name, { instance, metadata, methodName, classConstructor });
262
+ for (const alias of metadata.aliases) {
263
+ const aliasLower = alias.toLowerCase();
264
+ if (this.aliases.has(aliasLower) || this.commands.has(aliasLower)) {
265
+ console.warn(`[Mally] Duplicate alias: ${aliasLower}. Skipping...`);
266
+ continue;
267
+ }
268
+ this.aliases.set(aliasLower, name);
269
+ }
270
+ }
271
+ /**
272
+ * Get a command by name or alias
273
+ */
274
+ get(name) {
275
+ const lowerName = name.toLowerCase();
276
+ const resolvedName = this.aliases.get(lowerName) ?? lowerName;
277
+ return this.commands.get(resolvedName);
278
+ }
279
+ /**
280
+ * Check if a command exists
281
+ */
282
+ has(name) {
283
+ const lowerName = name.toLowerCase();
284
+ return this.commands.has(lowerName) || this.aliases.has(lowerName);
285
+ }
286
+ /**
287
+ * Get all registered commands
288
+ */
289
+ getAll() {
290
+ return Array.from(this.commands.values());
291
+ }
292
+ /**
293
+ * Get all command metadata
294
+ */
295
+ getAllMetadata() {
296
+ return this.getAll().map((c) => c.metadata);
297
+ }
298
+ /**
299
+ * Get commands grouped by category
300
+ */
301
+ getByCategory() {
302
+ const categories = /* @__PURE__ */ new Map();
303
+ for (const cmd of this.commands.values()) {
304
+ const category = cmd.metadata.category;
305
+ const existing = categories.get(category) ?? [];
306
+ existing.push(cmd);
307
+ categories.set(category, existing);
308
+ }
309
+ return categories;
310
+ }
311
+ /**
312
+ * Clear all commands
313
+ */
314
+ clear() {
315
+ this.commands.clear();
316
+ this.aliases.clear();
317
+ this.processedStoatClasses.clear();
318
+ }
319
+ /**
320
+ * Iterate over commands
321
+ */
322
+ [Symbol.iterator]() {
323
+ return this.commands.entries();
324
+ }
325
+ /**
326
+ * Iterate over command values
327
+ */
328
+ values() {
329
+ return this.commands.values();
330
+ }
331
+ /**
332
+ * Iterate over command names
333
+ */
334
+ keys() {
335
+ return this.commands.keys();
336
+ }
337
+ /**
338
+ * Validate that all guards on a command implement the required methods
339
+ * @param commandClass
340
+ * @param commandName
341
+ * @private
342
+ */
343
+ validateGuards(commandClass, commandName) {
344
+ const guards = Reflect.getMetadata("mally:command:guards", commandClass) || [];
345
+ for (const GuardClass of guards) {
346
+ const guardInstance = new GuardClass();
347
+ if (typeof guardInstance.run !== "function") {
348
+ console.error(
349
+ `[Mally] FATAL: Guard "${GuardClass.name}" on command "${commandName}" does not have a run() method.`
350
+ );
351
+ process.exit(1);
352
+ }
353
+ if (typeof guardInstance.guardFail !== "function") {
354
+ console.error(
355
+ `[Mally] FATAL: Guard "${GuardClass.name}" on command "${commandName}" does not have a guardFail() method.`
356
+ );
357
+ console.error(`[Mally] All guards must implement guardFail() to handle failed checks.`);
358
+ process.exit(1);
359
+ }
360
+ }
361
+ }
362
+ /**
363
+ * Load commands from a single file
364
+ */
365
+ async loadFile(filePath, baseDir) {
366
+ try {
367
+ const knownStoatClasses = new Set(decoratorStore.getStoatClasses().keys());
368
+ const fileUrl = (0, import_node_url.pathToFileURL)(filePath).href;
369
+ await import(fileUrl);
370
+ const allStoatClasses = decoratorStore.getStoatClasses();
371
+ for (const [stoatClass, stoatInstance] of allStoatClasses.entries()) {
372
+ if (knownStoatClasses.has(stoatClass) || this.processedStoatClasses.has(stoatClass)) {
373
+ continue;
374
+ }
375
+ this.registerStoatClassCommands(stoatClass, stoatInstance, filePath, baseDir);
376
+ }
377
+ } catch (error) {
378
+ console.error(`[Mally] Failed to load command file: ${filePath}`, error);
379
+ }
380
+ }
381
+ registerStoatClassCommands(stoatClass, instance, filePath, baseDir) {
382
+ const simpleCommands = getSimpleCommands(stoatClass);
383
+ const category = this.getCategoryFromPath(filePath, baseDir);
384
+ if (simpleCommands.length === 0) {
385
+ console.warn(
386
+ `[Mally] Class ${stoatClass.name} is decorated with @Stoat but has no @SimpleCommand methods. Skipping...`
387
+ );
388
+ this.processedStoatClasses.add(stoatClass);
389
+ return;
390
+ }
391
+ for (const cmdDef of simpleCommands) {
392
+ const method = instance[cmdDef.methodName];
393
+ if (typeof method !== "function") {
394
+ console.warn(`[Mally] Method ${cmdDef.methodName} not found on ${stoatClass.name}. Skipping...`);
395
+ continue;
396
+ }
397
+ const metadata = buildSimpleCommandMetadata(cmdDef.options, cmdDef.methodName, category);
398
+ this.register(instance, metadata, stoatClass, cmdDef.methodName);
399
+ }
400
+ this.processedStoatClasses.add(stoatClass);
401
+ }
402
+ /**
403
+ * Derive category from file path relative to base directory
404
+ */
405
+ getCategoryFromPath(filePath, baseDir) {
406
+ const relative2 = path.relative(baseDir, filePath);
407
+ const parts = relative2.split(path.sep);
408
+ if (parts.length > 1) {
409
+ return parts[0];
410
+ }
411
+ return void 0;
412
+ }
413
+ };
414
+ _CommandRegistry.DEFAULT_AUTO_DISCOVERY_IGNORES = [
415
+ "**/node_modules/**",
416
+ "**/.git/**",
417
+ "**/*.d.ts",
418
+ "**/*.test.*",
419
+ "**/*.spec.*"
420
+ ];
421
+ var CommandRegistry = _CommandRegistry;
422
+
423
+ // src/handler.ts
424
+ var import_reflect_metadata4 = require("reflect-metadata");
425
+ var MallyHandler = class {
426
+ constructor(options) {
427
+ this.cooldowns = /* @__PURE__ */ new Map();
428
+ this.client = options.client;
429
+ this.commandsDir = options.commandsDir;
430
+ this.discoveryOptions = options.discovery;
431
+ this.prefixResolver = options.prefix;
432
+ this.owners = new Set(options.owners ?? []);
433
+ this.registry = new CommandRegistry(options.extensions);
434
+ this.disableMentionPrefix = options.disableMentionPrefix ?? false;
435
+ }
436
+ /**
437
+ * Initialize the handler - load all commands
438
+ */
439
+ async init() {
440
+ if (this.commandsDir) {
441
+ await this.registry.loadFromDirectory(this.commandsDir);
442
+ return;
443
+ }
444
+ await this.registry.autoDiscover(this.discoveryOptions);
445
+ }
446
+ /**
447
+ * Parse a raw message into command context
448
+ */
449
+ async parseMessage(rawContent, message, meta) {
450
+ const prefix = await this.resolvePrefix(meta.serverId);
451
+ let usedPrefix = prefix;
452
+ let withoutPrefix = "";
453
+ if (rawContent.startsWith(prefix)) {
454
+ withoutPrefix = rawContent.slice(prefix.length).trim();
455
+ usedPrefix = prefix;
456
+ } else if (!this.disableMentionPrefix && rawContent.match(/^<@!?[\w]+>/)) {
457
+ const mentionMatch = rawContent.match(/^<@!?([\w]+)>\s*/);
458
+ if (mentionMatch) {
459
+ const mentionedId = mentionMatch[1];
460
+ const botId = this.client.user?.id;
461
+ if (botId && mentionedId === botId) {
462
+ usedPrefix = mentionMatch[0];
463
+ withoutPrefix = rawContent.slice(mentionMatch[0].length).trim();
464
+ } else {
465
+ }
466
+ }
467
+ }
468
+ if (!withoutPrefix) {
469
+ return null;
470
+ }
471
+ const [commandName, ...args] = withoutPrefix.split(/\s+/);
472
+ if (!commandName) {
473
+ return null;
474
+ }
475
+ return {
476
+ client: this.client,
477
+ content: rawContent,
478
+ authorId: meta.authorId,
479
+ channelId: meta.channelId,
480
+ serverId: meta.serverId,
481
+ args,
482
+ prefix: usedPrefix,
483
+ commandName: commandName.toLowerCase(),
484
+ reply: meta.reply,
485
+ message
486
+ };
487
+ }
488
+ /**
489
+ * Handle a message object using the configured message adapter
490
+ *
491
+ * @example
492
+ * ```ts
493
+ * // With message adapter configured
494
+ * client.on('messageCreate', (message) => {
495
+ * handler.handle(message);
496
+ * });
497
+ * ```
498
+ */
499
+ async handle(message) {
500
+ if (!message.channel || !message.author) {
501
+ return false;
502
+ }
503
+ if (message.author.bot) {
504
+ return false;
505
+ }
506
+ const rawContent = message.content;
507
+ const authorId = message.author.id;
508
+ const channelId = message.channel.id;
509
+ const serverId = message.server?.id;
510
+ const reply = async (content) => {
511
+ await message.channel.sendMessage(content);
512
+ };
513
+ return this.handleMessage(rawContent, message, {
514
+ authorId,
515
+ channelId,
516
+ serverId,
517
+ reply
518
+ });
519
+ }
520
+ /**
521
+ * Handle a raw message string with metadata
522
+ *
523
+ * @example
524
+ * ```ts
525
+ * // Manual usage without message adapter
526
+ * client.on('messageCreate', (message) => {
527
+ * handler.handleMessage(message.content, message, {
528
+ * authorId: message.author.id,
529
+ * channelId: message.channel.id,
530
+ * serverId: message.server?.id,
531
+ * reply: (content) => message.channel.sendMessage(content),
532
+ * });
533
+ * });
534
+ * ```
535
+ */
536
+ async handleMessage(rawContent, message, meta) {
537
+ const ctx = await this.parseMessage(rawContent, message, meta);
538
+ if (!ctx) {
539
+ return false;
540
+ }
541
+ return this.execute(ctx);
542
+ }
543
+ /**
544
+ * Execute a command with the given context
545
+ */
546
+ async execute(ctx) {
547
+ const registered = this.registry.get(ctx.commandName);
548
+ if (!registered) {
549
+ return false;
550
+ }
551
+ const { instance, metadata, methodName, classConstructor } = registered;
552
+ if (metadata.ownerOnly && !this.owners.has(ctx.authorId)) {
553
+ await ctx.reply("This command is owner-only.");
554
+ return false;
555
+ }
556
+ const guards = Reflect.getMetadata("mally:command:guards", classConstructor) || [];
557
+ for (const guardClass of guards) {
558
+ const guardInstance = new guardClass();
559
+ if (typeof guardInstance.run === "function") {
560
+ const guardResult = await guardInstance.run(ctx);
561
+ if (!guardResult) {
562
+ if (typeof guardInstance.guardFail === "function") {
563
+ await guardInstance.guardFail(ctx);
564
+ } else {
565
+ console.error("[Mally] Guard check failed but no guardFail method defined on", guardClass.name);
566
+ }
567
+ return false;
568
+ }
569
+ }
570
+ }
571
+ if (!this.checkCooldown(ctx.authorId, metadata)) {
572
+ const remaining = this.getRemainingCooldown(ctx.authorId, metadata);
573
+ if (typeof instance.onCooldown === "function") {
574
+ await instance.onCooldown(ctx, remaining);
575
+ } else {
576
+ await ctx.reply(`Please wait ${(remaining / 1e3).toFixed(1)} seconds before using this command again.`);
577
+ }
578
+ return false;
579
+ }
580
+ try {
581
+ await instance[methodName](ctx);
582
+ if (metadata.cooldown > 0) {
583
+ this.setCooldown(ctx.authorId, metadata);
584
+ }
585
+ return true;
586
+ } catch (error) {
587
+ if (typeof instance.onError === "function") {
588
+ await instance.onError(ctx, error);
589
+ } else {
590
+ console.error(`[Mally] Error in command ${metadata.name}:`, error);
591
+ await ctx.reply(`An error occurred: ${error.message}`);
592
+ }
593
+ return false;
594
+ }
595
+ }
596
+ /**
597
+ * Get the command registry
598
+ */
599
+ getRegistry() {
600
+ return this.registry;
601
+ }
602
+ /**
603
+ * Get a command by name or alias
604
+ */
605
+ getCommand(name) {
606
+ return this.registry.get(name);
607
+ }
608
+ /**
609
+ * Get all commands
610
+ */
611
+ getCommands() {
612
+ return this.registry.getAll();
613
+ }
614
+ /**
615
+ * Reload all commands
616
+ */
617
+ async reload() {
618
+ this.registry.clear();
619
+ this.cooldowns.clear();
620
+ if (this.commandsDir) {
621
+ await this.registry.loadFromDirectory(this.commandsDir);
622
+ return;
623
+ }
624
+ await this.registry.autoDiscover(this.discoveryOptions);
625
+ }
626
+ /**
627
+ * Check if a user is an owner
628
+ */
629
+ isOwner(userId) {
630
+ return this.owners.has(userId);
631
+ }
632
+ /**
633
+ * Add an owner
634
+ */
635
+ addOwner(userId) {
636
+ this.owners.add(userId);
637
+ }
638
+ /**
639
+ * Remove an owner
640
+ */
641
+ removeOwner(userId) {
642
+ this.owners.delete(userId);
643
+ }
644
+ /**
645
+ * Resolve the prefix for a context
646
+ */
647
+ async resolvePrefix(serverId) {
648
+ if (typeof this.prefixResolver === "function") {
649
+ return this.prefixResolver({ serverId });
650
+ }
651
+ return this.prefixResolver;
652
+ }
653
+ /**
654
+ * Check if user is on cooldown
655
+ */
656
+ checkCooldown(userId, metadata) {
657
+ if (metadata.cooldown <= 0) return true;
658
+ const commandCooldowns = this.cooldowns.get(metadata.name);
659
+ if (!commandCooldowns) return true;
660
+ const userCooldown = commandCooldowns.get(userId);
661
+ if (!userCooldown) return true;
662
+ return Date.now() >= userCooldown;
663
+ }
664
+ /**
665
+ * Get remaining cooldown time in ms
666
+ */
667
+ getRemainingCooldown(userId, metadata) {
668
+ const commandCooldowns = this.cooldowns.get(metadata.name);
669
+ if (!commandCooldowns) return 0;
670
+ const userCooldown = commandCooldowns.get(userId);
671
+ if (!userCooldown) return 0;
672
+ return Math.max(0, userCooldown - Date.now());
673
+ }
674
+ /**
675
+ * Set cooldown for a user
676
+ */
677
+ setCooldown(userId, metadata) {
678
+ if (!this.cooldowns.has(metadata.name)) {
679
+ this.cooldowns.set(metadata.name, /* @__PURE__ */ new Map());
680
+ }
681
+ const commandCooldowns = this.cooldowns.get(metadata.name);
682
+ commandCooldowns.set(userId, Date.now() + metadata.cooldown);
683
+ }
684
+ };
685
+ // Annotate the CommonJS export names for ESM import in node:
686
+ 0 && (module.exports = {
687
+ CommandRegistry,
688
+ Guard,
689
+ METADATA_KEYS,
690
+ MallyHandler,
691
+ SimpleCommand,
692
+ Stoat,
693
+ buildSimpleCommandMetadata,
694
+ getGuards,
695
+ getSimpleCommands,
696
+ isStoatClass
697
+ });