oopscord.js 0.0.30 → 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 (103) hide show
  1. package/LICENSE +674 -201
  2. package/README.md +212 -11
  3. package/dist/index.js +18 -1
  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 +6 -2
  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 +695 -316
  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 +32 -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 +21 -22
  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 +98 -137
  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 +35 -35
  32. package/dist/structures/components/BaseSelectMenu.js.map +1 -0
  33. package/dist/structures/components/Listener.js +6 -1
  34. package/dist/structures/components/Listener.js.map +1 -0
  35. package/dist/structures/components/index.js +21 -4
  36. package/dist/structures/components/index.js.map +1 -0
  37. package/dist/structures/decorators/CommandDecorator.d.ts +38 -37
  38. package/dist/structures/decorators/CommandDecorator.d.ts.map +1 -1
  39. package/dist/structures/decorators/CommandDecorator.js +206 -280
  40. package/dist/structures/decorators/CommandDecorator.js.map +1 -0
  41. package/dist/structures/decorators/Constants.d.ts +7 -5
  42. package/dist/structures/decorators/Constants.d.ts.map +1 -1
  43. package/dist/structures/decorators/Constants.js +37 -31
  44. package/dist/structures/decorators/Constants.js.map +1 -0
  45. package/dist/structures/decorators/DiscordModuleDecorator.d.ts +7 -2
  46. package/dist/structures/decorators/DiscordModuleDecorator.d.ts.map +1 -1
  47. package/dist/structures/decorators/DiscordModuleDecorator.js +16 -33
  48. package/dist/structures/decorators/DiscordModuleDecorator.js.map +1 -0
  49. package/dist/structures/decorators/EventDecorator.d.ts +3 -2
  50. package/dist/structures/decorators/EventDecorator.d.ts.map +1 -1
  51. package/dist/structures/decorators/EventDecorator.js +19 -11
  52. package/dist/structures/decorators/EventDecorator.js.map +1 -0
  53. package/dist/structures/decorators/ExecutionDecorator.d.ts +19 -0
  54. package/dist/structures/decorators/ExecutionDecorator.d.ts.map +1 -0
  55. package/dist/structures/decorators/ExecutionDecorator.js +23 -0
  56. package/dist/structures/decorators/ExecutionDecorator.js.map +1 -0
  57. package/dist/structures/decorators/InjectionMetadata.d.ts +35 -0
  58. package/dist/structures/decorators/InjectionMetadata.d.ts.map +1 -0
  59. package/dist/structures/decorators/InjectionMetadata.js +34 -0
  60. package/dist/structures/decorators/InjectionMetadata.js.map +1 -0
  61. package/dist/structures/decorators/InteractionHandlerDecorator.d.ts +17 -2
  62. package/dist/structures/decorators/InteractionHandlerDecorator.d.ts.map +1 -1
  63. package/dist/structures/decorators/InteractionHandlerDecorator.js +53 -8
  64. package/dist/structures/decorators/InteractionHandlerDecorator.js.map +1 -0
  65. package/dist/structures/decorators/MessageComponentDecorator.d.ts +24 -39
  66. package/dist/structures/decorators/MessageComponentDecorator.d.ts.map +1 -1
  67. package/dist/structures/decorators/MessageComponentDecorator.js +128 -122
  68. package/dist/structures/decorators/MessageComponentDecorator.js.map +1 -0
  69. package/dist/structures/decorators/Metadata.d.ts +16 -0
  70. package/dist/structures/decorators/Metadata.d.ts.map +1 -0
  71. package/dist/structures/decorators/Metadata.js +50 -0
  72. package/dist/structures/decorators/Metadata.js.map +1 -0
  73. package/dist/structures/decorators/PluginDecorator.d.ts +41 -0
  74. package/dist/structures/decorators/PluginDecorator.d.ts.map +1 -0
  75. package/dist/structures/decorators/PluginDecorator.js +36 -0
  76. package/dist/structures/decorators/PluginDecorator.js.map +1 -0
  77. package/dist/structures/decorators/UseDecorator.d.ts +44 -0
  78. package/dist/structures/decorators/UseDecorator.d.ts.map +1 -0
  79. package/dist/structures/decorators/UseDecorator.js +49 -0
  80. package/dist/structures/decorators/UseDecorator.js.map +1 -0
  81. package/dist/structures/decorators/index.d.ts +3 -0
  82. package/dist/structures/decorators/index.d.ts.map +1 -1
  83. package/dist/structures/decorators/index.js +26 -6
  84. package/dist/structures/decorators/index.js.map +1 -0
  85. package/dist/structures/index.d.ts +3 -1
  86. package/dist/structures/index.d.ts.map +1 -1
  87. package/dist/structures/index.js +26 -6
  88. package/dist/structures/index.js.map +1 -0
  89. package/dist/utils/Util.d.ts +2 -0
  90. package/dist/utils/Util.d.ts.map +1 -1
  91. package/dist/utils/Util.js +30 -11
  92. package/dist/utils/Util.js.map +1 -0
  93. package/dist/utils/cache.d.ts +4 -0
  94. package/dist/utils/cache.d.ts.map +1 -0
  95. package/dist/utils/cache.js +17 -0
  96. package/dist/utils/cache.js.map +1 -0
  97. package/dist/utils/customId.d.ts +12 -0
  98. package/dist/utils/customId.d.ts.map +1 -0
  99. package/dist/utils/customId.js +49 -0
  100. package/dist/utils/customId.js.map +1 -0
  101. package/package.json +64 -38
  102. package/bun.lock +0 -264
  103. package/tsdown.config.json +0 -3
