nuxt-discord 0.0.17 → 0.2.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 (132) hide show
  1. package/README.md +249 -171
  2. package/dist/module.d.mts +146 -10
  3. package/dist/module.json +3 -3
  4. package/dist/module.mjs +1077 -348
  5. package/dist/runtime/acknowledgement.d.ts +11 -0
  6. package/dist/runtime/acknowledgement.js +156 -0
  7. package/dist/runtime/client/chat-theme.css +52 -0
  8. package/dist/runtime/client/components/ChatAvatar.d.vue.ts +6 -0
  9. package/dist/runtime/client/components/ChatAvatar.vue +11 -0
  10. package/dist/runtime/client/components/ChatAvatar.vue.d.ts +6 -0
  11. package/dist/runtime/client/components/CommandPicker.d.vue.ts +24 -0
  12. package/dist/runtime/client/components/CommandPicker.vue +67 -0
  13. package/dist/runtime/client/components/CommandPicker.vue.d.ts +24 -0
  14. package/dist/runtime/client/components/CommandReference.d.vue.ts +20 -0
  15. package/dist/runtime/client/components/CommandReference.vue +21 -0
  16. package/dist/runtime/client/components/CommandReference.vue.d.ts +20 -0
  17. package/dist/runtime/client/components/CommandTestBar.d.vue.ts +60 -0
  18. package/dist/runtime/client/components/CommandTestBar.vue +332 -0
  19. package/dist/runtime/client/components/CommandTestBar.vue.d.ts +60 -0
  20. package/dist/runtime/client/components/CommandTranscript.d.vue.ts +39 -0
  21. package/dist/runtime/client/components/CommandTranscript.vue +147 -0
  22. package/dist/runtime/client/components/CommandTranscript.vue.d.ts +39 -0
  23. package/dist/runtime/client/components/ProjectLogo.d.vue.ts +3 -0
  24. package/dist/runtime/client/components/ProjectLogo.vue +31 -0
  25. package/dist/runtime/client/components/ProjectLogo.vue.d.ts +3 -0
  26. package/dist/runtime/client/components/ReferenceContent.d.ts +26 -0
  27. package/dist/runtime/client/components/ReferenceContent.js +73 -0
  28. package/dist/runtime/client/components/TheHeader.d.vue.ts +3 -0
  29. package/dist/runtime/client/components/TheHeader.vue +53 -16
  30. package/dist/runtime/client/components/TheHeader.vue.d.ts +2 -2
  31. package/dist/runtime/client/components/appearance-select.d.ts +17 -0
  32. package/dist/runtime/client/components/appearance-select.js +15 -0
  33. package/dist/runtime/client/pages/activity.d.vue.ts +3 -0
  34. package/dist/runtime/client/pages/activity.vue +202 -0
  35. package/dist/runtime/client/pages/activity.vue.d.ts +3 -0
  36. package/dist/runtime/client/pages/context-menus.d.vue.ts +3 -0
  37. package/dist/runtime/client/pages/context-menus.vue +120 -0
  38. package/dist/runtime/client/pages/context-menus.vue.d.ts +3 -0
  39. package/dist/runtime/client/pages/listeners.d.vue.ts +3 -0
  40. package/dist/runtime/client/pages/listeners.vue +68 -0
  41. package/dist/runtime/client/pages/listeners.vue.d.ts +3 -0
  42. package/dist/runtime/client/pages/overview.d.vue.ts +3 -0
  43. package/dist/runtime/client/pages/overview.vue +280 -0
  44. package/dist/runtime/client/pages/overview.vue.d.ts +3 -0
  45. package/dist/runtime/client/pages/slash-commands.d.vue.ts +3 -0
  46. package/dist/runtime/client/pages/slash-commands.vue +185 -359
  47. package/dist/runtime/client/pages/slash-commands.vue.d.ts +2 -3
  48. package/dist/runtime/client/reference.css +46 -0
  49. package/dist/runtime/client/style.css +4 -1
  50. package/dist/runtime/client/useActivityLog.d.ts +7 -0
  51. package/dist/runtime/client/useActivityLog.js +76 -0
  52. package/dist/runtime/client/useCommandRegistry.d.ts +7 -0
  53. package/dist/runtime/client/useCommandRegistry.js +34 -0
  54. package/dist/runtime/client/useDashboardCatalog.d.ts +5 -0
  55. package/dist/runtime/client/useDashboardCatalog.js +9 -0
  56. package/dist/runtime/client/useDiscordCommandReference.d.ts +2 -0
  57. package/dist/runtime/client/useDiscordCommandReference.js +6 -0
  58. package/dist/runtime/dashboard/auth.d.ts +4 -0
  59. package/dist/runtime/dashboard/auth.js +55 -0
  60. package/dist/runtime/dashboard/oauth.d.ts +17 -0
  61. package/dist/runtime/dashboard/oauth.js +172 -0
  62. package/dist/runtime/dashboard/origin.d.ts +3 -0
  63. package/dist/runtime/dashboard/origin.js +15 -0
  64. package/dist/runtime/dashboard/permissions.d.ts +4 -0
  65. package/dist/runtime/dashboard/permissions.js +84 -0
  66. package/dist/runtime/dashboard/signin.d.ts +3 -0
  67. package/dist/runtime/dashboard/signin.js +42 -0
  68. package/dist/runtime/diagnostics.d.ts +4 -0
  69. package/dist/runtime/diagnostics.js +24 -0
  70. package/dist/runtime/discordInvocation.d.ts +14 -0
  71. package/dist/runtime/discordInvocation.js +28 -0
  72. package/dist/runtime/middleware.d.ts +1 -0
  73. package/dist/runtime/middleware.js +12 -0
  74. package/dist/runtime/reference/access.d.ts +6 -0
  75. package/dist/runtime/reference/access.js +143 -0
  76. package/dist/runtime/reference/catalog.d.ts +2 -0
  77. package/dist/runtime/reference/catalog.js +9 -0
  78. package/dist/runtime/reference/document.d.ts +2 -0
  79. package/dist/runtime/reference/document.js +22 -0
  80. package/dist/runtime/reference/hosted.d.ts +2 -0
  81. package/dist/runtime/reference/hosted.js +16 -0
  82. package/dist/runtime/reference/oauth.d.ts +2 -0
  83. package/dist/runtime/reference/oauth.js +4 -0
  84. package/dist/runtime/registration.d.ts +65 -0
  85. package/dist/runtime/registration.js +354 -0
  86. package/dist/runtime/server/api/discord/activity.get.d.ts +2 -0
  87. package/dist/runtime/server/api/discord/activity.get.js +6 -0
  88. package/dist/runtime/server/api/discord/catalog.get.d.ts +2 -0
  89. package/dist/runtime/server/api/discord/catalog.get.js +3 -0
  90. package/dist/runtime/server/api/discord/slash-command/autocomplete.post.d.ts +2 -0
  91. package/dist/runtime/server/api/discord/slash-command/autocomplete.post.js +14 -0
  92. package/dist/runtime/server/api/discord/slash-command/register.post.d.ts +1 -1
  93. package/dist/runtime/server/api/discord/slash-command/register.post.js +1 -1
  94. package/dist/runtime/server/api/discord/slash-command/remote-all.get.d.ts +1 -1
  95. package/dist/runtime/server/api/discord/slash-command/remote-diff.post.d.ts +1 -238
  96. package/dist/runtime/server/api/discord/slash-command/remote-diff.post.js +3 -1
  97. package/dist/runtime/server/api/discord/slash-command/test.post.d.ts +20 -0
  98. package/dist/runtime/server/api/discord/slash-command/test.post.js +19 -0
  99. package/dist/runtime/server/plugins/discord.js +95 -31
  100. package/dist/runtime/server/utils/client.d.ts +59 -246
  101. package/dist/runtime/server/utils/client.js +413 -451
  102. package/dist/runtime/server/utils/defineContextMenu.d.ts +49 -0
  103. package/dist/runtime/server/utils/defineContextMenu.js +12 -0
  104. package/dist/runtime/server/utils/defineListener.d.ts +24 -0
  105. package/dist/runtime/server/utils/defineListener.js +7 -0
  106. package/dist/runtime/server/utils/defineMiddleware.d.ts +29 -0
  107. package/dist/runtime/server/utils/defineMiddleware.js +24 -0
  108. package/dist/runtime/server/utils/describeCommand.d.ts +2 -0
  109. package/dist/runtime/server/utils/describeOption.d.ts +1 -1
  110. package/dist/runtime/server/utils/messageSender.d.ts +37 -0
  111. package/dist/runtime/server/utils/messageSender.js +149 -0
  112. package/dist/runtime/server/utils/middleware/cooldown.d.ts +1 -0
  113. package/dist/runtime/server/utils/middleware/cooldown.js +39 -0
  114. package/dist/runtime/server/utils/middleware/guildOnly.d.ts +1 -0
  115. package/dist/runtime/server/utils/middleware/guildOnly.js +6 -0
  116. package/dist/runtime/server/utils/middleware/ownerOnly.d.ts +1 -0
  117. package/dist/runtime/server/utils/middleware/ownerOnly.js +10 -0
  118. package/dist/runtime/server/utils/middleware/requireRole.d.ts +1 -0
  119. package/dist/runtime/server/utils/middleware/requireRole.js +15 -0
  120. package/dist/runtime/server/utils/reply.d.ts +13 -3
  121. package/dist/runtime/server/utils/reply.js +111 -162
  122. package/dist/runtime/server/utils/simulateInteraction.d.ts +20 -0
  123. package/dist/runtime/server/utils/simulateInteraction.js +127 -0
  124. package/dist/runtime/server/utils/useTextChannel.d.ts +56 -0
  125. package/dist/runtime/server/utils/useTextChannel.js +105 -0
  126. package/dist/types.d.mts +11 -1
  127. package/dist/types.d.ts +11 -1
  128. package/package.json +62 -44
  129. package/dist/runtime/client/components/TheHeader.css +0 -1
  130. package/dist/runtime/client/pages/slash-commands.css +0 -1
  131. package/dist/runtime/client/uno.config.d.ts +0 -2
  132. package/dist/runtime/client/uno.config.js +0 -10
