oopscord.js 0.0.29 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/LICENSE +674 -201
  2. package/README.md +212 -11
  3. package/dist/index.js +1 -0
  4. package/dist/index.js.map +1 -0
  5. package/dist/structures/Constants.d.ts +2 -2
  6. package/dist/structures/Constants.d.ts.map +1 -1
  7. package/dist/structures/Constants.js +1 -0
  8. package/dist/structures/Constants.js.map +1 -0
  9. package/dist/structures/DiscordApp.d.ts +28 -10
  10. package/dist/structures/DiscordApp.d.ts.map +1 -1
  11. package/dist/structures/DiscordApp.js +681 -295
  12. package/dist/structures/DiscordApp.js.map +1 -0
  13. package/dist/structures/Plugin.d.ts +68 -0
  14. package/dist/structures/Plugin.d.ts.map +1 -1
  15. package/dist/structures/Plugin.js +28 -1
  16. package/dist/structures/Plugin.js.map +1 -0
  17. package/dist/structures/PluginManager.d.ts +122 -0
  18. package/dist/structures/PluginManager.d.ts.map +1 -0
  19. package/dist/structures/PluginManager.js +371 -0
  20. package/dist/structures/PluginManager.js.map +1 -0
  21. package/dist/structures/components/BaseButton.d.ts +2 -5
  22. package/dist/structures/components/BaseButton.d.ts.map +1 -1
  23. package/dist/structures/components/BaseButton.js +9 -14
  24. package/dist/structures/components/BaseButton.js.map +1 -0
  25. package/dist/structures/components/BaseModal.d.ts +13 -21
  26. package/dist/structures/components/BaseModal.d.ts.map +1 -1
  27. package/dist/structures/components/BaseModal.js +86 -132
  28. package/dist/structures/components/BaseModal.js.map +1 -0
  29. package/dist/structures/components/BaseSelectMenu.d.ts +2 -5
  30. package/dist/structures/components/BaseSelectMenu.d.ts.map +1 -1
  31. package/dist/structures/components/BaseSelectMenu.js +21 -25
  32. package/dist/structures/components/BaseSelectMenu.js.map +1 -0
  33. package/dist/structures/components/Listener.d.ts +18 -0
  34. package/dist/structures/components/Listener.d.ts.map +1 -0
  35. package/dist/structures/components/Listener.js +22 -0
  36. package/dist/structures/components/Listener.js.map +1 -0
  37. package/dist/structures/components/index.d.ts +1 -0
  38. package/dist/structures/components/index.d.ts.map +1 -1
  39. package/dist/structures/components/index.js +2 -0
  40. package/dist/structures/components/index.js.map +1 -0
  41. package/dist/structures/decorators/CommandDecorator.d.ts +39 -38
  42. package/dist/structures/decorators/CommandDecorator.d.ts.map +1 -1
  43. package/dist/structures/decorators/CommandDecorator.js +145 -250
  44. package/dist/structures/decorators/CommandDecorator.js.map +1 -0
  45. package/dist/structures/decorators/Constants.d.ts +12 -8
  46. package/dist/structures/decorators/Constants.d.ts.map +1 -1
  47. package/dist/structures/decorators/Constants.js +13 -8
  48. package/dist/structures/decorators/Constants.js.map +1 -0
  49. package/dist/structures/decorators/DiscordModuleDecorator.d.ts +11 -19
  50. package/dist/structures/decorators/DiscordModuleDecorator.d.ts.map +1 -1
  51. package/dist/structures/decorators/DiscordModuleDecorator.js +12 -54
  52. package/dist/structures/decorators/DiscordModuleDecorator.js.map +1 -0
  53. package/dist/structures/decorators/EventDecorator.d.ts +45 -0
  54. package/dist/structures/decorators/EventDecorator.d.ts.map +1 -0
  55. package/dist/structures/decorators/EventDecorator.js +52 -0
  56. package/dist/structures/decorators/EventDecorator.js.map +1 -0
  57. package/dist/structures/decorators/ExecutionDecorator.d.ts +19 -0
  58. package/dist/structures/decorators/ExecutionDecorator.d.ts.map +1 -0
  59. package/dist/structures/decorators/ExecutionDecorator.js +23 -0
  60. package/dist/structures/decorators/ExecutionDecorator.js.map +1 -0
  61. package/dist/structures/decorators/InjectionMetadata.d.ts +35 -0
  62. package/dist/structures/decorators/InjectionMetadata.d.ts.map +1 -0
  63. package/dist/structures/decorators/InjectionMetadata.js +34 -0
  64. package/dist/structures/decorators/InjectionMetadata.js.map +1 -0
  65. package/dist/structures/decorators/InteractionHandlerDecorator.d.ts +17 -2
  66. package/dist/structures/decorators/InteractionHandlerDecorator.d.ts.map +1 -1
  67. package/dist/structures/decorators/InteractionHandlerDecorator.js +48 -7
  68. package/dist/structures/decorators/InteractionHandlerDecorator.js.map +1 -0
  69. package/dist/structures/decorators/MessageComponentDecorator.d.ts +25 -40
  70. package/dist/structures/decorators/MessageComponentDecorator.d.ts.map +1 -1
  71. package/dist/structures/decorators/MessageComponentDecorator.js +66 -78
  72. package/dist/structures/decorators/MessageComponentDecorator.js.map +1 -0
  73. package/dist/structures/decorators/Metadata.d.ts +16 -0
  74. package/dist/structures/decorators/Metadata.d.ts.map +1 -0
  75. package/dist/structures/decorators/Metadata.js +50 -0
  76. package/dist/structures/decorators/Metadata.js.map +1 -0
  77. package/dist/structures/decorators/PluginDecorator.d.ts +41 -0
  78. package/dist/structures/decorators/PluginDecorator.d.ts.map +1 -0
  79. package/dist/structures/decorators/PluginDecorator.js +36 -0
  80. package/dist/structures/decorators/PluginDecorator.js.map +1 -0
  81. package/dist/structures/decorators/UseDecorator.d.ts +44 -0
  82. package/dist/structures/decorators/UseDecorator.d.ts.map +1 -0
  83. package/dist/structures/decorators/UseDecorator.js +49 -0
  84. package/dist/structures/decorators/UseDecorator.js.map +1 -0
  85. package/dist/structures/decorators/index.d.ts +4 -0
  86. package/dist/structures/decorators/index.d.ts.map +1 -1
  87. package/dist/structures/decorators/index.js +5 -0
  88. package/dist/structures/decorators/index.js.map +1 -0
  89. package/dist/structures/index.d.ts +3 -1
  90. package/dist/structures/index.d.ts.map +1 -1
  91. package/dist/structures/index.js +5 -1
  92. package/dist/structures/index.js.map +1 -0
  93. package/dist/utils/Util.d.ts +2 -0
  94. package/dist/utils/Util.d.ts.map +1 -1
  95. package/dist/utils/Util.js +23 -8
  96. package/dist/utils/Util.js.map +1 -0
  97. package/dist/utils/cache.d.ts +4 -0
  98. package/dist/utils/cache.d.ts.map +1 -0
  99. package/dist/utils/cache.js +17 -0
  100. package/dist/utils/cache.js.map +1 -0
  101. package/dist/utils/customId.d.ts +12 -0
  102. package/dist/utils/customId.d.ts.map +1 -0
  103. package/dist/utils/customId.js +49 -0
  104. package/dist/utils/customId.js.map +1 -0
  105. package/package.json +35 -9
  106. package/bun.lock +0 -264
@@ -1,14 +1,22 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.DiscordApp = exports.BaseDiscordModule = void 0;
4
+ const Metadata_1 = require("./decorators/Metadata");
4
5
  const discord_js_1 = require("discord.js");
5
6
  const v10_1 = require("discord-api-types/v10");
6
7
  const Constants_1 = require("./decorators/Constants");
8
+ const UseDecorator_1 = require("./decorators/UseDecorator");
9
+ const Plugin_1 = require("./Plugin");
7
10
  const Constants_2 = require("./Constants");
11
+ const PluginManager_1 = require("./PluginManager");
8
12
  const Util_1 = require("../utils/Util");
13
+ const customId_1 = require("../utils/customId");
14
+ const cache_1 = require("../utils/cache");
15
+ const huruhuru_1 = require("huruhuru");
9
16
  const defaultDiscordAppOptions = {
10
17
  logger: console,
11
- plugins: []
18
+ plugins: [],
19
+ pluginTimeout: 0
12
20
  };