@@ -1,11 +1,22 @@
1
- import { Client, Collection, ContextMenuCommandBuilder, REST, SlashCommandBuilder } from "discord.js";
2
- import { Routes } from "discord-api-types/v10";
3
- import { COMMAND_DESCRIPTION_KEY, COMMAND_NAME_KEY, COMMAND_PRIVATE_KEY, DICSORD_MODULE_OPTIONS_KEY, INTERNAL_EVENTS_KEY, INTERACTION_TYPE_KEY, COMMAND_OPTIONS_KEY, COMMAND_PRIVATE_GUILD_KEY, INTERACTION_RUN_METHOD_KEY, OPTIONS_PARAMETER_INDEX_KEY, INTERACTION_PARAMETER_INDEX_KEY, COMMAND_SUBCOMMAND_GROUPS_KEY, COMMAND_SUBCOMMANDS_KEY, MODULE_TYPE_KEY, ModuleType, COMMAND_MODULE_COMMANDS_KEY, MESSAGE_COMPONENT_MODULE_COMPONENTS_KEY, BUTTON_OPTIONS_KEY, SELECT_MENU_OPTIONS_KEY, MODAL_OPTIONS_KEY, MODAL_TEXT_INPUT_VALUE_INDEX_KEY, CONTEXT_MENU_TYPE_KEY, INTERACTION_INTEGRATION_TYPES_KEY, MODAL_SELECT_MENU_VALUE_INDEX_KEY, MODAL_FILE_UPLOAD_VALUE_INDEX_KEY, MODAL_COMPONENTS_KEY, EVENT_MODULE_LISTENERS_KEY } from "./decorators/Constants";
4
- import { InteractionType } from "./Constants";
5
- import { Util } from "../utils/Util";
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DiscordApp = exports.BaseDiscordModule = void 0;
4
+ const Metadata_1 = require("./decorators/Metadata");
5
+ const discord_js_1 = require("discord.js");
6
+ const v10_1 = require("discord-api-types/v10");
7
+ const Constants_1 = require("./decorators/Constants");
8
+ const UseDecorator_1 = require("./decorators/UseDecorator");
9
+ const Plugin_1 = require("./Plugin");
10
+ const Constants_2 = require("./Constants");
11
+ const PluginManager_1 = require("./PluginManager");
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");
6
16
  const defaultDiscordAppOptions = {
7
17
  logger: console,
8
- plugins: []
18
+ plugins: [],
19
+ pluginTimeout: 0
9
20
  };
10
21
  /**
11
22
  * The main class that you must extend to create a Discord application. You create an instance by using the `DiscordApp.create()` method.
@@ -30,7 +41,7 @@ const defaultDiscordAppOptions = {
30
41
  *
31
42
  * @see {@link DiscordApp.create}
32
43
  */