@@ -1,125 +1,343 @@
1
+ import { once } from "node:events";
1
2
  import process from "node:process";
2
- import { ApplicationCommandOptionType, Events, Client as InternalClient, REST, Routes, SlashCommandBuilder, SlashCommandSubcommandBuilder, SlashCommandSubcommandGroupBuilder } from "discord.js";
3
- import { useNitroApp } from "nitropack/runtime";
4
- import { effectScope, isRef } from "vue";
3
+ import { ApplicationCommandOptionType, Events, Client as InternalClient, MessageFlags, REST } from "discord.js";
4
+ import { useNitroApp, useRuntimeConfig, useStorage } from "nitropack/runtime";
5
+ import { effectScope, isRef, onScopeDispose } from "vue";
6
+ import { interactionSender, scheduleAcknowledgement } from "../../acknowledgement.js";
7
+ import { DiscordConfigurationError, discordDiagnostic, logDiscordFailure } from "../../diagnostics.js";
8
+ import { currentInvocation, runInvocation, setInvocationFields } from "../../discordInvocation.js";
5
9
  import { logger } from "../../logger.js";
10
+ import { resolveMiddlewareTags } from "../../middleware.js";
11
+ import { CommandRegistration, commandScopes, planRegistrations } from "../../registration.js";
12
+ import { MiddlewareError } from "./defineMiddleware.js";
6
13
  import { reply } from "./reply.js";
7
- let currentInteraction = null;
8
14
  export function useInteraction() {
9
- return currentInteraction;
15
+ return currentInvocation()?.interaction ?? null;
10
16
  }
