mini-interactions 0.0.0-stage → 0.15.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.
- package/LICENSE +21 -0
- package/MIGRATION.md +126 -0
- package/README.md +253 -2
- package/dist/bot.d.ts +58 -0
- package/dist/bot.js +217 -0
- package/dist/builders/ActionRowBuilder.d.ts +22 -0
- package/dist/builders/ActionRowBuilder.js +33 -0
- package/dist/builders/AutomodRuleBuilder.d.ts +45 -0
- package/dist/builders/AutomodRuleBuilder.js +151 -0
- package/dist/builders/ButtonBuilder.d.ts +53 -0
- package/dist/builders/ButtonBuilder.js +124 -0
- package/dist/builders/ChannelSelectMenuBuilder.d.ts +53 -0
- package/dist/builders/ChannelSelectMenuBuilder.js +105 -0
- package/dist/builders/CheckboxBuilder.d.ts +20 -0
- package/dist/builders/CheckboxBuilder.js +20 -0
- package/dist/builders/CheckboxGroupBuilder.d.ts +25 -0
- package/dist/builders/CheckboxGroupBuilder.js +48 -0
- package/dist/builders/EmbedBuilder.d.ts +33 -0
- package/dist/builders/EmbedBuilder.js +103 -0
- package/dist/builders/FileUploadBuilder.d.ts +17 -0
- package/dist/builders/FileUploadBuilder.js +22 -0
- package/dist/builders/LabelBuilder.d.ts +16 -0
- package/dist/builders/LabelBuilder.js +21 -0
- package/dist/builders/MiniContainerBuilder.d.ts +131 -0
- package/dist/builders/MiniContainerBuilder.js +347 -0
- package/dist/builders/ModalBuilder.d.ts +16 -0
- package/dist/builders/ModalBuilder.js +36 -0
- package/dist/builders/ModalChannelSelectMenuBuilder.d.ts +29 -0
- package/dist/builders/ModalChannelSelectMenuBuilder.js +25 -0
- package/dist/builders/ModalMentionableSelectMenuBuilder.d.ts +53 -0
- package/dist/builders/ModalMentionableSelectMenuBuilder.js +87 -0
- package/dist/builders/ModalRoleSelectMenuBuilder.d.ts +27 -0
- package/dist/builders/ModalRoleSelectMenuBuilder.js +24 -0
- package/dist/builders/ModalStringSelectMenuBuilder.d.ts +62 -0
- package/dist/builders/ModalStringSelectMenuBuilder.js +120 -0
- package/dist/builders/ModalUserSelectMenuBuilder.d.ts +53 -0
- package/dist/builders/ModalUserSelectMenuBuilder.js +96 -0
- package/dist/builders/RadioBuilder.d.ts +22 -0
- package/dist/builders/RadioBuilder.js +36 -0
- package/dist/builders/RoleSelectMenuBuilder.d.ts +47 -0
- package/dist/builders/RoleSelectMenuBuilder.js +92 -0
- package/dist/builders/StringSelectMenuBuilder.d.ts +52 -0
- package/dist/builders/StringSelectMenuBuilder.js +104 -0
- package/dist/builders/StringSelectMenuOptionBuilder.d.ts +46 -0
- package/dist/builders/StringSelectMenuOptionBuilder.js +106 -0
- package/dist/builders/TextInputBuilder.d.ts +23 -0
- package/dist/builders/TextInputBuilder.js +26 -0
- package/dist/builders/index.d.ts +44 -0
- package/dist/builders/index.js +22 -0
- package/dist/builders/shared.d.ts +8 -0
- package/dist/builders/shared.js +11 -0
- package/dist/commands/CommandBuilder.d.ts +278 -0
- package/dist/commands/CommandBuilder.js +687 -0
- package/dist/commands/ContextMenuCommandBuilder.d.ts +94 -0
- package/dist/commands/ContextMenuCommandBuilder.js +145 -0
- package/dist/core/http/DiscordRestClient.d.ts +400 -0
- package/dist/core/http/DiscordRestClient.js +988 -0
- package/dist/core/interactions/InteractionContext.d.ts +33 -0
- package/dist/core/interactions/InteractionContext.js +61 -0
- package/dist/core/interactions/InteractionVerifier.d.ts +8 -0
- package/dist/core/interactions/InteractionVerifier.js +9 -0
- package/dist/core/messages/DiscordSentMessage.d.ts +32 -0
- package/dist/core/messages/DiscordSentMessage.js +64 -0
- package/dist/core/messages/message-payloads.d.ts +94 -0
- package/dist/core/messages/message-payloads.js +99 -0
- package/dist/core/webhooks/DiscordWebhook.d.ts +14 -0
- package/dist/core/webhooks/DiscordWebhook.js +69 -0
- package/dist/database/MiniDataBuilder.d.ts +61 -0
- package/dist/database/MiniDataBuilder.js +98 -0
- package/dist/database/MiniDatabase.d.ts +67 -0
- package/dist/database/MiniDatabase.js +222 -0
- package/dist/database/MiniDatabaseBuilder.d.ts +58 -0
- package/dist/database/MiniDatabaseBuilder.js +84 -0
- package/dist/database/index.d.ts +5 -0
- package/dist/database/index.js +3 -0
- package/dist/identity/ApplicationIdentityProfile.d.ts +188 -0
- package/dist/identity/ApplicationIdentityProfile.js +207 -0
- package/dist/index.d.ts +54 -0
- package/dist/index.js +34 -0
- package/dist/lobby/Lobby.d.ts +150 -0
- package/dist/lobby/Lobby.js +90 -0
- package/dist/node/MiniInteraction.d.ts +199 -0
- package/dist/node/MiniInteraction.js +861 -0
- package/dist/node/index.d.ts +2 -0
- package/dist/node/index.js +1 -0
- package/dist/oauth2/DiscordOAuth.d.ts +49 -0
- package/dist/oauth2/DiscordOAuth.js +113 -0
- package/dist/oauth2/OAuth2Builder.d.ts +296 -0
- package/dist/oauth2/OAuth2Builder.js +435 -0
- package/dist/oauth2/OAuth2Scopes.d.ts +285 -0
- package/dist/oauth2/OAuth2Scopes.js +438 -0
- package/dist/oauth2/OAuthTokenStorage.d.ts +37 -0
- package/dist/oauth2/OAuthTokenStorage.js +109 -0
- package/dist/oauth2/index.d.ts +8 -0
- package/dist/oauth2/index.js +4 -0
- package/dist/router/AutocompleteContext.d.ts +36 -0
- package/dist/router/AutocompleteContext.js +82 -0
- package/dist/router/InteractionRouter.d.ts +82 -0
- package/dist/router/InteractionRouter.js +225 -0
- package/dist/types/ButtonStyle.d.ts +16 -0
- package/dist/types/ButtonStyle.js +17 -0
- package/dist/types/ChannelType.d.ts +2 -0
- package/dist/types/ChannelType.js +2 -0
- package/dist/types/Commands.d.ts +35 -0
- package/dist/types/Commands.js +1 -0
- package/dist/types/ComponentTypes.d.ts +19 -0
- package/dist/types/ComponentTypes.js +1 -0
- package/dist/types/InteractionFlags.d.ts +5 -0
- package/dist/types/InteractionFlags.js +6 -0
- package/dist/types/PermissionFlags.d.ts +56 -0
- package/dist/types/PermissionFlags.js +5 -0
- package/dist/types/RoleConnectionMetadata.d.ts +14 -0
- package/dist/types/RoleConnectionMetadata.js +1 -0
- package/dist/types/RoleConnectionMetadataTypes.d.ts +11 -0
- package/dist/types/RoleConnectionMetadataTypes.js +12 -0
- package/dist/types/SeparatorSpacingSize.d.ts +2 -0
- package/dist/types/SeparatorSpacingSize.js +2 -0
- package/dist/types/checkbox.d.ts +16 -0
- package/dist/types/checkbox.js +12 -0
- package/dist/types/discord.d.ts +2 -0
- package/dist/types/discord.js +1 -0
- package/dist/types/radio.d.ts +12 -0
- package/dist/types/radio.js +10 -0
- package/dist/types/validation.d.ts +14 -0
- package/dist/types/validation.js +40 -0
- package/dist/utils/CommandInteractionOptions.d.ts +66 -0
- package/dist/utils/CommandInteractionOptions.js +364 -0
- package/dist/utils/ContextMenuInteraction.d.ts +76 -0
- package/dist/utils/ContextMenuInteraction.js +152 -0
- package/dist/utils/MessageComponentInteraction.d.ts +148 -0
- package/dist/utils/MessageComponentInteraction.js +259 -0
- package/dist/utils/ModalSubmitInteraction.d.ts +86 -0
- package/dist/utils/ModalSubmitInteraction.js +267 -0
- package/dist/utils/cdn.d.ts +30 -0
- package/dist/utils/cdn.js +60 -0
- package/dist/utils/formatting.d.ts +76 -0
- package/dist/utils/formatting.js +132 -0
- package/dist/utils/interactionMessageHelpers.d.ts +40 -0
- package/dist/utils/interactionMessageHelpers.js +118 -0
- package/dist/utils/localization.d.ts +25 -0
- package/dist/utils/localization.js +38 -0
- package/dist/utils/snowflake.d.ts +19 -0
- package/dist/utils/snowflake.js +32 -0
- package/dist/webhooks/WebhookEvent.d.ts +229 -0
- package/dist/webhooks/WebhookEvent.js +59 -0
- package/dist/webhooks/WebhookEventRouter.d.ts +123 -0
- package/dist/webhooks/WebhookEventRouter.js +160 -0
- package/dist/webhooks/WebhookEventVerifier.d.ts +33 -0
- package/dist/webhooks/WebhookEventVerifier.js +37 -0
- package/dist/webhooks/index.d.ts +6 -0
- package/dist/webhooks/index.js +3 -0
- package/package.json +90 -4
|
@@ -0,0 +1,861 @@
|
|
|
1
|
+
import { readFile, readdir } from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { pathToFileURL } from "node:url";
|
|
4
|
+
import { waitUntil as vercelWaitUntil } from "@vercel/functions";
|
|
5
|
+
import { ApplicationCommandType, InteractionResponseType, InteractionType, } from "discord-api-types/v10";
|
|
6
|
+
import { createCommandInteraction } from "../utils/CommandInteractionOptions.js";
|
|
7
|
+
import { createAppCommandInteraction, createMessageContextMenuInteraction, createUserContextMenuInteraction, } from "../utils/ContextMenuInteraction.js";
|
|
8
|
+
import { createMessageComponentInteraction } from "../utils/MessageComponentInteraction.js";
|
|
9
|
+
import { createModalSubmitInteraction } from "../utils/ModalSubmitInteraction.js";
|
|
10
|
+
import { DiscordRestClient } from "../core/http/DiscordRestClient.js";
|
|
11
|
+
import { verifyAndParseInteraction } from "../core/interactions/InteractionVerifier.js";
|
|
12
|
+
import { generateOAuthUrl, getDiscordUser, getOAuthTokens, } from "../oauth2/DiscordOAuth.js";
|
|
13
|
+
export class MiniInteraction {
|
|
14
|
+
options;
|
|
15
|
+
projectRoot;
|
|
16
|
+
rest;
|
|
17
|
+
responseStates = new Map();
|
|
18
|
+
loadedModulesPromise;
|
|
19
|
+
constructor(options = {}) {
|
|
20
|
+
this.options = options;
|
|
21
|
+
this.projectRoot = path.resolve(options.cwd ?? (typeof process !== "undefined" ? process.cwd() : "/"));
|
|
22
|
+
const applicationId = this.resolveApplicationId();
|
|
23
|
+
const token = this.resolveToken();
|
|
24
|
+
if (applicationId && token) {
|
|
25
|
+
this.rest = this.createRestClient(applicationId, token);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
createRestClient(applicationId, token) {
|
|
29
|
+
return new DiscordRestClient({
|
|
30
|
+
applicationId,
|
|
31
|
+
token,
|
|
32
|
+
apiBaseUrl: this.options.apiBaseUrl,
|
|
33
|
+
maxRetries: this.options.maxRetries,
|
|
34
|
+
fetchImplementation: this.options.fetchImplementation,
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
resolveApplicationId(env) {
|
|
38
|
+
const processEnv = typeof process !== "undefined" ? process.env : undefined;
|
|
39
|
+
return (this.options.applicationId ??
|
|
40
|
+
env?.DISCORD_APPLICATION_ID ??
|
|
41
|
+
env?.DISCORD_APP_ID ??
|
|
42
|
+
processEnv?.DISCORD_APPLICATION_ID ??
|
|
43
|
+
processEnv?.DISCORD_APP_ID);
|
|
44
|
+
}
|
|
45
|
+
resolveToken(env) {
|
|
46
|
+
const processEnv = typeof process !== "undefined" ? process.env : undefined;
|
|
47
|
+
return (this.options.token ??
|
|
48
|
+
env?.DISCORD_BOT_TOKEN ??
|
|
49
|
+
env?.DISCORD_TOKEN ??
|
|
50
|
+
processEnv?.DISCORD_BOT_TOKEN ??
|
|
51
|
+
processEnv?.DISCORD_TOKEN);
|
|
52
|
+
}
|
|
53
|
+
primeRestClient(env) {
|
|
54
|
+
if (this.rest)
|
|
55
|
+
return;
|
|
56
|
+
const applicationId = this.resolveApplicationId(env);
|
|
57
|
+
const token = this.resolveToken(env);
|
|
58
|
+
if (applicationId && token) {
|
|
59
|
+
this.rest = this.createRestClient(applicationId, token);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
getRestClient(env) {
|
|
63
|
+
this.primeRestClient(env);
|
|
64
|
+
if (!this.rest) {
|
|
65
|
+
throw new Error("[MiniInteraction] Missing Discord REST credentials. Set applicationId/token or DISCORD_APPLICATION_ID + DISCORD_BOT_TOKEN.");
|
|
66
|
+
}
|
|
67
|
+
return this.rest;
|
|
68
|
+
}
|
|
69
|
+
createNodeHandler() {
|
|
70
|
+
return async (req, res) => {
|
|
71
|
+
let responseSent = false;
|
|
72
|
+
let resolveInitialCommit;
|
|
73
|
+
const initialCommitPromise = new Promise((resolve) => {
|
|
74
|
+
resolveInitialCommit = resolve;
|
|
75
|
+
});
|
|
76
|
+
const commitInitialResponse = (response) => {
|
|
77
|
+
if (responseSent)
|
|
78
|
+
return false;
|
|
79
|
+
this.sendJson(res, 200, response);
|
|
80
|
+
responseSent = true;
|
|
81
|
+
resolveInitialCommit?.();
|
|
82
|
+
return true;
|
|
83
|
+
};
|
|
84
|
+
try {
|
|
85
|
+
const body = await this.readRawBody(req);
|
|
86
|
+
const signature = this.getHeader(req.headers, "x-signature-ed25519");
|
|
87
|
+
const timestamp = this.getHeader(req.headers, "x-signature-timestamp");
|
|
88
|
+
const publicKey = this.options.publicKey ?? process.env.DISCORD_PUBLIC_KEY;
|
|
89
|
+
if (!publicKey) {
|
|
90
|
+
this.sendJson(res, 500, {
|
|
91
|
+
error: "[MiniInteraction] Missing DISCORD_PUBLIC_KEY.",
|
|
92
|
+
});
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
if (!signature || !timestamp) {
|
|
96
|
+
this.sendJson(res, 401, {
|
|
97
|
+
error: "[MiniInteraction] Missing Discord signature headers.",
|
|
98
|
+
});
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
const interaction = await verifyAndParseInteraction({
|
|
102
|
+
body,
|
|
103
|
+
signature,
|
|
104
|
+
timestamp,
|
|
105
|
+
publicKey,
|
|
106
|
+
});
|
|
107
|
+
if (interaction.type === InteractionType.Ping) {
|
|
108
|
+
this.sendJson(res, 200, { type: InteractionResponseType.Pong });
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
const dispatchPromise = this.dispatch(interaction, commitInitialResponse);
|
|
112
|
+
const backgroundPromise = dispatchPromise.catch((error) => {
|
|
113
|
+
if (this.options.debug) {
|
|
114
|
+
console.error("[MiniInteraction] Background interaction processing failed", error);
|
|
115
|
+
}
|
|
116
|
+
});
|
|
117
|
+
const settled = await Promise.race([
|
|
118
|
+
dispatchPromise.then((response) => ({ kind: "result", response }), (error) => ({ kind: "error", error })),
|
|
119
|
+
initialCommitPromise.then(() => ({ kind: "committed" })),
|
|
120
|
+
]);
|
|
121
|
+
if (settled.kind === "committed") {
|
|
122
|
+
this.scheduleBackgroundTask(backgroundPromise);
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
if (settled.kind === "error") {
|
|
126
|
+
throw settled.error;
|
|
127
|
+
}
|
|
128
|
+
const response = settled.response;
|
|
129
|
+
if (!responseSent) {
|
|
130
|
+
this.sendJson(res, 200, response ?? this.getDefaultInitialResponse(interaction));
|
|
131
|
+
responseSent = true;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
catch (error) {
|
|
135
|
+
const message = error instanceof Error ? error.message : "[MiniInteraction] Unknown error";
|
|
136
|
+
if (this.options.debug) {
|
|
137
|
+
console.error("[MiniInteraction] createNodeHandler failed", error);
|
|
138
|
+
}
|
|
139
|
+
if (!responseSent) {
|
|
140
|
+
this.sendJson(res, 500, { error: message });
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
async registerMetadata(botToken, metadata) {
|
|
146
|
+
if (!botToken) {
|
|
147
|
+
throw new Error("[MiniInteraction] botToken is required");
|
|
148
|
+
}
|
|
149
|
+
if (!Array.isArray(metadata) || metadata.length === 0) {
|
|
150
|
+
throw new Error("[MiniInteraction] metadata must be a non-empty array payload");
|
|
151
|
+
}
|
|
152
|
+
const payload = metadata.map((field) => ({
|
|
153
|
+
...field,
|
|
154
|
+
type: field.type,
|
|
155
|
+
}));
|
|
156
|
+
const applicationId = this.resolveApplicationId();
|
|
157
|
+
if (!applicationId) {
|
|
158
|
+
throw new Error("[MiniInteraction] Missing Discord application ID. Set options.applicationId or DISCORD_APPLICATION_ID.");
|
|
159
|
+
}
|
|
160
|
+
return this.createRestClient(applicationId, botToken).putApplicationRoleConnectionMetadata(payload);
|
|
161
|
+
}
|
|
162
|
+
async registerCommands(tokenOverride) {
|
|
163
|
+
const modules = await this.loadModules();
|
|
164
|
+
const payload = modules.commands.map((command) => this.resolveCommandPayload(command));
|
|
165
|
+
const applicationId = this.options.applicationId ??
|
|
166
|
+
process.env.DISCORD_APPLICATION_ID ??
|
|
167
|
+
process.env.DISCORD_APP_ID;
|
|
168
|
+
if (!applicationId) {
|
|
169
|
+
throw new Error("[MiniInteraction] Missing applicationId for command registration.");
|
|
170
|
+
}
|
|
171
|
+
const token = tokenOverride ??
|
|
172
|
+
this.options.token ??
|
|
173
|
+
process.env.DISCORD_BOT_TOKEN ??
|
|
174
|
+
process.env.DISCORD_TOKEN;
|
|
175
|
+
if (!token) {
|
|
176
|
+
throw new Error("[MiniInteraction] Missing bot token for command registration.");
|
|
177
|
+
}
|
|
178
|
+
const rest = this.createRestClient(applicationId, token);
|
|
179
|
+
const guildId = this.options.guildId ?? process.env.DISCORD_GUILD_ID;
|
|
180
|
+
const route = guildId
|
|
181
|
+
? `/applications/${applicationId}/guilds/${guildId}/commands`
|
|
182
|
+
: `/applications/${applicationId}/commands`;
|
|
183
|
+
if (this.options.debug) {
|
|
184
|
+
console.debug(`[MiniInteraction] Registering ${payload.length} command(s) on ${guildId ? `guild ${guildId}` : "global"} scope.`);
|
|
185
|
+
}
|
|
186
|
+
return rest.request(route, {
|
|
187
|
+
method: "PUT",
|
|
188
|
+
body: JSON.stringify(payload),
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
discordOAuthVerificationPage(options) {
|
|
192
|
+
return async (_req, res) => {
|
|
193
|
+
const oauthConfig = this.getOAuthConfig();
|
|
194
|
+
const { url, state } = generateOAuthUrl(oauthConfig, options.scopes ?? [
|
|
195
|
+
"applications.commands",
|
|
196
|
+
"identify",
|
|
197
|
+
"guilds",
|
|
198
|
+
"role_connections.write",
|
|
199
|
+
]);
|
|
200
|
+
const html = await this.loadHtmlFile(options.htmlFile);
|
|
201
|
+
const rendered = html.replaceAll("{{OAUTH_URL_RAW}}", url);
|
|
202
|
+
res.setHeader?.("Set-Cookie", `mini_oauth_state=${encodeURIComponent(state)}; Path=/; HttpOnly; SameSite=Lax; Max-Age=900`);
|
|
203
|
+
this.sendHtml(res, 200, rendered);
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
connectedOAuthPage(htmlFile) {
|
|
207
|
+
return { htmlFile };
|
|
208
|
+
}
|
|
209
|
+
failedOAuthPage(htmlFile) {
|
|
210
|
+
return { htmlFile };
|
|
211
|
+
}
|
|
212
|
+
discordOAuthCallback(options) {
|
|
213
|
+
return async (req, res) => {
|
|
214
|
+
try {
|
|
215
|
+
const requestUrl = new URL(req.url ?? "/", process.env.DISCORD_REDIRECT_URI ?? "http://localhost");
|
|
216
|
+
const error = requestUrl.searchParams.get("error");
|
|
217
|
+
const code = requestUrl.searchParams.get("code");
|
|
218
|
+
const state = requestUrl.searchParams.get("state");
|
|
219
|
+
const cookieState = this.getCookie(req, "mini_oauth_state");
|
|
220
|
+
if (error) {
|
|
221
|
+
await this.renderOAuthTemplate(res, options.templates.oauthError);
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
if (!code) {
|
|
225
|
+
await this.renderOAuthTemplate(res, options.templates.missingCode);
|
|
226
|
+
return;
|
|
227
|
+
}
|
|
228
|
+
if (!state || !cookieState || state !== cookieState) {
|
|
229
|
+
await this.renderOAuthTemplate(res, options.templates.invalidState);
|
|
230
|
+
return;
|
|
231
|
+
}
|
|
232
|
+
const tokens = await getOAuthTokens(code, this.getOAuthConfig());
|
|
233
|
+
const user = await getDiscordUser(tokens.access_token);
|
|
234
|
+
await options.onAuthorize?.({ user, tokens, req, res });
|
|
235
|
+
res.setHeader?.("Set-Cookie", "mini_oauth_state=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0");
|
|
236
|
+
await this.renderOAuthTemplate(res, options.templates.success);
|
|
237
|
+
}
|
|
238
|
+
catch (error) {
|
|
239
|
+
if (this.options.debug) {
|
|
240
|
+
console.error("[MiniInteraction] discordOAuthCallback failed", error);
|
|
241
|
+
}
|
|
242
|
+
await this.renderOAuthTemplate(res, options.templates.serverError);
|
|
243
|
+
}
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
async dispatch(interaction, commitInitialResponse) {
|
|
247
|
+
const modules = await this.loadModules();
|
|
248
|
+
if (interaction.type === InteractionType.ApplicationCommand) {
|
|
249
|
+
const command = modules.commandLookup.get(this.commandLookupKey(interaction.data.type, interaction.data.name));
|
|
250
|
+
if (!command)
|
|
251
|
+
return undefined;
|
|
252
|
+
return this.executeCommandHandler(command.handler, interaction, commitInitialResponse);
|
|
253
|
+
}
|
|
254
|
+
if (interaction.type === InteractionType.MessageComponent) {
|
|
255
|
+
const component = modules.componentLookup.get(interaction.data.custom_id);
|
|
256
|
+
if (!component)
|
|
257
|
+
return undefined;
|
|
258
|
+
return this.executeComponentHandler(component.handler, interaction, commitInitialResponse);
|
|
259
|
+
}
|
|
260
|
+
if (interaction.type === InteractionType.ModalSubmit) {
|
|
261
|
+
const modal = modules.modalLookup.get(interaction.data.custom_id);
|
|
262
|
+
if (!modal)
|
|
263
|
+
return undefined;
|
|
264
|
+
return this.executeModalHandler(modal.handler, interaction, commitInitialResponse);
|
|
265
|
+
}
|
|
266
|
+
return undefined;
|
|
267
|
+
}
|
|
268
|
+
async executeCommandHandler(handler, interaction, commitInitialResponse) {
|
|
269
|
+
return this.runWithResponseLifecycle(interaction, async (helpers) => {
|
|
270
|
+
switch (interaction.data.type) {
|
|
271
|
+
case ApplicationCommandType.ChatInput:
|
|
272
|
+
return handler(createCommandInteraction(interaction, helpers));
|
|
273
|
+
case ApplicationCommandType.User:
|
|
274
|
+
return handler(createUserContextMenuInteraction(interaction, helpers));
|
|
275
|
+
case ApplicationCommandType.Message:
|
|
276
|
+
return handler(createMessageContextMenuInteraction(interaction, helpers));
|
|
277
|
+
default:
|
|
278
|
+
if (interaction.data.type === ApplicationCommandType.PrimaryEntryPoint) {
|
|
279
|
+
return handler(createAppCommandInteraction(interaction, helpers));
|
|
280
|
+
}
|
|
281
|
+
throw new Error(`[MiniInteraction] Unsupported application command type: ${String(interaction.data.type)}`);
|
|
282
|
+
}
|
|
283
|
+
}, commitInitialResponse);
|
|
284
|
+
}
|
|
285
|
+
async executeComponentHandler(handler, interaction, commitInitialResponse) {
|
|
286
|
+
return this.runWithResponseLifecycle(interaction, async (helpers) => handler(createMessageComponentInteraction(interaction, helpers)), commitInitialResponse);
|
|
287
|
+
}
|
|
288
|
+
async executeModalHandler(handler, interaction, commitInitialResponse) {
|
|
289
|
+
return this.runWithResponseLifecycle(interaction, async (helpers) => handler(createModalSubmitInteraction(interaction, helpers)), commitInitialResponse);
|
|
290
|
+
}
|
|
291
|
+
async runWithResponseLifecycle(interaction, executor, commitInitialResponse) {
|
|
292
|
+
let ackResponse;
|
|
293
|
+
let initialResponseCommitted = false;
|
|
294
|
+
let followUpSent = false;
|
|
295
|
+
let committedInitialResponse;
|
|
296
|
+
const helpers = {
|
|
297
|
+
// Legacy helper contracts use canRespond for both initial acknowledgements
|
|
298
|
+
// and later editReply/followUp calls. The compat layer does not currently
|
|
299
|
+
// track Discord token expiry, so we only block on real expiry outside of
|
|
300
|
+
// this helper and allow the wrapped interaction methods to complete.
|
|
301
|
+
canRespond: (_interactionId) => true,
|
|
302
|
+
trackResponse: (interactionId, _token, state) => {
|
|
303
|
+
this.responseStates.set(interactionId, state);
|
|
304
|
+
},
|
|
305
|
+
onAck: (response) => {
|
|
306
|
+
ackResponse = response;
|
|
307
|
+
if (!initialResponseCommitted && commitInitialResponse?.(response)) {
|
|
308
|
+
initialResponseCommitted = true;
|
|
309
|
+
committedInitialResponse = response;
|
|
310
|
+
}
|
|
311
|
+
},
|
|
312
|
+
sendFollowUp: async (token, response, messageId) => {
|
|
313
|
+
// If the initial interaction response has not been sent yet, collapse the
|
|
314
|
+
// deferred/edit flow back into a single immediate response instead of
|
|
315
|
+
// calling the webhook endpoints early.
|
|
316
|
+
if (!initialResponseCommitted) {
|
|
317
|
+
ackResponse = response;
|
|
318
|
+
this.responseStates.set(interaction.id, "responded");
|
|
319
|
+
return;
|
|
320
|
+
}
|
|
321
|
+
const responseData = "data" in response ? response.data ?? {} : {};
|
|
322
|
+
if (messageId === "@original") {
|
|
323
|
+
await this.getRestClient().editOriginal(token, responseData);
|
|
324
|
+
followUpSent = true;
|
|
325
|
+
return;
|
|
326
|
+
}
|
|
327
|
+
await this.getRestClient().createFollowup(token, responseData);
|
|
328
|
+
followUpSent = true;
|
|
329
|
+
},
|
|
330
|
+
};
|
|
331
|
+
const autoDeferMs = Math.min(2500, this.options.timeoutConfig?.initialResponseTimeout ?? 2500);
|
|
332
|
+
const autoDeferTimer = this.options.timeoutConfig?.autoDeferSlowOperations === true
|
|
333
|
+
? setTimeout(() => {
|
|
334
|
+
if (initialResponseCommitted)
|
|
335
|
+
return;
|
|
336
|
+
if (this.responseStates.get(interaction.id))
|
|
337
|
+
return;
|
|
338
|
+
if (!helpers.canRespond(interaction.id))
|
|
339
|
+
return;
|
|
340
|
+
if (this.options.debug || this.options.timeoutConfig?.enableResponseDebugLogging) {
|
|
341
|
+
console.warn(`[MiniInteraction] Auto-deferred interaction ${interaction.id} after ${autoDeferMs}ms.`);
|
|
342
|
+
}
|
|
343
|
+
const deferredResponse = this.getDefaultInitialResponse(interaction);
|
|
344
|
+
ackResponse = deferredResponse;
|
|
345
|
+
helpers.trackResponse(interaction.id, interaction.token, "deferred");
|
|
346
|
+
if (!initialResponseCommitted && commitInitialResponse?.(deferredResponse)) {
|
|
347
|
+
initialResponseCommitted = true;
|
|
348
|
+
committedInitialResponse = deferredResponse;
|
|
349
|
+
}
|
|
350
|
+
}, autoDeferMs)
|
|
351
|
+
: undefined;
|
|
352
|
+
const timeoutWarningMs = this.options.timeoutConfig?.initialResponseTimeout;
|
|
353
|
+
const timeoutWarningTimer = this.options.timeoutConfig?.enableTimeoutWarnings && timeoutWarningMs
|
|
354
|
+
? setTimeout(() => {
|
|
355
|
+
if (this.responseStates.get(interaction.id))
|
|
356
|
+
return;
|
|
357
|
+
console.warn(`[MiniInteraction] Interaction ${interaction.id} exceeded ${timeoutWarningMs}ms without a response.`);
|
|
358
|
+
}, timeoutWarningMs)
|
|
359
|
+
: undefined;
|
|
360
|
+
try {
|
|
361
|
+
const result = await executor(helpers);
|
|
362
|
+
if (this.options.debug || this.options.timeoutConfig?.enableResponseDebugLogging) {
|
|
363
|
+
console.debug(`[MiniInteraction] Interaction ${interaction.id} completed with ${result ? "explicit" : "fallback"} response.`);
|
|
364
|
+
}
|
|
365
|
+
if (initialResponseCommitted &&
|
|
366
|
+
result &&
|
|
367
|
+
!followUpSent &&
|
|
368
|
+
committedInitialResponse &&
|
|
369
|
+
this.isDeferredResponse(committedInitialResponse) &&
|
|
370
|
+
!this.isDeferredResponse(result)) {
|
|
371
|
+
const responseData = "data" in result ? result.data ?? {} : {};
|
|
372
|
+
await this.getRestClient().editOriginal(interaction.token, responseData);
|
|
373
|
+
}
|
|
374
|
+
if (initialResponseCommitted) {
|
|
375
|
+
return undefined;
|
|
376
|
+
}
|
|
377
|
+
initialResponseCommitted = true;
|
|
378
|
+
return result ?? ackResponse;
|
|
379
|
+
}
|
|
380
|
+
finally {
|
|
381
|
+
if (autoDeferTimer)
|
|
382
|
+
clearTimeout(autoDeferTimer);
|
|
383
|
+
if (timeoutWarningTimer)
|
|
384
|
+
clearTimeout(timeoutWarningTimer);
|
|
385
|
+
this.responseStates.delete(interaction.id);
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
async loadModules() {
|
|
389
|
+
if (!this.loadedModulesPromise) {
|
|
390
|
+
this.loadedModulesPromise = this.discoverModules();
|
|
391
|
+
}
|
|
392
|
+
return this.loadedModulesPromise;
|
|
393
|
+
}
|
|
394
|
+
async discoverModules() {
|
|
395
|
+
const commands = this.options.commandsDirectory
|
|
396
|
+
? await this.loadDirectory(this.options.commandsDirectory)
|
|
397
|
+
: [];
|
|
398
|
+
const components = this.options.componentsDirectory
|
|
399
|
+
? await this.loadDirectory(this.options.componentsDirectory)
|
|
400
|
+
: [];
|
|
401
|
+
const loaded = {
|
|
402
|
+
commands: [],
|
|
403
|
+
components: [],
|
|
404
|
+
modals: [],
|
|
405
|
+
commandLookup: new Map(),
|
|
406
|
+
componentLookup: new Map(),
|
|
407
|
+
modalLookup: new Map(),
|
|
408
|
+
};
|
|
409
|
+
for (const { filePath, value } of commands) {
|
|
410
|
+
if (this.isInteractionCommand(value)) {
|
|
411
|
+
loaded.commands.push(value);
|
|
412
|
+
}
|
|
413
|
+
else if (this.options.debug) {
|
|
414
|
+
console.warn(`[MiniInteraction] Ignored non-command module: ${filePath}`);
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
for (const { filePath, value } of components) {
|
|
418
|
+
if (!this.isCustomIdHandler(value)) {
|
|
419
|
+
if (this.options.debug) {
|
|
420
|
+
console.warn(`[MiniInteraction] Ignored non-component module: ${filePath}`);
|
|
421
|
+
}
|
|
422
|
+
continue;
|
|
423
|
+
}
|
|
424
|
+
if (this.looksLikeModalFile(filePath)) {
|
|
425
|
+
loaded.modals.push(value);
|
|
426
|
+
}
|
|
427
|
+
else {
|
|
428
|
+
loaded.components.push(value);
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
for (const command of loaded.commands) {
|
|
432
|
+
const payload = this.resolveCommandPayload(command);
|
|
433
|
+
if (typeof payload.name !== "string")
|
|
434
|
+
continue;
|
|
435
|
+
const type = typeof payload.type === "number"
|
|
436
|
+
? payload.type
|
|
437
|
+
: ApplicationCommandType.ChatInput;
|
|
438
|
+
const key = this.commandLookupKey(type, payload.name);
|
|
439
|
+
if (!loaded.commandLookup.has(key)) {
|
|
440
|
+
loaded.commandLookup.set(key, command);
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
for (const component of loaded.components) {
|
|
444
|
+
if (!loaded.componentLookup.has(component.customId)) {
|
|
445
|
+
loaded.componentLookup.set(component.customId, component);
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
for (const modal of loaded.modals) {
|
|
449
|
+
if (!loaded.modalLookup.has(modal.customId)) {
|
|
450
|
+
loaded.modalLookup.set(modal.customId, modal);
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
return loaded;
|
|
454
|
+
}
|
|
455
|
+
commandLookupKey(type, name) {
|
|
456
|
+
return `${type}:${name}`;
|
|
457
|
+
}
|
|
458
|
+
async loadDirectory(directory) {
|
|
459
|
+
const absoluteDirectory = path.resolve(this.projectRoot, directory);
|
|
460
|
+
const files = await this.walkFiles(absoluteDirectory);
|
|
461
|
+
const loaded = await Promise.all(files
|
|
462
|
+
.filter((filePath) => this.isImportableModule(filePath))
|
|
463
|
+
.map(async (filePath) => ({
|
|
464
|
+
filePath,
|
|
465
|
+
values: this.normalizeModuleExports(await import(pathToFileURL(filePath).href)),
|
|
466
|
+
})));
|
|
467
|
+
return loaded.flatMap(({ filePath, values }) => values.map((value) => ({ filePath, value })));
|
|
468
|
+
}
|
|
469
|
+
normalizeModuleExports(moduleValue) {
|
|
470
|
+
const values = [];
|
|
471
|
+
if ("default" in moduleValue) {
|
|
472
|
+
values.push(...this.normalizeExportValue(moduleValue.default));
|
|
473
|
+
}
|
|
474
|
+
for (const [key, value] of Object.entries(moduleValue)) {
|
|
475
|
+
if (key === "default")
|
|
476
|
+
continue;
|
|
477
|
+
values.push(...this.normalizeExportValue(value));
|
|
478
|
+
}
|
|
479
|
+
return values;
|
|
480
|
+
}
|
|
481
|
+
normalizeExportValue(value) {
|
|
482
|
+
if (Array.isArray(value))
|
|
483
|
+
return value;
|
|
484
|
+
return [value];
|
|
485
|
+
}
|
|
486
|
+
async walkFiles(directory) {
|
|
487
|
+
const entries = await readdir(directory, { withFileTypes: true });
|
|
488
|
+
const results = await Promise.all(entries.map(async (entry) => {
|
|
489
|
+
const resolvedPath = path.join(directory, entry.name);
|
|
490
|
+
if (entry.isDirectory()) {
|
|
491
|
+
return this.walkFiles(resolvedPath);
|
|
492
|
+
}
|
|
493
|
+
return [resolvedPath];
|
|
494
|
+
}));
|
|
495
|
+
return results.flat();
|
|
496
|
+
}
|
|
497
|
+
scheduleBackgroundTask(promise, fallbackWaitUntil) {
|
|
498
|
+
if (fallbackWaitUntil) {
|
|
499
|
+
try {
|
|
500
|
+
fallbackWaitUntil(promise);
|
|
501
|
+
}
|
|
502
|
+
catch {
|
|
503
|
+
void promise;
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
else {
|
|
507
|
+
try {
|
|
508
|
+
vercelWaitUntil(promise);
|
|
509
|
+
}
|
|
510
|
+
catch {
|
|
511
|
+
void promise;
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
getDefaultInitialResponse(interaction) {
|
|
516
|
+
if (interaction.type === InteractionType.MessageComponent) {
|
|
517
|
+
return { type: InteractionResponseType.DeferredMessageUpdate };
|
|
518
|
+
}
|
|
519
|
+
return { type: InteractionResponseType.DeferredChannelMessageWithSource };
|
|
520
|
+
}
|
|
521
|
+
isDeferredResponse(response) {
|
|
522
|
+
return (response.type === InteractionResponseType.DeferredChannelMessageWithSource ||
|
|
523
|
+
response.type === InteractionResponseType.DeferredMessageUpdate);
|
|
524
|
+
}
|
|
525
|
+
isImportableModule(filePath) {
|
|
526
|
+
if (filePath.endsWith(".d.ts"))
|
|
527
|
+
return false;
|
|
528
|
+
return /\.(ts|mts|js|mjs|cjs)$/i.test(filePath);
|
|
529
|
+
}
|
|
530
|
+
isInteractionCommand(value) {
|
|
531
|
+
return (typeof value === "object" &&
|
|
532
|
+
value !== null &&
|
|
533
|
+
"data" in value &&
|
|
534
|
+
"handler" in value &&
|
|
535
|
+
typeof value.handler === "function");
|
|
536
|
+
}
|
|
537
|
+
resolveCommandPayload(command) {
|
|
538
|
+
const data = command.data;
|
|
539
|
+
if (typeof data.toJSON === "function") {
|
|
540
|
+
return data.toJSON();
|
|
541
|
+
}
|
|
542
|
+
return command.data;
|
|
543
|
+
}
|
|
544
|
+
isCustomIdHandler(value) {
|
|
545
|
+
return (typeof value === "object" &&
|
|
546
|
+
value !== null &&
|
|
547
|
+
"customId" in value &&
|
|
548
|
+
"handler" in value &&
|
|
549
|
+
typeof value.customId === "string" &&
|
|
550
|
+
typeof value.handler === "function");
|
|
551
|
+
}
|
|
552
|
+
looksLikeModalFile(filePath) {
|
|
553
|
+
const normalized = filePath.toLowerCase();
|
|
554
|
+
return (normalized.includes(`${path.sep}modals${path.sep}`) ||
|
|
555
|
+
normalized.endsWith(".modal.ts") ||
|
|
556
|
+
normalized.endsWith(".modal.js") ||
|
|
557
|
+
normalized.includes("_modal.") ||
|
|
558
|
+
normalized.includes("-modal."));
|
|
559
|
+
}
|
|
560
|
+
async readRawBody(req) {
|
|
561
|
+
if (typeof req.rawBody === "string")
|
|
562
|
+
return req.rawBody;
|
|
563
|
+
if (req.rawBody instanceof Uint8Array) {
|
|
564
|
+
return Buffer.from(req.rawBody).toString("utf8");
|
|
565
|
+
}
|
|
566
|
+
if (typeof req.body === "string")
|
|
567
|
+
return req.body;
|
|
568
|
+
if (req.body instanceof Uint8Array) {
|
|
569
|
+
return Buffer.from(req.body).toString("utf8");
|
|
570
|
+
}
|
|
571
|
+
if (req.body && typeof req.body === "object") {
|
|
572
|
+
return JSON.stringify(req.body);
|
|
573
|
+
}
|
|
574
|
+
if (typeof req[Symbol.asyncIterator] === "function") {
|
|
575
|
+
const chunks = [];
|
|
576
|
+
for await (const chunk of req) {
|
|
577
|
+
chunks.push(Buffer.from(chunk));
|
|
578
|
+
}
|
|
579
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
580
|
+
}
|
|
581
|
+
return "";
|
|
582
|
+
}
|
|
583
|
+
getHeader(headers, name) {
|
|
584
|
+
if (typeof headers.get === "function") {
|
|
585
|
+
return headers.get(name) ?? undefined;
|
|
586
|
+
}
|
|
587
|
+
const recordHeaders = headers;
|
|
588
|
+
const direct = recordHeaders[name] ??
|
|
589
|
+
recordHeaders[name.toLowerCase()] ??
|
|
590
|
+
recordHeaders[name.toUpperCase()];
|
|
591
|
+
if (Array.isArray(direct))
|
|
592
|
+
return direct[0];
|
|
593
|
+
return direct;
|
|
594
|
+
}
|
|
595
|
+
sendJson(res, statusCode, body) {
|
|
596
|
+
if (typeof res.status === "function" && typeof res.json === "function") {
|
|
597
|
+
const response = res.status(statusCode);
|
|
598
|
+
response.json?.(body);
|
|
599
|
+
return;
|
|
600
|
+
}
|
|
601
|
+
res.statusCode = statusCode;
|
|
602
|
+
res.setHeader?.("Content-Type", "application/json; charset=utf-8");
|
|
603
|
+
res.end(JSON.stringify(body));
|
|
604
|
+
}
|
|
605
|
+
async loadHtmlFile(htmlFile) {
|
|
606
|
+
const absolutePath = path.resolve(this.projectRoot, htmlFile);
|
|
607
|
+
return readFile(absolutePath, "utf8");
|
|
608
|
+
}
|
|
609
|
+
async renderOAuthTemplate(res, template) {
|
|
610
|
+
const html = await this.loadHtmlFile(template.htmlFile);
|
|
611
|
+
this.sendHtml(res, 200, html);
|
|
612
|
+
}
|
|
613
|
+
sendHtml(res, statusCode, html) {
|
|
614
|
+
if (typeof res.status === "function" && typeof res.end === "function") {
|
|
615
|
+
res.status(statusCode);
|
|
616
|
+
}
|
|
617
|
+
res.statusCode = statusCode;
|
|
618
|
+
res.setHeader?.("Content-Type", "text/html; charset=utf-8");
|
|
619
|
+
res.end(html);
|
|
620
|
+
}
|
|
621
|
+
getOAuthConfig() {
|
|
622
|
+
const appId = this.options.applicationId ??
|
|
623
|
+
process.env.DISCORD_APPLICATION_ID ??
|
|
624
|
+
process.env.DISCORD_APP_ID;
|
|
625
|
+
const appSecret = process.env.DISCORD_CLIENT_SECRET ?? process.env.DISCORD_APPLICATION_SECRET;
|
|
626
|
+
const redirectUri = process.env.DISCORD_REDIRECT_URI;
|
|
627
|
+
if (!appId || !appSecret || !redirectUri) {
|
|
628
|
+
throw new Error("[MiniInteraction] Missing OAuth config. Expected DISCORD_APPLICATION_ID, DISCORD_CLIENT_SECRET and DISCORD_REDIRECT_URI.");
|
|
629
|
+
}
|
|
630
|
+
return { appId, appSecret, redirectUri };
|
|
631
|
+
}
|
|
632
|
+
getCookie(req, name) {
|
|
633
|
+
const cookieHeader = this.getHeader(req.headers, "cookie");
|
|
634
|
+
if (!cookieHeader)
|
|
635
|
+
return undefined;
|
|
636
|
+
for (const rawPart of cookieHeader.split(";")) {
|
|
637
|
+
const [rawKey, ...rawValue] = rawPart.trim().split("=");
|
|
638
|
+
if (rawKey === name) {
|
|
639
|
+
return decodeURIComponent(rawValue.join("="));
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
return undefined;
|
|
643
|
+
}
|
|
644
|
+
// ───────────────────────────────────────────────
|
|
645
|
+
// Cloudflare Workers support
|
|
646
|
+
// ───────────────────────────────────────────────
|
|
647
|
+
/**
|
|
648
|
+
* Create a Cloudflare Workers handler.
|
|
649
|
+
*
|
|
650
|
+
* ```ts
|
|
651
|
+
* import { MiniInteraction } from "mini-interactions/node";
|
|
652
|
+
* const mini = new MiniInteraction();
|
|
653
|
+
* export default {
|
|
654
|
+
* async fetch(request: Request, env: Record<string, string>, ctx: ExecutionContext): Promise<Response> {
|
|
655
|
+
* return mini.createCloudflareHandler()(request, env, ctx);
|
|
656
|
+
* }
|
|
657
|
+
* };
|
|
658
|
+
* ```
|
|
659
|
+
*/
|
|
660
|
+
createCloudflareHandler() {
|
|
661
|
+
return async (request, env, ctx) => {
|
|
662
|
+
let responseSent = false;
|
|
663
|
+
let committedResponse;
|
|
664
|
+
let resolveInitialCommit;
|
|
665
|
+
const initialCommitPromise = new Promise((resolve) => {
|
|
666
|
+
resolveInitialCommit = resolve;
|
|
667
|
+
});
|
|
668
|
+
const commitInitialResponse = (response) => {
|
|
669
|
+
if (responseSent)
|
|
670
|
+
return false;
|
|
671
|
+
committedResponse = new Response(JSON.stringify(response), {
|
|
672
|
+
status: 200,
|
|
673
|
+
headers: { "Content-Type": "application/json; charset=utf-8" },
|
|
674
|
+
});
|
|
675
|
+
responseSent = true;
|
|
676
|
+
resolveInitialCommit?.();
|
|
677
|
+
return true;
|
|
678
|
+
};
|
|
679
|
+
try {
|
|
680
|
+
const body = await request.text();
|
|
681
|
+
const signature = request.headers.get("x-signature-ed25519") ?? undefined;
|
|
682
|
+
const timestamp = request.headers.get("x-signature-timestamp") ?? undefined;
|
|
683
|
+
const publicKey = this.options.publicKey ??
|
|
684
|
+
env.DISCORD_PUBLIC_KEY ??
|
|
685
|
+
(typeof process !== "undefined" ? process.env.DISCORD_PUBLIC_KEY : undefined);
|
|
686
|
+
if (!publicKey) {
|
|
687
|
+
return new Response(JSON.stringify({ error: "[MiniInteraction] Missing DISCORD_PUBLIC_KEY." }), { status: 500, headers: { "Content-Type": "application/json" } });
|
|
688
|
+
}
|
|
689
|
+
if (!signature || !timestamp) {
|
|
690
|
+
return new Response(JSON.stringify({ error: "[MiniInteraction] Missing Discord signature headers." }), { status: 401, headers: { "Content-Type": "application/json" } });
|
|
691
|
+
}
|
|
692
|
+
const interaction = await verifyAndParseInteraction({
|
|
693
|
+
body,
|
|
694
|
+
signature,
|
|
695
|
+
timestamp,
|
|
696
|
+
publicKey,
|
|
697
|
+
});
|
|
698
|
+
if (interaction.type === InteractionType.Ping) {
|
|
699
|
+
return new Response(JSON.stringify({ type: InteractionResponseType.Pong }), { status: 200, headers: { "Content-Type": "application/json" } });
|
|
700
|
+
}
|
|
701
|
+
this.primeRestClient(env);
|
|
702
|
+
const dispatchPromise = this.dispatch(interaction, commitInitialResponse);
|
|
703
|
+
const backgroundPromise = dispatchPromise.catch((error) => {
|
|
704
|
+
if (this.options.debug) {
|
|
705
|
+
console.error("[MiniInteraction] Background interaction processing failed", error);
|
|
706
|
+
}
|
|
707
|
+
});
|
|
708
|
+
const settled = await Promise.race([
|
|
709
|
+
dispatchPromise.then((response) => ({ kind: "result", response }), (error) => ({ kind: "error", error })),
|
|
710
|
+
initialCommitPromise.then(() => ({ kind: "committed" })),
|
|
711
|
+
]);
|
|
712
|
+
if (settled.kind === "committed") {
|
|
713
|
+
this.scheduleBackgroundTask(backgroundPromise, ctx.waitUntil);
|
|
714
|
+
return committedResponse;
|
|
715
|
+
}
|
|
716
|
+
if (settled.kind === "error") {
|
|
717
|
+
throw settled.error;
|
|
718
|
+
}
|
|
719
|
+
const response = settled.response;
|
|
720
|
+
if (!responseSent) {
|
|
721
|
+
const body = response ?? this.getDefaultInitialResponse(interaction);
|
|
722
|
+
committedResponse = new Response(JSON.stringify(body), {
|
|
723
|
+
status: 200,
|
|
724
|
+
headers: { "Content-Type": "application/json; charset=utf-8" },
|
|
725
|
+
});
|
|
726
|
+
responseSent = true;
|
|
727
|
+
}
|
|
728
|
+
return committedResponse;
|
|
729
|
+
}
|
|
730
|
+
catch (error) {
|
|
731
|
+
const message = error instanceof Error ? error.message : "[MiniInteraction] Unknown error";
|
|
732
|
+
if (this.options.debug) {
|
|
733
|
+
console.error("[MiniInteraction] createCloudflareHandler failed", error);
|
|
734
|
+
}
|
|
735
|
+
return new Response(JSON.stringify({ error: message }), { status: 500, headers: { "Content-Type": "application/json" } });
|
|
736
|
+
}
|
|
737
|
+
};
|
|
738
|
+
}
|
|
739
|
+
/**
|
|
740
|
+
* Cloudflare Workers version of discordOAuthVerificationPage().
|
|
741
|
+
* Returns a handler that reads HTML from the provided string instead of the filesystem.
|
|
742
|
+
*
|
|
743
|
+
* ```ts
|
|
744
|
+
* import { MiniInteraction } from "mini-interactions/node";
|
|
745
|
+
* import landingHtml from "../index.html";
|
|
746
|
+
* const mini = new MiniInteraction();
|
|
747
|
+
* export const oauthLanding = mini.cloudflareOAuthVerificationPage({
|
|
748
|
+
* html: landingHtml,
|
|
749
|
+
* });
|
|
750
|
+
* ```
|
|
751
|
+
*/
|
|
752
|
+
cloudflareOAuthVerificationPage(options) {
|
|
753
|
+
return async (request, env, _ctx) => {
|
|
754
|
+
const oauthConfig = this.getOAuthConfigFromEnv(env);
|
|
755
|
+
const { url, state } = generateOAuthUrl(oauthConfig, options.scopes ?? [
|
|
756
|
+
"applications.commands",
|
|
757
|
+
"identify",
|
|
758
|
+
"guilds",
|
|
759
|
+
"role_connections.write",
|
|
760
|
+
]);
|
|
761
|
+
const rendered = options.html.replaceAll("{{OAUTH_URL_RAW}}", url);
|
|
762
|
+
return new Response(rendered, {
|
|
763
|
+
status: 200,
|
|
764
|
+
headers: {
|
|
765
|
+
"Content-Type": "text/html; charset=utf-8",
|
|
766
|
+
"Set-Cookie": `mini_oauth_state=${encodeURIComponent(state)}; Path=/; HttpOnly; SameSite=Lax; Max-Age=900`,
|
|
767
|
+
},
|
|
768
|
+
});
|
|
769
|
+
};
|
|
770
|
+
}
|
|
771
|
+
/**
|
|
772
|
+
* Cloudflare Workers version of discordOAuthCallback().
|
|
773
|
+
* Returns a handler that renders HTML from strings instead of reading from the filesystem.
|
|
774
|
+
*
|
|
775
|
+
* ```ts
|
|
776
|
+
* import { MiniInteraction } from "mini-interactions/node";
|
|
777
|
+
* import successHtml from "../public/pages/connected.html";
|
|
778
|
+
* import failedHtml from "../public/pages/failed.html";
|
|
779
|
+
* const mini = new MiniInteraction();
|
|
780
|
+
* export const oauthCallback = mini.cloudflareOAuthCallback({
|
|
781
|
+
* templates: {
|
|
782
|
+
* success: { html: successHtml },
|
|
783
|
+
* missingCode: { html: failedHtml },
|
|
784
|
+
* oauthError: { html: failedHtml },
|
|
785
|
+
* invalidState: { html: failedHtml },
|
|
786
|
+
* serverError: { html: failedHtml },
|
|
787
|
+
* },
|
|
788
|
+
* onAuthorize: async ({ user, tokens }) => {
|
|
789
|
+
* // Store tokens, update metadata, etc.
|
|
790
|
+
* },
|
|
791
|
+
* });
|
|
792
|
+
* ```
|
|
793
|
+
*/
|
|
794
|
+
cloudflareOAuthCallback(options) {
|
|
795
|
+
return async (request, env, _ctx) => {
|
|
796
|
+
try {
|
|
797
|
+
const requestUrl = new URL(request.url);
|
|
798
|
+
const error = requestUrl.searchParams.get("error");
|
|
799
|
+
const code = requestUrl.searchParams.get("code");
|
|
800
|
+
const state = requestUrl.searchParams.get("state");
|
|
801
|
+
const cookieState = this.getCookieFromHeaders(request.headers, "mini_oauth_state");
|
|
802
|
+
if (error) {
|
|
803
|
+
return this.renderTemplateResponse(options.templates.oauthError);
|
|
804
|
+
}
|
|
805
|
+
if (!code) {
|
|
806
|
+
return this.renderTemplateResponse(options.templates.missingCode);
|
|
807
|
+
}
|
|
808
|
+
if (!state || !cookieState || state !== cookieState) {
|
|
809
|
+
return this.renderTemplateResponse(options.templates.invalidState);
|
|
810
|
+
}
|
|
811
|
+
const tokens = await getOAuthTokens(code, this.getOAuthConfigFromEnv(env));
|
|
812
|
+
const user = await getDiscordUser(tokens.access_token);
|
|
813
|
+
await options.onAuthorize?.({ user, tokens, request, env });
|
|
814
|
+
const response = this.renderTemplateResponse(options.templates.success);
|
|
815
|
+
response.headers.set("Set-Cookie", "mini_oauth_state=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0");
|
|
816
|
+
return response;
|
|
817
|
+
}
|
|
818
|
+
catch (error) {
|
|
819
|
+
if (this.options.debug) {
|
|
820
|
+
console.error("[MiniInteraction] cloudflareOAuthCallback failed", error);
|
|
821
|
+
}
|
|
822
|
+
return this.renderTemplateResponse(options.templates.serverError);
|
|
823
|
+
}
|
|
824
|
+
};
|
|
825
|
+
}
|
|
826
|
+
getOAuthConfigFromEnv(env) {
|
|
827
|
+
const processEnv = typeof process !== "undefined" ? process.env : undefined;
|
|
828
|
+
const appId = this.options.applicationId ??
|
|
829
|
+
(env?.DISCORD_APPLICATION_ID) ??
|
|
830
|
+
processEnv?.DISCORD_APPLICATION_ID ??
|
|
831
|
+
processEnv?.DISCORD_APP_ID;
|
|
832
|
+
const appSecret = (env?.DISCORD_CLIENT_SECRET) ??
|
|
833
|
+
processEnv?.DISCORD_CLIENT_SECRET ??
|
|
834
|
+
processEnv?.DISCORD_APPLICATION_SECRET;
|
|
835
|
+
const redirectUri = (env?.DISCORD_REDIRECT_URI) ??
|
|
836
|
+
processEnv?.DISCORD_REDIRECT_URI;
|
|
837
|
+
if (!appId || !appSecret || !redirectUri) {
|
|
838
|
+
throw new Error("[MiniInteraction] Missing OAuth config. Expected DISCORD_APPLICATION_ID, DISCORD_CLIENT_SECRET and DISCORD_REDIRECT_URI.");
|
|
839
|
+
}
|
|
840
|
+
return { appId, appSecret, redirectUri };
|
|
841
|
+
}
|
|
842
|
+
getCookieFromHeaders(headers, name) {
|
|
843
|
+
const cookieHeader = headers.get("cookie");
|
|
844
|
+
if (!cookieHeader)
|
|
845
|
+
return undefined;
|
|
846
|
+
for (const rawPart of cookieHeader.split(";")) {
|
|
847
|
+
const [rawKey, ...rawValue] = rawPart.trim().split("=");
|
|
848
|
+
if (rawKey === name) {
|
|
849
|
+
return decodeURIComponent(rawValue.join("="));
|
|
850
|
+
}
|
|
851
|
+
}
|
|
852
|
+
return undefined;
|
|
853
|
+
}
|
|
854
|
+
renderTemplateResponse(template) {
|
|
855
|
+
return new Response(template.html, {
|
|
856
|
+
status: 200,
|
|
857
|
+
headers: { "Content-Type": "text/html; charset=utf-8" },
|
|
858
|
+
});
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
export const LegacyMiniInteractionAdapter = MiniInteraction;
|