commandkit 0.1.11-dev.20250208131735 → 0.1.11-dev.20250213182706

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 CHANGED
@@ -1,6 +1,7 @@
1
1
  import * as discord_js from 'discord.js';
2
- import { Client, Interaction, CacheType, ChatInputCommandInteraction, ContextMenuCommandInteraction, UserContextMenuCommandInteraction, MessageContextMenuCommandInteraction, AutocompleteInteraction, PermissionsString, RESTPostAPIApplicationCommandsJSONBody, ClientEvents, Awaitable, ButtonInteraction, Events, ButtonBuilder, ModalSubmitInteraction, ModalBuilder, ActionRowBuilder, TextInputBuilder, ButtonStyle, ComponentEmojiResolvable, TextInputStyle } from 'discord.js';
2
+ import { Client, Interaction, CacheType, ChatInputCommandInteraction, ContextMenuCommandInteraction, UserContextMenuCommandInteraction, MessageContextMenuCommandInteraction, AutocompleteInteraction, PermissionsString, RESTPostAPIApplicationCommandsJSONBody, ClientEvents, Awaitable, ButtonInteraction, Events, ButtonBuilder, ModalSubmitInteraction, ModalBuilder, ActionRowBuilder, TextInputBuilder, ButtonStyle, ComponentEmojiResolvable, TextInputStyle, Locale, ApplicationCommandOptionType, Message, GuildMember, Attachment, User, Role, CommandInteractionOption, SlashCommandBuilder, ContextMenuCommandBuilder } from 'discord.js';
3
3
  import EventEmitter from 'node:events';
4
+ import { Channel } from 'diagnostics_channel';
4
5
  import * as commander from 'commander';
5
6
 