17
+ export function setCurrentChannel(channel) {
18
+ setInvocationFields({ channel });
19
+ }
20
+ export function getCurrentChannel() {
21
+ return currentInvocation()?.channel ?? null;
22
+ }
23
+ class UnknownCommandError extends Error {
24
+ }
25
+ class MissingOptionError extends Error {
26
+ constructor(option) {
27
+ super(`Missing required option "${option}"`);
28
+ this.option = option;
29
+ }
30
+ }
31
+ const LISTENER_CHANNEL_ACCESSORS = {
32
+ messageCreate: (msg) => msg.channel ?? null,
33
+ messageUpdate: (_old, newMsg) => newMsg?.channel ?? null,
34
+ messageDelete: (msg) => msg.channel ?? null,
35
+ messageReactionAdd: (reaction) => reaction?.message?.channel ?? null,
36
+ messageReactionRemove: (reaction) => reaction?.message?.channel ?? null,
37
+ typingStart: (typing) => typing?.channel ?? null,
38
+ channelCreate: (ch) => ch && "send" in ch ? ch : null,
39
+ channelUpdate: (_old, newCh) => newCh && "send" in newCh ? newCh : null,
40
+ channelDelete: (ch) => ch && "send" in ch ? ch : null,
41
+ threadCreate: (thread) => thread,
42
+ threadUpdate: (_old, newThread) => newThread,
43
+ threadDelete: (thread) => thread,
44
+ voiceStateUpdate: (_old, newState) => newState?.channel && "send" in newState.channel ? newState.channel : null
45
+ };
11
46
  export class DiscordClient {
12
47
  #client = null;
13
48
  get internalClient() {
14
49
  return this.#client;
15
50
  }
16
51
  #slashCommands = [];
52
+ #contextMenus = [];
53
+ #activityLog = [];
54
+ #activityId = 0;
55
+ #onActivity;
17
56
  #nitro = useNitroApp();
18
57
  #token;
19
- #clientId;
20
- #rest;
58
+ #registration;
59
+ #registeredGuildOverrides = /* @__PURE__ */ new Map();
21
60
  constructor() {
22
61
  if (!process.env.DISCORD_TOKEN) {
23
- throw new Error("DISCORD_TOKEN environment variable is not set");
62
+ throw new DiscordConfigurationError("DISCORD_TOKEN environment variable is not set");
24
63
  }
25
64
  this.#token = process.env.DISCORD_TOKEN;
26
- this.#rest = new REST().setToken(this.#token);
27
65
  if (!process.env.DISCORD_CLIENT_ID) {
28
- throw new Error("DISCORD_CLIENT_ID environment variable is not set");
66
+ throw new DiscordConfigurationError("DISCORD_CLIENT_ID environment variable is not set");
29
67
  }
30
- this.#clientId = process.env.DISCORD_CLIENT_ID;
31
- this.#nitro.hooks.hook("discord:client:error", (error) => {
32
- logger.error(error);
68
+ const appId = process.env.DISCORD_CLIENT_ID;
69
+ this.#registration = new CommandRegistration(new REST().setToken(this.#token), appId, {
70
+ load: () => useStorage("data").getItem(`nuxt-discord:${appId}:registration-scopes`),
71
+ save: (scopes) => useStorage("data").setItem(`nuxt-discord:${appId}:registration-scopes`, scopes)
72
+ }, (error) => {
73
+ logDiscordFailure("SlashCommandRegistrationError", error);
74
+ void this.#notify("discord:client:error", { type: "SlashCommandRegistrationError", client: this, error });
33
75
  });
76
+ const timeout = useRuntimeConfig().discord?.interactionTimeout;
77
+ if (typeof timeout === "number" && Number.isFinite(timeout) && timeout >= 0)
78
+ this.#interactionTimeout = timeout;
34
79
  }
35
80
  #clientOptions;