33
- export class BaseDiscordModule {
44
+ class BaseDiscordModule {
34
45
  client;
35
46
  logger;
36
47
  constructor(client, logger) {
@@ -41,7 +52,7 @@ export class BaseDiscordModule {
41
52
  _onReady() {
42
53
  }
43
54
  }
44
- let a1 = false;
55
+ exports.BaseDiscordModule = BaseDiscordModule;
45
56
  /**
46
57
  * Main application class for managing Discord bot functionality.
47
58
  *
@@ -65,11 +76,11 @@ let a1 = false;
65
76
  * - Must be instantiated using the static `create()` method
66
77
  * - Supports global and guild-specific (private) command deployment
67
78
  * - Routes interactions (commands, buttons, select menus, modals) to appropriate handlers
68
- * - Uses reflection metadata for decorator-based configuration
79
+ * - Uses standard decorator metadata for configuration and property injection
69
80
  *
70
81
  * @public
71
82
  */
72
- export class DiscordApp {
83
+ class DiscordApp {
73
84
  #rest;
74
85
  #client;
75
86
  #moduleFunction;
@@ -77,359 +88,726 @@ export class DiscordApp {
77
88
  #appOptions;
78
89
  #moduleOptions;
79
90
  #commands;
80
- #buttons;
81
- #selectMenus;
82
- #modals;
83
- #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 = [];
84
108
  constructor() {
85
- if (!a1)
86
- throw new ReferenceError("Please use DiscordApp.create()");
87
- a1 = false;
88
- this.#loadStartTimestamp = Date.now();
89
- this.#rest = new REST({ version: "10" });
109
+ this.#rest = new discord_js_1.REST({ version: "10" });
90
110
  }
91
- /**
92
- * Logs in to Discord and deploys the commands. This method must be called after creating the application with `DiscordApp.create()`.
93
- * @see {@link DiscordApp.create}
94
- */
95
- async login() {
96
- const commands = this.#commands.filter(i => Reflect.getMetadata(INTERACTION_TYPE_KEY, i) == InteractionType.CHAT_INPUT_COMMAND || Reflect.getMetadata(INTERACTION_TYPE_KEY, i) == InteractionType.CONTEXT_MENU_COMMAND);
97
- const privateCommands = commands.filter(c => Reflect.getMetadata(COMMAND_PRIVATE_KEY, c));
98
- const globalCommands = commands.filter(c => !Reflect.getMetadata(COMMAND_PRIVATE_KEY, c));
99
- 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)`);
100
- this.#module.logger.info("Mapping global commands...");
101
- // Prepare global commands
102
- const apiGlobalCommands = globalCommands.map(c => {
103
- const type = Reflect.getMetadata(INTERACTION_TYPE_KEY, c);
104
- const integrationTypes = Reflect.getMetadata(INTERACTION_INTEGRATION_TYPES_KEY, c);
105
- if (type == InteractionType.CHAT_INPUT_COMMAND)
106
- return this.#mapSlashCommand(Reflect.getMetadata(COMMAND_NAME_KEY, c), Reflect.getMetadata(COMMAND_DESCRIPTION_KEY, c), Reflect.getMetadata(COMMAND_OPTIONS_KEY, c), integrationTypes);
107
- else
108
- return this.#mapContextMenuCommand(Reflect.getMetadata(COMMAND_NAME_KEY, c), Reflect.getMetadata(CONTEXT_MENU_TYPE_KEY, c), integrationTypes);
109
- });
110
- this.#module.logger.info(`└─ Mapped ${apiGlobalCommands.length} global command(s). (${(Date.now() - this.#loadStartTimestamp)}ms)`);
111
- this.#module.logger.info("Mapping private commands...");
112
- // Prepare private commands
113
- const apiPrivateCommands = {};
114
- privateCommands.forEach(c => {
115
- const guildId = Reflect.getMetadata(COMMAND_PRIVATE_GUILD_KEY, c);
116
- const type = Reflect.getMetadata(INTERACTION_TYPE_KEY, c);
117
- const integrationTypes = Reflect.getMetadata(INTERACTION_INTEGRATION_TYPES_KEY, c);
118
- let data;
119
- if (type == InteractionType.CHAT_INPUT_COMMAND)
120
- data = this.#mapSlashCommand(Reflect.getMetadata(COMMAND_NAME_KEY, c), Reflect.getMetadata(COMMAND_DESCRIPTION_KEY, c), Reflect.getMetadata(COMMAND_OPTIONS_KEY, c), integrationTypes);
121
- else
122
- data = this.#mapContextMenuCommand(Reflect.getMetadata(COMMAND_NAME_KEY, c), Reflect.getMetadata(CONTEXT_MENU_TYPE_KEY, c), integrationTypes);
123
- if (!Array.isArray(apiPrivateCommands[guildId]))
124
- apiPrivateCommands[guildId] = [];
125
- apiPrivateCommands[guildId].push(data);
126
- });
127
- const wholePrivateCommands = Object.values(apiPrivateCommands).flat();
128
- 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();
129
114
  this.#rest.setToken(this.#moduleOptions.token);
130
- this.#module.logger.info("Logging in...");
131
115
  await this.#client.login(this.#moduleOptions.token);
132
- 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();
133
158
  try {
134
- this.#module.logger.info("Deploying commands...");
135
- if (this.#moduleOptions.test.enable) {
136
- await this.#rest.put(Routes.applicationGuildCommands(this.#client.user.id, this.#moduleOptions.test.guild), { body: apiGlobalCommands });
137
- this.#module.logger.info(`├─ Successfully registered global commands, in test guild ${this.#moduleOptions.test.guild}. (${(Date.now() - this.#loadStartTimestamp)}ms)`);
138
- }
139
- else {
140
- await this.#rest.put(Routes.applicationCommands(this.#client.user.id), { body: apiGlobalCommands });
141
- this.#module.logger.info(`├─ Successfully registered global commands. (${(Date.now() - this.#loadStartTimestamp)}ms)`);
142
- }
143
- for (const guildId in apiPrivateCommands) {
144
- await this.#rest.put(Routes.applicationGuildCommands(this.#client.user.id, guildId), { body: apiPrivateCommands[guildId] });
145
- 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);
146
200
  }
147
- this.#module.logger.info("└─ Successfully deployed all commands.");
148
201
  }
149
- catch (err) {
150
- this.#module.logger.warn("Failed to deploy commands.");
151
- 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 });
152
216
  }
153
- this.#module.logger.info("Application took " + (Date.now() - this.#loadStartTimestamp) + "ms to load.");
217
+ this.#module.logger.info("Successfully deployed all commands.");
154
218
  }
155
- /**
156
- * 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.
157
- * @param itr The chat input command interaction to handle.
158
- * @returns {void}
159
- * @internal
160
- */
161
- #chatInputCommandHandler(itr) {
162
- const commands = this.#commands.filter(i => Reflect.getMetadata(INTERACTION_TYPE_KEY, i) == InteractionType.CHAT_INPUT_COMMAND);
163
- const commandName = itr.commandName;
164
- const command = commands.find(c => Reflect.getMetadata(COMMAND_NAME_KEY, c) == commandName);
165
- if (!command)
166
- return;
167
- if (itr.options.getSubcommandGroup(false)) {
168
- let handler = Reflect.getMetadata(COMMAND_SUBCOMMAND_GROUPS_KEY, command)[itr.options.getSubcommandGroup(true)]?.find(c => Reflect.getMetadata(COMMAND_NAME_KEY, c) == itr.options.getSubcommand(true));
169
- if (!handler)
170
- return;
171
- let runMethod = Reflect.getMetadata(INTERACTION_RUN_METHOD_KEY, handler);
172
- let preArgs = [Reflect.getMetadata(INTERACTION_PARAMETER_INDEX_KEY, handler), ...(Reflect.getMetadata(OPTIONS_PARAMETER_INDEX_KEY, handler) || [])];
173
- let args = Array(preArgs.length).fill(null);
174
- if (runMethod == undefined)
175
- throw new TypeError("Failed to get the run method. Did you add the @Run decorator?");
176
- preArgs.forEach(arg => {
177
- if (typeof arg == "number")
178
- args[arg] = itr;
179
- else
180
- args[arg.index] = itr.options[arg.getMethod](arg.name);
181
- });
182
- let cmd = new handler(...args);
183
- cmd[runMethod]();
184
- }
185
- else if (itr.options.getSubcommand(false)) {
186
- let handler = Reflect.getMetadata(COMMAND_SUBCOMMANDS_KEY, command).find(c => Reflect.getMetadata(COMMAND_NAME_KEY, c) == itr.options.getSubcommand(true));
187
- if (!handler)
188
- return;
189
- let runMethod = Reflect.getMetadata(INTERACTION_RUN_METHOD_KEY, handler);
190
- let preArgs = [Reflect.getMetadata(INTERACTION_PARAMETER_INDEX_KEY, handler), ...(Reflect.getMetadata(OPTIONS_PARAMETER_INDEX_KEY, handler) || [])];
191
- let args = Array(preArgs.length).fill(null);
192
- if (runMethod == undefined)
193
- throw new TypeError("Failed to get the run method. Did you add the @Run decorator?");
194
- preArgs.forEach(arg => {
195
- if (typeof arg == "number")
196
- args[arg] = itr;
197
- else
198
- args[arg.index] = itr.options[arg.getMethod](arg.name);
199
- });
200
- let cmd = new handler(...args);
201
- 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 };
202
239
  }
203
- else {
204
- let runMethod = Reflect.getMetadata(INTERACTION_RUN_METHOD_KEY, command);
205
- let preArgs = [Reflect.getMetadata(INTERACTION_PARAMETER_INDEX_KEY, command), ...(Reflect.getMetadata(OPTIONS_PARAMETER_INDEX_KEY, command) || [])];
206
- let args = Array(preArgs.length).fill(null);
207
- if (runMethod == undefined)
208
- throw new TypeError("Failed to get the run method. Did you add the @Run decorator?");
209
- preArgs.forEach(arg => {
210
- if (typeof arg == "number")
211
- args[arg] = itr;
212
- else
213
- args[arg.index] = itr.options[arg.getMethod](arg.name);
214
- });
215
- let cmd = new command(...args);
216
- 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);
217
252
  }
253
+ return command;
218
254
  }
219
- /**
220
- * 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.
221
- * @param itr The context menu command interaction to handle.
222
- * @returns {void}
223
- * @internal
224
- */
225
- #contextMenuCommandHandler(itr) {
226
- const commands = this.#commands.filter(i => Reflect.getMetadata(INTERACTION_TYPE_KEY, i) == InteractionType.CONTEXT_MENU_COMMAND);
227
- const commandName = itr.commandName;
228
- const command = commands.find(c => Reflect.getMetadata(COMMAND_NAME_KEY, c) == commandName && Reflect.getMetadata(COMMAND_OPTIONS_KEY, c).type == itr.commandType);
229
- if (!command)
230
- return;
231
- let runMethod = Reflect.getMetadata(INTERACTION_RUN_METHOD_KEY, command);
232
- if (runMethod == undefined)
233
- throw new TypeError("Failed to get the run method. Did you add the @Run decorator?");
234
- let cmd = new command(itr);
235
- cmd[runMethod]();
255
+ #injections(constructor) {
256
+ return ((0, Metadata_1.getMetadata)(Constants_1.INJECTION_PROPERTIES_KEY, constructor) ?? []);
236
257
  }
237
- /**
238
- * 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.
239
- * @param itr The button interaction to handle.
240
- * @returns {void}
241
- * @internal
242
- */
243
- #buttonHandler(itr) {
244
- const button = this.#buttons.find(b => Reflect.getMetadata(BUTTON_OPTIONS_KEY, b).customId == itr.customId);
245
- if (!button)
246
- return;
247
- let runMethod = Reflect.getMetadata(INTERACTION_RUN_METHOD_KEY, button);
248
- if (runMethod == undefined)
249
- throw new TypeError("Failed to get the run method. Did you add the @Run decorator?");
250
- let cmd = new button(itr);
251
- 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)] : []);
252
261
  }