6
7
  interface CacheEntry<T = unknown> {
@@ -345,6 +346,238 @@ interface EventHandlerOptions {
345
346
  commandKitInstance: CommandKit;
346
347
  }
347
348
 
349
+ /**
350
+ * Matcher type for identifying command and middleware files.
351
+ * Can be a string suffix (e.g. '.cmd.js'), RegExp pattern, or custom matcher function.
352
+ */
353
+ type CommandsRouterMatcher = string | RegExp | ((path: string) => boolean);
354
+ /**
355
+ * Maps file type identifiers to their respective matchers.
356
+ * Used to identify command and middleware files in the directory structure.
357
+ */
358
+ type CommandsRouterMatchersMap = Record<'command' | 'middleware', CommandsRouterMatcher>;
359
+ /**
360
+ * Configuration options for the CommandsRouter
361
+ */
362
+ interface CommandsRouterOptions {
363
+ /**
364
+ * The path to the directory containing the command files.
365
+ */
366
+ entrypoint: string;
367
+ /**
368
+ * The path to the directory containing the middleware files.
369
+ */
370
+ matcher?: Partial<CommandsRouterMatchersMap>;
371
+ }
372
+ /**
373
+ * Represents a parsed command with its metadata
374
+ * @interface ParsedCommand
375
+ */
376
+ interface ParsedCommand {
377
+ /** Command name derived from the file name without extension */
378
+ name: string;
379
+ /** Absolute file system path to the command file */
380
+ path: string;
381
+ /** Parent command name for nested commands, or null if root-level command */
382
+ parent: string | null;
383
+ /** Array of command segments representing the command hierarchy */
384
+ parentSegments: string[];
385
+ /** Array of middleware IDs that apply to this command */
386
+ middlewares: string[];
387
+ /** Absolute path to this command */
388
+ fullPath: string;
389
+ }
390
+ /**
391
+ * Represents a parsed middleware with its metadata
392
+ * @interface ParsedMiddleware
393
+ */
394
+ interface ParsedMiddleware {
395
+ /** Unique identifier used to reference this middleware */
396
+ id: string;
397
+ /** Middleware name derived from the file path */
398
+ name: string;
399
+ /** Path to the middleware file, relative to the entrypoint */
400
+ path: string;
401
+ /** Absolute path to the middleware file */
402
+ fullPath: string;
403
+ }
404
+ /**
405
+ * Complete tree structure of all commands and middleware
406
+ * @interface CommandsTree
407
+ */
408
+ interface CommandsTree {
409
+ /** Map of command names to their parsed metadata */
410
+ commands: Record<string, ParsedCommand>;
411
+ /** Map of middleware IDs to their parsed metadata */
412
+ middleware: Record<string, ParsedMiddleware>;
413
+ }
414
+ /**
415
+ * Result of a successful command match operation
416
+ * @interface CommandMatchResult
417
+ */
418
+ interface CommandMatchResult {
419
+ /** The matched command metadata */
420
+ command: ParsedCommand;
421
+ /** Array of middleware that apply to the matched command */
422
+ middlewares: ParsedMiddleware[];
423
+ }
424
+ /**
425
+ * CommandsRouter handles the discovery and routing of commands and middleware files
426
+ * in a directory structure. It supports nested commands and middleware inheritance.
427
+ */
428
+ declare class CommandsRouter {
429
+ private readonly options;
430
+ private commands;
431
+ private middlewares;
432
+ /**
433
+ * Creates a new CommandsRouter instance
434
+ * @param options - Configuration options for the router
435
+ */
436
+ constructor(options: CommandsRouterOptions);
437
+ /**
438
+ * Gets the configured entrypoint directory
439
+ */
440
+ get entrypoint(): string;
441
+ /**
442
+ * Gets the configured matchers for command and middleware files
443
+ */
444
+ get matchers(): CommandsRouterMatchersMap;
445
+ /**
446
+ * Returns the cached data of the commands and middleware
447
+ */
448
+ getData(): {
449
+ commands: Map<string, ParsedCommand>;
450
+ middleware: Map<string, ParsedMiddleware>;
451
+ };
452
+ /**
453
+ * Checks if the entrypoint path is valid
454
+ */
455
+ isValidPath(): boolean;
456
+ /**
457
+ * Executes a matcher against a file path
458
+ * @param matcher - The matcher to use
459
+ * @param path - The file path to test
460
+ * @returns boolean indicating if the path matches
461
+ */
462
+ private execMatcher;
463
+ /**
464
+ * Converts an absolute path to a path relative to the entrypoint
465
+ * @param path - The absolute path to convert
466
+ */
467
+ private resolveRelativePath;
468
+ /**
469
+ * Matches a command by name or path segments
470
+ * @param commandOrSegment - Command name or array of path segments
471
+ * @returns Matched command and its middlewares, or null if no match
472
+ */
473
+ match(commandOrSegment: string | string[]): CommandMatchResult | null;
474
+ /**
475
+ * Reloads the commands tree by re-scanning the entrypoint directory
476
+ */
477
+ reload(): Promise<CommandsTree>;
478
+ /**
479
+ * Clears the internal commands and middleware maps
480
+ */
481
+ clear(): void;
482
+ /**
483
+ * Scans the entrypoint directory for commands and middleware
484
+ * @returns Promise resolving to the complete commands tree
485
+ */
486
+ scan(): Promise<CommandsTree>;
487
+ /**
488
+ * Converts the internal maps to a serializable object
489
+ * @returns CommandsTree containing all commands and middleware
490
+ */
491
+ toJSON(): CommandsTree;
492
+ /**
493
+ * Recursively scans a directory for files
494
+ * @param dir - Directory to scan
495
+ * @param entries - Accumulator for found files
496
+ * @returns Promise resolving to array of file paths
497
+ */
498
+ private scanDirectory;
499
+ }
500
+
501
+ /**
502
+ * Configuration options for the EventsRouter
503
+ * @interface EventsRouterOptions
504
+ */
505
+ interface EventsRouterOptions {
506
+ /** Root directory path where event handlers are located */
507
+ entrypoint: string;
508
+ }
509
+ /**
510
+ * Represents a parsed event with its handlers
511
+ * @interface ParsedEvent
512
+ */
513
+ interface ParsedEvent {
514
+ /** Name of the event derived from directory name */
515
+ event: string;
516
+ /** Absolute path to the event directory */
517
+ path: string;
518
+ /** Array of file paths to event listener handlers */
519
+ listeners: string[];
520
+ }
521
+ /** Map of event names to their parsed metadata */
522
+ type EventsTree = Record<string, ParsedEvent>;
523
+ /**
524
+ * Router for discovering and managing event handler files in a directory structure.
525
+ * Events are represented by directories, and handlers are files within those directories.
526
+ */
527
+ declare class EventsRouter {
528
+ private options;
529
+ /** Internal storage of parsed events */
530
+ private events;
531
+ /**
532
+ * Creates a new EventsRouter instance
533
+ * @param options - Configuration options for the router
534
+ * @throws Error if entrypoint is not provided
535
+ */
536
+ constructor(options: EventsRouterOptions);
537
+ /**
538
+ * Find a parsed event by its name
539
+ * @param event - Name of the event to find
540
+ * @returns Parsed event metadata or null if not found
541
+ */
542
+ match(event: string): ParsedEvent | null;
543
+ /**
544
+ * Get the entrypoint directory path
545
+ * @returns Entrypoint directory path
546
+ */
547
+ get entrypoint(): string;
548
+ /**
549
+ * Checks if the entrypoint path is valid
550
+ */
551
+ isValidPath(): boolean;
552
+ /**
553
+ * Clear all parsed events
554
+ */
555
+ clear(): void;
556
+ /**
557
+ * Reload and re-scan the entrypoint directory for events
558
+ * @returns Promise resolving to the updated events tree
559
+ */
560
+ reload(): Promise<EventsTree>;
561
+ /**
562
+ * Scan the entrypoint directory for events and their handlers
563
+ * @returns Promise resolving to the events tree
564
+ */
565
+ scan(): Promise<EventsTree>;
566
+ /**
567
+ * Convert the internal events map to a plain object
568
+ * @returns Events tree as a plain object
569
+ */
570
+ toJSON(): EventsTree;
571
+ /**
572
+ * Recursively scan a directory for event handlers
573
+ * @param event - Name of the event
574
+ * @param path - Path to the event directory
575
+ * @param listeners - Array to collect listener file paths
576
+ * @returns Promise resolving to the parsed event metadata
577
+ */
578
+ private scanEvent;
579
+ }
580
+
348
581
  /**
349
582
  * A handler for client events.
350
583
  */
@@ -352,6 +585,8 @@ declare class EventHandler {
352
585
  #private;
353
586
  constructor({ ...options }: EventHandlerOptions);
354
587
  init(): Promise<void>;
588
+ registerExternal(entry: ParsedEvent): Promise<void>;
589
+ resyncListeners(): void;
355
590
  get events(): {
356
591
  name: string;
357
592
  functions: Function[];
@@ -372,11 +607,20 @@ interface EventInterceptorContextData<E extends keyof ClientEvents> {
372
607
  * If the collector should automatically reset the timer when a button is clicked.
373
608
  */
374
609
  autoReset?: boolean;
610
+ /**
611
+ * Whether the collector should run only once.
612
+ */
613
+ once?: boolean;
375
614
  /**
376
615
  * The handler to run when the collector ends.
377
616
  */
378
617
  onEnd?: (reason: string) => Awaitable<void>;
618
+ /**
619
+ * The handler to run upon an error.
620
+ */
621
+ onError?: EventInterceptorErrorHandler;
379
622
  }
623
+ type EventInterceptorErrorHandler = (error: Error) => Awaitable<void>;
380
624
  declare class EventInterceptor {
381
625
  #private;
382
626
  readonly client: Client;
@@ -444,7 +688,7 @@ type OnButtonKitEnd = CommandKitButtonBuilderOnEnd;
444
688
  * The handler to run when a button is clicked. This handler is called with the interaction as the first argument.
445
689
  * If the first argument is null, it means that the interaction collector has been destroyed.
446
690
  */
447
- type CommandKitButtonBuilderInteractionCollectorDispatch = (interaction: ButtonInteraction) => Awaitable<void>;
691
+ type CommandKitButtonBuilderInteractionCollectorDispatch = (interaction: ButtonInteraction, context: ButtonKit) => Awaitable<void>;
448
692
  type CommandKitButtonBuilderOnEnd = (reason: string) => Awaitable<void>;
449
693
  type CommandKitButtonBuilderInteractionCollectorDispatchContextData = EventInterceptorContextData<Events.InteractionCreate>;
450
694
  declare class ButtonKit extends ButtonBuilder {
@@ -476,6 +720,12 @@ declare class ButtonKit extends ButtonBuilder {
476
720
  */
477
721
  onClick(handler: CommandKitButtonBuilderInteractionCollectorDispatch, data?: CommandKitButtonBuilderInteractionCollectorDispatchContextData): this;
478
722
  onEnd(handler: CommandKitButtonBuilderOnEnd): this;
723
+ /**
724
+ * Sets the handler to run when the interaction collector ends.
725
+ * @param handler - The handler to run when the interaction collector ends.
726
+ * @returns This instance of the modal builder.
727
+ */
728
+ onError(handler: EventInterceptorErrorHandler): this;
479
729
  /**
480
730
  * Sets a filter for the interaction collector.
481
731
  * @param predicate The filter to use for the interaction collector
@@ -500,7 +750,7 @@ type OnModalKitEnd = CommandKitModalBuilderOnEnd;
500
750
  * The handler to run when a modal is submitted. This handler is called with the interaction as the first argument.
501
751
  * If the first argument is null, it means that the interaction collector has been destroyed.
502
752
  */
503
- type CommandKitModalBuilderInteractionCollectorDispatch = (interaction: ModalSubmitInteraction) => Awaitable<void>;
753
+ type CommandKitModalBuilderInteractionCollectorDispatch = (interaction: ModalSubmitInteraction, context: ModalKit) => Awaitable<void>;
504
754
  type CommandKitModalBuilderOnEnd = (reason: string) => Awaitable<void>;
505
755
  type CommandKitModalBuilderInteractionCollectorDispatchContextData = EventInterceptorContextData<Events.InteractionCreate>;
506
756
  declare class ModalKit extends ModalBuilder {
@@ -529,6 +779,12 @@ declare class ModalKit extends ModalBuilder {
529
779
  * @returns This instance of the modal builder.
530
780
  */
531
781
  onEnd(handler: CommandKitModalBuilderOnEnd): this;
782
+ /**
783
+ * Sets the handler to run when the interaction collector ends.
784
+ * @param handler - The handler to run when the interaction collector ends.
785
+ * @returns This instance of the modal builder.
786
+ */
787
+ onError(handler: EventInterceptorErrorHandler): this;
532
788
  /**
533
789
  * Sets a filter for the interaction collector.
534
790
  * @param predicate - The filter to use for the interaction collector.
@@ -585,6 +841,7 @@ interface ButtonProps {
585
841
  url?: string;
586
842
  skuId?: string;
587
843
  onClick?: CommandKitButtonBuilderInteractionCollectorDispatch;
844
+ onError?: EventInterceptorErrorHandler;
588
845
  options?: CommandKitButtonBuilderInteractionCollectorDispatchContextData;
589
846
  onEnd?: CommandKitButtonBuilderOnEnd;
590
847
  children?: MaybeArray<ButtonChildrenLike>;
@@ -603,6 +860,7 @@ interface ModalProps {
603
860
  children?: MaybeArray<TextInputBuilder | ActionRowBuilder>;
604
861
  onSubmit?: OnModalKitSubmit;
605
862
  onEnd?: OnModalKitEnd;
863
+ onError?: EventInterceptorErrorHandler;
606
864
  options?: CommandKitModalBuilderInteractionCollectorDispatchContextData;
607
865
  }
608
866
  /**
@@ -645,11 +903,459 @@ declare function ShortInput(props: TextInputProps): CommandKitElement<'text-inpu
645
903
  */
646
904
  declare function ParagraphInput(props: TextInputProps): CommandKitElement<'text-input'>;
647
905
 
906
+ interface TranslatableCommand {
907
+ name?: string;
908
+ description?: string;
909
+ options?: TranslatableCommandOptions[];
910
+ }
911
+ interface TranslatableCommandOptions {
912
+ ref: string;
913
+ name?: string;
914
+ description?: string;
915
+ }
916
+ interface Translation {
917
+ command: TranslatableCommand;
918
+ translations: TranslatableArguments;
919
+ }
920
+ type TranslatableArguments = Record<string, string>;
921
+
922
+ interface LocalizationTranslationRequest {
923
+ locale: Locale;
924
+ scope: string;
925
+ key: string;
926
+ args?: Record<string, any> | undefined;
927
+ }
928
+ type TranslationResult = string;
929
+ interface LocalizationStrategy {
930
+ locateTranslation(scope: string, locale: Locale): Promise<Translation | null>;
931
+ getTranslation(scope: string, locale: Locale): Promise<Translation | null>;
932
+ getTranslationStrict(scope: string, locale: Locale): Promise<Translation>;
933
+ translate(request: LocalizationTranslationRequest): Promise<TranslationResult>;
934
+ }
935
+
936
+ interface LocalizationConfig {
937
+ /**
938
+ * The locale to use for localization.
939
+ */
940
+ locale: Locale;
941
+ /**
942
+ * The internalization data target.
943
+ */
944
+ target: string;
945
+ }
946
+ type Translator = (translatable: string, args?: TranslatableArguments | undefined) => Promise<TranslationResult>;
947
+ declare class Localization {
948
+ private readonly commandkit;
949
+ private readonly config;
950
+ /**
951
+ * Translates the given translatable object.
952
+ * @param translatable The translatable object to translate.
953
+ */
954
+ readonly t: Translator;
955
+ /**
956
+ * Creates a new localization instance.
957
+ * @param commandkit The command kit instance.
958
+ * @param config The localization configuration.
959
+ */
960
+ constructor(commandkit: CommandKit, config: LocalizationConfig);
961
+ /**
962
+ * Get the localization strategy.
963
+ */
964
+ getStrategy(): LocalizationStrategy;
965
+ /**
966
+ * Get the default locale
967
+ */
968
+ getDefaultLocale(): Locale;
969
+ /**
970
+ * Get the current locale
971
+ */
972
+ getLocale(): Locale;
973
+ /**
974
+ * Get the localization target
975
+ */
976
+ getTarget(): string;
977
+ }
978
+
979
+ interface ParsedMessageCommand {
980
+ command: string;
981
+ options: {
982
+ name: string;
983
+ value: unknown;
984
+ }[];
985
+ subcommand?: string;
986
+ subcommandGroup?: string;
987
+ }
988
+ type MessageCommandOptionsSchema = Record<string, ApplicationCommandOptionType>;
989
+ declare class MessageCommandParser {
990
+ #private;
991
+ message: Message;
992
+ private prefix;
993
+ private schema;
994
+ constructor(message: Message, prefix: string[], schema: (command: string) => MessageCommandOptionsSchema);
995
+ getArgs(): string[];
996
+ get options(): MessageCommandOptions;
997
+ getOption<T>(name: string): T | undefined;
998
+ getCommand(): string;
999
+ getSubcommand(): string | undefined;
1000
+ getSubcommandGroup(): string | undefined;
1001
+ getPrefix(): string | undefined;
1002
+ getFullCommand(): string;
1003
+ parse(): ParsedMessageCommand;
1004
+ }
1005
+ declare class MessageCommandOptions {
1006
+ private parser;
1007
+ constructor(parser: MessageCommandParser);
1008
+ private assertOption;
1009
+ getMember(name: string): GuildMember | null;
1010
+ getMember(name: string, required: true): GuildMember;
1011
+ getAttachment(name: string): Attachment | null;
1012
+ getAttachment(name: string, required: true): Attachment;
1013
+ getBoolean(name: string): boolean | null;
1014
+ getBoolean(name: string, required: true): boolean;
1015
+ getNumber(name: string): number | null;
1016
+ getNumber(name: string, required: true): number;
1017
+ getString(name: string): string | null;
1018
+ getString(name: string, required: true): string;
1019
+ getInteger(name: string): number | null;
1020
+ getInteger(name: string, required: true): number;
1021
+ getUser(name: string): User | null;
1022
+ getUser(name: string, required: true): User;
1023
+ getChannel(name: string): Channel | null;
1024
+ getChannel(name: string, required: true): Channel;
1025
+ getRole(name: string): Role | null;
1026
+ getRole(name: string, required: true): Role;
1027
+ getMentionable(name: string): NonNullable<CommandInteractionOption['member' | 'role' | 'user']> | null;
1028
+ getMentionable(name: string, required: true): NonNullable<CommandInteractionOption['member' | 'role' | 'user']>;
1029
+ getSubcommand(): string | null;
1030
+ getSubcommand(required: true): string;
1031
+ getSubcommandGroup(): string | null;
1032
+ getSubcommandGroup(required: true): string;
1033
+ }
1034
+
1035
+ type GenericFunction<A extends any[] = any[]> = (...args: A) => any;
1036
+ declare function exitContext<T>(fn: () => T): T;
1037
+ /**
1038
+ * Returns a context-aware version of the given function.
1039
+ * @param env - The commandkit environment data.
1040
+ * @param fn - The target function.
1041
+ * @param finalizer - An optional finalizer function to run after the target function. This function will be context-aware.
1042
+ * @internal
1043
+ */
1044
+ declare function makeContextAwareFunction<R extends GenericFunction, F extends GenericFunction>(env: CommandKitEnvironment, fn: R, finalizer?: F): R;
1045
+ /**
1046
+ * Retrieves commandkit
1047
+ * @private
1048
+ * @internal
1049
+ */
1050
+ declare function getCommandKit(): CommandKit | undefined;
1051
+ declare function getCommandKit(strict: true): CommandKit;
1052
+ declare function getCommandKit(strict: false): CommandKit | undefined;
1053
+ /**
1054
+ * Get the current commandkit context.
1055
+ * @internal
1056
+ */
1057
+ declare function getContext(): CommandKitEnvironment | undefined;
1058
+ /**
1059
+ * Use current commandkit context. Throws an error if no context is found.
1060
+ */
1061
+ declare function useEnvironment(): CommandKitEnvironment;
1062
+ /**
1063
+ * Ensures the command is only available in guilds.
1064
+ * Note: do not wrap this function in a try/catch block.
1065
+ */
1066
+ declare function guildOnly(): void;
1067
+ /**
1068
+ * Ensures the command is only available in DMs.
1069
+ * Note: do not wrap this function in a try/catch block.
1070
+ */
1071
+ declare function dmOnly(): void;
1072
+
1073
+ interface CommandKitEnvironmentInternalData {
1074
+ executionError: Error | null;
1075
+ type: CommandKitEnvironmentType | null;
1076
+ variables: Map<string, any>;
1077
+ deferredFunctions: Map<string, GenericFunction<[CommandKitEnvironment]>>;
1078
+ marker: string;
1079
+ markStart: number;
1080
+ markEnd: number;
1081
+ }
1082
+ declare class CommandKitEnvironment {
1083
+ #private;
1084
+ readonly commandkit: CommandKit;
1085
+ /**
1086
+ * Creates the commandkit execution environment.
1087
+ * @param commandkit - The commandkit instance.
1088
+ */
1089
+ constructor(commandkit: CommandKit);
1090
+ /**
1091
+ * Get the execution error.
1092
+ * @internal
1093
+ */
1094
+ getExecutionError(): Error | null;
1095
+ /**
1096
+ * Set the execution error.
1097
+ * @param error - The error to set.
1098
+ * @internal
1099
+ */
1100
+ setExecutionError(error: Error): void;
1101
+ /**
1102
+ * Get the environment type.
1103
+ */
1104
+ getType(): CommandKitEnvironmentType;
1105
+ /**
1106
+ * Set the environment type.
1107
+ * @param type - The environment type to set.
1108
+ * @internal
1109
+ */
1110
+ setType(type: CommandKitEnvironmentType): void;
1111
+ /**
1112
+ * The variables store for this environment.
1113
+ */
1114
+ get variables(): Map<string, any>;
1115
+ /**
1116
+ * Register a deferred function.
1117
+ * @param fn - The deferred function to register.
1118
+ * @returns The deferred function id.
1119
+ * @internal
1120
+ */
1121
+ registerDeferredFunction(fn: GenericFunction<[CommandKitEnvironment]>): string;
1122
+ /**
1123
+ * Clear a deferred function by id.
1124
+ * @param id - The deferred function id to clear.
1125
+ * @internal
1126
+ */
1127
+ clearDeferredFunction(id: string): void;
1128
+ /**
1129
+ * Run all deferred functions sequentially.
1130
+ * @internal
1131
+ */
1132
+ runDeferredFunctions(): Promise<void>;
1133
+ /**
1134
+ * Clear all deferred functions.
1135
+ * @internal
1136
+ */
1137
+ clearAllDeferredFunctions(): void;
1138
+ /**
1139
+ * Mark the start of a command execution.
1140
+ * @param marker - The marker to set.
1141
+ * @internal
1142
+ */
1143
+ markStart(marker: string): void;
1144
+ /**
1145
+ * Mark the end of a command execution.
1146
+ * @internal
1147
+ */
1148
+ markEnd(): void;
1149
+ /**
1150
+ * Get the marker.
1151
+ * @internal
1152
+ */
1153
+ getMarker(): string;
1154
+ /**
1155
+ * Get the execution time in milliseconds.
1156
+ * @internal
1157
+ */
1158
+ getExecutionTime(): number;
1159
+ }
1160
+ declare enum CommandKitEnvironmentType {
1161
+ CommandHandler = "COMMAND_HANDLER"
1162
+ }
1163
+ /**
1164
+ * Runs the given function after the current command has finished executing.
1165
+ * @param fn The function to run after the current command.
1166
+ * @returns The deferred function id. This can be used to cancel the deferred function.
1167
+ */
1168
+ declare function afterCommand(fn: GenericFunction<[CommandKitEnvironment]>): string;
1169
+ /**
1170
+ * Cancels a deferred function registered with `afterCommand`.
1171
+ * @param id The deferred function id to cancel.
1172
+ */
1173
+ declare function cancelAfterCommand(id: string): void;
1174
+
1175
+ declare const CommandExecutionMode: {
1176
+ readonly SlashCommand: "chatInput";
1177
+ readonly MessageContextMenu: "messageContextMenu";
1178
+ readonly UserContextMenu: "userContextMenu";
1179
+ readonly Autocomplete: "autocomplete";
1180
+ readonly Message: "message";
1181
+ };
1182
+ type CommandExecutionMode = (typeof CommandExecutionMode)[keyof typeof CommandExecutionMode];
1183
+ interface ContextParameters<T extends CommandExecutionMode> {
1184
+ environment?: CommandKitEnvironment;
1185
+ executionMode: T;
1186
+ interaction: T extends 'chatInput' ? ChatInputCommandInteraction : T extends 'messageContextMenu' ? MessageContextMenuCommandInteraction : T extends 'userContextMenu' ? UserContextMenuCommandInteraction : T extends 'autocomplete' ? AutocompleteInteraction : never;
1187
+ message: T extends 'message' ? Message : never;
1188
+ forwarded?: boolean;
1189
+ messageCommandParser?: T extends 'message' ? MessageCommandParser : never;
1190
+ }
1191
+ type MessageCommandContext = Context<'message'>;
1192
+ type InteractionCommandContext = Context<'autocomplete' | 'chatInput' | 'messageContextMenu' | 'userContextMenu'>;
1193
+ type MessageCommandMiddlewareContext = MiddlewareContext<'message'>;
1194
+ type InteractionCommandMiddlewareContext = MiddlewareContext<'autocomplete' | 'chatInput' | 'messageContextMenu' | 'userContextMenu'>;
1195
+ type SlashCommandContext = Context<'chatInput'>;
1196
+ type SlashCommandMiddlewareContext = MiddlewareContext<'chatInput'>;
1197
+ type AutocompleteCommandContext = Context<'autocomplete'>;
1198
+ type AutocompleteCommandMiddlewareContext = MiddlewareContext<'autocomplete'>;
1199
+ type MessageContextMenuCommandContext = Context<'messageContextMenu'>;
1200
+ type MessageContextMenuCommandMiddlewareContext = MiddlewareContext<'messageContextMenu'>;
1201
+ type UserContextMenuCommandContext = Context<'userContextMenu'>;
1202
+ type UserContextMenuCommandMiddlewareContext = MiddlewareContext<'userContextMenu'>;
1203
+ type CommandContextOptions<T extends CommandExecutionMode> = T extends 'message' ? MessageCommandOptions : T extends 'chatInput' ? ChatInputCommandInteraction['options'] : T extends 'autocomplete' ? AutocompleteInteraction['options'] : T extends 'messageContextMenu' ? MessageContextMenuCommandInteraction['options'] : T extends 'userContextMenu' ? UserContextMenuCommandInteraction['options'] : never;
1204
+ declare class Context<ExecutionMode extends CommandExecutionMode = CommandExecutionMode> {
1205
+ readonly commandkit: CommandKit;
1206
+ private readonly config;
1207
+ /**
1208
+ * The interaction that triggered the command.
1209
+ */
1210
+ readonly interaction: ContextParameters<ExecutionMode>['interaction'];
1211
+ /**
1212
+ * The message that triggered the command.
1213
+ */
1214
+ readonly message: ContextParameters<ExecutionMode>['message'];
1215
+ private _locale;
1216
+ /**
1217
+ * Creates a new command context.
1218
+ * @param commandkit The command kit instance.
1219
+ * @param config The context parameters.
1220
+ */
1221
+ constructor(commandkit: CommandKit, config: ContextParameters<ExecutionMode>);
1222
+ get commandName(): string;
1223
+ get options(): CommandContextOptions<ExecutionMode>;
1224
+ /**
1225
+ * Whether this context was forwarded from another context. This happens when a command forwards its context to another command.
1226
+ */
1227
+ get forwarded(): boolean;
1228
+ /**
1229
+ * Forwards the context to another command. The target handler will be the same as current handler.
1230
+ * @param command The command to forward to.
1231
+ */
1232
+ forwardCommand(command: string): Promise<never>;
1233
+ /**
1234
+ * The execution mode of the command.
1235
+ */
1236
+ get executionMode(): ExecutionMode;
1237
+ /**
1238
+ * Whether the command was triggered by an interaction.
1239
+ */
1240
+ isInteraction(): this is InteractionCommandContext;
1241
+ /**
1242
+ * Whether the command was triggered by a slash command interaction.
1243
+ */
1244
+ isSlashCommand(): this is SlashCommandContext;
1245
+ /**
1246
+ * Whether the command was triggered by an autocomplete interaction.
1247
+ */
1248
+ isAutocomplete(): this is AutocompleteCommandContext;
1249
+ /**
1250
+ * Whether the command was triggered by a message context menu interaction.
1251
+ */
1252
+ isMessageContextMenu(): this is MessageContextMenuCommandContext;
1253
+ /**
1254
+ * Whether the command was triggered by a user context menu interaction.
1255
+ */
1256
+ isUserContextMenu(): this is UserContextMenuCommandContext;
1257
+ /**
1258
+ * Whether the command was triggered by a message.
1259
+ */
1260
+ isMessage(): this is Context<'message'>;
1261
+ /**
1262
+ * Returns the command identifier.
1263
+ */
1264
+ getCommandIdentifier(): string;
1265
+ /**
1266
+ * Returns the locale of the guild where this command was triggered.
1267
+ */
1268
+ getGuildLocale(): Locale | null;
1269
+ /**
1270
+ * Returns the locale of the user who triggered this command.
1271
+ */
1272
+ getUserLocale(): Locale | null;
1273
+ /**
1274
+ * Returns the locale for this command.
1275
+ * @param preferUser Whether to prefer the user's locale over the guild's locale.
1276
+ * @returns The locale for this command. If no locale is found, the default locale is returned.
1277
+ */
1278
+ getLocale(preferUser?: boolean): Locale;
1279
+ /**
1280
+ * Sets the locale for this command.
1281
+ * @param locale The locale to set.
1282
+ */
1283
+ setLocale(locale: Locale | null): void;
1284
+ /**
1285
+ * Returns the i18n api for this command.
1286
+ * @param locale The locale to use for the i18n api.
1287
+ */
1288
+ locale(locale?: Locale): Localization;
1289
+ /**
1290
+ * Creates a clone of this context
1291
+ */
1292
+ clone(config?: Partial<ContextParameters<ExecutionMode>>): Context<ExecutionMode>;
1293
+ isMiddleware(): this is MiddlewareContext<ExecutionMode>;
1294
+ args(): string[];
1295
+ }
1296
+ declare class MiddlewareContext<T extends CommandExecutionMode> extends Context<T> {
1297
+ #private;
1298
+ /**
1299
+ * Whether the command execution was cancelled.
1300
+ */
1301
+ get cancelled(): boolean;
1302
+ /**
1303
+ * Cancels the command execution.
1304
+ */
1305
+ cancel(): void;
1306
+ }
1307
+
1308
+ interface AppCommand {
1309
+ command: SlashCommandBuilder | Record<string, any>;
1310
+ chatInput?: (ctx: Context) => Awaitable<unknown>;
1311
+ autocomplete?: (ctx: Context) => Awaitable<unknown>;
1312
+ message?: (ctx: Context) => Awaitable<unknown>;
1313
+ messageContextMenu?: (ctx: Context) => Awaitable<unknown>;
1314
+ userContextMenu?: (ctx: Context) => Awaitable<unknown>;
1315
+ }
1316
+ interface AppCommandMiddleware {
1317
+ beforeExecute: (ctx: Context) => Awaitable<unknown>;
1318
+ afterExecute: (ctx: Context) => Awaitable<unknown>;
1319
+ }
1320
+ interface LoadedCommand {
1321
+ command: ParsedCommand;
1322
+ data: AppCommand;
1323
+ }
1324
+ interface LoadedMiddleware {
1325
+ middleware: ParsedMiddleware;
1326
+ data: AppCommandMiddleware;
1327
+ }
1328
+ interface PreparedAppCommandExecution {
1329
+ command: LoadedCommand;
1330
+ middlewares: LoadedMiddleware[];
1331
+ messageCommandParser?: MessageCommandParser;
1332
+ }
1333
+ type CommandBuilderLike = SlashCommandBuilder | ContextMenuCommandBuilder | Record<string, any>;
1334
+ declare class AppCommandHandler {
1335
+ readonly commandkit: CommandKit;
1336
+ private loadedCommands;
1337
+ private loadedMiddlewares;
1338
+ constructor(commandkit: CommandKit);
1339
+ getCommandsArray(): any[];
1340
+ prepareCommandRun(source: Interaction | Message): Promise<PreparedAppCommandExecution | null>;
1341
+ loadCommands(): Promise<void>;
1342
+ applyLocalizations(command: CommandBuilderLike): Promise<discord_js.RESTPostAPIContextMenuApplicationCommandsJSONBody | CommandBuilderLike>;
1343
+ }
1344
+
1345
+ interface CommandKitConfiguration {
1346
+ defaultLocale: Locale;
1347
+ localizationStrategy: LocalizationStrategy;
1348
+ getMessageCommandPrefix: (message: Message) => Awaitable<string | string[]>;
1349
+ }
648
1350
  declare class CommandKit extends EventEmitter {
649
1351
  #private;
650
1352
  readonly eventInterceptor: EventInterceptor;
651
1353
  static readonly createElement: typeof createElement;
652
1354
  static readonly Fragment: typeof Fragment;
1355
+ readonly config: CommandKitConfiguration;
1356
+ commandsRouter: CommandsRouter;
1357
+ eventsRouter: EventsRouter;
1358
+ appCommandsHandler: AppCommandHandler;
653
1359
  static instance: CommandKit | undefined;
654
1360
  /**
655
1361
  * Create a new command and event handler with CommandKit.
@@ -658,6 +1364,21 @@ declare class CommandKit extends EventEmitter {
658
1364
  * @see {@link https://commandkit.js.org/docs/guide/commandkit-setup}
659
1365
  */
660
1366
  constructor(options: CommandKitOptions);
1367
+ /**
1368
+ * Sets the prefix resolver for the command handler.
1369
+ * @param resolver The resolver function.
1370
+ */
1371
+ setPrefixResolver(resolver: (message: Message) => Awaitable<string | string[]>): this;
1372
+ /**
1373
+ * Sets the default locale for the command handler.
1374
+ * @param locale The default locale.
1375
+ */
1376
+ setDefaultLocale(locale: Locale): this;
1377
+ /**
1378
+ * Sets the localization strategy for the command handler.
1379
+ * @param strategy The localization strategy.
1380
+ */
1381
+ setLocalizationStrategy(strategy: LocalizationStrategy): this;
661
1382
  /**
662
1383
  * Resolves the current cache provider.
663
1384
  */
@@ -722,6 +1443,14 @@ declare class CommandKit extends EventEmitter {
722
1443
  * Decrement the client listeners count.
723
1444
  */
724
1445
  decrementClientListenersCount(): void;
1446
+ /**
1447
+ * Path to the app directory. Returns `null` if not found.
1448
+ * The lookup order is:
1449
+ * - `./app`
1450
+ * - `./src/app`
1451
+ */
1452
+ getAppDirectory(): string | null;
1453
+ getPath(to: 'locales' | 'commands' | 'events'): string | null;
725
1454
  }
726
1455
 
727
1456
  interface CommandKitConfig {
@@ -776,146 +1505,6 @@ type R = (typeof requiredProps)[number];
776
1505
  type PartialConfig<T extends CommandKitConfig> = Partial<Omit<T, R>> & Pick<T, R>;
777
1506
  declare function defineConfig(config: PartialConfig<CommandKitConfig>): Partial<CommandKitConfig>;
778
1507
 
779
- interface CommandKitEnvironmentInternalData {
780
- executionError: Error | null;
781
- type: CommandKitEnvironmentType | null;
782
- variables: Map<string, any>;
783
- deferredFunctions: Map<string, GenericFunction<[CommandKitEnvironment]>>;
784
- marker: string;
785
- markStart: number;
786
- markEnd: number;
787
- }
788
- declare class CommandKitEnvironment {
789
- #private;
790
- readonly commandkit: CommandKit;
791
- /**
792
- * Creates the commandkit execution environment.
793
- * @param commandkit - The commandkit instance.
794
- */
795
- constructor(commandkit: CommandKit);
796
- /**
797
- * Get the execution error.
798
- * @internal
799
- */
800
- getExecutionError(): Error | null;
801
- /**
802
- * Set the execution error.
803
- * @param error - The error to set.
804
- * @internal
805
- */
806
- setExecutionError(error: Error): void;
807
- /**
808
- * Get the environment type.
809
- */
810
- getType(): CommandKitEnvironmentType;
811
- /**
812
- * Set the environment type.
813
- * @param type - The environment type to set.
814
- * @internal
815
- */
816
- setType(type: CommandKitEnvironmentType): void;
817
- /**
818
- * The variables store for this environment.
819
- */
820
- get variables(): Map<string, any>;
821
- /**
822
- * Register a deferred function.
823
- * @param fn - The deferred function to register.
824
- * @returns The deferred function id.
825
- * @internal
826
- */
827
- registerDeferredFunction(fn: GenericFunction<[CommandKitEnvironment]>): string;
828
- /**
829
- * Clear a deferred function by id.
830
- * @param id - The deferred function id to clear.
831
- * @internal
832
- */
833
- clearDeferredFunction(id: string): void;
834
- /**
835
- * Run all deferred functions sequentially.
836
- * @internal
837
- */
838
- runDeferredFunctions(): Promise<void>;
839
- /**
840
- * Clear all deferred functions.
841
- * @internal
842
- */
843
- clearAllDeferredFunctions(): void;
844
- /**
845
- * Mark the start of a command execution.
846
- * @param marker - The marker to set.
847
- * @internal
848
- */
849
- markStart(marker: string): void;
850
- /**
851
- * Mark the end of a command execution.
852
- * @internal
853
- */
854
- markEnd(): void;
855
- /**
856
- * Get the marker.
857
- * @internal
858
- */
859
- getMarker(): string;
860
- /**
861
- * Get the execution time in milliseconds.
862
- * @internal
863
- */
864
- getExecutionTime(): number;
865
- }
866
- declare enum CommandKitEnvironmentType {
867
- CommandHandler = "COMMAND_HANDLER"
868
- }
869
- /**
870
- * Runs the given function after the current handler has finished executing.
871
- * @param fn The function to run after the current handler.
872
- * @returns The deferred function id. This can be used to cancel the deferred function.
873
- */
874
- declare function after(fn: GenericFunction<[CommandKitEnvironment]>): string;
875
- /**
876
- * Cancels a deferred function registered with `after`.
877
- * @param id The deferred function id to cancel.
878
- */
879
- declare function cancelAfter(id: string): void;
880
-
881
- type GenericFunction<A extends any[] = any[]> = (...args: A) => any;
882
- declare function exitContext<T>(fn: () => T): T;
883
- /**
884
- * Returns a context-aware version of the given function.
885
- * @param env - The commandkit environment data.
886
- * @param fn - The target function.
887
- * @param finalizer - An optional finalizer function to run after the target function. This function will be context-aware.
888
- * @internal
889
- */
890
- declare function makeContextAwareFunction<R extends GenericFunction, F extends GenericFunction>(env: CommandKitEnvironment, fn: R, finalizer?: F): R;
891
- /**
892
- * Retrieves commandkit
893
- * @private
894
- * @internal
895
- */
896
- declare function getCommandKit(): CommandKit | undefined;
897
- declare function getCommandKit(strict: true): CommandKit;
898
- declare function getCommandKit(strict: false): CommandKit | undefined;
899
- /**
900
- * Get the current commandkit context.
901
- * @internal
902
- */
903
- declare function getContext(): CommandKitEnvironment | void;
904
- /**
905
- * Use current commandkit context. Throws an error if no context is found.
906
- */
907
- declare function useEnvironment(): CommandKitEnvironment;
908
- /**
909
- * Ensures the command is only available in guilds.
910
- * Note: do not wrap this function in a try/catch block.
911
- */
912
- declare function guildOnly(): void;
913
- /**
914
- * Ensures the command is only available in DMs.
915
- * Note: do not wrap this function in a try/catch block.
916
- */
917
- declare function dmOnly(): void;
918
-
919
1508
  declare class MemoryCache extends CacheProvider {
920
1509
  #private;
921
1510
  get<T>(key: string): Promise<CacheEntry<T> | undefined>;
@@ -979,6 +1568,30 @@ declare function invalidate(tag: string): Promise<void>;
979
1568
  */
980
1569
  declare function revalidate<R = any>(tag: string, ...args: any[]): Promise<R | undefined>;
981
1570
 
1571
+ declare class DefaultLocalizationStrategy implements LocalizationStrategy {
1572
+ private readonly commandkit;
1573
+ private translations;
1574
+ constructor(commandkit: CommandKit);
1575
+ locateTranslation(scope: string, locale: Locale): Promise<Translation | null>;
1576
+ getTranslationStrict(scope: string, locale: Locale): Promise<Translation>;
1577
+ getTranslation(scope: string, locale: Locale): Promise<Translation | null>;
1578
+ translate(request: LocalizationTranslationRequest): Promise<TranslationResult>;
1579
+ private applyTranslation;
1580
+ }
1581
+
1582
+ /**
1583
+ * Cancel upcoming middleware execution.
1584
+ * If this is called inside pre-stage middleware, the next run will be the actual command, skipping all other pre-stage middlewares.
1585
+ * If this is called inside a command itself, it will skip all post-stage middlewares.
1586
+ * If this is called inside post-stage middleware, it will skip all other post-stage middlewares.
1587
+ */
1588
+ declare function exitMiddleware(): never;
1589
+ /**
1590
+ * Rethrow the error if it is a CommandKit error.
1591
+ * @param error The error to rethrow.
1592
+ */
1593
+ declare function rethrow(error: unknown): void;
1594
+
982
1595
  /**
983
1596
  * Creates a command line interface for CommandKit.
984
1597
  * @param argv The arguments passed to the CLI.
@@ -991,4 +1604,4 @@ declare function bootstrapCommandkitCLI(argv: string[], options?: commander.Pars
991
1604
  */
992
1605
  declare const version: string;
993
1606
 
994
- export { ActionRow, type ActionRowProps, type AnyCommandKitElement, type AsyncFunction, type AutocompleteProps, Button, type ButtonChildrenLike, ButtonKit, type ButtonKitPredicate, type ButtonProps, type CacheEntry, type CacheParams, CacheProvider, type CacheTag, type CommandContext, type CommandData, type CommandFileObject, CommandKit, type CommandKitButtonBuilderInteractionCollectorDispatch, type CommandKitButtonBuilderInteractionCollectorDispatchContextData, type CommandKitButtonBuilderOnEnd, type CommandKitConfig, type CommandKitData, type CommandKitElement, type CommandKitElementData, CommandKitEnvironment, type CommandKitEnvironmentInternalData, CommandKitEnvironmentType, type CommandKitModalBuilderInteractionCollectorDispatch, type CommandKitModalBuilderInteractionCollectorDispatchContextData, type CommandKitModalBuilderOnEnd, type CommandKitOptions, type CommandObject, type CommandOptions, type CommandProps, type ContextMenuCommandProps, ElementType, EventInterceptor, type EventInterceptorContextData, Fragment, type FragmentElementProps, type GenericFunction, type MaybeArray, MemoryCache, type MessageContextMenuCommandProps, Modal, ModalKit, type ModalKitPredicate, type ModalProps, type OnButtonKitClick, type OnButtonKitEnd, type OnModalKitEnd, type OnModalKitSubmit, ParagraphInput, type ReloadOptions, ReloadType, ShortInput, type SlashCommandProps, TextInput, type TextInputProps, type UserContextMenuCommandProps, type ValidationProps, after, bootstrapCommandkitCLI, cache, cacheLife, cacheTag, cancelAfter, createElement, CommandKit as default, defineConfig, dmOnly, exitContext, getCommandKit, getConfig, getContext, getElement, guildOnly, invalidate, isCommandKitElement, makeContextAwareFunction, revalidate, useCache as super_duper_secret_internal_for_use_cache_directive_of_commandkit_cli_do_not_use_it_directly_or_you_will_be_fired_from_your_job_kthxbai, useEnvironment, version };
1607
+ export { ActionRow, type ActionRowProps, type AnyCommandKitElement, AppCommandHandler, type AsyncFunction, type AutocompleteCommandContext, type AutocompleteCommandMiddlewareContext, type AutocompleteProps, Button, type ButtonChildrenLike, ButtonKit, type ButtonKitPredicate, type ButtonProps, type CacheEntry, type CacheParams, CacheProvider, type CacheTag, type CommandContext, type CommandContextOptions, type CommandData, CommandExecutionMode, type CommandFileObject, CommandKit, type CommandKitButtonBuilderInteractionCollectorDispatch, type CommandKitButtonBuilderInteractionCollectorDispatchContextData, type CommandKitButtonBuilderOnEnd, type CommandKitConfig, type CommandKitConfiguration, type CommandKitData, type CommandKitElement, type CommandKitElementData, CommandKitEnvironment, type CommandKitEnvironmentInternalData, CommandKitEnvironmentType, type CommandKitModalBuilderInteractionCollectorDispatch, type CommandKitModalBuilderInteractionCollectorDispatchContextData, type CommandKitModalBuilderOnEnd, type CommandKitOptions, type CommandObject, type CommandOptions, type CommandProps, Context, type ContextMenuCommandProps, type ContextParameters, DefaultLocalizationStrategy, ElementType, EventInterceptor, type EventInterceptorContextData, type EventInterceptorErrorHandler, Fragment, type FragmentElementProps, type GenericFunction, type InteractionCommandContext, type InteractionCommandMiddlewareContext, Localization, type LocalizationConfig, type LocalizationStrategy, type LocalizationTranslationRequest, type MaybeArray, MemoryCache, type MessageCommandContext, type MessageCommandMiddlewareContext, MessageCommandOptions, type MessageCommandOptionsSchema, MessageCommandParser, type MessageContextMenuCommandContext, type MessageContextMenuCommandMiddlewareContext, type MessageContextMenuCommandProps, MiddlewareContext, Modal, ModalKit, type ModalKitPredicate, type ModalProps, type OnButtonKitClick, type OnButtonKitEnd, type OnModalKitEnd, type OnModalKitSubmit, ParagraphInput, type ParsedMessageCommand, type PreparedAppCommandExecution, type ReloadOptions, ReloadType, ShortInput, type SlashCommandContext, type SlashCommandMiddlewareContext, type SlashCommandProps, TextInput, type TextInputProps, type TranslatableArguments, type TranslatableCommand, type TranslatableCommandOptions, type Translation, type TranslationResult, type Translator, type UserContextMenuCommandContext, type UserContextMenuCommandMiddlewareContext, type UserContextMenuCommandProps, type ValidationProps, afterCommand, bootstrapCommandkitCLI, cache, cacheLife, cacheTag, cancelAfterCommand, createElement, CommandKit as default, defineConfig, dmOnly, exitContext, exitMiddleware, getCommandKit, getConfig, getContext, getElement, guildOnly, invalidate, isCommandKitElement, makeContextAwareFunction, rethrow, revalidate, useCache as super_duper_secret_internal_for_use_cache_directive_of_commandkit_cli_do_not_use_it_directly_or_you_will_be_fired_from_your_job_kthxbai, useEnvironment, version };