36
- async start(options) {
81
+ #listeners = [];
82
+ #connection;
83
+ #starting;
84
+ #stopping;
85
+ start(options) {
86
+ if (this.#stopping)
87
+ return this.#stopping.then(() => this.start(options));
88
+ if (this.#starting)
89
+ return this.#starting;
90
+ const connection = new AbortController();
91
+ this.#connection = connection;
92
+ this.#starting = this.#connect(options, connection.signal).catch(async (error) => {
93
+ if (!connection.signal.aborted)
94
+ await this.stop();
95
+ throw error;
96
+ });
97
+ return this.#starting;
98
+ }
99
+ async #connect(options, signal) {
37
100
  this.#clientOptions = { ...options };
38
101
  await this.#nitro.hooks.callHook("discord:client:config", this.#clientOptions);
39
- this.#client = new InternalClient(this.#clientOptions);
40
- this.#client.on(Events.InteractionCreate, (interaction) => this.#handleInteraction(interaction));
102
+ signal.throwIfAborted();
103
+ const client = new InternalClient(this.#clientOptions);
104
+ this.#client = client;
105
+ client.on(Events.InteractionCreate, (interaction) => this.dispatchInteraction(interaction));
41
106
  this.startScope();
42
- const { resolve, promise } = Promise.withResolvers();
43
- this.#client.once(Events.ClientReady, (readyClient) => {
44
- logger.log(`Discord client is ready! Logged in as ${readyClient.user?.tag}`);
45
- this.#nitro.hooks.callHook("discord:client:ready", this);
46
- resolve(void 0);
47
- });
48
- await this.#client.login(this.#token);
49
- return promise;
107
+ this.#attachListeners(this.#listeners);
108
+ await Promise.all([once(client, Events.ClientReady, { signal }), client.login(this.#token)]);
109
+ signal.throwIfAborted();
110
+ logger.log(`Discord client is ready! Logged in as ${client.user?.tag}`);
111
+ void this.#nitro.hooks.callHook("discord:client:ready", this)?.catch((error) => logDiscordFailure("Discord ready hook failed:", error));
50
112
  }
51
- async #handleInteraction(interaction) {
52
- if (!interaction.isAutocomplete() && !interaction.isChatInputCommand()) {
53
- return;
54
- }
55
- const commandName = interaction.commandName;
56
- let command = this.#slashCommands.find((cmd) => cmd.name === commandName);
57
- if (!command) {
58
- logger.warn(`Unknown slash command: ${commandName}`);
59
- this.#nitro.hooks.callHook("discord:client:error", {
60
- type: "UnknownSlashCommandError",
61
- client: this,
62
- interaction
63
- });
113
+ registerListeners(listeners) {
114
+ this.#listeners.push(...listeners);
115
+ if (this.#client)
116
+ this.#attachListeners(listeners);
117
+ }
118
+ #attachListeners(listeners) {
119
+ if (!this.#client)
64
120
  return;
65
- }
66
- if (command.subcommands != null && (command.subcommands?.length ?? 0) > 0) {
67
- const group = interaction.options.getSubcommandGroup(false);
68
- const subcommand = interaction.options.getSubcommand(false);
69
- if (group && subcommand) {
70
- command = command.subcommands.find((subcmd) => subcmd.name === group)?.subcommands?.find((subcmd) => subcmd.name === subcommand);
71
- } else if (subcommand) {
72
- command = command.subcommands.find((subcmd) => subcmd.name === subcommand);
121
+ for (const listener of listeners) {
122
+ const accessor = LISTENER_CHANNEL_ACCESSORS[listener.event];
123
+ const handler = async (...args) => {
124
+ const scope = this.#createScope();
125
+ try {
126
+ const channel = accessor?.(...args) ?? null;
127
+ await runInvocation(scope, { channel }, () => listener.execute(...args));
128
+ } catch (error) {
129
+ logDiscordFailure(`Listener error [${listener.event}]:`, error);
130
+ } finally {
131
+ scope.stop();
132
+ }
133
+ };
134
+ if (listener.once) {
135
+ this.#client.once(listener.event, handler);
73
136
  } else {
74
- logger.warn(`Unknown slash command subcommand: ${commandName} ${group ?? ""} ${subcommand}`);
137
+ this.#client.on(listener.event, handler);
75
138
  }
76
139
  }
77
- if (!command) {
78
- logger.warn(`Unknown slash command: ${commandName}`);
79
- this.#nitro.hooks.callHook("discord:client:error", {
80
- type: "UnknownSlashCommandError",
81
- client: this,
82
- interaction
83
- });
84
- return;
140
+ if (listeners.length > 0) {
141
+ logger.log(`Registered ${listeners.length} event listener(s)`);
85
142
  }
86
- if (!command.execute && command.load) {
87
- try {
88
- const dynamicCommand = await command.load();
89
- Object.assign(command, dynamicCommand);
90
- } catch (error) {
91
- this.#nitro.hooks.callHook("discord:client:error", {
92
- type: "SlashCommandExecutionError",
93
- client: this,
94
- interaction,
95
- command,
96
- error
97
- });
98
- return;
99
- }
143
+ }
144
+ addContextMenus(menus) {
145
+ this.#contextMenus.push(...menus);
146
+ }
147
+ getContextMenus() {
148
+ return this.#contextMenus;
149
+ }
150
+ async dispatchInteraction(interaction, options = {}) {
151
+ const scope = this.#createScope();
152
+ const dispose = () => scope.stop();
153
+ const menu = interaction.isUserContextMenuCommand() || interaction.isMessageContextMenuCommand();
154
+ if (!menu && !interaction.isChatInputCommand() && !interaction.isAutocomplete()) {
155
+ dispose();
156
+ return { status: "error", detail: "Unsupported interaction type", dispose };
100
157
  }
101
- if (!command.execute && !command.load) {
102
- this.#nitro.hooks.callHook("discord:client:error", {
103
- type: "SlashCommandExecutionError",
104
- client: this,
105
- interaction,
106
- command,
107
- error: new Error(`Slash command "${commandName}" cannot be executed or loaded`)
158
+ const type = menu ? "context-menu" : interaction.isAutocomplete() ? "autocomplete" : "command";
159
+ const start = Date.now();
160
+ const ctx = { interaction, type };
161
+ const middleware = {};
162
+ const result = { status: "ok", dispose };
163
+ let command;
164
+ let activityDetail;
165
+ let cancelAcknowledgement;
166
+ if (!options.simulation && this.#interactionTimeout !== 0) {
167
+ const timeout = this.#interactionTimeout ?? Math.max(0, DiscordClient.DISCORD_TOKEN_LIFETIME - (start - (interaction.createdTimestamp ?? start)));
168
+ const timer = setTimeout(dispose, timeout);
169
+ timer.unref();
170
+ scope.run(() => onScopeDispose(() => clearTimeout(timer)));
171
+ }
172
+ try {
173
+ if (interaction.isChatInputCommand() || interaction.isAutocomplete())
174
+ command = this.resolveSlashCommand(interaction.commandName, interaction.options.getSubcommandGroup?.(false), interaction.options.getSubcommand?.(false), interaction.commandGuildId);
175
+ if (!interaction.isAutocomplete() && (command?.defer || !options.simulation && this.#clientOptions?.deferOnPromise)) {
176
+ cancelAcknowledgement = scheduleAcknowledgement(interaction, command?.defer, !options.simulation);
177
+ scope.run(() => onScopeDispose(cancelAcknowledgement));
178
+ }
179
+ await runInvocation(scope, { channel: interaction.channel, interaction: interaction.isChatInputCommand() ? interaction : void 0, middleware }, async () => {
180
+ if (!options.simulation && type !== "autocomplete")
181
+ await this.#nitro.hooks.callHook("discord:interaction:before", ctx);
182
+ if (interaction.isUserContextMenuCommand() || interaction.isMessageContextMenuCommand()) {
183
+ const menuType = interaction.isUserContextMenuCommand() ? "user" : "message";
184
+ const menu2 = this.#contextMenus.find((m) => m.name === interaction.commandName && m.type === menuType && this.#matchesScope(m, interaction.commandGuildId));
185
+ if (!menu2)
186
+ throw new UnknownCommandError(`Unknown context menu "${interaction.commandName}"`);
187
+ const entries2 = [...resolveMiddlewareTags(menu2.middleware, menu2.name), ...menu2.middlewareEntries ?? []];
188
+ await this.#runMiddleware(entries2, interaction, void 0, "context-menu", middleware, async () => {
189
+ const value = scope.run(() => {
190
+ if (menu2.type === "user" && interaction.isUserContextMenuCommand())
191
+ return menu2.execute(interaction);
192
+ if (menu2.type === "message" && interaction.isMessageContextMenuCommand())
193
+ return menu2.execute(interaction);
194
+ });
195
+ await this.#respond(value, interaction, scope);
196
+ });
197
+ return;
198
+ }
199
+ if (!command)
200
+ throw new UnknownCommandError(`Unknown slash command "${interaction.commandName}"`);
201
+ if (interaction.isAutocomplete()) {
202
+ await this.#handleAutocomplete(interaction, command, scope);
203
+ return;
204
+ }
205
+ if (!command.execute && command.load)
206
+ Object.assign(command, await command.load());
207
+ const resolved = command;
208
+ const entries = [...resolveMiddlewareTags(resolved.middleware, resolved.path), ...resolved.middlewareEntries ?? []];
209
+ await this.#runMiddleware(entries, interaction, resolved, "command", middleware, async () => {
210
+ const args = this.#commandArgs(interaction, resolved);
211
+ if (!resolved.execute)
212
+ throw new Error(`Command "${interaction.commandName}" has no execute function`);
213
+ await this.#respond(scope.run(() => resolved.execute(...args)), interaction, scope);
214
+ });
108
215
  });
109
- return;
216
+ } catch (error) {
217
+ result.status = error instanceof MiddlewareError ? "denied" : "error";
218
+ result.detail = error instanceof Error ? error.message : String(error);
219
+ if (interaction.isAutocomplete()) {
220
+ if (scope.active && !interaction.responded)
221
+ await interaction.respond([]).catch(() => {
222
+ });
223
+ } else if (scope.active && !interaction.replied) {
224
+ const sender = interactionSender(interaction);
225
+ await sender.send({ content: result.status === "denied" ? result.detail : "An error occurred.", flags: MessageFlags.Ephemeral }).catch(() => {
226
+ });
227
+ }
228
+ if (!options.simulation) {
229
+ let hookError;
230
+ if (error instanceof MiddlewareError) {
231
+ const denied = { ...ctx, middleware: error.identifier ?? "unknown", reason: error.reason };
232
+ hookError = { ...denied, type: "MiddlewareDeniedError", identifier: error.identifier, client: this };
233
+ await this.#notify("discord:interaction:denied", denied);
234
+ } else if (error instanceof UnknownCommandError) {
235
+ hookError = { type: "UnknownSlashCommandError", interaction, client: this };
236
+ } else if (error instanceof MissingOptionError) {
237
+ hookError = { type: "MissingRequiredOptionError", interaction, client: this, command, option: error.option };
238
+ } else {
239
+ hookError = { type: "SlashCommandExecutionError", interaction, client: this, command, error };
240
+ }
241
+ logDiscordFailure(hookError.type, error);
242
+ activityDetail = result.status === "denied" ? "Denied by middleware" : discordDiagnostic(error);
243
+ await this.#notify("discord:client:error", hookError);
244
+ }
245
+ } finally {
246
+ cancelAcknowledgement?.();
247
+ if (!options.simulation && type !== "autocomplete") {
248
+ this.#logActivity({
249
+ type,
250
+ name: menu ? interaction.commandName : `/${interaction.commandName}`,
251
+ status: result.status,
252
+ detail: activityDetail,
253
+ duration: Date.now() - start,
254
+ userId: interaction.user?.id,
255
+ userName: interaction.user?.displayName,
256
+ guildId: interaction.guildId ?? void 0,
257
+ guildName: interaction.guild?.name,
258
+ channelId: interaction.channelId ?? void 0
259
+ });
260
+ await this.#notify("discord:interaction:after", { ...ctx, status: result.status, detail: result.detail });
261
+ }
262
+ if (result.status !== "ok" || type === "autocomplete")
263
+ dispose();
110
264
  }