13
21
  /**
14
22
  * The main class that you must extend to create a Discord application. You create an instance by using the `DiscordApp.create()` method.
@@ -45,7 +53,6 @@ class BaseDiscordModule {
45
53
  }
46
54
  }
47
55
  exports.BaseDiscordModule = BaseDiscordModule;
48
- let a1 = false;
49
56
  /**
50
57
  * Main application class for managing Discord bot functionality.
51
58
  *
@@ -69,7 +76,7 @@ let a1 = false;
69
76
  * - Must be instantiated using the static `create()` method
70
77
  * - Supports global and guild-specific (private) command deployment
71
78
  * - Routes interactions (commands, buttons, select menus, modals) to appropriate handlers
72
- * - Uses reflection metadata for decorator-based configuration
79
+ * - Uses standard decorator metadata for configuration and property injection
73
80
  *
74
81
  * @public
75
82
  */
@@ -81,322 +88,689 @@ class DiscordApp {
81
88
  #appOptions;
82
89
  #moduleOptions;
83
90
  #commands;
84
- #buttons;
85
- #selectMenus;
86
- #modals;
87
- #loadStartTimestamp;
91
+ #initialization;
92
+ #plugins;
93
+ #validatedHandlers = [];
94
+ /** Every support: registered with `supports`, provided by a plugin, or created on first use. */
95
+ #supports = [];
96
+ #stopPromise;
97
+ #stopped = false;
98
+ #inFlight = new Set();
99
+ #interactionListener = (itr) => {
100
+ if (!this.#stopped)
101
+ this.#track(this.#autoHandler(itr));
102
+ };
103
+ #cooldowns = new Map();
104
+ #commandRegistry = new Map();
105
+ #componentRegistry = new Map();
106
+ #componentPatterns = new Map();
107
+ #eventBindings = [];
88
108
  constructor() {
89
- if (!a1)
90
- throw new ReferenceError("Please use DiscordApp.create()");
91
- a1 = false;
92
- this.#loadStartTimestamp = Date.now();
93
109
  this.#rest = new discord_js_1.REST({ version: "10" });
94
110
  }
95
- /**
96
- * Logs in to Discord and deploys the commands. This method must be called after creating the application with `DiscordApp.create()`.
97
- * @see {@link DiscordApp.create}
98
- */
99
- async login() {
100
- const commands = this.#commands.filter(i => Reflect.getMetadata(Constants_1.INTERACTION_TYPE_KEY, i) == Constants_2.InteractionType.CHAT_INPUT_COMMAND || Reflect.getMetadata(Constants_1.INTERACTION_TYPE_KEY, i) == Constants_2.InteractionType.CONTEXT_MENU_COMMAND);
101
- const privateCommands = commands.filter(c => Reflect.getMetadata(Constants_1.COMMAND_PRIVATE_KEY, c));
102
- const globalCommands = commands.filter(c => !Reflect.getMetadata(Constants_1.COMMAND_PRIVATE_KEY, c));
103
- this.#module.logger.info(`Found ${commands.length} command(s) in total, ${globalCommands.length} global command(s) and ${privateCommands.length} private command(s). (${(Date.now() - this.#loadStartTimestamp)}ms)`);
104
- this.#module.logger.info("Mapping global commands...");
105
- // Prepare global commands
106
- const apiGlobalCommands = globalCommands.map(c => {
107
- const type = Reflect.getMetadata(Constants_1.INTERACTION_TYPE_KEY, c);
108
- const integrationTypes = Reflect.getMetadata(Constants_1.INTERACTION_INTEGRATION_TYPES_KEY, c);
109
- if (type == Constants_2.InteractionType.CHAT_INPUT_COMMAND)
110
- return this.#mapSlashCommand(Reflect.getMetadata(Constants_1.COMMAND_NAME_KEY, c), Reflect.getMetadata(Constants_1.COMMAND_DESCRIPTION_KEY, c), Reflect.getMetadata(Constants_1.COMMAND_OPTIONS_KEY, c), integrationTypes);
111
- else
112
- return this.#mapContextMenuCommand(Reflect.getMetadata(Constants_1.COMMAND_NAME_KEY, c), Reflect.getMetadata(Constants_1.CONTEXT_MENU_TYPE_KEY, c), integrationTypes);
113
- });
114
- this.#module.logger.info(`└─ Mapped ${apiGlobalCommands.length} global command(s). (${(Date.now() - this.#loadStartTimestamp)}ms)`);
115
- this.#module.logger.info("Mapping private commands...");
116
- // Prepare private commands
117
- const apiPrivateCommands = {};
118
- privateCommands.forEach(c => {
119
- const guildId = Reflect.getMetadata(Constants_1.COMMAND_PRIVATE_GUILD_KEY, c);
120
- const type = Reflect.getMetadata(Constants_1.INTERACTION_TYPE_KEY, c);
121
- const integrationTypes = Reflect.getMetadata(Constants_1.INTERACTION_INTEGRATION_TYPES_KEY, c);
122
- let data;
123
- if (type == Constants_2.InteractionType.CHAT_INPUT_COMMAND)
124
- data = this.#mapSlashCommand(Reflect.getMetadata(Constants_1.COMMAND_NAME_KEY, c), Reflect.getMetadata(Constants_1.COMMAND_DESCRIPTION_KEY, c), Reflect.getMetadata(Constants_1.COMMAND_OPTIONS_KEY, c), integrationTypes);
125
- else
126
- data = this.#mapContextMenuCommand(Reflect.getMetadata(Constants_1.COMMAND_NAME_KEY, c), Reflect.getMetadata(Constants_1.CONTEXT_MENU_TYPE_KEY, c), integrationTypes);
127
- if (!Array.isArray(apiPrivateCommands[guildId]))
128
- apiPrivateCommands[guildId] = [];
129
- apiPrivateCommands[guildId].push(data);
130
- });
131
- const wholePrivateCommands = Object.values(apiPrivateCommands).flat();
132
- this.#module.logger.info(`└─ Mapped ${Object.keys(apiPrivateCommands).length} guild(s) with ${wholePrivateCommands.length} private command(s). (${(Date.now() - this.#loadStartTimestamp)}ms)`);
111
+ /** Logs in and deploys commands by default. Pass false to manage deployment separately. */
112
+ async login(options = {}) {
113
+ await this.initialize();
133
114
  this.#rest.setToken(this.#moduleOptions.token);
134
- this.#module.logger.info("Logging in...");
135
115
  await this.#client.login(this.#moduleOptions.token);
136
- this.#module.logger.info(`Successfully logged in. (${(Date.now() - this.#loadStartTimestamp)}ms)`);
116
+ this.#module.logger.info("Successfully logged in.");
117
+ if (options.deployCommands !== false)
118
+ await this.deployCommands();
119
+ }
120
+ #pluginContext() {
121
+ return { app: this, client: this.#client, logger: this.#module.logger, plugins: this.#plugins };
122
+ }
123
+ /** Looks up plugins and enables or disables them at runtime. */
124
+ get plugins() {
125
+ return this.#plugins;
126
+ }
127
+ /** Enables plugins once, including concurrent calls; no Discord connection is required. */
128
+ async initialize() {
129
+ if (this.#stopped)
130
+ throw new Error("Application has stopped.");
131
+ this.#initialization ??= this.#plugins.enableAll();
132
+ await this.#initialization;
133
+ if (this.#stopped)
134
+ throw new Error("Application has stopped.");
135
+ }
136
+ #track(task) {
137
+ this.#inFlight.add(task);
138
+ task.then(() => this.#inFlight.delete(task), error => {
139
+ this.#inFlight.delete(task);
140
+ this.#logError(error);
141
+ });
142
+ }
143
+ /** Stops accepting events, drains handlers, disables plugins in reverse order, and destroys the client. */
144
+ stop() {
145
+ this.#stopPromise ??= this.#stop();
146
+ return this.#stopPromise;
147
+ }
148
+ async #stop() {
149
+ this.#stopped = true;
150
+ this.#client.off("interactionCreate", this.#interactionListener);
151
+ for (const binding of this.#eventBindings)
152
+ this.#client.off(binding.event, binding.listener);
153
+ this.#eventBindings = [];
154
+ if (this.#initialization)
155
+ await this.#initialization.catch(error => this.#logError(error));
156
+ await Promise.allSettled([...this.#inFlight]);
157
+ const errors = await this.#plugins.disableAll();
137
158
  try {
138
- this.#module.logger.info("Deploying commands...");
139
- if (this.#moduleOptions.test.enable) {
140
- await this.#rest.put(v10_1.Routes.applicationGuildCommands(this.#client.user.id, this.#moduleOptions.test.guild), { body: apiGlobalCommands });
141
- this.#module.logger.info(`├─ Successfully registered global commands, in test guild ${this.#moduleOptions.test.guild}. (${(Date.now() - this.#loadStartTimestamp)}ms)`);
142
- }
143
- else {
144
- await this.#rest.put(v10_1.Routes.applicationCommands(this.#client.user.id), { body: apiGlobalCommands });
145
- this.#module.logger.info(`├─ Successfully registered global commands. (${(Date.now() - this.#loadStartTimestamp)}ms)`);
146
- }
147
- for (const guildId in apiPrivateCommands) {
148
- await this.#rest.put(v10_1.Routes.applicationGuildCommands(this.#client.user.id, guildId), { body: apiPrivateCommands[guildId] });
149
- this.#module.logger.info(`├─ Successfully registered private commands in ${guildId}. (${(Date.now() - this.#loadStartTimestamp)}ms)`);
159
+ await this.#client.destroy();
160
+ }
161
+ catch (error) {
162
+ this.#logError(error);
163
+ errors.push(error);
164
+ }
165
+ this.#rest.clearHashSweeper();
166
+ this.#rest.clearHandlerSweeper();
167
+ this.#cooldowns.clear();
168
+ if (errors.length)
169
+ throw new AggregateError(errors, "Application shutdown failed.");
170
+ }
171
+ /** Builds command JSON without logging in or making REST requests. Commands of disabled plugins are left out. */
172
+ getCommandManifest() {
173
+ const manifest = { global: [], guilds: {} };
174
+ for (const command of this.#commands) {
175
+ if (this.#plugins.withdrawn(command))
176
+ continue;
177
+ const type = (0, Metadata_1.getMetadata)(Constants_1.INTERACTION_TYPE_KEY, command);
178
+ const integrationTypes = (0, Metadata_1.getMetadata)(Constants_1.INTERACTION_INTEGRATION_TYPES_KEY, command);
179
+ const name = (0, Metadata_1.getMetadata)(Constants_1.COMMAND_NAME_KEY, command);
180
+ const data = type === Constants_2.InteractionType.CHAT_INPUT_COMMAND
181
+ ? this.#mapSlashCommand(name, (0, Metadata_1.getMetadata)(Constants_1.COMMAND_DESCRIPTION_KEY, command), (0, Metadata_1.getMetadata)(Constants_1.COMMAND_OPTIONS_KEY, command), integrationTypes)
182
+ : this.#mapContextMenuCommand(name, (0, Metadata_1.getMetadata)(Constants_1.CONTEXT_MENU_TYPE_KEY, command), integrationTypes);
183
+ const privateGuild = (0, Metadata_1.getMetadata)(Constants_1.COMMAND_PRIVATE_KEY, command) ? (0, Metadata_1.getMetadata)(Constants_1.COMMAND_PRIVATE_GUILD_KEY, command) : undefined;
184
+ const guild = privateGuild ?? (this.#moduleOptions.test?.enable ? this.#moduleOptions.test.guild : undefined);
185
+ if (guild)
186
+ (manifest.guilds[guild] ??= []).push(data);
187
+ else
188
+ manifest.global.push(data);
189
+ }
190
+ // Even an empty test manifest should clear that test guild's registrations.
191
+ if (this.#moduleOptions.test?.enable)
192
+ manifest.guilds[this.#moduleOptions.test.guild] ??= [];
193
+ for (const [scope, commands] of [["global", manifest.global], ...Object.entries(manifest.guilds)]) {
194
+ const keys = new Set();
195
+ for (const command of commands) {
196
+ const key = JSON.stringify([command.type ?? 1, command.name]);
197
+ if (keys.has(key))
198
+ throw new TypeError("Duplicate deployed command " + command.name + " in " + scope);
199
+ keys.add(key);
150
200
  }
151
- this.#module.logger.info("└─ Successfully deployed all commands.");
152
201
  }
153
- catch (err) {
154
- this.#module.logger.warn("Failed to deploy commands.");
155
- this.#module.logger.warn(err.stack);
202
+ return manifest;
203
+ }
204
+ /** Deploys each scope once; REST failures reject instead of reporting startup success. */
205
+ async deployCommands() {
206
+ if (this.#stopped)
207
+ throw new Error("Application has stopped.");
208
+ if (!this.#client.user)
209
+ throw new Error("Log in before deploying commands.");
210
+ const manifest = this.getCommandManifest();
211
+ if (!this.#moduleOptions.test?.enable) {
212
+ await this.#rest.put(v10_1.Routes.applicationCommands(this.#client.user.id), { body: manifest.global });
213
+ }
214
+ for (const [guild, commands] of Object.entries(manifest.guilds)) {
215
+ await this.#rest.put(v10_1.Routes.applicationGuildCommands(this.#client.user.id, guild), { body: commands });
156
216
  }
157
- this.#module.logger.info("Application took " + (Date.now() - this.#loadStartTimestamp) + "ms to load.");
217
+ this.#module.logger.info("Successfully deployed all commands.");
158
218
  }
159
- /**
160
- * Handles incoming chat input command interactions by routing them to the appropriate command handler based on the command name, subcommand group, and subcommand. It uses reflection metadata to determine which handler to invoke and what arguments to pass.
161
- * @param itr The chat input command interaction to handle.
162
- * @returns {void}
163
- * @internal
164
- */
165
- #chatInputCommandHandler(itr) {
166
- const commands = this.#commands.filter(i => Reflect.getMetadata(Constants_1.INTERACTION_TYPE_KEY, i) == Constants_2.InteractionType.CHAT_INPUT_COMMAND);
167
- const commandName = itr.commandName;
168
- const command = commands.find(c => Reflect.getMetadata(Constants_1.COMMAND_NAME_KEY, c) == commandName);
169
- if (!command)
170
- return;
171
- if (itr.options.getSubcommandGroup(false)) {
172
- let handler = Reflect.getMetadata(Constants_1.COMMAND_SUBCOMMAND_GROUPS_KEY, command)[itr.options.getSubcommandGroup(true)]?.find(c => Reflect.getMetadata(Constants_1.COMMAND_NAME_KEY, c) == itr.options.getSubcommand(true));
173
- if (!handler)
174
- return;
175
- let runMethod = Reflect.getMetadata(Constants_1.INTERACTION_RUN_METHOD_KEY, handler);
176
- let preArgs = [Reflect.getMetadata(Constants_1.INTERACTION_PARAMETER_INDEX_KEY, handler), ...(Reflect.getMetadata(Constants_1.OPTIONS_PARAMETER_INDEX_KEY, handler) || [])];
177
- let args = Array(preArgs.length).fill(null);
178
- if (runMethod == undefined)
179
- throw new TypeError("Failed to get the run method. Did you add the @Run decorator?");
180
- preArgs.forEach(arg => {
181
- if (typeof arg == "number")
182
- args[arg] = itr;
183
- else
184
- args[arg.index] = itr.options[arg.getMethod](arg.name);
185
- });
186
- let cmd = new handler(...args);
187
- cmd[runMethod]();
188
- }
189
- else if (itr.options.getSubcommand(false)) {
190
- let handler = Reflect.getMetadata(Constants_1.COMMAND_SUBCOMMANDS_KEY, command).find(c => Reflect.getMetadata(Constants_1.COMMAND_NAME_KEY, c) == itr.options.getSubcommand(true));
191
- if (!handler)
192
- return;
193
- let runMethod = Reflect.getMetadata(Constants_1.INTERACTION_RUN_METHOD_KEY, handler);
194
- let preArgs = [Reflect.getMetadata(Constants_1.INTERACTION_PARAMETER_INDEX_KEY, handler), ...(Reflect.getMetadata(Constants_1.OPTIONS_PARAMETER_INDEX_KEY, handler) || [])];
195
- let args = Array(preArgs.length).fill(null);
196
- if (runMethod == undefined)
197
- throw new TypeError("Failed to get the run method. Did you add the @Run decorator?");
198
- preArgs.forEach(arg => {
199
- if (typeof arg == "number")
200
- args[arg] = itr;
201
- else
202
- args[arg.index] = itr.options[arg.getMethod](arg.name);
203
- });
204
- let cmd = new handler(...args);
205
- cmd[runMethod]();
219
+ #commandKey(type, name, guild = "global", contextType = 0) {
220
+ return JSON.stringify([guild, type, contextType, name]);
221
+ }
222
+ #findCommand(itr) {
223
+ const type = itr.isContextMenuCommand() ? Constants_2.InteractionType.CONTEXT_MENU_COMMAND : Constants_2.InteractionType.CHAT_INPUT_COMMAND;
224
+ const contextType = type === Constants_2.InteractionType.CONTEXT_MENU_COMMAND ? itr.commandType : 0;
225
+ const privateHandler = itr.guildId ? this.#commandRegistry.get(this.#commandKey(type, itr.commandName, itr.guildId, contextType)) : undefined;
226
+ return privateHandler ?? this.#commandRegistry.get(this.#commandKey(type, itr.commandName, "global", contextType));
227
+ }
228
+ #componentKey(type, customId) {
229
+ return JSON.stringify([type, customId]);
230
+ }
231
+ #matchComponent(type, customId) {
232
+ const exact = this.#componentRegistry.get(this.#componentKey(type, customId));
233
+ if (exact)
234
+ return { handler: exact, parameters: {} };
235
+ for (const { handler, route } of this.#componentPatterns.get(type) ?? []) {
236
+ const parameters = route.match(customId);
237
+ if (parameters)
238
+ return { handler, parameters };
206
239
  }
207
- else {
208
- let runMethod = Reflect.getMetadata(Constants_1.INTERACTION_RUN_METHOD_KEY, command);
209
- let preArgs = [Reflect.getMetadata(Constants_1.INTERACTION_PARAMETER_INDEX_KEY, command), ...(Reflect.getMetadata(Constants_1.OPTIONS_PARAMETER_INDEX_KEY, command) || [])];
210
- let args = Array(preArgs.length).fill(null);
211
- if (runMethod == undefined)
212
- throw new TypeError("Failed to get the run method. Did you add the @Run decorator?");
213
- preArgs.forEach(arg => {
214
- if (typeof arg == "number")
215
- args[arg] = itr;
216
- else
217
- args[arg.index] = itr.options[arg.getMethod](arg.name);
218
- });
219
- let cmd = new command(...args);
220
- cmd[runMethod]();
240
+ return undefined;
241
+ }
242
+ #resolveChatHandler(command, itr) {
243
+ const group = itr.options.getSubcommandGroup(false);
244
+ const subcommand = itr.options.getSubcommand(false);
245
+ if (group) {
246
+ const groups = (0, Metadata_1.getMetadata)(Constants_1.COMMAND_SUBCOMMAND_GROUPS_KEY, command) ?? {};
247
+ return groups[group]?.find(c => (0, Metadata_1.getMetadata)(Constants_1.COMMAND_NAME_KEY, c) === subcommand);
248
+ }
249
+ if (subcommand) {
250
+ const children = ((0, Metadata_1.getMetadata)(Constants_1.COMMAND_SUBCOMMANDS_KEY, command) ?? []);
251
+ return children.find(c => (0, Metadata_1.getMetadata)(Constants_1.COMMAND_NAME_KEY, c) === subcommand);
221
252
  }
253
+ return command;
222
254
  }
223
- /**
224
- * Handles incoming context menu command interactions by routing them to the appropriate command handler based on the command name and type. It uses reflection metadata to determine which handler to invoke and what arguments to pass.
225
- * @param itr The context menu command interaction to handle.
226
- * @returns {void}
227
- * @internal
228
- */
229
- #contextMenuCommandHandler(itr) {
230
- const commands = this.#commands.filter(i => Reflect.getMetadata(Constants_1.INTERACTION_TYPE_KEY, i) == Constants_2.InteractionType.CONTEXT_MENU_COMMAND);
231
- const commandName = itr.commandName;
232
- const command = commands.find(c => Reflect.getMetadata(Constants_1.COMMAND_NAME_KEY, c) == commandName && Reflect.getMetadata(Constants_1.COMMAND_OPTIONS_KEY, c).type == itr.commandType);
233
- if (!command)
234
- return;
235
- let runMethod = Reflect.getMetadata(Constants_1.INTERACTION_RUN_METHOD_KEY, command);
236
- if (runMethod == undefined)
237
- throw new TypeError("Failed to get the run method. Did you add the @Run decorator?");
238
- let cmd = new command(itr);
239
- cmd[runMethod]();
255
+ #injections(constructor) {
256
+ return ((0, Metadata_1.getMetadata)(Constants_1.INJECTION_PROPERTIES_KEY, constructor) ?? []);
240
257
  }
241
- /**
242
- * Handles incoming button interactions by routing them to the appropriate button handler based on the custom ID. It uses reflection metadata to determine which handler to invoke and what arguments to pass.
243
- * @param itr The button interaction to handle.
244
- * @returns {void}
245
- * @internal
246
- */
247
- #buttonHandler(itr) {
248
- const button = this.#buttons.find(b => Reflect.getMetadata(Constants_1.BUTTON_OPTIONS_KEY, b).customId == itr.customId);
249
- if (!button)
250
- return;
251
- let runMethod = Reflect.getMetadata(Constants_1.INTERACTION_RUN_METHOD_KEY, button);
252
- if (runMethod == undefined)
253
- throw new TypeError("Failed to get the run method. Did you add the @Run decorator?");
254
- let cmd = new button(itr);
255
- cmd[runMethod]();
258
+ /** The classes a class declares with `@Use`. */
259
+ #usedClasses(constructor) {
260
+ return this.#injections(constructor).flatMap(property => property.kind === "use" ? [(0, UseDecorator_1.resolveUsed)(property.use)] : []);
256
261
  }
257
- /**
258
- * Handles incoming select menu interactions by routing them to the appropriate select menu handler based on the custom ID. It uses reflection metadata to determine which handler to invoke and what arguments to pass.
259
- * @param itr The select menu interaction to handle.
260
- * @returns {void}
261
- * @internal
262
- */
263
- #selectMenuHandler(itr) {
264
- const selectMenu = this.#selectMenus.find(b => Reflect.getMetadata(Constants_1.SELECT_MENU_OPTIONS_KEY, b).customId == itr.customId);
265
- if (!selectMenu)
266
- return;
267
- let runMethod = Reflect.getMetadata(Constants_1.INTERACTION_RUN_METHOD_KEY, selectMenu);
268
- if (runMethod == undefined)
269
- throw new TypeError("Failed to get the run method. Did you add the @Run decorator?");
270
- let cmd = new selectMenu(itr);
271
- cmd[runMethod]();
262
+ /** What `@Use` injects for a class: the registered plugin, then a registered support, otherwise a shared instance created on first use. */
263
+ #provide(target) {
264
+ const plugin = this.#plugins.get(target);
265
+ if (plugin)
266
+ return plugin;
267
+ let support = this.#supports.find(candidate => candidate instanceof target);
268
+ if (!support) {
269
+ support = new target(this.#client, this.#appOptions.logger);
270
+ // Stored before its own fields are injected, so classes that use each other get the same instances.
271
+ this.#supports.push(support);
272
+ this.#validateUses(target, false);
273
+ this.#injectUses(support, target);
274
+ }
275
+ return support;
276
+ }
277
+ /** Sets the `@Use` fields of an instance the application constructs itself: modules, listeners, plugins, and shared instances. */
278
+ #injectUses(instance, constructor) {
279
+ for (const property of this.#injections(constructor)) {
280
+ if (property.kind === "use")
281
+ property.set(instance, this.#provide((0, UseDecorator_1.resolveUsed)(property.use)));
282
+ }
272
283
  }
273
284
  /**
274
- * Handles incoming modal submit interactions by routing them to the appropriate modal handler based on the custom ID. It uses reflection metadata to determine which handler to invoke and what arguments to pass, including extracting values from text input components if necessary.
275
- * @param itr The modal submit interaction to handle.
276
- * @returns {void}
277
- * @internal
285
+ * Fails startup when a class uses a `Plugin` that is not registered, or injects anything but `@Use` where nothing
286
+ * else is available. Other classes used are created now, so their constructors fail at startup too.
278
287
  */
279
- #modalHandler(itr) {
280
- const modal = this.#modals.find(b => Reflect.getMetadata(Constants_1.MODAL_OPTIONS_KEY, b).customId == itr.customId);
281
- if (!modal)
282
- return;
283
- const modalComponents = Reflect.getMetadata(Constants_1.MODAL_COMPONENTS_KEY, modal);
284
- let runMethod = Reflect.getMetadata(Constants_1.INTERACTION_RUN_METHOD_KEY, modal);
285
- let preArgs = [Reflect.getMetadata(Constants_1.INTERACTION_PARAMETER_INDEX_KEY, modal), ...(Reflect.getMetadata(Constants_1.MODAL_TEXT_INPUT_VALUE_INDEX_KEY, modal) || []), ...(Reflect.getMetadata(Constants_1.MODAL_SELECT_MENU_VALUE_INDEX_KEY, modal) || []), ...(Reflect.getMetadata(Constants_1.MODAL_FILE_UPLOAD_VALUE_INDEX_KEY, modal) || [])];
286
- let args = Array(preArgs.length).fill(null);
287
- preArgs.forEach(arg => {
288
- if (typeof arg == "number") {
289
- args[arg] = itr;
288
+ #validateUses(constructor, handler) {
289
+ for (const property of this.#injections(constructor)) {
290
+ if (property.kind !== "use") {
291
+ if (!handler)
292
+ throw new TypeError(constructor.name + ": only @Use can be injected into this class.");
293
+ continue;
290
294
  }
291
- else {
292
- const fieldIndex = arg;
293
- switch (fieldIndex.type) {
294
- case "text_input":
295
- args[arg.index] = itr.fields.getTextInputValue(fieldIndex.customId);
296
- break;
297
- case "select_menu":
298
- const getMethods = {
299
- "string_select": itr.fields.getStringSelectValues,
300
- "user_select": itr.fields.getSelectedUsers,
301
- "role_select": itr.fields.getSelectedRoles,
302
- "mentionable_select": itr.fields.getSelectedMentionables,
303
- "channel_select": itr.fields.getSelectedChannels
304
- };
305
- const label = modalComponents.find(c => c.outerType == "label" && c.innerType.endsWith("select") && c.component.data.component?.data?.custom_id == fieldIndex.customId);
306
- const getMethod = getMethods[label?.innerType];
307
- if (!getMethod)
308
- throw new TypeError(`Failed to get the select menu values for custom ID ${fieldIndex.customId}. Failed to gather necessary metadata.`);
309
- const result = getMethod.bind(itr.fields)(fieldIndex.customId);
310
- if (result instanceof discord_js_1.Collection)
311
- args[arg.index] = result.toJSON();
312
- else
313
- args[arg.index] = result;
314
- break;
315
- case "file_upload":
316
- args[arg.index] = itr.fields.getUploadedFiles(fieldIndex.customId);
317
- break;
318
- case "radio_group":
319
- args[arg.index] = itr.fields.getRadioGroup(fieldIndex.customId);
320
- break;
321
- case "checkbox":
322
- args[arg.index] = itr.fields.getCheckbox(fieldIndex.customId);
323
- break;
324
- case "checkbox_group":
325
- args[arg.index] = itr.fields.getCheckboxGroup(fieldIndex.customId);
295
+ const target = (0, UseDecorator_1.resolveUsed)(property.use);
296
+ if (this.#plugins.get(target))
297
+ continue;
298
+ if (target.prototype instanceof Plugin_1.Plugin)
299
+ throw new TypeError(`${constructor.name}: @Use(${target.name}) requires that plugin to be registered.`);
300
+ this.#provide(target);
301
+ }
302
+ }
303
+ #injectProperties(handler, instance, itr, parameters) {
304
+ const properties = this.#injections(handler);
305
+ let commandContext;
306
+ for (const property of properties) {
307
+ let value;
308
+ switch (property.kind) {
309
+ case "interaction":
310
+ value = itr;
311
+ break;
312
+ case "use":
313
+ value = this.#provide((0, UseDecorator_1.resolveUsed)(property.use));
314
+ break;
315
+ case "context":
316
+ if (itr.isChatInputCommand())
317
+ value = commandContext ??= new huruhuru_1.CommandContext(itr);
318
+ break;
319
+ case "custom_id":
320
+ value = parameters[property.name];
321
+ break;
322
+ case "option":
323
+ if (itr.isChatInputCommand() || itr.isAutocomplete()) {
324
+ const getter = itr.options[property.getMethod];
325
+ value = typeof getter === "function" ? getter.call(itr.options, property.name) : itr.options.get(property.name)?.value ?? null;
326
+ }
327
+ break;
328
+ case "modal_field":
329
+ if (!itr.isModalSubmit())
326
330
  break;
331
+ switch (property.type) {
332
+ case "text_input":
333
+ value = itr.fields.getTextInputValue(property.customId);
334
+ break;
335
+ case "file_upload":
336
+ value = itr.fields.getUploadedFiles(property.customId);
337
+ break;
338
+ case "radio_group":
339
+ value = itr.fields.getRadioGroup(property.customId);
340
+ break;
341
+ case "checkbox":
342
+ value = itr.fields.getCheckbox(property.customId);
343
+ break;
344
+ case "checkbox_group":
345
+ value = itr.fields.getCheckboxGroup(property.customId);
346
+ break;
347
+ case "select_menu": {
348
+ const components = ((0, Metadata_1.getMetadata)(Constants_1.MODAL_COMPONENTS_KEY, handler) ?? []);
349
+ const label = components.find(c => c.outerType === "label" && c.component.data.component?.data.custom_id === property.customId);
350
+ const methods = {
351
+ string_select: itr.fields.getStringSelectValues, user_select: itr.fields.getSelectedUsers,
352
+ role_select: itr.fields.getSelectedRoles, mentionable_select: itr.fields.getSelectedMentionables,
353
+ channel_select: itr.fields.getSelectedChannels
354
+ };
355
+ const result = methods[label.innerType].call(itr.fields, property.customId);
356
+ value = result instanceof discord_js_1.Collection ? result.toJSON() : result;
357
+ break;
358
+ }
359
+ }
360
+ break;
361
+ }
362
+ property.set(instance, value);
363
+ }
364
+ }
365
+ async #deny(itr, content) {
366
+ if (itr.isAutocomplete()) {
367
+ if (!itr.responded)
368
+ await itr.respond([]);
369
+ }
370
+ else if (itr.isRepliable() && !itr.replied) {
371
+ if (itr.deferred)
372
+ await itr.editReply({ content });
373
+ else
374
+ await itr.reply({ content, flags: discord_js_1.MessageFlags.Ephemeral });
375
+ }
376
+ }
377
+ async #checkGuards(handler, itr, parameters, parents = []) {
378
+ const handlers = [...new Set([...parents, handler])];
379
+ for (const current of handlers) {
380
+ const guards = ((0, Metadata_1.getMetadata)(Constants_1.INTERACTION_GUARDS_KEY, current) ?? []);
381
+ for (const guard of guards) {
382
+ if (!await guard({ interaction: itr, handler, parameters, logger: this.#module.logger })) {
383
+ await this.#deny(itr, "You cannot use this interaction.");
384
+ return false;
327
385
  }
328
386
  }
329
- });
330
- if (runMethod == undefined)
331
- throw new TypeError("Failed to get the run method. Did you add the @Run decorator?");
332
- let cmd = new modal(...args);
333
- cmd[runMethod]();
387
+ }
388
+ return true;
334
389
  }
335
- /**
336
- * Automatically handles incoming interactions by determining their type (chat input command, context menu command, button interaction, select menu interaction, or modal submit) and routing them to the appropriate handler method. This method is called internally whenever an interaction is created.
337
- * @param itr The interaction to handle.
338
- * @returns {void}
339
- * @internal
340
- */
341
- #autoHandler(itr) {
342
- if (itr.isChatInputCommand()) {
343
- this.#chatInputCommandHandler(itr);
390
+ async #checkCooldowns(handler, itr, parents) {
391
+ const handlers = [...new Set([...parents, handler])];
392
+ const now = Date.now();
393
+ const reservations = [];
394
+ for (const current of handlers) {
395
+ const cooldown = (0, Metadata_1.getMetadata)(Constants_1.INTERACTION_COOLDOWN_KEY, current);
396
+ if (!cooldown)
397
+ continue;
398
+ const entries = this.#cooldowns.get(current) ?? new Map();
399
+ for (const [key, expiry] of entries)
400
+ if (expiry <= now)
401
+ entries.delete(key);
402
+ const key = cooldown.scope === "global" ? "global" : cooldown.scope === "guild" ? itr.guildId ?? "dm:" + itr.user.id : itr.user.id;
403
+ const expiry = entries.get(key) ?? 0;
404
+ if (expiry > now) {
405
+ const seconds = Math.ceil((expiry - now) / 1000);
406
+ await this.#deny(itr, "Try again in " + seconds + (seconds === 1 ? " second." : " seconds."));
407
+ return false;
408
+ }
409
+ this.#cooldowns.set(current, entries);
410
+ reservations.push({ handler: current, key, expiry: now + cooldown.duration });
344
411
  }
345
- else if (itr.isContextMenuCommand()) {
346
- this.#contextMenuCommandHandler(itr);
412
+ // Reserve all scopes together before execution, including simultaneous dispatches.
413
+ for (const reservation of reservations)
414
+ this.#cooldowns.get(reservation.handler).set(reservation.key, reservation.expiry);
415
+ return true;
416
+ }
417
+ async #execute(handler, itr, parameters = {}, parents = [], methodOverride, useCooldown = true) {
418
+ const chain = [...parents, handler];
419
+ if (this.#plugins.blocked(chain, this.#usedClasses(handler))) {
420
+ await this.#deny(itr, "This feature is currently disabled.");
421
+ return;
347
422
  }
348
- else if (itr.isButton()) {
349
- this.#buttonHandler(itr);
423
+ if (!await this.#checkGuards(handler, itr, parameters, parents))
424
+ return;
425
+ const context = { ...this.#pluginContext(), interaction: itr, handler, parameters };
426
+ const entries = this.#plugins.observers(chain);
427
+ if (!await this.#plugins.prefix(entries, context)) {
428
+ await this.#deny(itr, "You cannot use this interaction.");
429
+ return;
350
430
  }
351
- else if (itr.isAnySelectMenu()) {
352
- this.#selectMenuHandler(itr);
431
+ if (useCooldown && !await this.#checkCooldowns(handler, itr, parents))
432
+ return;
433
+ const method = methodOverride ?? (0, Metadata_1.getMetadata)(Constants_1.INTERACTION_RUN_METHOD_KEY, handler);
434
+ const instance = new handler();
435
+ this.#injectProperties(handler, instance, itr, parameters);
436
+ context.result = await instance[method]();
437
+ await this.#plugins.postfix(entries, context);
438
+ return context.result;
439
+ }
440
+ async #autoHandler(itr) {
441
+ // Handlers resolved so far, so a failure reaches the plugins that own them.
442
+ let scope = [];
443
+ try {
444
+ await this.initialize();
445
+ if (this.#stopped)
446
+ return;
447
+ if (itr.isAutocomplete()) {
448
+ const command = this.#findCommand(itr);
449
+ const handler = command && this.#resolveChatHandler(command, itr);
450
+ const optionName = itr.options.getFocused(true).name;
451
+ const method = handler && (0, Metadata_1.getMetadata)(Constants_1.AUTOCOMPLETE_METHODS_KEY, handler)?.[optionName];
452
+ if (!handler || method === undefined) {
453
+ await itr.respond([]);
454
+ return;
455
+ }
456
+ scope = command ? [command, handler] : [handler];
457
+ const choices = await this.#execute(handler, itr, {}, command ? [command] : [], method, false);
458
+ if (!itr.responded)
459
+ await itr.respond(choices ?? []);
460
+ }
461
+ else if (itr.isChatInputCommand()) {
462
+ const command = this.#findCommand(itr);
463
+ const handler = command && this.#resolveChatHandler(command, itr);
464
+ if (handler) {
465
+ scope = command ? [command, handler] : [handler];
466
+ await this.#execute(handler, itr, {}, command ? [command] : []);
467
+ }
468
+ }
469
+ else if (itr.isContextMenuCommand()) {
470
+ const handler = this.#findCommand(itr);
471
+ if (handler) {
472
+ scope = [handler];
473
+ await this.#execute(handler, itr);
474
+ }
475
+ }
476
+ else {
477
+ let type;
478
+ if (itr.isButton())
479
+ type = Constants_2.InteractionType.BUTTON;
480
+ else if (itr.isAnySelectMenu())
481
+ type = Constants_2.InteractionType.SELECT_MENU;
482
+ else if (itr.isModalSubmit())
483
+ type = Constants_2.InteractionType.MODAL_SUBMIT;
484
+ else
485
+ return;
486
+ const match = this.#matchComponent(type, itr.customId);
487
+ if (match) {
488
+ scope = [match.handler];
489
+ await this.#execute(match.handler, itr, match.parameters);
490
+ }
491
+ }
353
492
  }
354
- else if (itr.isModalSubmit()) {
355
- this.#modalHandler(itr);
493
+ catch (error) {
494
+ await this.#reportError(error, itr, scope);
495
+ try {
496
+ if (itr.isAutocomplete() && !itr.responded)
497
+ await itr.respond([]);
498
+ else if (itr.isRepliable() && !itr.replied) {
499
+ if (itr.deferred)
500
+ await itr.editReply({ content: "An error occurred while handling this interaction." });
501
+ else
502
+ await itr.reply({ content: "An error occurred while handling this interaction.", flags: discord_js_1.MessageFlags.Ephemeral });
503
+ }
504
+ }
505
+ catch (responseError) {
506
+ this.#logError(responseError);
507
+ }
508
+ }
509
+ }
510
+ #logError(error) {
511
+ this.#module.logger.error((0, PluginManager_1.describeError)(error));
512
+ }
513
+ async #reportError(error, interaction, handlers = [], owner) {
514
+ this.#logError(error);
515
+ await this.#plugins.error(error, interaction, handlers, owner);
516
+ }
517
+ /** Binds `@EventHandler` methods of an instance; `owner` receives their errors and must be enabled for them to run. */
518
+ #registerEvents(instance, constructor, owner) {
519
+ const events = ((0, Metadata_1.getMetadata)(Constants_1.INTERNAL_EVENTS_KEY, constructor) ?? []);
520
+ const uses = this.#usedClasses(constructor);
521
+ for (const event of events) {
522
+ if (typeof instance[event.methodName] !== "function")
523
+ throw new TypeError(constructor.name + ": invalid event method " + String(event.methodName));
524
+ const listener = (...args) => {
525
+ if (this.#stopped || (owner && owner.state !== "enabled") || this.#plugins.blocked([], uses))
526
+ return;
527
+ try {
528
+ this.#track(Promise.resolve(instance[event.methodName](...args)).catch(error => this.#reportError(error, undefined, [], owner)));
529
+ }
530
+ catch (error) {
531
+ this.#track(this.#reportError(error, undefined, [], owner));
532
+ }
533
+ };
534
+ this.#client.on(event.eventName, listener);
535
+ this.#eventBindings.push({ event: event.eventName, listener });
356
536
  }
357
- return;
358
537
  }
359
- /**
360
- * Initializes the Discord application by creating the Discord client, setting up event listeners based on the provided module, and preparing command and component handlers. This method is called internally by the `create()` method after setting the main module and options.
361
- * @internal
362
- */
363
538
  #init() {
364
- const options = Reflect.getMetadata(Constants_1.DICSORD_MODULE_OPTIONS_KEY, this.#moduleFunction);
365
- const internalEvents = Reflect.getMetadata(Constants_1.DISCORD_MODULE_INTERNAL_EVENTS_KEY, this.#moduleFunction);
366
- // const externalEvents = Reflect.getMetadata(DISCORD_MODULE_EXTERNAL_EVENTS_KEY, this.#moduleFunction) as ExternalModuleEvents[];
367
- this.#client = new discord_js_1.Client(options);
368
- this.#module = new this.#moduleFunction(this.#client, this.#appOptions.logger);
539
+ const options = (0, Metadata_1.getMetadata)(Constants_1.DICSORD_MODULE_OPTIONS_KEY, this.#moduleFunction);
540
+ if (!options)
541
+ throw new TypeError(this.#moduleFunction.name + ": missing @DiscordModule decorator.");
542
+ if (options.test?.enable && !options.test.guild)
543
+ throw new TypeError("Test mode requires a guild ID.");
369
544
  this.#moduleOptions = options;
370
- const module = this.#module;
371
- internalEvents.forEach(e => {
372
- this.#client.on(e.eventName, (...args) => module[e.methodName](...args));
545
+ this.#plugins = new PluginManager_1.PluginRuntime({
546
+ logger: this.#appOptions.logger,
547
+ timeout: this.#appOptions.pluginTimeout ?? 0,
548
+ context: () => this.#pluginContext(),
549
+ initialize: () => this.initialize()
373
550
  });
374
- this.#client.on("interactionCreate", (itr) => this.#autoHandler(itr));
375
- this.#moduleOptions.imports.forEach(module => {
376
- const moduleType = Reflect.getMetadata(Constants_1.MODULE_TYPE_KEY, module);
377
- switch (moduleType) {
378
- case Constants_1.ModuleType.COMMAND:
379
- if (!this.#commands)
380
- this.#commands = [];
381
- this.#commands.push(...Reflect.getMetadata(Constants_1.COMMAND_MODULE_COMMANDS_KEY, module));
382
- break;
383
- case Constants_1.ModuleType.MESSAGE_COMPONENT:
384
- const components = Reflect.getMetadata(Constants_1.MESSAGE_COMPONENT_MODULE_COMPONENTS_KEY, module);
385
- const buttons = components.filter(c => Reflect.getMetadata(Constants_1.INTERACTION_TYPE_KEY, c) == Constants_2.InteractionType.BUTTON);
386
- const selectMenus = components.filter(c => Reflect.getMetadata(Constants_1.INTERACTION_TYPE_KEY, c) == Constants_2.InteractionType.SELECT_MENU);
387
- const modals = components.filter(c => Reflect.getMetadata(Constants_1.INTERACTION_TYPE_KEY, c) == Constants_2.InteractionType.MODAL_SUBMIT);
388
- if (!this.#buttons)
389
- this.#buttons = [];
390
- this.#buttons.push(...buttons);
391
- if (!this.#selectMenus)
392
- this.#selectMenus = [];
393
- this.#selectMenus.push(...selectMenus);
394
- if (!this.#modals)
395
- this.#modals = [];
396
- this.#modals.push(...modals);
397
- break;
551
+ this.#commands = [];
552
+ const components = [];
553
+ const eventModules = [];
554
+ const listeners = [];
555
+ const supportSources = [];
556
+ // What a plugin owns is recorded on its slot, so its hooks can be scoped to those handlers.
557
+ const gather = (source, owner) => {
558
+ for (const command of source.commands ?? []) {
559
+ this.#commands.push(command);
560
+ owner?.owned.add(command);
398
561
  }
562
+ for (const component of source.components ?? []) {
563
+ components.push(component);
564
+ owner?.owned.add(component);
565
+ }
566
+ for (const listener of source.listeners ?? [])
567
+ listeners.push({ listener, owner });
568
+ for (const support of source.supports ?? [])
569
+ supportSources.push({ source: support, owner });
570
+ for (const module of source.imports ?? []) {
571
+ switch ((0, Metadata_1.getMetadata)(Constants_1.MODULE_TYPE_KEY, module)) {
572
+ case Constants_1.ModuleType.COMMAND:
573
+ gather({ commands: (0, Metadata_1.getMetadata)(Constants_1.COMMAND_MODULE_COMMANDS_KEY, module) }, owner);
574
+ break;
575
+ case Constants_1.ModuleType.MESSAGE_COMPONENT:
576
+ gather({ components: (0, Metadata_1.getMetadata)(Constants_1.MESSAGE_COMPONENT_MODULE_COMPONENTS_KEY, module) }, owner);
577
+ break;
578
+ case Constants_1.ModuleType.EVENT:
579
+ eventModules.push({ module, owner });
580
+ gather({ listeners: (0, Metadata_1.getMetadata)(Constants_1.EVENT_MODULE_LISTENERS_KEY, module) }, owner);
581
+ break;
582
+ default: throw new TypeError(module.name + ": invalid imported module.");
583
+ }
584
+ }
585
+ };
586
+ gather(options);
587
+ const slots = [];
588
+ const declared = new Set();
589
+ for (const source of this.#appOptions.plugins ?? []) {
590
+ const constructor = typeof source === "function" ? source : source.constructor;
591
+ const config = (0, Metadata_1.getMetadata)(Constants_1.PLUGIN_MODULE_OPTIONS_KEY, constructor);
592
+ // Without @PluginModule a plugin owns nothing, so it observes the whole application.
593
+ const slot = { source, constructor, global: !config || config.scope === "global", owned: new Set() };
594
+ if (config) {
595
+ if (declared.has(constructor))
596
+ throw new TypeError("Duplicate plugin: " + constructor.name);
597
+ declared.add(constructor);
598
+ gather(config, slot);
599
+ }
600
+ slots.push(slot);
601
+ }
602
+ for (const command of this.#commands)
603
+ this.#registerCommand(command);
604
+ for (const component of components)
605
+ this.#registerComponent(component);
606
+ this.getCommandManifest();
607
+ const { token: _token, imports: _imports, commands: _commands, components: _components, listeners: _listeners, supports: _supports, test: _test, disableCache, ...clientOptions } = options;
608
+ if (disableCache) {
609
+ if (clientOptions.makeCache)
610
+ throw new TypeError("Use either disableCache or makeCache, not both.");
611
+ clientOptions.makeCache = (0, cache_1.createUncachedFactory)();
612
+ }
613
+ this.#client = new discord_js_1.Client(clientOptions);
614
+ this.#module = new this.#moduleFunction(this.#client, this.#appOptions.logger);
615
+ const logger = this.#appOptions.logger;
616
+ // Supports are created first, so each plugin knows which ones it provides.
617
+ const supports = supportSources.map(({ source, owner }) => {
618
+ if (typeof source !== "function" && (typeof source !== "object" || source === null))
619
+ throw new TypeError("Supports must be classes or objects.");
620
+ const instance = (typeof source === "function" ? new source(this.#client, logger) : source);
621
+ if (instance instanceof Plugin_1.Plugin)
622
+ throw new TypeError(instance.constructor.name + ": register plugins through the plugins option, not supports.");
623
+ return { instance, owner };
399
624
  });
625
+ supports.forEach(({ instance }, index) => {
626
+ if (instance.constructor !== Object && supports.slice(0, index).some(other => other.instance.constructor === instance.constructor))
627
+ throw new TypeError("Duplicate support: " + instance.constructor.name);
628
+ });
629
+ this.#supports = supports.map(({ instance }) => instance);
630
+ const registeredSupports = [...this.#supports];
631
+ // Registration returns one entry per slot, in the order given. A plugin that @Use-s another depends on it.
632
+ const pluginEntries = this.#plugins.register(slots.map(slot => ({
633
+ plugin: typeof slot.source === "function" ? new slot.source(this.#client, logger) : slot.source,
634
+ global: slot.global,
635
+ owned: slot.owned,
636
+ supports: supports.filter(({ owner }) => owner === slot).map(({ instance }) => instance),
637
+ uses: this.#usedClasses(slot.constructor)
638
+ })));
639
+ const entries = new Map(slots.map((slot, index) => [slot, pluginEntries[index]]));
640
+ // Every plugin is registered, so @Use can be checked and injected before any hook or event handler runs.
641
+ for (const handler of this.#validatedHandlers)
642
+ this.#validateUses(handler, true);
643
+ const constructed = [this.#moduleFunction, ...slots.map(slot => slot.constructor), ...registeredSupports.map(support => support.constructor), ...eventModules.map(({ module }) => module), ...listeners.map(({ listener }) => listener)];
644
+ for (const constructor of constructed)
645
+ this.#validateUses(constructor, false);
646
+ this.#injectUses(this.#module, this.#moduleFunction);
647
+ for (const entry of pluginEntries)
648
+ this.#injectUses(entry.plugin, entry.plugin.constructor);
649
+ for (const support of registeredSupports)
650
+ this.#injectUses(support, support.constructor);
651
+ const create = (constructor) => {
652
+ const instance = new constructor(this.#client, logger);
653
+ this.#injectUses(instance, constructor);
654
+ return instance;
655
+ };
656
+ this.#registerEvents(this.#module, this.#moduleFunction);
657
+ for (const entry of pluginEntries)
658
+ this.#registerEvents(entry.plugin, entry.plugin.constructor, entry);
659
+ for (const { module, owner } of eventModules)
660
+ this.#registerEvents(create(module), module, owner && entries.get(owner));
661
+ for (const { listener, owner } of listeners)
662
+ this.#registerEvents(create(listener), listener, owner && entries.get(owner));
663
+ this.#client.on("interactionCreate", this.#interactionListener);
664
+ }
665
+ #registerCommand(command) {
666
+ const type = (0, Metadata_1.getMetadata)(Constants_1.INTERACTION_TYPE_KEY, command);
667
+ if (type !== Constants_2.InteractionType.CHAT_INPUT_COMMAND && type !== Constants_2.InteractionType.CONTEXT_MENU_COMMAND)
668
+ throw new TypeError(command.name + ": missing command decorator.");
669
+ const name = (0, Metadata_1.getMetadata)(Constants_1.COMMAND_NAME_KEY, command);
670
+ const guild = (0, Metadata_1.getMetadata)(Constants_1.COMMAND_PRIVATE_KEY, command) ? (0, Metadata_1.getMetadata)(Constants_1.COMMAND_PRIVATE_GUILD_KEY, command) : "global";
671
+ if (!guild)
672
+ throw new TypeError(command.name + ": private command requires a guild ID.");
673
+ const contextType = type === Constants_2.InteractionType.CONTEXT_MENU_COMMAND ? (0, Metadata_1.getMetadata)(Constants_1.CONTEXT_MENU_TYPE_KEY, command) : 0;
674
+ const key = this.#commandKey(type, name, guild, contextType);
675
+ if (this.#commandRegistry.has(key))
676
+ throw new TypeError("Duplicate command: " + name + " in " + guild);
677
+ const children = [
678
+ ...((0, Metadata_1.getMetadata)(Constants_1.COMMAND_SUBCOMMANDS_KEY, command) ?? []),
679
+ ...Object.values((0, Metadata_1.getMetadata)(Constants_1.COMMAND_SUBCOMMAND_GROUPS_KEY, command) ?? {}).flat()
680
+ ];
681
+ if (children.length === 0)
682
+ this.#validateHandler(command);
683
+ else
684
+ for (const child of children)
685
+ this.#validateHandler(child);
686
+ if (type === Constants_2.InteractionType.CHAT_INPUT_COMMAND)
687
+ this.#mapSlashCommand(name, (0, Metadata_1.getMetadata)(Constants_1.COMMAND_DESCRIPTION_KEY, command), (0, Metadata_1.getMetadata)(Constants_1.COMMAND_OPTIONS_KEY, command));
688
+ else
689
+ this.#mapContextMenuCommand(name, contextType);
690
+ this.#commandRegistry.set(key, command);
691
+ }
692
+ #registerComponent(component) {
693
+ const type = (0, Metadata_1.getMetadata)(Constants_1.INTERACTION_TYPE_KEY, component);
694
+ const keys = new Map([
695
+ [Constants_2.InteractionType.BUTTON, Constants_1.BUTTON_OPTIONS_KEY],
696
+ [Constants_2.InteractionType.SELECT_MENU, Constants_1.SELECT_MENU_OPTIONS_KEY],
697
+ [Constants_2.InteractionType.MODAL_SUBMIT, Constants_1.MODAL_OPTIONS_KEY]
698
+ ]);
699
+ const metadataKey = keys.get(type);
700
+ const options = metadataKey && (0, Metadata_1.getMetadata)(metadataKey, component);
701
+ if (!options)
702
+ throw new TypeError(component.name + ": missing component decorator.");
703
+ // Link and premium buttons are rendered by Discord and have no interaction handler.
704
+ if (type === Constants_2.InteractionType.BUTTON && options.customId === undefined)
705
+ return;
706
+ if (typeof options.customId !== "string" || options.customId.length === 0 || options.customId.length > 100)
707
+ throw new TypeError(component.name + ": custom ID must contain 1-100 characters.");
708
+ this.#validateHandler(component);
709
+ const pattern = (0, Metadata_1.getMetadata)(Constants_1.CUSTOM_ID_PATTERN_KEY, component);
710
+ if (pattern !== undefined) {
711
+ const route = (0, customId_1.compileCustomId)(pattern);
712
+ const routes = this.#componentPatterns.get(type) ?? [];
713
+ if (routes.some(existing => (0, customId_1.customIdRoutesOverlap)(existing.route, route)))
714
+ throw new TypeError("Ambiguous custom ID pattern: " + pattern);
715
+ routes.push({ handler: component, route });
716
+ this.#componentPatterns.set(type, routes);
717
+ }
718
+ else {
719
+ const key = this.#componentKey(type, options.customId);
720
+ if (this.#componentRegistry.has(key))
721
+ throw new TypeError("Duplicate component custom ID: " + options.customId);
722
+ this.#componentRegistry.set(key, component);
723
+ }
724
+ }
725
+ #validateHandler(handler) {
726
+ this.#validatedHandlers.push(handler);
727
+ const method = (0, Metadata_1.getMetadata)(Constants_1.INTERACTION_RUN_METHOD_KEY, handler);
728
+ if (method === undefined || typeof handler.prototype[method] !== "function")
729
+ throw new TypeError(handler.name + ": missing or invalid @Run method.");
730
+ const definitions = (0, Metadata_1.getMetadata)(Constants_1.COMMAND_OPTIONS_KEY, handler) ?? [];
731
+ const autocomplete = ((0, Metadata_1.getMetadata)(Constants_1.AUTOCOMPLETE_METHODS_KEY, handler) ?? {});
732
+ for (const definition of definitions) {
733
+ if (definition.autocomplete && autocomplete[definition.name] === undefined)
734
+ throw new TypeError(handler.name + ": missing @Autocomplete for " + definition.name);
735
+ }
736
+ for (const [name, autocompleteMethod] of Object.entries(autocomplete)) {
737
+ if (!definitions.some((definition) => definition.name === name && definition.autocomplete) || typeof handler.prototype[autocompleteMethod] !== "function")
738
+ throw new TypeError(handler.name + ": invalid autocomplete handler " + name);
739
+ }
740
+ this.#validateInjections(handler);
741
+ }
742
+ #validateInjections(handler) {
743
+ const properties = ((0, Metadata_1.getMetadata)(Constants_1.INJECTION_PROPERTIES_KEY, handler) ?? []);
744
+ const type = (0, Metadata_1.getMetadata)(Constants_1.INTERACTION_TYPE_KEY, handler);
745
+ const pattern = (0, Metadata_1.getMetadata)(Constants_1.CUSTOM_ID_PATTERN_KEY, handler);
746
+ const names = pattern === undefined ? [] : (0, customId_1.compileCustomId)(pattern).names;
747
+ for (const property of properties) {
748
+ if (property.kind === "context" && type !== Constants_2.InteractionType.CHAT_INPUT_COMMAND)
749
+ throw new TypeError(handler.name + ": @Context requires a slash command.");
750
+ if (property.kind === "option" && type !== Constants_2.InteractionType.CHAT_INPUT_COMMAND)
751
+ throw new TypeError(handler.name + ": option properties require a slash command.");
752
+ if (property.kind === "custom_id" && !names.includes(property.name))
753
+ throw new TypeError(handler.name + ": unknown custom ID parameter " + property.name);
754
+ }
755
+ const components = ((0, Metadata_1.getMetadata)(Constants_1.MODAL_COMPONENTS_KEY, handler) ?? []);
756
+ const fieldIds = new Set();
757
+ for (const component of components) {
758
+ if (component.outerType !== "label")
759
+ continue;
760
+ const id = component.component.data.component?.data.custom_id;
761
+ if (id && fieldIds.has(id))
762
+ throw new TypeError(handler.name + ": duplicate modal field " + id);
763
+ if (id)
764
+ fieldIds.add(id);
765
+ }
766
+ for (const field of properties) {
767
+ if (field.kind !== "modal_field")
768
+ continue;
769
+ const component = components.find(c => c.outerType === "label" && c.component.data.component?.data.custom_id === field.customId);
770
+ const expected = field.type === "select_menu" ? component?.innerType.endsWith("_select") : component?.innerType === field.type;
771
+ if (!expected)
772
+ throw new TypeError(handler.name + ": invalid modal field injection " + field.customId);
773
+ }
400
774
  }
401
775
  #setModule(discordModule) {
402
776
  this.#moduleFunction = discordModule;
@@ -405,15 +779,28 @@ class DiscordApp {
405
779
  this.#appOptions = Util_1.Util.mergeDefault(defaultDiscordAppOptions, options);
406
780
  }
407
781
  #mapSlashCommand(name, description, options = [], integrationTypes = []) {
408
- const requiredOptions = options.filter(o => o.required);
409
- const data = new discord_js_1.SlashCommandBuilder()
410
- .setName(name)
411
- .setDescription(description);
782
+ const builder = new discord_js_1.SlashCommandBuilder().setName(name).setDescription(description);
412
783
  if (integrationTypes.length > 0)
413
- data.setIntegrationTypes(integrationTypes);
414
- Reflect.set(data, "options", [...requiredOptions, ...options.filter(o => !o.required)]);
415
- this.#module.logger.info(`├─ Mapped slash command ${name}. (${(Date.now() - this.#loadStartTimestamp)}ms)`);
416
- return data.toJSON();
784
+ builder.setIntegrationTypes(integrationTypes);
785
+ const data = builder.toJSON();
786
+ data.options = options.map(option => option.toJSON());
787
+ this.#sortOptions(data.options);
788
+ return data;
789
+ }
790
+ #sortOptions(options) {
791
+ if (options.length > 25)
792
+ throw new TypeError("Commands support at most 25 options.");
793
+ const names = new Set();
794
+ for (const option of options) {
795
+ if (names.has(option.name))
796
+ throw new TypeError("Duplicate command option " + option.name);
797
+ names.add(option.name);
798
+ if ("options" in option && option.options)
799
+ this.#sortOptions(option.options);
800
+ }
801
+ if (options.some(option => option.type === 1 || option.type === 2) && options.some(option => option.type !== 1 && option.type !== 2))
802
+ throw new TypeError("Subcommands cannot be mixed with ordinary options.");
803
+ options.sort((a, b) => Number("required" in b && b.required) - Number("required" in a && a.required));
417
804
  }
418
805
  #mapContextMenuCommand(name, type, integrationTypes = []) {
419
806
  const data = new discord_js_1.ContextMenuCommandBuilder()
@@ -421,7 +808,6 @@ class DiscordApp {
421
808
  .setType(type);
422
809
  if (integrationTypes.length > 0)
423
810
  data.setIntegrationTypes(integrationTypes);
424
- this.#module.logger.info(`├─ Mapped context command ${name}. (${(Date.now() - this.#loadStartTimestamp)}ms)`);
425
811
  return data.toJSON();
426
812
  }
427
813
  /**
@@ -443,7 +829,6 @@ class DiscordApp {
443
829
  * ```
444
830
  */
445
831
  static create(discordModule, options = {}) {
446
- a1 = true;
447
832
  const app = new DiscordApp();
448
833
  app.#setModule(discordModule);
449
834
  app.#setOptions(options);
@@ -452,3 +837,4 @@ class DiscordApp {
452
837
  }
453
838
  }
454
839
  exports.DiscordApp = DiscordApp;
840
+ //# sourceMappingURL=DiscordApp.js.map