253
- /**
254
- * 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.
255
- * @param itr The select menu interaction to handle.
256
- * @returns {void}
257
- * @internal
258
- */
259
- #selectMenuHandler(itr) {
260
- const selectMenu = this.#selectMenus.find(b => Reflect.getMetadata(SELECT_MENU_OPTIONS_KEY, b).customId == itr.customId);
261
- if (!selectMenu)
262
- return;
263
- let runMethod = Reflect.getMetadata(INTERACTION_RUN_METHOD_KEY, selectMenu);
264
- if (runMethod == undefined)
265
- throw new TypeError("Failed to get the run method. Did you add the @Run decorator?");
266
- let cmd = new selectMenu(itr);
267
- 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
+ }
268
283
  }
269
284
  /**
270
- * 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.
271
- * @param itr The modal submit interaction to handle.
272
- * @returns {void}
273
- * @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.
274
287
  */
275
- #modalHandler(itr) {
276
- const modal = this.#modals.find(b => Reflect.getMetadata(MODAL_OPTIONS_KEY, b).customId == itr.customId);
277
- if (!modal)
278
- return;
279
- const modalComponents = Reflect.getMetadata(MODAL_COMPONENTS_KEY, modal);
280
- let runMethod = Reflect.getMetadata(INTERACTION_RUN_METHOD_KEY, modal);
281
- let preArgs = [Reflect.getMetadata(INTERACTION_PARAMETER_INDEX_KEY, modal), ...(Reflect.getMetadata(MODAL_TEXT_INPUT_VALUE_INDEX_KEY, modal) || []), ...(Reflect.getMetadata(MODAL_SELECT_MENU_VALUE_INDEX_KEY, modal) || []), ...(Reflect.getMetadata(MODAL_FILE_UPLOAD_VALUE_INDEX_KEY, modal) || [])];
282
- let args = Array(preArgs.length).fill(null);
283
- preArgs.forEach(arg => {
284
- if (typeof arg == "number") {
285
- 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;
286
294
  }
287
- else {
288
- const fieldIndex = arg;
289
- switch (fieldIndex.type) {
290
- case "text_input":
291
- args[arg.index] = itr.fields.getTextInputValue(fieldIndex.customId);
292
- break;
293
- case "select_menu":
294
- const getMethods = {
295
- "string_select": itr.fields.getStringSelectValues,
296
- "user_select": itr.fields.getSelectedUsers,
297
- "role_select": itr.fields.getSelectedRoles,
298
- "mentionable_select": itr.fields.getSelectedMentionables,
299
- "channel_select": itr.fields.getSelectedChannels
300
- };
301
- const label = modalComponents.find(c => c.outerType == "label" && c.innerType.endsWith("select") && c.component.data.component?.data?.custom_id == fieldIndex.customId);
302
- const getMethod = getMethods[label?.innerType];
303
- if (!getMethod)
304
- throw new TypeError(`Failed to get the select menu values for custom ID ${fieldIndex.customId}. Failed to gather necessary metadata.`);
305
- const result = getMethod.bind(itr.fields)(fieldIndex.customId);
306
- if (result instanceof Collection)
307
- args[arg.index] = result.toJSON();
308
- else
309
- args[arg.index] = result;
310
- break;
311
- case "file_upload":
312
- args[arg.index] = itr.fields.getUploadedFiles(fieldIndex.customId);
313
- break;
314
- case "radio_group":
315
- args[arg.index] = itr.fields.getRadioGroup(fieldIndex.customId);
316
- break;
317
- case "checkbox":
318
- args[arg.index] = itr.fields.getCheckbox(fieldIndex.customId);
319
- break;
320
- case "checkbox_group":
321
- 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())
322
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;
323
385
  }
324
386
  }
325
- });
326
- // if (runMethod == undefined) throw new TypeError("Failed to get the run method. Did you add the @Run decorator?");
327
- let cmd = new modal(...args);
328
- if (runMethod) {
329
- cmd[runMethod]();
330
387
  }