111
- if (interaction.isAutocomplete()) {
112
- await this.#handleAutocomplete(interaction, command);
113
- } else if (interaction.isChatInputCommand()) {
114
- await this.#handleSlashCommand(interaction, command);
265
+ return result;
266
+ }
267
+ resolveSlashCommand(name, group, leaf, commandGuildId) {
268
+ const root = this.getSlashCommand(name, commandGuildId);
269
+ if (!root?.subcommands?.length)
270
+ return group || leaf ? void 0 : root;
271
+ if (!leaf)
272
+ return void 0;
273
+ if (group)
274
+ return root.subcommands.find((cmd) => cmd.name === group)?.subcommands?.find((cmd) => cmd.name === leaf);
275
+ return root.subcommands.find((cmd) => cmd.name === leaf && !cmd.subcommands?.length);
276
+ }
277
+ async #notify(name, event) {
278
+ try {
279
+ await this.#nitro.hooks.callHook(name, event);
280
+ } catch (error) {
281
+ logDiscordFailure(`Discord observer failed [${name}]`, error);
115
282
  }
116
283
  }
117
- async stop() {
118
- if (this.#client) {
119
- await this.#client.destroy();
120
- this.#client = null;
284
+ #logActivity(entry) {
285
+ const full = { ...entry, id: ++this.#activityId, timestamp: Date.now() };
286
+ this.#activityLog.push(full);
287
+ if (this.#activityLog.length > 200)
288
+ this.#activityLog.shift();
289
+ try {
290
+ this.#onActivity?.(full);
291
+ } catch (error) {
292
+ logDiscordFailure("Discord activity observer failed:", error);
121
293
  }
294
+ return full;
295
+ }
296
+ onActivity(callback) {
297
+ this.#onActivity = callback;
298
+ }
299
+ getActivityLog() {
300
+ return this.#activityLog;
301
+ }
302
+ async #runMiddleware(entries, interaction, command, type, context, execute) {
303
+ const runChain = async (index) => {
304
+ const entry = entries[index];
305
+ if (!entry)
306
+ return execute();
307
+ let continuation;
308
+ await entry.fn({
309
+ interaction,
310
+ command,
311
+ type,
312
+ next: async (ctx) => {
313
+ if (continuation)
314
+ throw new Error(`Middleware ${entry.name} called next() twice`);
315
+ Object.assign(context, ctx);
316
+ continuation = runChain(index + 1);
317
+ await continuation;
318
+ }
319
+ }, entry.options);
320
+ if (!continuation)
321
+ throw new MiddlewareError("Command was stopped by middleware.", entry.name);
322
+ await continuation;
323
+ };
324
+ await runChain(0);
325
+ }
326
+ stop() {
327
+ if (this.#stopping)
328
+ return this.#stopping;
329
+ this.#connection?.abort();
330
+ this.#connection = void 0;
331
+ this.#starting = void 0;
332
+ const client = this.#client;
333
+ this.#client = null;
122
334
  this.stopScope();
335
+ if (!client)
336
+ return Promise.resolve();
337
+ this.#stopping = Promise.resolve().then(() => client.destroy()).finally(() => {
338
+ this.#stopping = void 0;
339
+ });
340
+ return this.#stopping;
123
341
  }
124
342
  #scope;
125
343
  startScope() {
@@ -140,7 +358,7 @@ export class DiscordClient {
140
358
  return this.#client?.isReady() ?? false;
141
359
  }
142
360
  addSlashCommand(command) {
143
- const existingCommandIndex = this.#slashCommands.findIndex((cmd) => cmd.name === command.name);
361
+ const existingCommandIndex = this.#slashCommands.findIndex((cmd) => cmd.name === command.name && cmd.path === command.path);
144
362
  if (existingCommandIndex !== -1) {
145
363
  this.#slashCommands[existingCommandIndex] = command;
146
364
  } else {
@@ -152,8 +370,8 @@ export class DiscordClient {
152
370
  this.addSlashCommand(command);
153
371
  }
154
372
  }
155
- removeSlashCommand(name) {
156
- const index = this.#slashCommands.findIndex((cmd) => cmd.name === name);
373
+ removeSlashCommand(name, commandGuildId) {
374
+ const index = this.#slashCommands.findIndex((cmd) => cmd.name === name && this.#matchesScope(cmd, commandGuildId));
157
375
  if (index !== -1) {
158
376
  this.#slashCommands.splice(index, 1);
159
377
  }
@@ -164,388 +382,132 @@ export class DiscordClient {
164
382
  getSlashCommands() {
165
383
  return this.#slashCommands;
166
384
  }
167
- getSlashCommand(name) {
168
- return this.#slashCommands.find((cmd) => cmd.name === name);
385
+ #configuredGuilds() {
386
+ const configured = useRuntimeConfig().discord?.guilds;
387
+ return configured?.length ? configured : (process.env.DISCORD_GUILD_ID ?? "").split(",").map((id) => id.trim()).filter(Boolean);
388
+ }
389
+ #matchesScope(command, commandGuildId) {
390
+ if (commandGuildId === void 0)
391
+ return true;
392
+ if (command.guilds === true && commandGuildId != null)
393
+ return this.#registeredGuildOverrides.get(commandGuildId) ?? this.#configuredGuilds().includes(commandGuildId);
394
+ return commandScopes(command.guilds, []).includes(commandGuildId ?? "global");
395
+ }
396
+ getSlashCommand(name, commandGuildId) {
397
+ return this.#slashCommands.find((cmd) => cmd.name === name && this.#matchesScope(cmd, commandGuildId));
398
+ }
399
+ #interactionTimeout;
400
+ static DISCORD_TOKEN_LIFETIME = 15 * 60 * 1e3;
401
+ #createScope() {
402
+ return this.#scope?.run(() => effectScope()) ?? effectScope(true);
169
403
  }
170
- #interactionScopes = /* @__PURE__ */ new WeakMap();
171
- #commandFinalizationRegistry = new FinalizationRegistry((scope) => scope.stop());
172
- async #handleSlashCommand(interaction, command) {
404
+ #commandArgs(interaction, command) {
173
405
  const args = [];
174
406
  for (const option of command.options) {
175
- const opt = interaction.options.get(option.name, option.required);
176
- if (option.required && opt == null) {
177
- this.#nitro.hooks.callHook("discord:client:error", {
178
- type: "MissingRequiredOptionError",
179
- client: this,
180
- interaction,
181
- command,
182
- option: option.name
183
- });
184
- return;
407
+ const opt = interaction.options.get(option.name, false);
408
+ if (option.required && opt == null)
409
+ throw new MissingOptionError(option.name);
410
+ switch (option.type) {
411
+ case ApplicationCommandOptionType.Channel:
412
+ args.push(opt?.channel ?? void 0);
413
+ break;
414
+ case ApplicationCommandOptionType.User:
415
+ args.push(opt?.user ?? void 0);
416
+ break;
417
+ case ApplicationCommandOptionType.Role:
418
+ args.push(opt?.role ?? void 0);
419
+ break;
420
+ case ApplicationCommandOptionType.Mentionable:
421
+ args.push(opt?.user ?? opt?.member ?? opt?.role ?? void 0);
422
+ break;
423
+ case ApplicationCommandOptionType.Attachment:
424
+ args.push(opt?.attachment ?? void 0);
425
+ break;
426
+ default:
427
+ args.push(opt?.value);
428
+ break;
185
429
  }
186
- args.push(opt?.value);
187
- }
188
- let scope;
189
- if (this.#scope) {
190
- this.#scope.run(() => scope = effectScope());
191
- } else {
192
- scope = effectScope();
193
- }
194
- this.#interactionScopes.set(interaction, scope);
195
- if (import.meta.dev)
196
- this.#commandFinalizationRegistry.register(command, scope);
197
- try {
198
- let result;
199
- scope.run(() => {
200
- currentInteraction = interaction;
201
- result = command.execute(...args);
202
- currentInteraction = null;
203
- });
204
- if (this.#clientOptions?.deferOnPromise && isPromise(result)) {
205
- await interaction.deferReply();
206
- }
207
- await this.#handleSlashCommandReturn(result, interaction, command);
208
- } catch (error) {
209
- this.#nitro.hooks.callHook("discord:client:error", {
210
- type: "SlashCommandExecutionError",
211
- client: this,
212
- interaction,
213
- command,
214
- error
215
- });
216
430
  }
431
+ return args;
217
432
  }
