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