388
+ return true;
331
389
  }
332
- /**
333
- * 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.
334
- * @param itr The interaction to handle.
335
- * @returns {void}
336
- * @internal
337
- */
338
- #autoHandler(itr) {
339
- if (itr.isChatInputCommand()) {
340
- 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 });
341
411
  }
342
- else if (itr.isContextMenuCommand()) {
343
- 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;
344
422
  }
345
- else if (itr.isButton()) {
346
- 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;
347
430
  }
348
- else if (itr.isAnySelectMenu()) {
349
- 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
+ }
350
492
  }
351
- else if (itr.isModalSubmit()) {
352
- 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 });
353
536
  }
354
- return;
355
537
  }
356
- /**
357
- * 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.
358
- * @internal
359
- */
360
538
  #init() {
361
- const options = Reflect.getMetadata(DICSORD_MODULE_OPTIONS_KEY, this.#moduleFunction);
362
- const internalEvents = Reflect.getMetadata(INTERNAL_EVENTS_KEY, this.#moduleFunction);
363
- // const externalEvents = Reflect.getMetadata(DISCORD_MODULE_EXTERNAL_EVENTS_KEY, this.#moduleFunction) as ExternalModuleEvents[];
364
- this.#client = new Client(options);
365
- 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.");
366
544
  this.#moduleOptions = options;
367
- this.#commands = [];
368
- this.#buttons = [];
369
- this.#selectMenus = [];
370
- this.#modals = [];
371
- const module = this.#module;
372
- internalEvents.forEach(e => {
373
- 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()
374
550
  });
375
- this.#client.on("interactionCreate", (itr) => this.#autoHandler(itr));
376
- this.#moduleOptions.imports.forEach(module => {
377
- const moduleType = Reflect.getMetadata(MODULE_TYPE_KEY, module);
378
- switch (moduleType) {
379
- case ModuleType.COMMAND:
380
- this.#commands.push(...Reflect.getMetadata(COMMAND_MODULE_COMMANDS_KEY, module));
381
- break;
382
- case ModuleType.MESSAGE_COMPONENT:
383
- const components = Reflect.getMetadata(MESSAGE_COMPONENT_MODULE_COMPONENTS_KEY, module);
384
- const buttons = components.filter(c => Reflect.getMetadata(INTERACTION_TYPE_KEY, c) == InteractionType.BUTTON);
385
- const selectMenus = components.filter(c => Reflect.getMetadata(INTERACTION_TYPE_KEY, c) == InteractionType.SELECT_MENU);
386
- const modals = components.filter(c => Reflect.getMetadata(INTERACTION_TYPE_KEY, c) == InteractionType.MODAL_SUBMIT);
387
- this.#buttons.push(...buttons);
388
- this.#selectMenus.push(...selectMenus);
389
- this.#modals.push(...modals);
390
- break;
391
- case ModuleType.EVENT:
392
- const moduleEvents = (Reflect.getMetadata(INTERNAL_EVENTS_KEY, module) ?? []);
393
- moduleEvents.forEach(e => {
394
- const moduleInstance = new module(this.#client, this.#appOptions.logger);
395
- this.#client.on(e.eventName, (...args) => moduleInstance[e.methodName](...args));
396
- });
397
- const listeners = (Reflect.getMetadata(EVENT_MODULE_LISTENERS_KEY, module) ?? []);
398
- listeners.forEach(listener => {
399
- const listenerInstance = new listener(this.#client, this.#appOptions.logger);
400
- const listenerEvents = (Reflect.getMetadata(INTERNAL_EVENTS_KEY, listener) ?? []);
401
- listenerEvents.forEach(e => {
402
- this.#client.on(e.eventName, (...args) => listenerInstance[e.methodName](...args));
403
- });
404
- });
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);
405
561
  }
406
- ;
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 };
407
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
+ }
408
774
  }