218
- async #handleSlashCommandReturn(result, interaction, command) {
219
- result = await result;
220
- if (!result) {
433
+ async #respond(value, interaction, scope) {
434
+ const result = await value;
435
+ if (result == null || !scope.active)
221
436
  return;
437
+ if (typeof result === "string" || isRef(result))
438
+ return this.#respond(reply(result), interaction, scope);
439
+ if (typeof result === "function")
440
+ return scope.run(() => result.call(this, interaction, this));
441
+ if (typeof result !== "object")
442
+ throw new TypeError(`Unexpected command return type: ${typeof result}`);
443
+ const generator = Symbol.asyncIterator in result ? result[Symbol.asyncIterator]() : Symbol.iterator in result ? result[Symbol.iterator]() : void 0;
444
+ if (!generator) {
445
+ if (interaction.replied || interaction.deferred)
446
+ return result;
447
+ throw new Error("Unexpected command return value");
222
448
  }
223
- try {
224
- if (typeof result === "string" || isRef(result)) {
225
- return this.#handleSlashCommandReturn(reply(result), interaction, command);
226
- } else if (typeof result === "function") {
227
- const scope = this.#interactionScopes.get(interaction);
228
- if (!scope) {
229
- return result.call(this, interaction, this);
230
- } else {
231
- return scope.run(() => result.call(this, interaction, this));
232
- }
233
- } else if (Symbol.iterator in result && typeof result[Symbol.iterator] === "function") {
234
- const gen = result[Symbol.iterator]();
235
- let next = gen.next();
236
- while (!next.done) {
237
- next = gen.next(await this.#handleSlashCommandReturn(await next.value, interaction, command));
238
- }
239
- if (next.value != null) {
240
- return this.#handleSlashCommandReturn(next.value, interaction, command);
241
- }
242
- } else if (Symbol.asyncIterator in result && typeof result[Symbol.asyncIterator] === "function") {
243
- const gen = result[Symbol.asyncIterator]();
244
- let next = await gen.next();
245
- while (!next.done) {
246
- next = await gen.next(await this.#handleSlashCommandReturn(await next.value, interaction, command));
247
- }
248
- if (next.value != null) {
249
- return this.#handleSlashCommandReturn(next.value, interaction, command);
250
- }
251
- } else {
252
- if (result != null) {
253
- throw new Error(`Unexpected return type from slash command: ${typeof result}`);
254
- }
255
- }
256
- } catch (error) {
257
- this.#nitro.hooks.callHook("discord:client:error", {
258
- type: "SlashCommandExecutionError",
259
- client: this,
260
- interaction,
261
- command,
262
- error
263
- });
264
- }
265
- }
266
- async #handleAutocomplete(interaction, command) {
267
- const commandName = interaction.commandName;
268
- if (!command) {
269
- logger.warn(`Unknown slash command: ${commandName}`);
270
- this.#nitro.hooks.callHook("discord:client:error", {
271
- type: "UnknownSlashCommandError",
272
- client: this,
273
- interaction
274
- });
275
- return;
276
- }
277
- const focusedOption = interaction.options.getFocused(true);
278
- const varname = command.options.find((opt) => opt.name === focusedOption.name)?.varname;
279
- if (!varname) {
280
- return;
281
- }
282
- const autocompleteFunction = command.optionMacros?.[varname]?.autocomplete;
283
- if (!autocompleteFunction) {
284
- return;
285
- }
286
- const choices = await autocompleteFunction(focusedOption.value, interaction);
287
- await interaction.respond(choices);
288
- }
289
- #getSlashCommandBuilder(command, builder) {
290
- builder ??= new SlashCommandBuilder();
291
- builder.setName(command.name).setDescription(command.description);
292
- if (command.subcommands != null && command.subcommands.length > 0) {
293
- for (const subcommand of command.subcommands) {
294
- if (builder instanceof SlashCommandBuilder) {
295
- if ("subcommands" in subcommand && (subcommand.subcommands?.length ?? 0) > 0) {
296
- builder.addSubcommandGroup((subcommandGroupBuilder) => this.#getSlashCommandBuilder(subcommand, subcommandGroupBuilder));
297
- } else {
298
- builder.addSubcommand((subcommandBuilder) => this.#getSlashCommandBuilder(subcommand, subcommandBuilder));
299
- }
300
- } else if (builder instanceof SlashCommandSubcommandGroupBuilder) {
301
- builder.addSubcommand((subcommandBuilder) => this.#getSlashCommandBuilder(subcommand, subcommandBuilder));
302
- } else {
303
- throw new TypeError(`Unexpected builder type: ${builder.constructor.name}`);
304
- }
305
- }
306
- } else if (builder instanceof SlashCommandBuilder || builder instanceof SlashCommandSubcommandBuilder) {
307
- for (const option of command.options) {
308
- switch (option.type) {
309
- case ApplicationCommandOptionType.String:
310
- builder.addStringOption((opt) => {
311
- opt.setName(option.name).setRequired(option.required);
312
- if (option.description.length > 0)
313
- opt = opt.setDescription(option.description);
314
- if (option.minLength)
315
- opt = opt.setMinLength(option.minLength);
316
- if (option.maxLength)
317
- opt = opt.setMaxLength(option.maxLength);
318
- if (option.choices)
319
- opt = opt.addChoices(...option.choices);
320
- if (option.hasAutocomplete) {
321
- opt = opt.setAutocomplete(true);
322
- }
323
- return opt;
324
- });
325
- break;
326
- case ApplicationCommandOptionType.Integer:
327
- builder.addIntegerOption((opt) => {
328
- opt.setName(option.name).setRequired(option.required);
329
- if (option.description.length > 0)
330
- opt = opt.setDescription(option.description);
331
- if (option.min)
332
- opt = opt.setMinValue(option.min);
333
- if (option.max)
334
- opt = opt.setMaxValue(option.max);
335
- if (option.choices)
336
- opt = opt.addChoices(...option.choices);
337
- if (option.hasAutocomplete)
338
- opt = opt.setAutocomplete(true);
339
- return opt;
340
- });
341
- break;
342
- case ApplicationCommandOptionType.Number:
343
- builder.addNumberOption((opt) => {
344
- opt.setName(option.name).setRequired(option.required);
345
- if (option.description.length > 0)
346
- opt = opt.setDescription(option.description);
347
- if (option.min)
348
- opt = opt.setMinValue(option.min);
349
- if (option.max)
350
- opt = opt.setMaxValue(option.max);
351
- if (option.choices)
352
- opt = opt.addChoices(...option.choices);
353
- if (option.hasAutocomplete)
354
- opt = opt.setAutocomplete(true);
355
- return opt;
356
- });
357
- break;
358
- case ApplicationCommandOptionType.Boolean:
359
- builder.addBooleanOption((opt) => {
360
- opt.setName(option.name).setRequired(option.required);
361
- if (option.description.length > 0)
362
- opt = opt.setDescription(option.description);
363
- return opt;
364
- });
365
- break;
366
- }
367
- }
368
- }
369
- return builder;
370
- }
371
- #cachedRemoteSlashCommands = null;
372
- async getRemoteSlashCommands() {
373
- this.#cachedRemoteSlashCommands = await this.#rest.get(Routes.applicationCommands(this.#clientId));
374
- return this.#cachedRemoteSlashCommands;
375
- }
376
- async diffRemoteSlashCommands(localCommands = this.#slashCommands, forceRefresh = false) {
377
- if (!this.#cachedRemoteSlashCommands || forceRefresh) {
378
- await this.getRemoteSlashCommands();
449
+ let step = await scope.run(() => generator.next());
450
+ while (step && !step.done && scope.active) {
451
+ const response = await this.#respond(step.value, interaction, scope);
452
+ step = await scope.run(() => generator.next(response));
379
453
  }
380
- const remoteCommands = this.#cachedRemoteSlashCommands;
381
- const flattenedRemoteCommands = remoteCommands.flatMap((cmd) => {
382
- const subcommands = cmd.options?.flatMap((option) => {
383
- const name = `${cmd.name} ${option.name}`;
384
- if (option.type === ApplicationCommandOptionType.Subcommand) {
385
- return [{ ...option, name, subcommands: [] }];
386
- } else if (option.type === ApplicationCommandOptionType.SubcommandGroup) {
387
- const subcommands2 = option.options?.flatMap((suboption) => {
388
- return suboption.type === ApplicationCommandOptionType.Subcommand ? [{ ...suboption, name: `${name} ${suboption.name}`, subcommands: [] }] : [];
389
- }) ?? [];
390
- return [
391
- { ...option, name, subcommands: subcommands2 },
392
- ...subcommands2
393
- ];
394
- }
395
- return [];
396
- }) ?? [];
397
- return [
398
- { ...cmd, subcommands },
399
- ...subcommands
400
- ];
401
- });
402
- const flattenedLocalCommands = localCommands.flatMap(
403
- (cmd) => [
404
- cmd,
405
- ...cmd.subcommands?.flatMap((subcmd) => {
406
- const name = `${cmd.name} ${subcmd.name}`;
407
- return [
408
- { ...subcmd, name },
409
- ...subcmd.subcommands?.map((subsubcmd) => ({ ...subsubcmd, name: `${name} ${subsubcmd.name}` })) ?? []
410
- ];
411
- }) ?? []
412
- ]
413
- );
414
- const nameToCommands = flattenedLocalCommands.reduce((acc, command) => {
415
- (acc[command.name] ??= []).push(command);
416
- return acc;
417
- }, {});
418
- return flattenedLocalCommands.reduce((acc, command) => {
419
- if (nameToCommands[command.name].length > 1) {
420
- acc.conflict.push(command);
421
- return acc;
422
- }
423
- const remoteCommand = flattenedRemoteCommands.find((cmd) => cmd.name === command.name);
424
- if (!remoteCommand) {
425
- acc.added.push(command);
426
- } else if (
427
- // if some properties are different
428
- !propsEqual(command, remoteCommand, [
429
- "description"
430
- /* TODO: more */
431
- ]) || !((command.subcommands?.length ?? 0) > 0 && remoteCommand.subcommands.length > 0) && ((command.options?.length ?? 0) !== (remoteCommand.options?.length ?? 0) || (remoteCommand.options ?? []).some((opt, i) => !optionEqual(command.options[i], opt)))
432
- ) {
433
- acc.changed.push({ local: command, remote: remoteCommand });
434
- } else {
435
- if ("id" in remoteCommand && !command.id) {
436
- command.id = remoteCommand.id;
437
- }
438
- acc.synced.push({ local: command, remote: remoteCommand });
439
- }
440
- return acc;
441
- }, {
442
- added: [],
443
- removed: flattenedRemoteCommands.filter(({ name }) => !(name in nameToCommands)),
444
- changed: [],
445
- synced: [],
446
- conflict: []
447
- });
454
+ if (step?.done && step.value != null)
455
+ return this.#respond(step.value, interaction, scope);
448
456
  }
449
- async registerSlashCommands() {
450
- const diff = await this.diffRemoteSlashCommands();
451
- if (diff.added.length === 0 && diff.removed.length === 0 && diff.changed.length === 0) {
452
- logger.log("No changes to slash commands, skipping registration.");
453
- return [];
454
- }
455
- this.#cachedRemoteSlashCommands = null;
456
- if (true) {
457
- try {
458
- const result = await this.#rest.put(
459
- Routes.applicationCommands(this.#clientId),
460
- { body: this.#slashCommands.map((command) => this.#getSlashCommandBuilder(command).toJSON()) }
461
- );
462
- result.forEach((command, i) => {
463
- const localCommand = this.#slashCommands[i];
464
- if (localCommand) {
465
- localCommand.id = command.id;
466
- }
467
- });
468
- return result;
469
- } catch (error) {
470
- this.#nitro.hooks.callHook("discord:client:error", {
471
- type: "SlashCommandRegistrationError",
472
- client: this,
473
- error
474
- });
475
- return [];
476
- }
477
- } else {
478
- const results = await Promise.allSettled(
479
- diff.changed.map((command) => {
480
- if (!("id" in command.remote))
481
- return Promise.reject(new Error(`Remote command ${command.local.name} does not have an ID`));
482
- logger.log(`Updating slash command: ${command.local.name}`);
483
- const builder = this.#getSlashCommandBuilder(command.local);
484
- return this.#rest.patch(
485
- Routes.applicationCommand(this.#clientId, command.remote.id),
486
- { body: builder.toJSON() }
487
- );
488
- })
489
- );
490
- results.forEach((result, i) => {
491
- if (result.status === "rejected") {
492
- this.#nitro.hooks.callHook("discord:client:error", {
493
- type: "SlashCommandRegistrationError",
494
- client: this,
495
- command: result.reason.command,
496
- error: result.reason.error
497
- });
498
- } else {
499
- const command = diff.changed[i];
500
- command.local.id = result.value.id;
501
- }
502
- });
503
- return results;
457
+ async #handleAutocomplete(interaction, command, scope) {
458
+ const choices = async () => {
459
+ if (!command.execute && command.load)
460
+ Object.assign(command, await command.load());
461
+ const focused = interaction.options.getFocused(true);
462
+ const varname = command.options.find((opt) => opt.name === focused.name)?.varname;
463
+ const complete = varname && command.optionMacros?.[varname]?.autocomplete;
464
+ if (!complete)
465
+ throw new Error(`No autocomplete handler for "${focused.name}"`);
466
+ return complete(String(focused.value), interaction);
467
+ };
468
+ const fallback = Promise.withResolvers();
469
+ const elapsed = Date.now() - (interaction.createdTimestamp ?? Date.now());
470
+ const timer = setTimeout(() => fallback.resolve([]), Math.max(0, 2e3 - elapsed));
471
+ timer.unref();
472
+ scope.run(() => onScopeDispose(() => fallback.resolve([])));
473
+ try {
474
+ const result = await Promise.race([choices(), fallback.promise]);
475
+ if (scope.active && !interaction.responded)
476
+ await interaction.respond(result.slice(0, 25));
477
+ } finally {
478
+ clearTimeout(timer);
504
479
  }
505
480
  }
506
- }
507
- function propsEqual(a, b, props) {
508
- for (const prop of props) {
509
- if (a[prop] !== b[prop]) {
510
- return false;
511
- }
481
+ getRemoteSlashCommands() {
482
+ return this.#registration.read("global");
512
483
  }
513
- return true;
514
- }
515
- function optionEqual(a, b) {
516
- if (a.name !== b.name || a.description !== b.description || a.required !== !!b.required || a.type !== b.type) {
517
- return false;
518
- }
519
- if (!!("choices" in a && a.choices) !== !!("choices" in b && b.choices)) {
520
- return false;
521
- } else if ("choices" in a && a.choices && "choices" in b && b.choices) {
522
- if (a.choices.length !== b.choices.length) {
523
- return false;
524
- }
525
- for (let i = 0; i < a.choices.length; i++) {
526
- if (a.choices[i].name !== b.choices[i].name || a.choices[i].value !== b.choices[i].value) {
527
- return false;
528
- }
529
- }
484
+ diffRemoteSlashCommands(commands = this.#slashCommands, _forceRefresh = false) {
485
+ return this.#registration.diff(this.#registrationPlan(commands));
530
486
  }
531
- if (a.type === ApplicationCommandOptionType.Integer || a.type === ApplicationCommandOptionType.Number) {
532
- if ("min" in a !== "min_value" in b) {
533
- return false;
534
- } else if ("min" in a && "min_value" in b && a.min !== b.min_value) {
535
- return false;
536
- }
487
+ #registrationPlan(commands = this.#slashCommands, guilds) {
488
+ return planRegistrations(commands, this.#contextMenus, guilds ?? this.#configuredGuilds());
537
489
  }
538
- if (a.type === ApplicationCommandOptionType.String) {
539
- if ("minLength" in a !== "min_length" in b) {
540
- return false;
541
- } else if ("minLength" in a && "min_length" in b && a.minLength !== b.min_length) {
542
- return false;
490
+ async syncCommandRegistrations(options = {}) {
491
+ const configured = this.#configuredGuilds();
492
+ const guilds = options.guilds ?? configured;
493
+ const results = await this.#registration.sync(this.#registrationPlan(this.#slashCommands, guilds), options.changedOnly);
494
+ for (const { scope, error } of results) {
495
+ if (scope === "global" || error)
496
+ continue;
497
+ if (guilds.includes(scope) === configured.includes(scope))
498
+ this.#registeredGuildOverrides.delete(scope);
499
+ else
500
+ this.#registeredGuildOverrides.set(scope, guilds.includes(scope));
543
501
  }
502
+ return results;
544
503
  }
545
- if (a.hasAutocomplete !== !!("autocomplete" in b && b.autocomplete)) {
546
- return false;
504
+ async registerSlashCommands(guilds) {
505
+ const results = await this.syncCommandRegistrations({ guilds });
506
+ const errors = results.filter((result) => result.error);
507
+ if (errors.length)
508
+ throw new Error(errors.map((result) => `${result.scope}: ${result.error}`).join(", "));
509
+ return results.flatMap((result) => result.commands);
547
510
  }
548
- return true;
549
511
  }
550
512
  export function isPromise(value) {
551
513
  return typeof value?.then === "function";