stoatx 0.8.0 → 1.0.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.d.mts +199 -211
- package/dist/index.d.ts +199 -211
- package/dist/index.js +513 -395
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +497 -392
- package/dist/index.mjs.map +1 -1
- package/package.json +3 -3
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/decorators/Stoat.ts","../src/decorators/keys.ts","../src/decorators/store.ts","../src/decorators/SimpleCommand.ts","../src/decorators/Guard.ts","../src/decorators/Events.ts","../src/decorators/utils.ts","../src/registry.ts","../src/handler.ts","../src/error.ts","../src/client.ts"],"sourcesContent":["// Types\nexport * from \"./types\";\n\n// Decorators\nexport * from \"./decorators\";\n\n// Registry\nexport * from \"./registry\";\n\n// Handler\nexport { DefaultCooldownManager } from \"./handler\";\nexport { Client } from \"./client\";\nexport type { StoatxHandler } from \"./handler\";\nexport { CommandValidationError } from \"./error\";\nexport * from \"@stoatx/client\";\n","import \"reflect-metadata\";\nimport { METADATA_KEYS } from \"./keys\";\nimport { decoratorStore } from \"./store\";\n\n/**\n * @Stoat\n * Marks a class as a Stoat command container.\n * Use this decorator on classes that contain @SimpleCommand methods.\n *\n * @example\n * ```ts\n * import { Stoat, SimpleCommand, CommandContext } from 'stoatx';\n *\n * @Stoat()\n * class ModerationCommands {\n * @SimpleCommand({ name: 'ban', description: 'Ban a user' })\n * async ban(ctx: CommandContext) {\n * await ctx.reply('User banned!');\n * }\n *\n * @SimpleCommand({ name: 'kick', description: 'Kick a user' })\n * async kick(ctx: CommandContext) {\n * await ctx.reply('User kicked!');\n * }\n * }\n * ```\n */\nexport function Stoat(): ClassDecorator {\n return (target: Function) => {\n Reflect.defineMetadata(METADATA_KEYS.IS_STOAT_CLASS, true, target);\n decoratorStore.registerStoatClass(target);\n };\n}\n\n/**\n * Check if a class is decorated with @Stoat\n */\nexport function isStoatClass(target: Function): boolean {\n return Reflect.getMetadata(METADATA_KEYS.IS_STOAT_CLASS, target) === true;\n}\n","/**\n * Metadata keys used by decorators\n */\nexport const METADATA_KEYS = {\n IS_STOAT_CLASS: Symbol(\"stoatx:stoat:isClass\"),\n SIMPLE_COMMANDS: Symbol(\"stoatx:stoat:simpleCommands\"),\n GUARDS: \"stoatx:command:guards\",\n EVENTS: Symbol(\"stoatx:stoat:events\"),\n} as const;\n","import type { RegisteredCommand } from \"../registry\";\n\n/**\n * Global store for all decorated classes and commands\n * This allows automatic registration without directory scanning\n */\nexport class DecoratorStore {\n private static instance: DecoratorStore;\n\n /** Stoat classes with their SimpleCommand methods */\n private stoatClasses: Map<Function, object> = new Map();\n\n /** Registered commands from @Stoat/@SimpleCommand decorators */\n private commands: RegisteredCommand[] = [];\n\n /** Whether the store has been initialized */\n private initialized = false;\n\n private constructor() {}\n\n static getInstance(): DecoratorStore {\n if (!DecoratorStore.instance) {\n DecoratorStore.instance = new DecoratorStore();\n }\n return DecoratorStore.instance;\n }\n\n /**\n * Register a @Stoat decorated class\n */\n registerStoatClass(classConstructor: Function): void {\n if (!this.stoatClasses.has(classConstructor)) {\n // Create instance immediately when decorated\n const instance = new (classConstructor as new () => object)();\n this.stoatClasses.set(classConstructor, instance);\n }\n }\n\n /**\n * Get all registered Stoat classes with their instances\n */\n getStoatClasses(): Map<Function, object> {\n return this.stoatClasses;\n }\n\n /**\n * Add a registered command\n */\n addCommand(command: RegisteredCommand): void {\n this.commands.push(command);\n }\n\n /**\n * Get all registered commands\n */\n getCommands(): RegisteredCommand[] {\n return this.commands;\n }\n\n /**\n * Clear all registered classes (useful for testing)\n */\n clear(): void {\n this.stoatClasses.clear();\n this.commands = [];\n this.initialized = false;\n }\n\n /**\n * Mark as initialized\n */\n markInitialized(): void {\n this.initialized = true;\n }\n\n /**\n * Check if initialized\n */\n isInitialized(): boolean {\n return this.initialized;\n }\n}\n\nexport const decoratorStore = DecoratorStore.getInstance();\n","import \"reflect-metadata\";\nimport type { CommandContext, SimpleCommandOptions } from \"../types\";\nimport { METADATA_KEYS } from \"./keys\";\n\n/**\n * Stored simple command metadata from method decorator\n */\nexport interface SimpleCommandDefinition {\n methodName: string;\n options: SimpleCommandOptions;\n}\n\ntype CommandMethod = (ctx: CommandContext) => Promise<void>;\n\n/**\n * @SimpleCommand\n * Marks a method as a simple command within a @Stoat() decorated class.\n *\n * @example\n * ```ts\n * @Stoat()\n * class Example {\n * @SimpleCommand({ name: 'ping', description: 'Replies with Pong!' })\n * async ping(ctx: CommandContext) {\n * await ctx.reply('Pong!');\n * }\n *\n * @SimpleCommand({ aliases: ['perm'], name: 'permission' })\n * async permission(ctx: CommandContext) {\n * await ctx.reply('Access granted');\n * }\n * }\n * ```\n */\nexport function SimpleCommand(options: SimpleCommandOptions = {}) {\n return <T extends CommandMethod>(\n target: Object,\n propertyKey: string | symbol,\n descriptor: TypedPropertyDescriptor<T>,\n ) => {\n const constructor = target.constructor;\n\n const existingCommands: SimpleCommandDefinition[] =\n Reflect.getMetadata(METADATA_KEYS.SIMPLE_COMMANDS, constructor) || [];\n\n existingCommands.push({\n methodName: String(propertyKey),\n options,\n });\n\n Reflect.defineMetadata(METADATA_KEYS.SIMPLE_COMMANDS, existingCommands, constructor);\n\n return descriptor;\n };\n}\n\n/**\n * Get all simple command definitions from a @Stoat class\n */\nexport function getSimpleCommands(target: Function): SimpleCommandDefinition[] {\n return Reflect.getMetadata(METADATA_KEYS.SIMPLE_COMMANDS, target) || [];\n}\n","import \"reflect-metadata\";\nimport { METADATA_KEYS } from \"./keys\";\n\n/**\n * @Guard\n * Runs before a command to check if it should execute.\n * Should return true to allow execution, false to block.\n * Applied on @Stoat classes to guard all contained @SimpleCommand methods.\n *\n * @example\n * ```ts\n * import { Guard, Stoat, SimpleCommand, CommandContext } from 'stoatx';\n *\n * // Define a guard\n * class NotBot implements StoatxGuard {\n * run(ctx: CommandContext): boolean {\n * return !ctx.message.author.bot;\n * }\n *\n * guardFail(ctx: CommandContext): void {\n * ctx.reply(\"Bots cannot use this command!\");\n * }\n * }\n *\n * @Stoat()\n * @Guard(NotBot)\n * class AdminCommands {\n * @SimpleCommand({ name: 'admin', description: 'Admin only command' })\n * async admin(ctx: CommandContext) {\n * ctx.reply(\"You passed the guard check!\");\n * }\n * }\n * ```\n */\nexport function Guard(guardClass: Function): ClassDecorator {\n return (target: Function) => {\n const existingGuards: Function[] = Reflect.getMetadata(METADATA_KEYS.GUARDS, target) || [];\n existingGuards.push(guardClass);\n Reflect.defineMetadata(METADATA_KEYS.GUARDS, existingGuards, target);\n };\n}\n\n/**\n * Get all guards from a decorated class\n */\nexport function getGuards(target: Function): Function[] {\n return Reflect.getMetadata(METADATA_KEYS.GUARDS, target) || [];\n}\n","import \"reflect-metadata\";\nimport { METADATA_KEYS } from \"./keys\";\n\nexport interface EventDefinition {\n methodName: string;\n event: string;\n type: \"on\" | \"once\";\n}\n\nfunction createEventDecorator(event: string, type: \"on\" | \"once\"): MethodDecorator {\n return (target: Object, propertyKey: string | symbol, descriptor: PropertyDescriptor) => {\n const constructor = target.constructor;\n\n // Retrieve existing events or initialize a fresh array\n const existingEvents: EventDefinition[] = Reflect.getMetadata(METADATA_KEYS.EVENTS, constructor) || [];\n\n existingEvents.push({\n methodName: String(propertyKey),\n event,\n type,\n });\n\n Reflect.defineMetadata(METADATA_KEYS.EVENTS, existingEvents, constructor);\n\n return descriptor;\n };\n}\n\n/**\n * @On\n * Triggered on every occurrence of the event.\n * Marks a method to be executed whenever the specified client event is emitted.\n *\n * @example\n * ```ts\n * import { Stoat, On } from 'stoatx';\n * import { Message, Client } from 'stoat.js';\n *\n * @Stoat()\n * class BotEvents {\n * @On('messageCreate')\n * async onMessage(message: Message, client: Client) {\n * console.log('New message received:', message.content);\n * }\n * }\n * ```\n *\n * @param event The name of the client event to listen to\n */\nexport function On(event: string): MethodDecorator {\n return createEventDecorator(event, \"on\");\n}\n\n/**\n * @Once\n * Triggered only fully once.\n * Marks a method to be executed only the FIRST time the specified client event is emitted.\n *\n * @example\n * ```ts\n * import { Stoat, Once } from 'stoatx';\n * import { Client } from 'stoat.js';\n *\n * @Stoat()\n * class BotEvents {\n * @Once('ready')\n * async onReady(client: Client) {\n * console.log('Bot successfully started and logged in!');\n * }\n * }\n * ```\n *\n * @param event The name of the client event to listen to\n */\nexport function Once(event: string): MethodDecorator {\n return createEventDecorator(event, \"once\");\n}\n\n/**\n * Get all event definitions from a @Stoat class\n */\nexport function getEventsMetadata(target: Function): EventDefinition[] {\n return Reflect.getMetadata(METADATA_KEYS.EVENTS, target) || [];\n}\n","import type { CommandMetadata, SimpleCommandOptions } from \"../types\";\n\n/**\n * Build CommandMetadata from SimpleCommandOptions\n */\nexport function buildSimpleCommandMetadata(\n options: SimpleCommandOptions,\n methodName: string,\n category?: string,\n): CommandMetadata {\n return {\n name: options.name ?? methodName.toLowerCase(),\n description: options.description ?? \"No description provided\",\n aliases: options.aliases ?? [],\n permissions: options.permissions ?? [],\n category: options.category ?? category ?? \"uncategorized\",\n cooldown: options.cooldown ?? 0,\n ...(options.cooldownStorage !== undefined ? { cooldownStorage: options.cooldownStorage } : {}),\n nsfw: options.nsfw ?? false,\n ownerOnly: options.ownerOnly ?? false,\n options: options.options ?? [],\n args: options.args ?? [],\n };\n}\n","import * as path from \"node:path\";\nimport * as fs from \"node:fs/promises\";\nimport { pathToFileURL } from \"node:url\";\nimport { glob } from \"tinyglobby\";\nimport { buildSimpleCommandMetadata, getSimpleCommands, getEventsMetadata } from \"./decorators\";\nimport { decoratorStore } from \"./decorators/store\";\nimport type { CommandMetadata } from \"./types\";\n\ninterface AutoDiscoveryOptions {\n roots?: string[];\n include?: string[];\n ignore?: string[];\n}\n\n/**\n * Stored command entry from @Stoat/@SimpleCommand registration.\n */\nexport interface RegisteredCommand {\n /** Instance of the @Stoat class */\n instance: object;\n /** Command metadata */\n metadata: CommandMetadata;\n /** Method name to call */\n methodName: string;\n /** The original class constructor (for guard validation) */\n classConstructor: Function;\n}\n\n/**\n * Stored event entry from @On/@Once registration.\n */\nexport interface RegisteredEvent {\n instance: object;\n methodName: string;\n event: string;\n type: \"on\" | \"once\";\n}\n\n/**\n * CommandRegistry - Scans directories and stores commands in a Map\n *\n * @example\n * ```ts\n * const registry = new CommandRegistry();\n * await registry.loadFromDirectory('./src/commands');\n *\n * const ping = registry.get('ping');\n * const allCommands = registry.getAll();\n * ```\n */\nexport class CommandRegistry {\n private static readonly DEFAULT_AUTO_DISCOVERY_IGNORES = [\n \"**/node_modules/**\",\n \"**/.git/**\",\n \"**/*.d.ts\",\n \"**/*.test.*\",\n \"**/*.spec.*\",\n ];\n\n private readonly commands: Map<string, RegisteredCommand> = new Map();\n private readonly aliases: Map<string, string> = new Map();\n private readonly registeredEvents: RegisteredEvent[] = [];\n private readonly extensions: string[];\n private readonly processedStoatClasses: Set<Function> = new Set();\n\n constructor(extensions: string[] = [\".js\", \".mjs\", \".cjs\"]) {\n this.extensions = extensions;\n }\n\n /**\n * Get the number of registered commands\n */\n get size(): number {\n return this.commands.size;\n }\n\n /**\n * Load commands from a directory using glob pattern matching\n */\n async loadFromDirectory(directory: string): Promise<void> {\n const patterns = this.extensions.map((ext) => path.join(directory, \"**\", `*${ext}`).replace(/\\\\/g, \"/\"));\n\n for (const pattern of patterns) {\n const files = await glob(pattern, {\n ignore: [\"**/*.d.ts\", \"**/*.test.ts\", \"**/*.spec.ts\"],\n absolute: true,\n });\n\n for (const file of files) {\n await this.loadFile(file, directory);\n }\n }\n\n console.log(`[Stoatx] Loaded ${this.commands.size} command(s) and ${this.registeredEvents.length} event(s)`);\n }\n\n /**\n * Auto-discover command files across one or more roots.\n */\n async autoDiscover(options: AutoDiscoveryOptions = {}): Promise<void> {\n const roots = options.roots?.length ? options.roots : [process.cwd()];\n const includePatterns = options.include?.length ? options.include : this.getDefaultAutoDiscoveryPatterns();\n\n const patterns = roots.flatMap((root) =>\n includePatterns.map((pattern) => path.join(root, pattern).replace(/\\\\/g, \"/\")),\n );\n\n const files = await glob(patterns, {\n ignore: [...CommandRegistry.DEFAULT_AUTO_DISCOVERY_IGNORES, ...(options.ignore ?? [])],\n absolute: true,\n });\n\n const uniqueFiles = [...new Set(files)];\n let candidateFiles = 0;\n for (const file of uniqueFiles) {\n if (!(await this.isLikelyCommandModule(file))) {\n continue;\n }\n candidateFiles++;\n\n const baseDir =\n roots.find((root) => {\n const relative = path.relative(root, file);\n return relative && !relative.startsWith(\"..\") && !path.isAbsolute(relative);\n }) ?? roots[0]!;\n await this.loadFile(file, baseDir);\n }\n\n console.log(`[Stoatx] Loaded ${this.commands.size} command(s) and ${this.registeredEvents.length} event(s)`);\n }\n\n private getDefaultAutoDiscoveryPatterns(): string[] {\n // discordx-like default: scan broadly, then register only decorated classes\n return this.extensions.map((ext) => `**/*${ext}`);\n }\n\n private async isLikelyCommandModule(filePath: string): Promise<boolean> {\n try {\n const source = await fs.readFile(filePath, \"utf8\");\n return source.includes(\"Stoat\") || source.includes(\"SimpleCommand\") || source.includes(\"stoatx:command\");\n } catch {\n // If the file can't be pre-read, fall back to attempting import.\n return true;\n }\n }\n\n /**\n * Register a command instance\n */\n register(instance: object, metadata: CommandMetadata, classConstructor: Function, methodName: string): void {\n const name = metadata.name.toLowerCase();\n\n if (this.commands.has(name)) {\n console.warn(`[Stoatx] Duplicate command name: ${name}. Skipping...`);\n return;\n }\n\n this.validateGuards(classConstructor, metadata.name);\n\n this.commands.set(name, { instance, metadata, methodName, classConstructor });\n\n for (const alias of metadata.aliases) {\n const aliasLower = alias.toLowerCase();\n if (this.aliases.has(aliasLower) || this.commands.has(aliasLower)) {\n console.warn(`[Stoatx] Duplicate alias: ${aliasLower}. Skipping...`);\n continue;\n }\n this.aliases.set(aliasLower, name);\n }\n }\n\n /**\n * Get a command by name or alias\n */\n get(name: string): RegisteredCommand | undefined {\n const lowerName = name.toLowerCase();\n const resolvedName = this.aliases.get(lowerName) ?? lowerName;\n return this.commands.get(resolvedName);\n }\n\n /**\n * Check if a command exists\n */\n has(name: string): boolean {\n const lowerName = name.toLowerCase();\n return this.commands.has(lowerName) || this.aliases.has(lowerName);\n }\n\n /**\n * Get all registered commands\n */\n getAll(): RegisteredCommand[] {\n return Array.from(this.commands.values());\n }\n\n /**\n * Get all command metadata\n */\n getAllMetadata(): CommandMetadata[] {\n return this.getAll().map((c) => c.metadata);\n }\n\n /**\n * Get all registered events\n */\n getEvents(): RegisteredEvent[] {\n return this.registeredEvents;\n }\n\n /**\n * Get commands grouped by category\n */\n getByCategory(): Map<string, RegisteredCommand[]> {\n const categories = new Map<string, RegisteredCommand[]>();\n\n for (const cmd of this.commands.values()) {\n const category = cmd.metadata.category;\n const existing = categories.get(category) ?? [];\n existing.push(cmd);\n categories.set(category, existing);\n }\n\n return categories;\n }\n\n /**\n * Clear all commands\n */\n clear(): void {\n this.commands.clear();\n this.aliases.clear();\n this.registeredEvents.length = 0;\n this.processedStoatClasses.clear();\n }\n\n /**\n * Iterate over commands\n */\n [Symbol.iterator](): IterableIterator<[string, RegisteredCommand]> {\n return this.commands.entries();\n }\n\n /**\n * Iterate over command values\n */\n values(): IterableIterator<RegisteredCommand> {\n return this.commands.values();\n }\n\n /**\n * Iterate over command names\n */\n keys(): IterableIterator<string> {\n return this.commands.keys();\n }\n\n /**\n * Validate that all guards on a command implement the required methods\n * @param commandClass\n * @param commandName\n * @private\n */\n private validateGuards(commandClass: Function, commandName: string): void {\n const guards: Function[] = Reflect.getMetadata(\"stoatx:command:guards\", commandClass) || [];\n\n for (const GuardClass of guards) {\n const guardInstance = new (GuardClass as any)();\n\n if (typeof guardInstance.run !== \"function\") {\n console.error(\n `[Stoatx] FATAL: Guard \"${GuardClass.name}\" on command \"${commandName}\" does not have a run() method.`,\n );\n process.exit(1);\n }\n\n if (typeof guardInstance.guardFail !== \"function\") {\n console.error(\n `[Stoatx] FATAL: Guard \"${GuardClass.name}\" on command \"${commandName}\" does not have a guardFail() method.`,\n );\n console.error(`[Stoatx] All guards must implement guardFail() to handle failed checks.`);\n process.exit(1);\n }\n }\n }\n\n /**\n * Load commands from a single file\n */\n private async loadFile(filePath: string, baseDir: string): Promise<void> {\n try {\n const knownStoatClasses = new Set(decoratorStore.getStoatClasses().keys());\n const fileUrl = pathToFileURL(filePath).href;\n await import(fileUrl);\n\n const allStoatClasses = decoratorStore.getStoatClasses();\n for (const [stoatClass, stoatInstance] of allStoatClasses.entries()) {\n if (knownStoatClasses.has(stoatClass) || this.processedStoatClasses.has(stoatClass)) {\n continue;\n }\n this.registerStoatClassCommands(stoatClass, stoatInstance, filePath, baseDir);\n }\n } catch (error) {\n console.error(`[Stoatx] Failed to load command file: ${filePath}`, error);\n }\n }\n\n private registerStoatClassCommands(stoatClass: Function, instance: object, filePath: string, baseDir: string): void {\n const simpleCommands = getSimpleCommands(stoatClass);\n const events = getEventsMetadata(stoatClass);\n const category = this.getCategoryFromPath(filePath, baseDir);\n\n if (simpleCommands.length === 0 && events.length === 0) {\n console.warn(\n `[Stoatx] Class ${stoatClass.name} is decorated with @Stoat but has no @SimpleCommand, @On or @Once methods. Skipping...`,\n );\n this.processedStoatClasses.add(stoatClass);\n return;\n }\n\n for (const cmdDef of simpleCommands) {\n const method = (instance as any)[cmdDef.methodName];\n if (typeof method !== \"function\") {\n console.warn(`[Stoatx] Method ${cmdDef.methodName} not found on ${stoatClass.name}. Skipping...`);\n continue;\n }\n\n const metadata = buildSimpleCommandMetadata(cmdDef.options, cmdDef.methodName, category);\n this.register(instance, metadata, stoatClass, cmdDef.methodName);\n }\n\n for (const eventDef of events) {\n const method = (instance as any)[eventDef.methodName];\n if (typeof method !== \"function\") {\n console.warn(`[Stoatx] Method ${eventDef.methodName} not found on ${stoatClass.name}. Skipping...`);\n continue;\n }\n\n this.registeredEvents.push({\n instance,\n methodName: eventDef.methodName,\n event: eventDef.event,\n type: eventDef.type,\n });\n }\n\n this.processedStoatClasses.add(stoatClass);\n }\n\n /**\n * Derive category from file path relative to base directory\n */\n private getCategoryFromPath(filePath: string, baseDir: string): string | undefined {\n const relative = path.relative(baseDir, filePath);\n const parts = relative.split(path.sep);\n\n if (parts.length > 1) {\n return parts[0];\n }\n\n return undefined;\n }\n}\n","import \"reflect-metadata\";\nimport { CommandRegistry, RegisteredCommand } from \"./registry\";\nimport type {\n CommandContext,\n CommandMetadata,\n StoatxDiscoveryOptions,\n StoatxHandlerOptions,\n CooldownManager,\n} from \"./types\";\nimport { ClientEvents, Message } from \"@stoatx/client\";\nimport { Client } from \"./client\";\nimport { CommandValidationError } from \"./error\";\n\n/**\n * Default in-memory cooldown manager\n */\nexport class DefaultCooldownManager implements CooldownManager {\n private readonly cooldowns: Map<string, Map<string, number>> = new Map();\n\n check(ctx: CommandContext, metadata: CommandMetadata): boolean {\n if (metadata.cooldown <= 0) return true;\n\n const commandCooldowns = this.cooldowns.get(metadata.name);\n if (!commandCooldowns) return true;\n\n const expirationTime = commandCooldowns.get(ctx.authorId);\n if (!expirationTime) return true;\n\n if (Date.now() > expirationTime) {\n commandCooldowns.delete(ctx.authorId);\n return true;\n }\n\n return false;\n }\n\n getRemaining(ctx: CommandContext, metadata: CommandMetadata): number {\n const commandCooldowns = this.cooldowns.get(metadata.name);\n if (!commandCooldowns) return 0;\n\n const userCooldown = commandCooldowns.get(ctx.authorId);\n if (!userCooldown) return 0;\n\n return Math.max(0, userCooldown - Date.now());\n }\n\n set(ctx: CommandContext, metadata: CommandMetadata): void {\n if (!this.cooldowns.has(metadata.name)) {\n this.cooldowns.set(metadata.name, new Map());\n }\n\n const commandCooldowns = this.cooldowns.get(metadata.name)!;\n commandCooldowns.set(ctx.authorId, Date.now() + metadata.cooldown);\n }\n\n clear(): void {\n this.cooldowns.clear();\n }\n}\n\n/**\n * StoatxHandler - The execution engine for commands\n *\n * Handles message parsing, middleware execution, and command dispatching\n *\n * @internal This class is not intended to be instantiated directly. Use the `Client` from `stoatx` instead.\n */\nexport class StoatxHandler {\n private readonly commandsDir: string | undefined;\n private readonly discoveryOptions: StoatxDiscoveryOptions | undefined;\n private readonly prefixResolver: string | ((ctx: { serverId?: string | undefined }) => string | Promise<string>);\n private readonly owners: Set<string>;\n private readonly registry: CommandRegistry;\n private readonly cooldownManager: CooldownManager;\n private readonly disableMentionPrefix: boolean;\n private readonly client: Client;\n private readonly flagPrefix: string;\n constructor(options: StoatxHandlerOptions) {\n this.client = options.client;\n this.commandsDir = options.commandsDir;\n this.discoveryOptions = options.discovery;\n this.prefixResolver = options.prefix;\n this.owners = new Set(options.owners ?? []);\n this.registry = new CommandRegistry(options.extensions);\n this.disableMentionPrefix = options.disableMentionPrefix ?? false;\n this.cooldownManager = options.cooldownManager ?? new DefaultCooldownManager();\n this.flagPrefix = options.flagPrefix || \"-\";\n }\n\n /**\n * Initialize the handler - load all commands\n */\n async init(): Promise<void> {\n if (this.commandsDir) {\n await this.registry.loadFromDirectory(this.commandsDir);\n } else {\n await this.registry.autoDiscover(this.discoveryOptions);\n }\n\n this.attachEvents();\n }\n\n /**\n * Attach registered events to the client\n */\n private attachEvents(): void {\n const events = this.registry.getEvents();\n\n for (const eventDef of events) {\n const handler = async (...args: any[]) => {\n try {\n await (eventDef.instance as any)[eventDef.methodName](...args, this.client);\n } catch (error) {\n console.error(\n `[Stoatx] Event Handler Error in @${eventDef.type === \"on\" ? \"On\" : \"Once\"}('${eventDef.event}'):`,\n error,\n );\n }\n };\n\n const eventName = eventDef.event as keyof ClientEvents;\n if (eventDef.type === \"once\") {\n this.client.once(eventName, handler);\n } else {\n this.client.on(eventName, handler);\n }\n }\n }\n\n /**\n * Parses raw string arguments into positional args and key-value options\n */\n private parseCommandOptions(rawArgs: string[]): { args: string[]; options: Record<string, string | boolean> } {\n const args: string[] = [];\n const options: Record<string, string | boolean> = {};\n\n for (let i = 0; i < rawArgs.length; i++) {\n const arg = rawArgs[i];\n if (arg === undefined) continue;\n\n // Check if it starts with the configured prefix (e.g., \"-\" or \"+\")\n if (arg.startsWith(this.flagPrefix)) {\n let key = arg;\n\n // Strip all leading prefixes (e.g., turns \"++force\" into \"force\")\n while (key.startsWith(this.flagPrefix)) {\n key = key.slice(this.flagPrefix.length);\n }\n\n const nextArg = rawArgs[i + 1];\n\n // Check if next argument exists and is NOT another flag\n if (nextArg !== undefined && !nextArg.startsWith(this.flagPrefix)) {\n options[key] = nextArg;\n i++;\n } else {\n options[key] = true;\n }\n } else {\n args.push(arg);\n }\n }\n\n return { args, options };\n }\n\n /**\n * Parse a raw message into command context\n */\n async parseMessage(\n rawContent: string,\n message: Message,\n meta: {\n authorId: string;\n channelId: string;\n serverId?: string | undefined;\n reply: (content: string) => Promise<Message>;\n },\n ): Promise<CommandContext | null> {\n const prefix = await this.resolvePrefix(meta.serverId);\n let usedPrefix = prefix;\n let withoutPrefix = \"\";\n\n // Check for string prefix\n if (rawContent.startsWith(prefix)) {\n withoutPrefix = rawContent.slice(prefix.length).trim();\n usedPrefix = prefix;\n }\n // Check for mention prefix (e.g., \"<@bot-id> command\") - unless disabled\n else if (!this.disableMentionPrefix && rawContent.match(/^<@!?[\\w]+>/)) {\n const mentionMatch = rawContent.match(/^<@!?([\\w]+)>\\s*/);\n if (mentionMatch) {\n const mentionedId = mentionMatch[1];\n const botId = this.client.user?.id;\n\n // Only process if mentioned user is the bot\n if (botId && mentionedId === botId) {\n usedPrefix = mentionMatch[0];\n withoutPrefix = rawContent.slice(mentionMatch[0].length).trim();\n } else {\n }\n }\n }\n\n if (!withoutPrefix) {\n return null;\n }\n\n const [commandName, ...rawArgs] = withoutPrefix.split(/\\s+/);\n\n if (!commandName) {\n return null;\n }\n\n const { args, options } = this.parseCommandOptions(rawArgs);\n\n return {\n client: this.client,\n content: rawContent,\n authorId: meta.authorId,\n channelId: meta.channelId,\n serverId: meta.serverId,\n args,\n options,\n prefix: usedPrefix,\n commandName: commandName.toLowerCase(),\n reply: meta.reply,\n message,\n };\n }\n\n /**\n * Handle a message object using the configured message adapter\n *\n * @example\n * ```ts\n * // With message adapter configured\n * client.on('messageCreate', (message) => {\n * handler.handle(message);\n * });\n * ```\n */\n async handle(message: Message): Promise<boolean> {\n if (!message.channel || !message.author || !message.content) {\n return false;\n }\n\n // Skip messages from bots\n if (message.author.bot) {\n return false;\n }\n\n const rawContent = message.content;\n const authorId = message.author.id;\n const channelId = message.channel.id;\n const serverId = message.server?.id;\n const reply = async (content: string) => {\n return await message.channel!.send(content);\n };\n\n await this.handleMessage(rawContent, message, {\n authorId,\n channelId,\n serverId,\n reply,\n });\n\n return true;\n }\n\n /**\n * Handle a raw message string with metadata\n *\n * @example\n * ```ts\n * // Manual usage without message adapter\n * client.on('messageCreate', (message) => {\n * handler.handleMessage(message.content, message, {\n * authorId: message.author.id,\n * channelId: message.channel.id,\n * serverId: message.server?.id,\n * reply: (content) => message.channel.sendMessage(content),\n * });\n * });\n * ```\n */\n async handleMessage(\n rawContent: string,\n message: Message,\n meta: {\n authorId: string;\n channelId: string;\n serverId?: string | undefined;\n reply: (content: string) => Promise<Message>;\n },\n ): Promise<void> {\n const ctx = await this.parseMessage(rawContent, message, meta);\n\n if (!ctx) {\n return;\n }\n\n await this.execute(ctx);\n }\n\n /**\n * Execute a command with the given context\n */\n async execute(ctx: CommandContext): Promise<boolean> {\n const registered = this.registry.get(ctx.commandName);\n\n if (!registered) {\n return false;\n }\n\n const { instance, metadata, methodName, classConstructor } = registered;\n console.log(`[Debug] Metadata options for ${ctx.commandName}:`, metadata.options);\n // Owner-only check\n if (metadata.ownerOnly && !this.owners.has(ctx.authorId)) {\n await ctx.reply(\"This command is owner-only.\");\n return false;\n }\n\n // Permissions check\n if (metadata.permissions) {\n const server = ctx.message.server;\n const member = server ? await server.members.fetch(ctx.authorId) : null;\n\n if (!member || !member.permissions.has(metadata.permissions)) {\n if (typeof (instance as any).onMissingPermissions === \"function\") {\n const missing = member?.permissions.missing(metadata.permissions) || [];\n await (instance as any).onMissingPermissions(ctx, missing);\n } else {\n await ctx.reply(\"You do not have permission to use this command.\");\n }\n return false;\n }\n }\n\n // Guard checks - use classConstructor for guard metadata\n const guards: Function[] = Reflect.getMetadata(\"stoatx:command:guards\", classConstructor) || [];\n for (const guardClass of guards) {\n const guardInstance = new (guardClass as any)();\n if (typeof guardInstance.run === \"function\") {\n const guardResult = await guardInstance.run(ctx);\n if (!guardResult) {\n if (typeof guardInstance.guardFail === \"function\") {\n await guardInstance.guardFail(ctx);\n } else {\n console.error(\"[Stoatx] Guard check failed but no guardFail method defined on\", guardClass.name);\n }\n return false;\n }\n }\n }\n\n if (metadata.args) {\n const finalArgs: (string | number | boolean)[] = [];\n\n for (let i = 0; i < metadata.args.length; i++) {\n const def = metadata.args[i];\n // Positional args are read by index\n const rawValue = ctx.args[i] as string | undefined;\n\n if (def === undefined) continue;\n\n // Check if a required argument is missing\n if (rawValue === undefined) {\n if (def.required) {\n try {\n throw new CommandValidationError(def.name, `Missing required argument: \\`<${def.name}>\\``);\n } catch (error) {\n if (typeof (instance as any).onError === \"function\") {\n await (instance as any).onError(ctx, error as Error);\n } else {\n await ctx.reply(`Missing required argument: \\`<${def.name}>\\``);\n }\n return false;\n }\n }\n break; // If a positional arg is missing, everything after it is missing too\n }\n\n // Type Casting and Validation\n if (def.type === \"number\") {\n const numValue = Number(rawValue);\n if (isNaN(numValue)) {\n try {\n throw new CommandValidationError(def.name, `Invalid value for \\`<${def.name}>\\`. Expected a number.`);\n } catch (error) {\n if (typeof (instance as any).onError === \"function\") {\n await (instance as any).onError(ctx, error as Error);\n } else {\n await ctx.reply(`Invalid value for \\`<${def.name}>\\`. Expected a number.`);\n }\n return false;\n }\n }\n finalArgs[i] = numValue;\n } else if (def.type === \"boolean\") {\n finalArgs[i] = rawValue === \"false\" ? false : Boolean(rawValue);\n } else if (def.type === \"user\") {\n const match = String(rawValue).match(/^(?:<@)?([0-7][0-9A-HJKMNP-TV-Z]{25})>?$/i);\n if (!match) {\n try {\n throw new CommandValidationError(def.name, `Invalid user mention for \\`<${def.name}>\\`.`);\n } catch (error) {\n if (typeof (instance as any).onError === \"function\") {\n await (instance as any).onError(ctx, error as Error);\n } else {\n await ctx.reply(`Invalid user mention for \\`<${def.name}>\\`.`);\n }\n return false;\n }\n }\n finalArgs[i] = match[1]!;\n } else if (def.type === \"channel\") {\n const match = String(rawValue).match(/^(?:<#)?([0-7][0-9A-HJKMNP-TV-Z]{25})>?$/i);\n if (!match) {\n try {\n throw new CommandValidationError(def.name, `Invalid channel mention for \\`<${def.name}>\\`.`);\n } catch (error) {\n if (typeof (instance as any).onError === \"function\") {\n await (instance as any).onError(ctx, error as Error);\n } else {\n await ctx.reply(`Invalid channel mention for \\`<${def.name}>\\`.`);\n }\n return false;\n }\n }\n finalArgs[i] = match[1]!;\n } else if (def.type === \"role\") {\n const match = String(rawValue).match(/^(?:<%)?([0-7][0-9A-HJKMNP-TV-Z]{25})>?$/i);\n if (!match) {\n try {\n throw new CommandValidationError(def.name, `Invalid role mention for \\`<${def.name}>\\`.`);\n } catch (error) {\n if (typeof (instance as any).onError === \"function\") {\n await (instance as any).onError(ctx, error as Error);\n } else {\n await ctx.reply(`Invalid role mention for \\`<${def.name}>\\`.`);\n }\n return false;\n }\n }\n finalArgs[i] = match[1]!;\n } else {\n finalArgs[i] = String(rawValue);\n }\n }\n\n // Preserve any extra, unmapped arguments the user typed at the end\n if (ctx.args.length > metadata.args.length) {\n for (let i = metadata.args.length; i < ctx.args.length; i++) {\n if (ctx.args[i] !== undefined) {\n finalArgs.push(ctx.args[i]!);\n }\n }\n }\n\n // Overwrite the context args with our strictly parsed ones\n ctx.args = finalArgs;\n }\n\n const finalOptions: Record<string, string | number | boolean> = {};\n const currentOptions = ctx.options || {};\n if (metadata.options) {\n for (const def of metadata.options) {\n const rawValue = currentOptions[def.name];\n\n if (rawValue === undefined) {\n if (def.required) {\n // Wait to throw inside the try/catch block so onError catches it\n try {\n throw new CommandValidationError(def.name, `Missing required option: \\`--${def.name}\\``);\n } catch (error) {\n if (typeof (instance as any).onError === \"function\") {\n await (instance as any).onError(ctx, error as Error);\n } else {\n await ctx.reply(`Missing required option: \\`--${def.name}\\``);\n }\n return false;\n }\n }\n continue;\n }\n\n if (def.type === \"number\") {\n const numValue = Number(rawValue);\n if (isNaN(numValue)) {\n try {\n throw new CommandValidationError(def.name, `Invalid value for \\`--${def.name}\\`. Expected a number.`);\n } catch (error) {\n if (typeof (instance as any).onError === \"function\") {\n await (instance as any).onError(ctx, error as Error);\n } else {\n await ctx.reply(`Invalid value for \\`--${def.name}\\`. Expected a number.`);\n }\n return false;\n }\n }\n finalOptions[def.name] = numValue;\n } else if (def.type === \"boolean\") {\n finalOptions[def.name] = rawValue === \"false\" ? false : Boolean(rawValue);\n } else if (def.type === \"user\") {\n // Matches <@ULID>, <@!ULID>, or just raw ULID\n const match = String(rawValue).match(/^(?:<@)?([0-7][0-9A-HJKMNP-TV-Z]{25})>?$/i);\n if (!match) {\n try {\n throw new CommandValidationError(def.name, `Invalid user mention for \\`--${def.name}\\`.`);\n } catch (error) {\n if (typeof (instance as any).onError === \"function\") {\n await (instance as any).onError(ctx, error as Error);\n } else {\n await ctx.reply(`Invalid user mention for \\`--${def.name}\\`.`);\n }\n return false;\n }\n }\n finalOptions[def.name] = match[1]!; // Stores just the extracted ULID\n } else if (def.type === \"channel\") {\n // Matches <#ULID> or raw ULID\n const match = String(rawValue).match(/^(?:<#)?([0-7][0-9A-HJKMNP-TV-Z]{25})>?$/i);\n if (!match) {\n try {\n throw new CommandValidationError(def.name, `Invalid channel mention for \\`--${def.name}\\`.`);\n } catch (error) {\n if (typeof (instance as any).onError === \"function\") {\n await (instance as any).onError(ctx, error as Error);\n } else {\n await ctx.reply(`Invalid channel mention for \\`--${def.name}\\`.`);\n }\n return false;\n }\n }\n finalOptions[def.name] = match[1]!;\n } else if (def.type === \"role\") {\n // Matches <@%ULID> or raw ULID\n const match = String(rawValue).match(/^(?:<%)?([0-7][0-9A-HJKMNP-TV-Z]{25})>?$/i);\n if (!match) {\n try {\n throw new CommandValidationError(def.name, `Invalid role mention for \\`--${def.name}\\`.`);\n } catch (error) {\n if (typeof (instance as any).onError === \"function\") {\n await (instance as any).onError(ctx, error as Error);\n } else {\n await ctx.reply(`Invalid role mention for \\`--${def.name}\\`.`);\n }\n return false;\n }\n }\n finalOptions[def.name] = match[1]!;\n } else {\n finalOptions[def.name] = String(rawValue);\n }\n }\n // Re-assign the strictly typed options back to the context\n ctx.options = finalOptions;\n }\n\n // Cooldown check\n if (!(await this.cooldownManager.check(ctx, metadata))) {\n const remaining = await this.cooldownManager.getRemaining(ctx, metadata);\n\n // For method-based commands, check if instance has onCooldown\n if (typeof (instance as any).onCooldown === \"function\") {\n await (instance as any).onCooldown(ctx, remaining);\n } else {\n await ctx.reply(`Please wait ${(remaining / 1000).toFixed(1)} seconds before using this command again.`);\n }\n return false;\n }\n\n try {\n // Set cooldown before execution to prevent concurrent executions\n if (metadata.cooldown > 0) {\n await this.cooldownManager.set(ctx, metadata);\n }\n\n await (instance as any)[methodName](ctx);\n\n return true;\n } catch (error) {\n // Handle errors\n if (typeof (instance as any).onError === \"function\") {\n await (instance as any).onError(ctx, error as Error);\n } else {\n console.error(`[Stoatx] Error in command ${metadata.name}:`, error);\n }\n return false;\n }\n }\n\n /**\n * Get the command registry\n */\n getRegistry(): CommandRegistry {\n return this.registry;\n }\n\n /**\n * Get a command by name or alias\n */\n getCommand(name: string): RegisteredCommand | undefined {\n return this.registry.get(name);\n }\n\n /**\n * Get all commands\n */\n getCommands(): RegisteredCommand[] {\n return this.registry.getAll();\n }\n\n /**\n * Reload all commands\n */\n async reload(): Promise<void> {\n this.registry.clear();\n if (this.cooldownManager.clear) {\n await this.cooldownManager.clear();\n }\n if (this.commandsDir) {\n await this.registry.loadFromDirectory(this.commandsDir);\n return;\n }\n\n await this.registry.autoDiscover(this.discoveryOptions);\n }\n\n /**\n * Check if a user is an owner\n */\n isOwner(userId: string): boolean {\n return this.owners.has(userId);\n }\n\n /**\n * Add an owner\n */\n addOwner(userId: string): void {\n this.owners.add(userId);\n }\n\n /**\n * Remove an owner\n */\n removeOwner(userId: string): void {\n this.owners.delete(userId);\n }\n\n /**\n * Resolve the prefix for a context\n */\n private async resolvePrefix(serverId?: string | undefined): Promise<string> {\n if (typeof this.prefixResolver === \"function\") {\n return this.prefixResolver({ serverId });\n }\n return this.prefixResolver;\n }\n}\n","export class CommandValidationError extends Error {\n constructor(\n public readonly optionName: string,\n message: string,\n ) {\n super(message);\n this.name = \"CommandValidationError\";\n }\n}\n","import { Client as StoatClient, ClientOptions, Message } from \"@stoatx/client\";\nimport type { StoatxHandlerOptions } from \"./types\";\nimport { StoatxHandler } from \"./handler\";\n\n/**\n * Client - An extended Client that integrates StoatxHandler directly\n *\n * @example\n * ```ts\n * import { Client } from 'stoatx';\n *\n * const client = new Client({\n * prefix: '!',\n * owners: ['owner-user-id'],\n * });\n *\n * await client.initCommands();\n * ```\n */\nexport class Client extends StoatClient {\n public readonly handler: StoatxHandler;\n\n constructor(options: Omit<StoatxHandlerOptions, \"client\"> & ClientOptions) {\n super(options);\n this.handler = new StoatxHandler({ ...options, client: this });\n }\n\n override async login(token: string): Promise<string> {\n await this.handler.init();\n return super.login(token);\n }\n\n async executeCommand(message: Message): Promise<void> {\n await this.handler.handle(message);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;;;;;;;ACAA,8BAAO;;;ACGA,IAAMA,gBAAgB;EAC3BC,gBAAgBC,uBAAO,sBAAA;EACvBC,iBAAiBD,uBAAO,6BAAA;EACxBE,QAAQ;EACRC,QAAQH,uBAAO,qBAAA;AACjB;;;ACFO,IAAMI,iBAAN,MAAMA,gBAAAA;EAJb,OAIaA;;;EACX,OAAeC;;EAGPC,eAAsC,oBAAIC,IAAAA;;EAG1CC,WAAgC,CAAA;;EAGhCC,cAAc;EAEtB,cAAsB;EAAC;EAEvB,OAAOC,cAA8B;AACnC,QAAI,CAACN,gBAAeC,UAAU;AAC5BD,sBAAeC,WAAW,IAAID,gBAAAA;IAChC;AACA,WAAOA,gBAAeC;EACxB;;;;EAKAM,mBAA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mBvD,IAAMmH,SAAN,cAAqBC,cAAAA,OAAAA;EAnB5B,OAmB4BA;;;EACVC;EAEhB,YAAYC,SAA+D;AACzE,UAAMA,OAAAA;AACN,SAAKD,UAAU,IAAIE,cAAc;MAAE,GAAGD;MAASE,QAAQ;IAAK,CAAA;EAC9D;EAEA,MAAeC,MAAMC,OAAgC;AACnD,UAAM,KAAKL,QAAQM,KAAI;AACvB,WAAO,MAAMF,MAAMC,KAAAA;EACrB;EAEA,MAAME,eAAeC,SAAiC;AACpD,UAAM,KAAKR,QAAQS,OAAOD,OAAAA;EAC5B;AACF;;;AXrBA,0BAAc,2BAdd;","names":["METADATA_KEYS","IS_STOAT_CLASS","Symbol","SIMPLE_COMMANDS","GUARDS","EVENTS","DecoratorStore","instance","stoatClasses","Map","commands","initialized","getInstance","registerStoatClass","classConstructor","has","set","getStoatClasses","addCommand","command","push","getCommands","clear","markInitialized","isInitialized","decoratorStore","Stoat","target","Reflect","defineMetadata","METADATA_KEYS","IS_STOAT_CLASS","decoratorStore","registerStoatClass","isStoatClass","getMetadata","import_reflect_metadata","SimpleCommand","options","target","propertyKey","descriptor","constructor","existingCommands","Reflect","getMetadata","METADATA_KEYS","SIMPLE_COMMANDS","push","methodName","String","defineMetadata","getSimpleCommands","import_reflect_metadata","Guard","guardClass","target","existingGuards","Reflect","getMetadata","METADATA_KEYS","GUARDS","push","defineMetadata","getGuards","import_reflect_metadata","createEventDecorator","event","type","target","propertyKey","descriptor","constructor","existingEvents","Reflect","getMetadata","METADATA_KEYS","EVENTS","push","methodName","String","defineMetadata","On","Once","getEventsMetadata","buildSimpleCommandMetadata","options","methodName","category","name","toLowerCase","description","aliases","permissions","cooldown","cooldownStorage","undefined","nsfw","ownerOnly","args","CommandRegistry","DEFAULT_AUTO_DISCOVERY_IGNORES","commands","Map","aliases","registeredEvents","extensions","processedStoatClasses","Set","size","loadFromDirectory","directory","patterns","map","ext","join","replace","pattern","files","glob","ignore","absolute","file","loadFile","console","log","length","autoDiscover","options","roots","process","cwd","includePatterns","include","getDefaultAutoDiscoveryPatterns","flatMap","root","uniqueFiles","candidateFiles","isLikelyCommandModule","baseDir","find","relative","startsWith","isAbsolute","filePath","source","readFile","includes","register","instance","metadata","classConstructor","methodName","name","toLowerCase","has","warn","validateGuards","set","alias","aliasLower","get","lowerName","resolvedName","getAll","Array","from","values","getAllMetadata","c","getEvents","getByCategory","categories","cmd","category","existing","push","clear","Symbol","iterator","entries","keys","commandClass","commandName","guards","Reflect","getMetadata","GuardClass","guardInstance","run","error","exit","guardFail","knownStoatClasses","decoratorStore","getStoatClasses","fileUrl","pathToFileURL","href","allStoatClasses","stoatClass","stoatInstance","registerStoatClassCommands","simpleCommands","getSimpleCommands","events","getEventsMetadata","getCategoryFromPath","add","cmdDef","method","buildSimpleCommandMetadata","eventDef","event","type","parts","split","sep","undefined","import_reflect_metadata","CommandValidationError","Error","optionName","message","name","DefaultCooldownManager","cooldowns","Map","check","ctx","metadata","cooldown","commandCooldowns","get","name","expirationTime","authorId","Date","now","delete","getRemaining","userCooldown","Math","max","set","has","clear","StoatxHandler","commandsDir","discoveryOptions","prefixResolver","owners","registry","cooldownManager","disableMentionPrefix","client","flagPrefix","options","discovery","prefix","Set","CommandRegistry","extensions","init","loadFromDirectory","autoDiscover","attachEvents","events","getEvents","eventDef","handler","args","instance","methodName","error","console","type","event","eventName","once","on","parseCommandOptions","rawArgs","i","length","arg","undefined","startsWith","key","slice","nextArg","push","parseMessage","rawContent","message","meta","resolvePrefix","serverId","usedPrefix","withoutPrefix","trim","match","mentionMatch","mentionedId","botId","user","id","commandName","split","content","channelId","toLowerCase","reply","handle","channel","author","bot","server","send","handleMessage","execute","registered","classConstructor","log","ownerOnly","permissions","member","members","fetch","onMissingPermissions","missing","guards","Reflect","getMetadata","guardClass","guardInstance","run","guardResult","guardFail","finalArgs","def","rawValue","required","CommandValidationError","onError","numValue","Number","isNaN","Boolean","String","finalOptions","currentOptions","remaining","onCooldown","toFixed","getRegistry","getCommand","getCommands","getAll","reload","isOwner","userId","addOwner","add","removeOwner","Client","StoatClient","handler","options","StoatxHandler","client","login","token","init","executeCommand","message","handle"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/types.ts","../src/decorators/Stoat.ts","../src/decorators/keys.ts","../src/decorators/store.ts","../src/decorators/SimpleCommand.ts","../src/decorators/Guard.ts","../src/decorators/Events.ts","../src/decorators/Arg.ts","../src/decorators/Option.ts","../src/decorators/Injectable.ts","../src/decorators/CommandGroup.ts","../src/decorators/SubCommand.ts","../src/decorators/utils.ts","../src/registry.ts","../src/handler.ts","../src/error.ts","../src/di/Container.ts","../src/client.ts"],"sourcesContent":["// Types\nexport * from \"./types\";\n\n// Errors\n\n// Decorators\nexport * from \"./decorators\";\n\n// Registry\nexport * from \"./registry\";\n\n// Handler\nexport { DefaultCooldownManager } from \"./handler\";\nexport { Client } from \"./client\";\nexport type { StoatxHandler } from \"./handler\";\nexport * from \"./error\";\nexport * from \"@stoatx/client\";\n","import { Client as StoatClient, Message, PermissionResolvable, User, BaseChannel, Role } from \"@stoatx/client\";\nimport { Client } from \"./client\";\nimport { CommandValidationError } from \"./error\";\n\n/**\n * Resolved parameter type from reflect-metadata or explicit decorator config\n */\nexport type ResolvedParamType = \"string\" | \"number\" | \"boolean\" | \"user\" | \"channel\" | \"role\" | \"ctx\";\n\n/**\n * Schema for a single method parameter decorated with @Arg, @Option, or inferred as ctx\n */\nexport interface ParamSchema {\n index: number;\n kind: \"arg\" | \"option\" | \"ctx\";\n resolvedType: ResolvedParamType;\n name?: string;\n required?: boolean | undefined;\n fetch?: boolean | undefined;\n}\n\n/**\n * Simple command options passed to @SimpleCommand decorator\n */\nexport interface SimpleCommandOptions {\n /** Command name (defaults to method name) */\n name?: string;\n /** Command description */\n description?: string;\n /** Command aliases */\n aliases?: string[];\n /** Required permissions to run the command */\n permissions?: PermissionResolvable[];\n /** Command category (auto-detected from directory if not provided) */\n category?: string;\n /** Cooldown in milliseconds */\n cooldown?: number;\n /** Storage strategy or identifier for cooldowns (e.g. \"memory\", \"database\") */\n cooldownStorage?: string;\n /** Whether the command is NSFW only */\n nsfw?: boolean;\n /** Whether the command is owner only */\n ownerOnly?: boolean;\n}\n\nexport interface GroupOptions {\n name: string;\n description?: string;\n permissions?: PermissionResolvable[];\n ownerOnly?: boolean;\n cooldown?: number;\n nsfw?: boolean;\n}\n\n/**\n * Resolved command metadata with required fields\n */\nexport interface CommandMetadata {\n name: string;\n description: string;\n aliases: string[];\n permissions: PermissionResolvable[];\n category: string;\n cooldown: number;\n cooldownStorage?: string;\n nsfw: boolean;\n ownerOnly: boolean;\n /** Parameter schema built at scan time from @Arg/@Option decorators */\n params: ParamSchema[];\n}\n\n/**\n * Command execution context — carries message context only.\n * Args and options are injected directly as typed method parameters.\n */\nexport interface CommandContext<TClient extends StoatClient = Client> {\n /** The client instance */\n client: TClient;\n /** The raw message content */\n content: string;\n /** The author ID */\n authorId: string;\n /** The channel ID */\n channelId: string;\n /** The server/guild ID (if applicable) */\n serverId?: string | undefined;\n /** The prefix used */\n prefix: string;\n /** The command name used (could be an alias) */\n commandName: string;\n /** Reply to the message */\n reply: (content: string) => Promise<Message>;\n /** The original message object */\n message: Message;\n}\n\n/**\n * Optional lifecycle hooks for @Stoat() class instances\n */\nexport interface StoatLifecycle {\n onError?(ctx: CommandContext, error: Error): Promise<void> | void;\n onValidationError?(ctx: CommandContext, error: CommandValidationError): Promise<void> | void;\n onCooldown?(ctx: CommandContext, remaining: number): Promise<void> | void;\n onMissingPermissions?(ctx: CommandContext, missing: PermissionResolvable[]): Promise<void> | void;\n [method: string]: any;\n}\n\nexport interface GuardInterface {\n run(ctx: CommandContext): Promise<boolean> | boolean;\n guardFail?(ctx: CommandContext): Promise<void> | void;\n}\n\n/**\n * Cooldown manager interface for custom cooldown storage\n */\nexport interface CooldownManager {\n check(ctx: CommandContext, metadata: CommandMetadata): boolean | Promise<boolean>;\n getRemaining(ctx: CommandContext, metadata: CommandMetadata): number | Promise<number>;\n set(ctx: CommandContext, metadata: CommandMetadata): void | Promise<void>;\n clear?(): void | Promise<void>;\n}\n\nexport interface StoatxGuard {\n run(ctx: CommandContext): Promise<boolean> | boolean;\n guardFail?(ctx: CommandContext): Promise<void> | void;\n}\n\n/**\n * Discovery options for automatic command module loading\n */\nexport interface StoatxDiscoveryOptions {\n roots?: string[];\n include?: string[];\n ignore?: string[];\n}\n\n/**\n * Handler options\n */\nexport interface StoatxHandlerOptions {\n client: Client;\n commandsDir?: string;\n discovery?: StoatxDiscoveryOptions;\n prefix:\n | string\n | string[]\n | ((ctx: { serverId?: string | undefined }) => string | string[] | Promise<string | string[]>);\n owners?: string[];\n extensions?: string[];\n disableMentionPrefix?: boolean;\n cooldownManager?: CooldownManager;\n flagPrefix?: string;\n globalGuards?: Function[];\n}\n\n/**\n * Map from reflect-metadata design:paramtypes constructor to resolved param type\n */\nexport const PARAM_TYPE_MAP = new Map<Function, ResolvedParamType>([\n [String, \"string\"],\n [Number, \"number\"],\n [Boolean, \"boolean\"],\n [User, \"user\"],\n [BaseChannel, \"channel\"],\n [Role, \"role\"],\n]);\n","import \"reflect-metadata\";\nimport { METADATA_KEYS } from \"./keys\";\nimport { decoratorStore } from \"./store\";\n\n/**\n * @Stoat\n * Marks a class as a Stoat command container.\n * Use this decorator on classes that contain @SimpleCommand methods.\n *\n * @example\n * ```ts\n * import { Stoat, SimpleCommand, CommandContext } from 'stoatx';\n *\n * @Stoat()\n * class ModerationCommands {\n * @SimpleCommand({ name: 'ban', description: 'Ban a user' })\n * async ban(ctx: CommandContext) {\n * await ctx.reply('User banned!');\n * }\n *\n * @SimpleCommand({ name: 'kick', description: 'Kick a user' })\n * async kick(ctx: CommandContext) {\n * await ctx.reply('User kicked!');\n * }\n * }\n * ```\n */\nexport function Stoat(): ClassDecorator {\n return (target: Function) => {\n Reflect.defineMetadata(METADATA_KEYS.IS_STOAT_CLASS, true, target);\n decoratorStore.registerStoatClass(target);\n };\n}\n\n/**\n * Check if a class is decorated with @Stoat\n */\nexport function isStoatClass(target: Function): boolean {\n return Reflect.getMetadata(METADATA_KEYS.IS_STOAT_CLASS, target) === true;\n}\n","/**\n * Metadata keys used by decorators\n */\nexport const METADATA_KEYS = {\n IS_STOAT_CLASS: Symbol(\"stoatx:stoat:isClass\"),\n SIMPLE_COMMANDS: Symbol(\"stoatx:stoat:simpleCommands\"),\n GUARDS: \"stoatx:command:guards\",\n EVENTS: Symbol(\"stoatx:stoat:events\"),\n ARGS: Symbol(\"stoatx:param:args\"),\n OPTIONS: Symbol(\"stoatx:param:options\"),\n INJECTABLE: Symbol(\"stoatx:injectable\"),\n SUBCOMMAND: Symbol(\"stoatx:subcommand\"),\n COMMAND_GROUP: Symbol(\"stoatx:commandGroup\"),\n} as const;\n","import type { RegisteredCommand } from \"../registry\";\n\n/**\n * Global store for all decorated classes and commands\n * This allows automatic registration without directory scanning\n */\nexport class DecoratorStore {\n private static instance: DecoratorStore;\n\n /** Stoat classes with their SimpleCommand methods */\n private stoatClasses: Set<Function> = new Set();\n\n /** Registered commands from @Stoat/@SimpleCommand decorators */\n private commands: RegisteredCommand[] = [];\n\n /** Whether the store has been initialized */\n private initialized = false;\n\n private constructor() {}\n\n static getInstance(): DecoratorStore {\n if (!DecoratorStore.instance) {\n DecoratorStore.instance = new DecoratorStore();\n }\n return DecoratorStore.instance;\n }\n\n /**\n * Register a @Stoat decorated class\n */\n registerStoatClass(classConstructor: Function): void {\n this.stoatClasses.add(classConstructor);\n }\n\n /**\n * Get all registered Stoat classes with their instances\n */\n getStoatClasses(): Set<Function> {\n return this.stoatClasses;\n }\n\n /**\n * Add a registered command\n */\n addCommand(command: RegisteredCommand): void {\n this.commands.push(command);\n }\n\n /**\n * Get all registered commands\n */\n getCommands(): RegisteredCommand[] {\n return this.commands;\n }\n\n /**\n * Clear all registered classes (useful for testing)\n */\n clear(): void {\n this.stoatClasses.clear();\n this.commands = [];\n this.initialized = false;\n }\n\n /**\n * Mark as initialized\n */\n markInitialized(): void {\n this.initialized = true;\n }\n\n /**\n * Check if initialized\n */\n isInitialized(): boolean {\n return this.initialized;\n }\n}\n\nexport const decoratorStore = DecoratorStore.getInstance();\n","import \"reflect-metadata\";\nimport type { SimpleCommandOptions } from \"../types\";\nimport { METADATA_KEYS } from \"./keys\";\n\n/**\n * Stored simple command metadata from method decorator\n */\nexport interface SimpleCommandDefinition {\n methodName: string;\n options: SimpleCommandOptions;\n}\n\ntype CommandMethod = (...args: any[]) => Promise<void>;\n\n/**\n * @SimpleCommand\n * Marks a method as a simple command within a @Stoat() decorated class.\n *\n * @example\n * ```ts\n * @Stoat()\n * class Example {\n * @SimpleCommand({ name: 'ping', description: 'Replies with Pong!' })\n * async ping(ctx: CommandContext) {\n * await ctx.reply('Pong!');\n * }\n *\n * @SimpleCommand({ aliases: ['perm'], name: 'permission' })\n * async permission(ctx: CommandContext) {\n * await ctx.reply('Access granted');\n * }\n * }\n * ```\n */\nexport function SimpleCommand(options: SimpleCommandOptions = {}) {\n return <T extends CommandMethod>(\n target: Object,\n propertyKey: string | symbol,\n descriptor: TypedPropertyDescriptor<T>,\n ) => {\n const constructor = target.constructor;\n\n const existingCommands: SimpleCommandDefinition[] =\n Reflect.getMetadata(METADATA_KEYS.SIMPLE_COMMANDS, constructor) || [];\n\n existingCommands.push({\n methodName: String(propertyKey),\n options,\n });\n\n Reflect.defineMetadata(METADATA_KEYS.SIMPLE_COMMANDS, existingCommands, constructor);\n\n return descriptor;\n };\n}\n\n/**\n * Get all simple command definitions from a @Stoat class\n */\nexport function getSimpleCommands(target: Function): SimpleCommandDefinition[] {\n return Reflect.getMetadata(METADATA_KEYS.SIMPLE_COMMANDS, target) || [];\n}\n","import \"reflect-metadata\";\nimport { METADATA_KEYS } from \"./keys\";\n\n/**\n * @Guard\n * Runs before a command to check if it should execute.\n * Should return true to allow execution, false to block.\n * Applied on @Stoat classes to guard all contained @SimpleCommand methods.\n *\n * @example\n * ```ts\n * import { Guard, Stoat, SimpleCommand, CommandContext } from 'stoatx';\n *\n * // Define a guard\n * class NotBot implements StoatxGuard {\n * run(ctx: CommandContext): boolean {\n * return !ctx.message.author.bot;\n * }\n *\n * guardFail(ctx: CommandContext): void {\n * ctx.reply(\"Bots cannot use this command!\");\n * }\n * }\n *\n * @Stoat()\n * @Guard(NotBot)\n * class AdminCommands {\n * @SimpleCommand({ name: 'admin', description: 'Admin only command' })\n * async admin(ctx: CommandContext) {\n * ctx.reply(\"You passed the guard check!\");\n * }\n * }\n * ```\n */\nexport function Guard(guardClass: Function) {\n return (target: any, propertyKey?: string | symbol) => {\n if (propertyKey) {\n // METHOD DECORATOR: target is the prototype, propertyKey is the method name\n const existingGuards: Function[] = Reflect.getMetadata(METADATA_KEYS.GUARDS, target, propertyKey) || [];\n existingGuards.push(guardClass);\n Reflect.defineMetadata(METADATA_KEYS.GUARDS, existingGuards, target, propertyKey);\n } else {\n // CLASS DECORATOR: target is the class constructor\n const existingGuards: Function[] = Reflect.getMetadata(METADATA_KEYS.GUARDS, target) || [];\n existingGuards.push(guardClass);\n Reflect.defineMetadata(METADATA_KEYS.GUARDS, existingGuards, target);\n }\n };\n}\n\n/**\n * Get all guards from a decorated class\n */\nexport function getGuards(target: Function, propertyKey?: string | symbol): Function[] {\n if (propertyKey) {\n return Reflect.getMetadata(METADATA_KEYS.GUARDS, target.prototype, propertyKey) || [];\n }\n return Reflect.getMetadata(METADATA_KEYS.GUARDS, target) || [];\n}\n","import \"reflect-metadata\";\nimport { METADATA_KEYS } from \"./keys\";\nimport { ClientEvents } from \"@stoatx/client\";\n\nexport interface EventDefinition {\n methodName: string;\n event: string;\n type: \"on\" | \"once\";\n}\n\nfunction createEventDecorator(event: string, type: \"on\" | \"once\"): MethodDecorator {\n return (target: Object, propertyKey: string | symbol, descriptor: PropertyDescriptor) => {\n const constructor = target.constructor;\n\n // Retrieve existing events or initialize a fresh array\n const existingEvents: EventDefinition[] = Reflect.getMetadata(METADATA_KEYS.EVENTS, constructor) || [];\n\n existingEvents.push({\n methodName: String(propertyKey),\n event,\n type,\n });\n\n Reflect.defineMetadata(METADATA_KEYS.EVENTS, existingEvents, constructor);\n\n return descriptor;\n };\n}\n\n/**\n * @On\n * Triggered on every occurrence of the event.\n * Marks a method to be executed whenever the specified client event is emitted.\n *\n * @example\n * ```ts\n * import { Stoat, On } from 'stoatx';\n * import { Message, Client } from 'stoat.js';\n *\n * @Stoat()\n * class BotEvents {\n * @On('messageCreate')\n * async onMessage(message: Message, client: Client) {\n * console.log('New message received:', message.content);\n * }\n * }\n * ```\n *\n * @param event The name of the client event to listen to\n */\nexport function On(event: keyof ClientEvents): MethodDecorator {\n return createEventDecorator(event, \"on\");\n}\n\n/**\n * @Once\n * Triggered only fully once.\n * Marks a method to be executed only the FIRST time the specified client event is emitted.\n *\n * @example\n * ```ts\n * import { Stoat, Once } from 'stoatx';\n * import { Client } from 'stoat.js';\n *\n * @Stoat()\n * class BotEvents {\n * @Once('ready')\n * async onReady(client: Client) {\n * console.log('Bot successfully started and logged in!');\n * }\n * }\n * ```\n *\n * @param event The name of the client event to listen to\n */\nexport function Once(event: keyof ClientEvents): MethodDecorator {\n return createEventDecorator(event, \"once\");\n}\n\n/**\n * Get all event definitions from a @Stoat class\n */\nexport function getEventsMetadata(target: Function): EventDefinition[] {\n return Reflect.getMetadata(METADATA_KEYS.EVENTS, target) || [];\n}\n","import \"reflect-metadata\";\nimport { METADATA_KEYS } from \"./keys\";\n\nexport interface ArgDefinition {\n index: number;\n name?: string;\n required?: boolean;\n fetch?: boolean;\n}\n\n/**\n * Marks a method parameter as a positional command argument.\n * Type is inferred from the TypeScript parameter type via reflect-metadata.\n *\n * @example\n * ```ts\n * @SimpleCommand({ name: \"ban\" })\n * async ban(\n * @Arg({ required: true }) target: User,\n * @Arg() reason: string | undefined,\n * ctx: CommandContext\n * ) {}\n * ```\n */\nexport function Arg(options: Omit<ArgDefinition, \"index\"> = {}) {\n return (target: Object, propertyKey: string | symbol, parameterIndex: number) => {\n const existing: ArgDefinition[] = Reflect.getMetadata(METADATA_KEYS.ARGS, target, propertyKey) || [];\n existing.push({ ...options, index: parameterIndex });\n Reflect.defineMetadata(METADATA_KEYS.ARGS, existing, target, propertyKey);\n };\n}\n\nexport function getArgs(target: Object, propertyKey: string): ArgDefinition[] {\n return Reflect.getMetadata(METADATA_KEYS.ARGS, target, propertyKey) || [];\n}\n","import \"reflect-metadata\";\nimport { METADATA_KEYS } from \"./keys\";\n\nexport interface OptionDefinition {\n index: number;\n name: string;\n required?: boolean;\n}\n\n/**\n * @Option\n * Marks a method parameter as a named flag option (e.g. --reason value).\n * Type is inferred from the TypeScript parameter type via reflect-metadata.\n *\n * @example\n * ```ts\n * @SimpleCommand({ name: \"ban\" })\n * async ban(\n * @Option({ name: \"reason\" }) reason: string | undefined,\n * @Option({ name: \"days\" }) days: number | undefined,\n * ctx: CommandContext\n * ) {}\n * ```\n */\nexport function Option(options: Omit<OptionDefinition, \"index\">) {\n return (target: Object, propertyKey: string | symbol, parameterIndex: number) => {\n const existing: OptionDefinition[] = Reflect.getMetadata(METADATA_KEYS.OPTIONS, target, propertyKey) || [];\n existing.push({ ...options, index: parameterIndex });\n Reflect.defineMetadata(METADATA_KEYS.OPTIONS, existing, target, propertyKey);\n };\n}\n\nexport function getOptions(target: Object, propertyKey: string): OptionDefinition[] {\n return Reflect.getMetadata(METADATA_KEYS.OPTIONS, target, propertyKey) || [];\n}\n","import \"reflect-metadata\";\nimport { METADATA_KEYS } from \"./keys\";\n\nexport function Injectable(): ClassDecorator {\n return (target: Function) => {\n Reflect.defineMetadata(METADATA_KEYS.INJECTABLE, true, target);\n };\n}\n","import \"reflect-metadata\";\nimport { METADATA_KEYS } from \"./keys\";\nimport { GroupOptions } from \"../types\";\n\nexport function CommandGroup(name: GroupOptions): ClassDecorator {\n return (target: Function) => {\n Reflect.defineMetadata(METADATA_KEYS.COMMAND_GROUP, name, target);\n };\n}\n","import \"reflect-metadata\";\nimport { METADATA_KEYS } from \"./keys\";\nimport type { SimpleCommandOptions } from \"../types\";\n\nexport function SubCommand(options: SimpleCommandOptions | string): MethodDecorator {\n const opts = typeof options === \"string\" ? { name: options } : options;\n return (target: object, propertyKey: string | symbol) => {\n Reflect.defineMetadata(METADATA_KEYS.SUBCOMMAND, opts, target, propertyKey);\n };\n}\n","import type { CommandMetadata, ParamSchema, SimpleCommandOptions } from \"../types\";\nimport { METADATA_KEYS } from \"./keys\";\n\n/**\n * Build CommandMetadata from SimpleCommandOptions\n */\nexport function buildSimpleCommandMetadata(\n options: SimpleCommandOptions,\n methodName: string,\n category: string | undefined,\n params: ParamSchema[],\n): CommandMetadata {\n return {\n name: options.name ?? methodName.toLowerCase(),\n description: options.description ?? \"No description provided\",\n aliases: options.aliases ?? [],\n permissions: options.permissions ?? [],\n category: options.category ?? category ?? \"uncategorized\",\n cooldown: options.cooldown ?? 0,\n ...(options.cooldownStorage !== undefined ? { cooldownStorage: options.cooldownStorage } : {}),\n nsfw: options.nsfw ?? false,\n ownerOnly: options.ownerOnly ?? false,\n params,\n };\n}\n\nexport function getSubCommands(target: Function): { methodName: string; options: any }[] {\n const methods = Object.getOwnPropertyNames(target.prototype);\n const subCommands = [];\n\n for (const method of methods) {\n const options = Reflect.getMetadata(METADATA_KEYS.SUBCOMMAND, target.prototype, method);\n if (options) {\n subCommands.push({ methodName: method, options });\n }\n }\n return subCommands;\n}\n","import * as path from \"node:path\";\nimport * as fs from \"node:fs/promises\";\nimport { pathToFileURL } from \"node:url\";\nimport { glob } from \"tinyglobby\";\nimport { buildSimpleCommandMetadata, getEventsMetadata, getSimpleCommands, METADATA_KEYS } from \"./decorators\";\nimport { getArgs } from \"./decorators/Arg\";\nimport { getOptions } from \"./decorators/Option\";\nimport { decoratorStore } from \"./decorators/store\";\nimport type { CommandMetadata, GuardInterface, ParamSchema } from \"./types\";\nimport { PARAM_TYPE_MAP } from \"./types\";\nimport { StoatxContainer } from \"./di/Container\";\nimport { getSubCommands } from \"./decorators/utils\";\n\ninterface AutoDiscoveryOptions {\n roots?: string[];\n include?: string[];\n ignore?: string[];\n}\n\nexport interface RegisteredCommand {\n instance: object;\n metadata: CommandMetadata;\n methodName: string;\n classConstructor: Function;\n}\n\nexport interface RegisteredEvent {\n instance: object;\n methodName: string;\n event: string;\n type: \"on\" | \"once\";\n}\n\nexport class CommandRegistry {\n private static readonly DEFAULT_AUTO_DISCOVERY_IGNORES = [\n \"**/node_modules/**\",\n \"**/.git/**\",\n \"**/*.d.ts\",\n \"**/*.test.*\",\n \"**/*.spec.*\",\n ];\n\n private readonly commands: Map<string, RegisteredCommand> = new Map();\n private readonly aliases: Map<string, string> = new Map();\n private readonly registeredEvents: RegisteredEvent[] = [];\n private readonly extensions: string[];\n private readonly processedStoatClasses: Set<Function> = new Set();\n private readonly container: StoatxContainer;\n\n constructor(container: StoatxContainer, extensions: string[] = [\".js\", \".mjs\", \".cjs\"]) {\n this.container = container;\n this.extensions = extensions;\n }\n\n get size(): number {\n return this.commands.size;\n }\n\n async loadFromDirectory(directory: string): Promise<void> {\n const patterns = this.extensions.map((ext) => path.join(directory, \"**\", `*${ext}`).replace(/\\\\/g, \"/\"));\n\n for (const pattern of patterns) {\n const files = await glob(pattern, {\n ignore: [\"**/*.d.ts\", \"**/*.test.ts\", \"**/*.spec.ts\"],\n absolute: true,\n });\n\n for (const file of files) {\n await this.loadFile(file, directory);\n }\n }\n\n console.log(`[Stoatx] Loaded ${this.commands.size} command(s) and ${this.registeredEvents.length} event(s)`);\n }\n\n async autoDiscover(options: AutoDiscoveryOptions = {}): Promise<void> {\n const roots = options.roots?.length ? options.roots : [process.cwd()];\n const includePatterns = options.include?.length ? options.include : this.getDefaultAutoDiscoveryPatterns();\n\n const patterns = roots.flatMap((root) =>\n includePatterns.map((pattern) => path.join(root, pattern).replace(/\\\\/g, \"/\")),\n );\n\n const files = await glob(patterns, {\n ignore: [...CommandRegistry.DEFAULT_AUTO_DISCOVERY_IGNORES, ...(options.ignore ?? [])],\n absolute: true,\n });\n\n const uniqueFiles = [...new Set(files)];\n for (const file of uniqueFiles) {\n if (!(await this.isLikelyCommandModule(file))) {\n continue;\n }\n\n const baseDir =\n roots.find((root) => {\n const relative = path.relative(root, file);\n return relative && !relative.startsWith(\"..\") && !path.isAbsolute(relative);\n }) ?? roots[0]!;\n await this.loadFile(file, baseDir);\n }\n\n console.log(`[Stoatx] Loaded ${this.commands.size} command(s) and ${this.registeredEvents.length} event(s)`);\n }\n\n private getDefaultAutoDiscoveryPatterns(): string[] {\n return this.extensions.map((ext) => `**/*${ext}`);\n }\n\n private async isLikelyCommandModule(filePath: string): Promise<boolean> {\n try {\n const source = await fs.readFile(filePath, \"utf8\");\n return source.includes(\"Stoat\") || source.includes(\"SimpleCommand\") || source.includes(\"stoatx:command\");\n } catch {\n return true;\n }\n }\n\n register(instance: object, metadata: CommandMetadata, classConstructor: Function, methodName: string): void {\n const groupOptions = Reflect.getMetadata(METADATA_KEYS.COMMAND_GROUP, classConstructor);\n const subCommandOptions = Reflect.getMetadata(METADATA_KEYS.SUBCOMMAND, instance, methodName);\n\n const subCommandName = subCommandOptions?.name;\n\n const name =\n groupOptions && subCommandName\n ? `${groupOptions.name}:${subCommandName}`.toLowerCase()\n : metadata.name.toLowerCase();\n\n if (this.commands.has(name)) {\n console.warn(`[Stoatx] Duplicate command name: ${name}. Skipping...`);\n return;\n }\n\n this.validateGuards(classConstructor, metadata.name);\n this.commands.set(name, { instance, metadata, methodName, classConstructor });\n\n for (const alias of metadata.aliases) {\n const aliasLower = alias.toLowerCase();\n if (this.aliases.has(aliasLower) || this.commands.has(aliasLower)) {\n console.warn(`[Stoatx] Duplicate alias: ${aliasLower}. Skipping...`);\n continue;\n }\n this.aliases.set(aliasLower, name);\n }\n }\n\n get(name: string): RegisteredCommand | undefined {\n const lowerName = name.toLowerCase();\n const resolvedName = this.aliases.get(lowerName) ?? lowerName;\n return this.commands.get(resolvedName);\n }\n\n has(name: string): boolean {\n const lowerName = name.toLowerCase();\n return this.commands.has(lowerName) || this.aliases.has(lowerName);\n }\n\n getAll(): RegisteredCommand[] {\n return Array.from(this.commands.values());\n }\n\n getAllMetadata(): CommandMetadata[] {\n return this.getAll().map((c) => c.metadata);\n }\n\n getEvents(): RegisteredEvent[] {\n return this.registeredEvents;\n }\n\n getByCategory(): Map<string, RegisteredCommand[]> {\n const categories = new Map<string, RegisteredCommand[]>();\n\n for (const cmd of this.commands.values()) {\n const category = cmd.metadata.category;\n const existing = categories.get(category) ?? [];\n existing.push(cmd);\n categories.set(category, existing);\n }\n\n return categories;\n }\n\n clear(): void {\n this.commands.clear();\n this.aliases.clear();\n this.registeredEvents.length = 0;\n this.processedStoatClasses.clear();\n }\n\n [Symbol.iterator](): IterableIterator<[string, RegisteredCommand]> {\n return this.commands.entries();\n }\n\n values(): IterableIterator<RegisteredCommand> {\n return this.commands.values();\n }\n\n keys(): IterableIterator<string> {\n return this.commands.keys();\n }\n\n private validateGuards(commandClass: Function, commandName: string): void {\n const guards: Function[] = Reflect.getMetadata(METADATA_KEYS.GUARDS, commandClass) || [];\n\n for (const GuardClass of guards) {\n const guardInstance = this.container.resolve<GuardInterface>(GuardClass);\n\n if (typeof guardInstance.run !== \"function\") {\n console.error(\n `[Stoatx] FATAL: Guard \"${GuardClass.name}\" on command \"${commandName}\" does not have a run() method.`,\n );\n process.exit(1);\n }\n\n if (typeof guardInstance.guardFail !== \"function\") {\n console.error(\n `[Stoatx] FATAL: Guard \"${GuardClass.name}\" on command \"${commandName}\" does not have a guardFail() method.`,\n );\n process.exit(1);\n }\n }\n }\n\n private async loadFile(filePath: string, baseDir: string): Promise<void> {\n try {\n const knownStoatClasses = new Set(decoratorStore.getStoatClasses().keys());\n const fileUrl = pathToFileURL(filePath).href;\n await import(fileUrl);\n\n const allStoatClasses = decoratorStore.getStoatClasses();\n for (const [stoatClass] of allStoatClasses.entries()) {\n if (knownStoatClasses.has(stoatClass) || this.processedStoatClasses.has(stoatClass)) {\n continue;\n }\n this.registerStoatClassCommands(stoatClass, filePath, baseDir);\n }\n } catch (error) {\n console.error(`[Stoatx] Failed to load command file: ${filePath}`, error);\n }\n }\n\n private registerStoatClassCommands(stoatClass: Function, filePath: string, baseDir: string): void {\n const instance = this.container.resolve<object>(stoatClass);\n\n const simpleCommands = getSimpleCommands(stoatClass);\n const subCommands = getSubCommands(stoatClass);\n const events = getEventsMetadata(stoatClass);\n const category = this.getCategoryFromPath(filePath, baseDir);\n\n const allCommands = [...simpleCommands, ...subCommands];\n\n if (allCommands.length === 0 && events.length === 0) {\n this.processedStoatClasses.add(stoatClass);\n return;\n }\n\n for (const cmdDef of allCommands) {\n const method = (instance as any)[cmdDef.methodName];\n if (typeof method !== \"function\") continue;\n\n const params = this.buildParamSchema(stoatClass.prototype, cmdDef.methodName);\n\n const metadata = buildSimpleCommandMetadata(cmdDef.options, cmdDef.methodName, category, params);\n\n this.register(instance, metadata, stoatClass, cmdDef.methodName);\n }\n\n for (const eventDef of events) {\n const method = (instance as any)[eventDef.methodName];\n if (typeof method !== \"function\") {\n console.warn(`[Stoatx] Method ${eventDef.methodName} not found on ${stoatClass.name}. Skipping...`);\n continue;\n }\n\n this.registeredEvents.push({\n instance,\n methodName: eventDef.methodName,\n event: eventDef.event,\n type: eventDef.type,\n });\n }\n\n this.processedStoatClasses.add(stoatClass);\n }\n\n /**\n * Build the parameter schema for a command method by combining\n * reflect-metadata param types with @Arg/@Option decorator metadata.\n */\n private buildParamSchema(prototype: object, methodName: string): ParamSchema[] {\n // Reflected constructor list for each parameter position\n const paramTypes: Function[] = Reflect.getMetadata(\"design:paramtypes\", prototype, methodName) ?? [];\n\n const argDefs = getArgs(prototype, methodName);\n const optionDefs = getOptions(prototype, methodName);\n\n // Index lookup for fast access\n const argByIndex = new Map(argDefs.map((a) => [a.index, a]));\n const optionByIndex = new Map(optionDefs.map((o) => [o.index, o]));\n\n const params: ParamSchema[] = [];\n\n for (let i = 0; i < paramTypes.length; i++) {\n const reflectedType = paramTypes[i];\n\n if (optionByIndex.has(i)) {\n const optDef = optionByIndex.get(i)!;\n const resolvedType = reflectedType ? (PARAM_TYPE_MAP.get(reflectedType) ?? \"string\") : \"string\";\n params.push({\n index: i,\n kind: \"option\",\n resolvedType,\n name: optDef.name,\n required: optDef.required,\n });\n continue;\n }\n\n if (argByIndex.has(i)) {\n const argDef = argByIndex.get(i)!;\n const resolvedType = reflectedType ? (PARAM_TYPE_MAP.get(reflectedType) ?? \"string\") : \"string\";\n params.push({\n index: i,\n kind: \"arg\",\n resolvedType,\n required: argDef.required,\n fetch: argDef.fetch,\n });\n continue;\n }\n\n // No decorator — treat as ctx (should be the last parameter)\n params.push({\n index: i,\n kind: \"ctx\",\n resolvedType: \"ctx\",\n });\n }\n\n return params;\n }\n\n private getCategoryFromPath(filePath: string, baseDir: string): string | undefined {\n const relative = path.relative(baseDir, filePath);\n const parts = relative.split(path.sep);\n return parts.length > 1 ? parts[0] : undefined;\n }\n}\n","import \"reflect-metadata\";\nimport { CommandRegistry, RegisteredCommand } from \"./registry\";\nimport type {\n CommandContext,\n CommandMetadata,\n ParamSchema,\n StoatxDiscoveryOptions,\n StoatxHandlerOptions,\n CooldownManager,\n GuardInterface,\n} from \"./types\";\nimport { ClientEvents, Message } from \"@stoatx/client\";\nimport { Client } from \"./client\";\nimport {\n CommandValidationError,\n FetchFailedError,\n InvalidMentionError,\n InvalidTypeError,\n MissingArgumentError,\n MissingOptionError,\n NoServerContextError,\n} from \"./error\";\nimport { METADATA_KEYS } from \"./decorators\";\nimport { StoatxContainer } from \"./di/Container\";\n\n/**\n * Default in-memory cooldown manager\n */\nexport class DefaultCooldownManager implements CooldownManager {\n private readonly cooldowns: Map<string, Map<string, number>> = new Map();\n\n check(ctx: CommandContext, metadata: CommandMetadata): boolean {\n if (metadata.cooldown <= 0) return true;\n const commandCooldowns = this.cooldowns.get(metadata.name);\n if (!commandCooldowns) return true;\n const expirationTime = commandCooldowns.get(ctx.authorId);\n if (!expirationTime) return true;\n if (Date.now() > expirationTime) {\n commandCooldowns.delete(ctx.authorId);\n return true;\n }\n return false;\n }\n\n getRemaining(ctx: CommandContext, metadata: CommandMetadata): number {\n const commandCooldowns = this.cooldowns.get(metadata.name);\n if (!commandCooldowns) return 0;\n const userCooldown = commandCooldowns.get(ctx.authorId);\n if (!userCooldown) return 0;\n return Math.max(0, userCooldown - Date.now());\n }\n\n set(ctx: CommandContext, metadata: CommandMetadata): void {\n if (!this.cooldowns.has(metadata.name)) {\n this.cooldowns.set(metadata.name, new Map());\n }\n const commandCooldowns = this.cooldowns.get(metadata.name)!;\n commandCooldowns.set(ctx.authorId, Date.now() + metadata.cooldown);\n }\n\n clear(): void {\n this.cooldowns.clear();\n }\n}\n\n/**\n * StoatxHandler - The execution engine for commands\n * @internal\n */\nexport class StoatxHandler {\n private readonly commandsDir: string | undefined;\n private readonly discoveryOptions: StoatxDiscoveryOptions | undefined;\n // After\n private readonly prefixResolver:\n | string\n | string[]\n | ((ctx: { serverId?: string | undefined }) => string | string[] | Promise<string | string[]>);\n private readonly owners: Set<string>;\n private readonly registry: CommandRegistry;\n private readonly cooldownManager: CooldownManager;\n private readonly disableMentionPrefix: boolean;\n private readonly client: Client;\n private readonly flagPrefix: string;\n private readonly globalGuards: Function[];\n public readonly container = new StoatxContainer();\n\n constructor(options: StoatxHandlerOptions) {\n this.client = options.client;\n this.commandsDir = options.commandsDir;\n this.discoveryOptions = options.discovery;\n this.prefixResolver = options.prefix;\n this.owners = new Set(options.owners ?? []);\n this.registry = new CommandRegistry(this.container, options.extensions);\n this.disableMentionPrefix = options.disableMentionPrefix ?? false;\n this.cooldownManager = options.cooldownManager ?? new DefaultCooldownManager();\n this.flagPrefix = options.flagPrefix || \"-\";\n this.globalGuards = options.globalGuards ?? [];\n }\n\n async init(): Promise<void> {\n if (this.commandsDir) {\n await this.registry.loadFromDirectory(this.commandsDir);\n } else {\n await this.registry.autoDiscover(this.discoveryOptions);\n }\n this.attachEvents();\n }\n\n private attachEvents(): void {\n const events = this.registry.getEvents();\n for (const eventDef of events) {\n const handler = async (...args: any[]) => {\n try {\n await (eventDef.instance as any)[eventDef.methodName](...args, this.client);\n } catch (error) {\n console.error(\n `[Stoatx] Event Handler Error in @${eventDef.type === \"on\" ? \"On\" : \"Once\"}('${eventDef.event}'):`,\n error,\n );\n }\n };\n const eventName = eventDef.event as keyof ClientEvents;\n if (eventDef.type === \"once\") {\n this.client.once(eventName, handler);\n } else {\n this.client.on(eventName, handler);\n }\n }\n }\n\n private parseRawInput(rawArgs: string[]): { args: string[]; flags: Record<string, string | boolean> } {\n const args: string[] = [];\n const flags: Record<string, string | boolean> = {};\n\n for (let i = 0; i < rawArgs.length; i++) {\n const arg = rawArgs[i];\n if (arg === undefined) continue;\n\n if (arg.startsWith(this.flagPrefix)) {\n let key = arg;\n while (key.startsWith(this.flagPrefix)) {\n key = key.slice(this.flagPrefix.length);\n }\n const nextArg = rawArgs[i + 1];\n if (nextArg !== undefined && !nextArg.startsWith(this.flagPrefix)) {\n flags[key] = nextArg;\n i++;\n } else {\n flags[key] = true;\n }\n } else {\n args.push(arg);\n }\n }\n\n return { args, flags };\n }\n\n async parseMessage(\n rawContent: string,\n message: Message,\n meta: {\n authorId: string;\n channelId: string;\n serverId?: string | undefined;\n reply: (content: string) => Promise<Message>;\n },\n ): Promise<(CommandContext & { _rawArgs: string[]; _rawFlags: Record<string, string | boolean> }) | null> {\n const prefixes = await this.resolvePrefix(meta.serverId);\n let usedPrefix = \"\";\n let withoutPrefix = \"\";\n\n const matchedPrefix = prefixes.find((p) => rawContent.startsWith(p));\n if (matchedPrefix !== undefined) {\n usedPrefix = matchedPrefix;\n withoutPrefix = rawContent.slice(matchedPrefix.length).trim();\n } else if (!this.disableMentionPrefix && rawContent.match(/^<@!?\\w+>/)) {\n const mentionMatch = rawContent.match(/^<@!?(\\w+)>\\s*/);\n if (mentionMatch) {\n const mentionedId = mentionMatch[1];\n const botId = this.client.user?.id;\n if (botId && mentionedId === botId) {\n usedPrefix = mentionMatch[0];\n withoutPrefix = rawContent.slice(mentionMatch[0].length).trim();\n }\n }\n }\n\n if (!withoutPrefix) return null;\n\n const parts = withoutPrefix.split(/\\s+/);\n const part1 = parts[0];\n const part2 = parts[1];\n\n if (!part1) return null;\n\n let commandKey = part1.toLowerCase();\n let remainingParts = parts.slice(1);\n\n if (part2 && this.registry.has(`${part1}:${part2}`)) {\n commandKey = `${part1}:${part2}`.toLowerCase();\n remainingParts = parts.slice(2);\n }\n\n // 4. Parse the remaining parts\n const { args, flags } = this.parseRawInput(remainingParts);\n\n return {\n client: this.client,\n content: rawContent,\n authorId: meta.authorId,\n channelId: meta.channelId,\n serverId: meta.serverId,\n prefix: usedPrefix,\n commandName: commandKey,\n reply: meta.reply,\n message,\n _rawArgs: args,\n _rawFlags: flags,\n };\n }\n\n async handle(message: Message): Promise<boolean> {\n if (!message.channel || !message.author || !message.content) return false;\n if (message.author.bot) return false;\n\n const rawContent = message.content;\n const authorId = message.author.id;\n const channelId = message.channel.id;\n const serverId = message.server?.id;\n const reply = async (content: string) => await message.channel!.send(content);\n\n await this.handleMessage(rawContent, message, { authorId, channelId, serverId, reply });\n return true;\n }\n\n async handleMessage(\n rawContent: string,\n message: Message,\n meta: {\n authorId: string;\n channelId: string;\n serverId?: string | undefined;\n reply: (content: string) => Promise<Message>;\n },\n ): Promise<void> {\n const ctx = await this.parseMessage(rawContent, message, meta);\n if (!ctx) return;\n await this.execute(ctx);\n }\n\n async execute(\n ctx: CommandContext & { _rawArgs: string[]; _rawFlags: Record<string, string | boolean> },\n ): Promise<boolean> {\n const registered = this.registry.get(ctx.commandName);\n if (!registered) return false;\n\n const { instance, metadata, methodName, classConstructor } = registered;\n\n // Owner-only check\n if (metadata.ownerOnly && !this.owners.has(ctx.authorId)) {\n await ctx.reply(\"This command is owner-only.\");\n return false;\n }\n\n // Permissions check\n if (metadata.permissions.length > 0) {\n const server = ctx.message.server;\n const member = server ? await server.members.fetch(ctx.authorId) : null;\n if (!member || !member.permissions.has(metadata.permissions)) {\n if (typeof (instance as any).onMissingPermissions === \"function\") {\n const missing = member?.permissions.missing(metadata.permissions) || [];\n await (instance as any).onMissingPermissions(ctx, missing);\n } else {\n await ctx.reply(\"You do not have permission to use this command.\");\n }\n return false;\n }\n }\n\n // Guard checks\n const globalGuards = this.globalGuards;\n\n const classGuards: Function[] = Reflect.getMetadata(METADATA_KEYS.GUARDS, classConstructor) || [];\n\n const methodGuards: Function[] = Reflect.getMetadata(METADATA_KEYS.GUARDS, instance, methodName) || [];\n\n const allGuards = [...globalGuards, ...classGuards, ...methodGuards];\n\n for (const guardClass of allGuards) {\n const guardInstance = this.container.resolve<GuardInterface>(guardClass);\n if (typeof guardInstance.run === \"function\") {\n const guardResult = await guardInstance.run(ctx);\n if (!guardResult) {\n if (typeof guardInstance.guardFail === \"function\") {\n await guardInstance.guardFail(ctx);\n } else {\n console.error(\"[Stoatx] Guard check failed but no guardFail method defined on\", guardClass.name);\n }\n return false;\n }\n }\n }\n\n // Cooldown check\n if (!(await this.cooldownManager.check(ctx, metadata))) {\n const remaining = await this.cooldownManager.getRemaining(ctx, metadata);\n if (typeof (instance as any).onCooldown === \"function\") {\n await (instance as any).onCooldown(ctx, remaining);\n } else {\n await ctx.reply(`Please wait ${(remaining / 1000).toFixed(1)} seconds before using this command again.`);\n }\n return false;\n }\n\n // Resolve parameters\n const resolvedParams = await this.resolveParams(metadata.params, ctx, instance);\n if (resolvedParams === null) return false;\n\n try {\n if (metadata.cooldown > 0) {\n await this.cooldownManager.set(ctx, metadata);\n }\n await (instance as any)[methodName](...resolvedParams);\n return true;\n } catch (error) {\n if (typeof (instance as any).onError === \"function\") {\n await (instance as any).onError(ctx, error as Error);\n } else {\n console.error(`[Stoatx] Error in command ${metadata.name}:`, error);\n await ctx.reply(\"Something went wrong. Please try again later.\");\n }\n return false;\n }\n }\n\n /**\n * Report a validation error to the instance via onValidationError → onError → default reply\n */\n private async reportValidationError(\n instance: object,\n ctx: CommandContext,\n error: CommandValidationError,\n ): Promise<null> {\n if (typeof (instance as any).onValidationError === \"function\") {\n await (instance as any).onValidationError(ctx, error);\n } else if (typeof (instance as any).onError === \"function\") {\n await (instance as any).onError(ctx, error);\n } else {\n await ctx.reply(error.message);\n }\n return null;\n }\n\n private async resolveParams(\n params: ParamSchema[],\n ctx: CommandContext & { _rawArgs: string[]; _rawFlags: Record<string, string | boolean> },\n instance: object,\n ): Promise<any[] | null> {\n const resolved: any[] = new Array(params.length);\n let argCursor = 0;\n\n for (const param of params) {\n if (param.kind === \"ctx\") {\n resolved[param.index] = ctx;\n continue;\n }\n\n if (param.kind === \"arg\") {\n const rawValue = ctx._rawArgs[argCursor++];\n\n if (rawValue === undefined) {\n if (param.required) {\n const paramName = param.name ?? `arg[${param.index}]`;\n return this.reportValidationError(instance, ctx, new MissingArgumentError(paramName));\n }\n resolved[param.index] = undefined;\n continue;\n }\n\n const value = await this.resolveValue(rawValue, param, ctx, instance, \"arg\");\n if (value === null) return null;\n resolved[param.index] = value;\n continue;\n }\n\n if (param.kind === \"option\") {\n const rawValue = ctx._rawFlags[param.name!];\n\n if (rawValue === undefined) {\n if (param.required) {\n return this.reportValidationError(instance, ctx, new MissingOptionError(param.name!, this.flagPrefix));\n }\n resolved[param.index] = undefined;\n continue;\n }\n\n const value = await this.resolveValue(String(rawValue), param, ctx, instance, \"option\");\n if (value === null) return null;\n resolved[param.index] = value;\n }\n }\n\n return resolved;\n }\n\n private async resolveValue(\n rawValue: string,\n param: ParamSchema,\n ctx: CommandContext,\n instance: object,\n kind: \"arg\" | \"option\",\n ): Promise<any | null> {\n const paramName = kind === \"arg\" ? (param.name ?? `arg[${param.index}]`) : param.name!;\n\n switch (param.resolvedType) {\n case \"string\":\n return String(rawValue);\n\n case \"number\": {\n const num = Number(rawValue);\n if (isNaN(num)) {\n return this.reportValidationError(instance, ctx, new InvalidTypeError(paramName, kind, \"a number\", rawValue));\n }\n return num;\n }\n\n case \"boolean\":\n return rawValue === \"false\" ? false : Boolean(rawValue);\n\n case \"user\": {\n const match = rawValue.match(/^(?:<@!?)?([0-7][0-9A-HJKMNP-TV-Z]{25})>?$/i);\n if (!match) {\n return this.reportValidationError(instance, ctx, new InvalidMentionError(paramName, kind, \"user\", rawValue));\n }\n const userId = match[1]!;\n if (param.fetch) {\n try {\n return await this.client.users.fetch(userId);\n } catch {\n return this.reportValidationError(instance, ctx, new FetchFailedError(paramName, kind, \"user\", userId));\n }\n }\n return this.client.users.cache.get(userId) ?? userId;\n }\n\n case \"channel\": {\n const match = rawValue.match(/^(?:<#)?([0-7][0-9A-HJKMNP-TV-Z]{25})>?$/i);\n if (!match) {\n return this.reportValidationError(\n instance,\n ctx,\n new InvalidMentionError(paramName, kind, \"channel\", rawValue),\n );\n }\n const channelId = match[1]!;\n if (param.fetch) {\n try {\n return await this.client.channels.fetch(channelId);\n } catch {\n return this.reportValidationError(\n instance,\n ctx,\n new FetchFailedError(paramName, kind, \"channel\", channelId),\n );\n }\n }\n return this.client.channels.cache.get(channelId) ?? channelId;\n }\n\n case \"role\": {\n const match = rawValue.match(/^(?:<@&)?([0-7][0-9A-HJKMNP-TV-Z]{25})>?$/i);\n if (!match) {\n return this.reportValidationError(instance, ctx, new InvalidMentionError(paramName, kind, \"role\", rawValue));\n }\n const roleId = match[1]!;\n if (param.fetch) {\n const server = ctx.message.server;\n if (!server) {\n return this.reportValidationError(instance, ctx, new NoServerContextError(paramName, kind));\n }\n try {\n return await server.roles.fetch(roleId);\n } catch {\n return this.reportValidationError(instance, ctx, new FetchFailedError(paramName, kind, \"role\", roleId));\n }\n }\n return ctx.message.server?.roles.cache.get(roleId) ?? roleId;\n }\n\n default:\n return rawValue;\n }\n }\n\n getRegistry(): CommandRegistry {\n return this.registry;\n }\n\n getCommand(name: string): RegisteredCommand | undefined {\n return this.registry.get(name);\n }\n\n getCommands(): RegisteredCommand[] {\n return this.registry.getAll();\n }\n\n async reload(): Promise<void> {\n this.registry.clear();\n if (this.cooldownManager.clear) {\n await this.cooldownManager.clear();\n }\n if (this.commandsDir) {\n await this.registry.loadFromDirectory(this.commandsDir);\n return;\n }\n await this.registry.autoDiscover(this.discoveryOptions);\n }\n\n isOwner(userId: string): boolean {\n return this.owners.has(userId);\n }\n\n addOwner(userId: string): void {\n this.owners.add(userId);\n }\n\n removeOwner(userId: string): void {\n this.owners.delete(userId);\n }\n\n private async resolvePrefix(serverId?: string | undefined): Promise<string[]> {\n const result =\n typeof this.prefixResolver === \"function\" ? await this.prefixResolver({ serverId }) : this.prefixResolver;\n return Array.isArray(result) ? result : [result];\n }\n}\n","/**\n * Base error class for all Stoatx errors\n */\nexport class StoatxError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"StoatxError\";\n }\n}\n\n/**\n * Base class for all command validation errors.\n * Thrown before the command body runs when user input fails validation.\n */\nexport class CommandValidationError extends StoatxError {\n constructor(\n public readonly paramName: string,\n public readonly paramKind: \"arg\" | \"option\",\n message: string,\n ) {\n super(message);\n this.name = \"CommandValidationError\";\n }\n}\n\n/**\n * Thrown when a required positional argument is missing\n */\nexport class MissingArgumentError extends CommandValidationError {\n constructor(paramName: string) {\n super(paramName, \"arg\", `Missing required argument: \\`<${paramName}>\\``);\n this.name = \"MissingArgumentError\";\n }\n}\n\n/**\n * Thrown when a required named option is missing\n */\nexport class MissingOptionError extends CommandValidationError {\n constructor(paramName: string, flagPrefix: string) {\n super(paramName, \"option\", `Missing required option: \\`${flagPrefix.repeat(2)}${paramName}\\``);\n this.name = \"MissingOptionError\";\n }\n}\n\n/**\n * Thrown when a value cannot be cast to the expected type\n */\nexport class InvalidTypeError extends CommandValidationError {\n constructor(\n paramName: string,\n paramKind: \"arg\" | \"option\",\n public readonly expected: string,\n public readonly received: string,\n ) {\n super(paramName, paramKind, `Invalid value for \\`${paramName}\\`. Expected ${expected}, got \\`${received}\\`.`);\n this.name = \"InvalidTypeError\";\n }\n}\n\n/**\n * Thrown when a mention string cannot be parsed as a valid ULID\n */\nexport class InvalidMentionError extends CommandValidationError {\n constructor(\n paramName: string,\n paramKind: \"arg\" | \"option\",\n public readonly mentionKind: \"user\" | \"channel\" | \"role\",\n public readonly rawValue: string,\n ) {\n super(paramName, paramKind, `Invalid ${mentionKind} mention for \\`${paramName}\\`.`);\n this.name = \"InvalidMentionError\";\n }\n}\n\n/**\n * Thrown when fetch: true is set but the API call fails\n */\nexport class FetchFailedError extends CommandValidationError {\n constructor(\n paramName: string,\n paramKind: \"arg\" | \"option\",\n public readonly mentionKind: \"user\" | \"channel\" | \"role\",\n public readonly resolvedId: string,\n ) {\n super(paramName, paramKind, `Could not fetch ${mentionKind} \\`${resolvedId}\\` for \\`${paramName}\\`.`);\n this.name = \"FetchFailedError\";\n }\n}\n\n/**\n * Thrown when a role fetch is attempted outside a server context\n */\nexport class NoServerContextError extends CommandValidationError {\n constructor(paramName: string, paramKind: \"arg\" | \"option\") {\n super(paramName, paramKind, `Cannot fetch role for \\`${paramName}\\` outside of a server.`);\n this.name = \"NoServerContextError\";\n }\n}\n","// src/di/Container.ts\nimport \"reflect-metadata\";\n\nexport class StoatxContainer {\n private instances = new Map<Function, any>();\n\n /**\n * Resolves a class instance, injecting any required dependencies.\n */\n resolve<T>(target: any): T {\n if (this.instances.has(target)) {\n return this.instances.get(target);\n }\n\n const paramTypes: any[] = Reflect.getMetadata(\"design:paramtypes\", target) || [];\n\n const injections = paramTypes.map((param: any) => {\n if (!param) {\n throw new Error(\n `[Stoatx DI] Cannot resolve dependency for ${target.name}. Ensure all injected services are decorated with @Injectable().`,\n );\n }\n return this.resolve(param);\n });\n\n const instance = new target(...injections);\n\n this.instances.set(target, instance);\n\n return instance;\n }\n}\n","import { Client as StoatClient, ClientOptions, Message } from \"@stoatx/client\";\nimport type { StoatxHandlerOptions } from \"./types\";\nimport { StoatxHandler } from \"./handler\";\n\n/**\n * Client - An extended Client that integrates StoatxHandler directly\n *\n * @example\n * ```ts\n * import { Client } from 'stoatx';\n *\n * const client = new Client({\n * prefix: '!',\n * owners: ['owner-user-id'],\n * });\n *\n * await client.initCommands();\n * ```\n */\nexport class Client extends StoatClient {\n public readonly handler: StoatxHandler;\n\n constructor(options: Omit<StoatxHandlerOptions, \"client\"> & ClientOptions) {\n super(options);\n this.handler = new StoatxHandler({ ...options, client: this });\n }\n\n override async login(token: string): Promise<string> {\n await this.handler.init();\n return super.login(token);\n }\n\n async executeCommand(message: Message): Promise<void> {\n await this.handler.handle(message);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA,oBAA8F;AA8JvF,IAAMA,iBAAiB,oBAAIC,IAAiC;EACjE;IAACC;IAAQ;;EACT;IAACC;IAAQ;;EACT;IAACC;IAAS;;EACV;IAACC;IAAM;;EACP;IAACC;IAAa;;EACd;IAACC;IAAM;;CACR;;;ACrKD,8BAAO;;;ACGA,IAAMC,gBAAgB;EAC3BC,gBAAgBC,uBAAO,sBAAA;EACvBC,iBAAiBD,uBAAO,6BAAA;EACxBE,QAAQ;EACRC,QAAQH,uBAAO,qBAAA;EACfI,MAAMJ,uBAAO,mBAAA;EACbK,SAASL,uBAAO,sBAAA;EAChBM,YAAYN,uBAAO,mBAAA;EACnBO,YAAYP,uBAAO,mBAAA;EACnBQ,eAAeR,uBAAO,qBAAA;AACxB;;;ACPO,IAAMS,iBAAN,MAAMA,gBAAAA;EAJb,OAIaA;;;EACX,OAAeC;;EAGPC,eAA8B,oBAAIC,IAAAA;;EAGlCC,WAAgC,CAAA;;EAGhCC,cAAc;EAEtB,cAAsB;EAAC;EAEvB,OAAOC,cAA8B;AACnC,QAAI,CAACN,gBAAeC,UAAU;AAC5BD,sBAAeC,WAAW,IAAID,gBAAAA;IAChC;AACA,WAAOA,gBAAeC;EACxB;;;;EAKAM,mBAAmBC,kBAAkC;AACnD,SAAKN,aAAaO,IAAID,gBAAAA;EACxB;;;;EAKAE,kBAAiC;AAC/B,WAAO,KAAKR;EACd;;;;EAKAS,WAAWC,SAAkC;AAC3C,SAAKR,SAASS,KAAKD,OAAAA;EACrB;;;;EAKAE,cAAmC;AACjC,WAAO,KAAK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B,aAAa,MAAM,KAAKA,eAAe;MAAEoD;IAAS,CAAA,IAAK,KAAKpD;AAC7F,WAAOsH,MAAMsC,QAAQD,MAAAA,IAAUA,SAAS;MAACA;;EAC3C;AACF;;;AGxhBA,IAAAE,iBAA8D;AAmBvD,IAAMC,SAAN,cAAqBC,eAAAA,OAAAA;EAnB5B,OAmB4BA;;;EACVC;EAEhB,YAAYC,SAA+D;AACzE,UAAMA,OAAAA;AACN,SAAKD,UAAU,IAAIE,cAAc;MAAE,GAAGD;MAASE,QAAQ;IAAK,CAAA;EAC9D;EAEA,MAAeC,MAAMC,OAAgC;AACnD,UAAM,KAAKL,QAAQM,KAAI;AACvB,WAAO,MAAMF,MAAMC,KAAAA;EACrB;EAEA,MAAME,eAAeC,SAAiC;AACpD,UAAM,KAAKR,QAAQS,OAAOD,OAAAA;EAC5B;AACF;;;AlBnBA,0BAAc,2BAhBd;","names":["PARAM_TYPE_MAP","Map","String","Number","Boolean","User","BaseChannel","Role","METADATA_KEYS","IS_STOAT_CLASS","Symbol","SIMPLE_COMMANDS","GUARDS","EVENTS","ARGS","OPTIONS","INJECTABLE","SUBCOMMAND","COMMAND_GROUP","DecoratorStore","instance","stoatClasses","Set","commands","initialized","getInstance","registerStoatClass","classConstructor","add","getStoatClasses","addCommand","command","push","getCommands","clear","markInitialized","isInitialized","decoratorStore","Stoat","target","Reflect","defineMetadata","METADATA_KEYS","IS_STOAT_CLASS","decoratorStore","registerStoatClass","isStoatClass","getMetadata","import_reflect_metadata","SimpleCommand","options","target","propertyKey","descriptor","constructor","existingCommands","Reflect","getMetadata","METADATA_KEYS","SIMPLE_COMMANDS","push","methodName","String","defineMetadata","getSimpleCommands","import_reflect_metadata","Guard","guardClass","target","propertyKey","existingGuards","Reflect","getMetadata","METADATA_KEYS","GUARDS","push","defineMetadata","getGuards","prototype","import_reflect_metadata","createEventDecorator","event","type","target","propertyKey","descriptor","constructor","existingEvents","Reflect","getMetadata","METADATA_KEYS","EVENTS","push","methodName","String","defineMetadata","On","Once","getEventsMetadata","import_reflect_metadata","Arg","options","target","propertyKey","parameterIndex","existing","Reflect","getMetadata","METADATA_KEYS","ARGS","push","index","defineMetadata","getArgs","import_reflect_metadata","Option","options","target","propertyKey","parameterIndex","existing","Reflect","getMetadata","METADATA_KEYS","OPTIONS","push","index","defineMetadata","getOptions","import_reflect_metadata","Injectable","target","Reflect","defineMetadata","METADATA_KEYS","INJECTABLE","import_reflect_metadata","CommandGroup","name","target","Reflect","defineMetadata","METADATA_KEYS","COMMAND_GROUP","import_reflect_metadata","SubCommand","options","opts","name","target","propertyKey","Reflect","defineMetadata","METADATA_KEYS","SUBCOMMAND","buildSimpleCommandMetadata","options","methodName","category","params","name","toLowerCase","description","aliases","permissions","cooldown","cooldownStorage","undefined","nsfw","ownerOnly","getSubCommands","target","methods","Object","getOwnPropertyNames","prototype","subCommands","method","Reflect","getMetadata","METADATA_KEYS","SUBCOMMAND","push","CommandRegistry","DEFAULT_AUTO_DISCOVERY_IGNORES","commands","Map","aliases","registeredEvents","extensions","processedStoatClasses","Set","container","size","loadFromDirectory","directory","patterns","map","ext","join","replace","pattern","files","glob","ignore","absolute","file","loadFile","console","log","length","autoDiscover","options","roots","process","cwd","includePatterns","include","getDefaultAutoDiscoveryPatterns","flatMap","root","uniqueFiles","isLikelyCommandModule","baseDir","find","relative","startsWith","isAbsolute","filePath","source","readFile","includes","register","instance","metadata","classConstructor","methodName","groupOptions","Reflect","getMetadata","METADATA_KEYS","COMMAND_GROUP","subCommandOptions","SUBCOMMAND","subCommandName","name","toLowerCase","has","warn","validateGuards","set","alias","aliasLower","get","lowerName","resolvedName","getAll","Array","from","values","getAllMetadata","c","getEvents","getByCategory","categories","cmd","category","existing","push","clear","Symbol","iterator","entries","keys","commandClass","commandName","guards","GUARDS","GuardClass","guardInstance","resolve","run","error","exit","guardFail","knownStoatClasses","decoratorStore","getStoatClasses","fileUrl","pathToFileURL","href","allStoatClasses","stoatClass","registerStoatClassCommands","simpleCommands","getSimpleCommands","subCommands","getSubCommands","events","getEventsMetadata","getCategoryFromPath","allCommands","add","cmdDef","method","params","buildParamSchema","prototype","buildSimpleCommandMetadata","eventDef","event","type","paramTypes","argDefs","getArgs","optionDefs","getOptions","argByIndex","a","index","optionByIndex","o","i","reflectedType","optDef","resolvedType","PARAM_TYPE_MAP","kind","required","argDef","fetch","parts","split","sep","undefined","import_reflect_metadata","StoatxError","Error","message","name","CommandValidationError","paramName","paramKind","MissingArgumentError","MissingOptionError","flagPrefix","repeat","InvalidTypeError","expected","received","InvalidMentionError","mentionKind","rawValue","FetchFailedError","resolvedId","NoServerContextError","import_reflect_metadata","StoatxContainer","instances","Map","resolve","target","has","get","paramTypes","Reflect","getMetadata","injections","map","param","Error","name","instance","set","DefaultCooldownManager","cooldowns","Map","check","ctx","metadata","cooldown","commandCooldowns","get","name","expirationTime","authorId","Date","now","delete","getRemaining","userCooldown","Math","max","set","has","clear","StoatxHandler","commandsDir","discoveryOptions","prefixResolver","owners","registry","cooldownManager","disableMentionPrefix","client","flagPrefix","globalGuards","container","StoatxContainer","options","discovery","prefix","Set","CommandRegistry","extensions","init","loadFromDirectory","autoDiscover","attachEvents","events","getEvents","eventDef","handler","args","instance","methodName","error","console","type","event","eventName","once","on","parseRawInput","rawArgs","flags","i","length","arg","undefined","startsWith","key","slice","nextArg","push","parseMessage","rawContent","message","meta","prefixes","resolvePrefix","serverId","usedPrefix","withoutPrefix","matchedPrefix","find","p","trim","match","mentionMatch","mentionedId","botId","user","id","parts","split","part1","part2","commandKey","toLowerCase","remainingParts","content","channelId","commandName","reply","_rawArgs","_rawFlags","handle","channel","author","bot","server","send","handleMessage","execute","registered","classConstructor","ownerOnly","permissions","member","members","fetch","onMissingPermissions","missing","classGuards","Reflect","getMetadata","METADATA_KEYS","GUARDS","methodGuards","allGuards","guardClass","guardInstance","resolve","run","guardResult","guardFail","remaining","onCooldown","toFixed","resolvedParams","resolveParams","params","onError","reportValidationError","onValidationError","resolved","Array","argCursor","param","kind","index","rawValue","required","paramName","MissingArgumentError","value","resolveValue","MissingOptionError","String","resolvedType","num","Number","isNaN","InvalidTypeError","Boolean","InvalidMentionError","userId","users","FetchFailedError","cache","channels","roleId","NoServerContextError","roles","getRegistry","getCommand","getCommands","getAll","reload","isOwner","addOwner","add","removeOwner","result","isArray","import_client","Client","StoatClient","handler","options","StoatxHandler","client","login","token","init","executeCommand","message","handle"]}
|