409
775
  #setModule(discordModule) {
410
776
  this.#moduleFunction = discordModule;
411
777
  }
412
778
  #setOptions(options) {
413
- this.#appOptions = Util.mergeDefault(defaultDiscordAppOptions, options);
779
+ this.#appOptions = Util_1.Util.mergeDefault(defaultDiscordAppOptions, options);
414
780
  }
415
781
  #mapSlashCommand(name, description, options = [], integrationTypes = []) {
416
- const requiredOptions = options.filter(o => o.required);
417
- const data = new SlashCommandBuilder()
418
- .setName(name)
419
- .setDescription(description);
782
+ const builder = new discord_js_1.SlashCommandBuilder().setName(name).setDescription(description);
420
783
  if (integrationTypes.length > 0)
421
- data.setIntegrationTypes(integrationTypes);
422
- Reflect.set(data, "options", [...requiredOptions, ...options.filter(o => !o.required)]);
423
- this.#module.logger.info(`├─ Mapped slash command ${name}. (${(Date.now() - this.#loadStartTimestamp)}ms)`);
424
- 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));
425
804
  }
426
805
  #mapContextMenuCommand(name, type, integrationTypes = []) {
427
- const data = new ContextMenuCommandBuilder()
806
+ const data = new discord_js_1.ContextMenuCommandBuilder()
428
807
  .setName(name)
429
808
  .setType(type);
430
809
  if (integrationTypes.length > 0)
431
810
  data.setIntegrationTypes(integrationTypes);
432
- this.#module.logger.info(`├─ Mapped context command ${name}. (${(Date.now() - this.#loadStartTimestamp)}ms)`);
433
811
  return data.toJSON();
434
812
  }
435
813
  /**
@@ -451,7 +829,6 @@ export class DiscordApp {
451
829
  * ```
452
830
  */
453
831
  static create(discordModule, options = {}) {
454
- a1 = true;
455
832
  const app = new DiscordApp();
456
833
  app.#setModule(discordModule);
457
834
  app.#setOptions(options);
@@ -459,3 +836,5 @@ export class DiscordApp {
459
836
  return app;
460
837
  }
461
838
  }
839
+ exports.DiscordApp = DiscordApp;
840
+ //# sourceMappingURL=DiscordApp.js.map