@seedcord/http 0.1.0-next.0 → 0.1.0-next.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/RouteManifest-BHdAeyLG.d.mts +60 -0
- package/dist/edge.index-BAgNb6TV.mjs +1046 -0
- package/dist/edge.index-BAgNb6TV.mjs.map +1 -0
- package/dist/edge.index-CTOyjsO4.d.mts +501 -0
- package/dist/edge.index-D-60VfMn.cjs +1175 -0
- package/dist/edge.index-D-60VfMn.cjs.map +1 -0
- package/dist/edge.index.cjs +22 -0
- package/dist/edge.index.d.cts +1 -0
- package/dist/edge.index.d.mts +4 -0
- package/dist/edge.index.mjs +5 -0
- package/dist/index.cjs +359 -971
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.mts +49 -493
- package/dist/index.mjs +350 -963
- package/dist/index.mjs.map +1 -1
- package/dist/manifest.index.cjs +16 -0
- package/dist/manifest.index.cjs.map +1 -0
- package/dist/manifest.index.d.cts +1 -0
- package/dist/manifest.index.d.mts +11 -0
- package/dist/manifest.index.mjs +15 -0
- package/dist/manifest.index.mjs.map +1 -0
- package/dist/rolldown-runtime-BUUfjzRC.mjs +36 -0
- package/package.json +31 -9
package/dist/index.cjs
CHANGED
|
@@ -1,1026 +1,414 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
-
|
|
2
|
+
const require_edge_index = require('./edge.index-D-60VfMn.cjs');
|
|
3
3
|
let _seedcord_errors_internal = require("@seedcord/errors/internal");
|
|
4
|
-
let _seedcord_logger = require("@seedcord/logger");
|
|
5
|
-
let discord_api_types_v10 = require("discord-api-types/v10");
|
|
6
4
|
let envapt = require("envapt");
|
|
7
5
|
let _discordjs_rest = require("@discordjs/rest");
|
|
8
|
-
let _seedcord_core = require("@seedcord/core");
|
|
9
6
|
let _seedcord_core_internal = require("@seedcord/core/internal");
|
|
7
|
+
let _seedcord_logger = require("@seedcord/logger");
|
|
10
8
|
let _seedcord_rate_limiter = require("@seedcord/rate-limiter");
|
|
11
|
-
let
|
|
9
|
+
let discord_api_types_v10 = require("discord-api-types/v10");
|
|
10
|
+
let _seedcord_errors = require("@seedcord/errors");
|
|
11
|
+
let node_events = require("node:events");
|
|
12
|
+
let node_http = require("node:http");
|
|
13
|
+
let _seedcord_core_node_internal = require("@seedcord/core/node/internal");
|
|
14
|
+
let _seedcord_logger_node = require("@seedcord/logger/node");
|
|
15
|
+
let _seedcord_types_internal = require("@seedcord/types/internal");
|
|
16
|
+
let _seedcord_core_hmr = require("@seedcord/core/hmr");
|
|
17
|
+
let _seedcord_utils = require("@seedcord/utils");
|
|
18
|
+
let _seedcord_utils_node = require("@seedcord/utils/node");
|
|
12
19
|
|
|
13
|
-
//#region src/
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
}
|
|
21
|
-
function wireAttachments(files) {
|
|
22
|
-
if (!files?.some((file) => file.description)) return null;
|
|
23
|
-
return files.map((file, index) => ({
|
|
24
|
-
id: index,
|
|
25
|
-
...file.name && { filename: file.name },
|
|
26
|
-
...file.description && { description: file.description }
|
|
27
|
-
}));
|
|
28
|
-
}
|
|
29
|
-
function callbackData(reply, flags) {
|
|
30
|
-
const attachments = wireAttachments(reply.files);
|
|
31
|
-
return {
|
|
32
|
-
flags,
|
|
33
|
-
components: reply.components,
|
|
34
|
-
...reply.allowedMentions && { allowed_mentions: wireAllowedMentions(reply.allowedMentions) },
|
|
35
|
-
...attachments && { attachments }
|
|
36
|
-
};
|
|
37
|
-
}
|
|
38
|
-
/**
|
|
39
|
-
* Writes interaction responses over the Discord REST callback and webhook endpoints. Construction is
|
|
40
|
-
* internal to the repliable handler bases and the dispatcher.
|
|
41
|
-
*/
|
|
42
|
-
var ReplySender = class extends _seedcord_core_internal.BaseReplySender {
|
|
43
|
-
ref;
|
|
44
|
-
rest;
|
|
45
|
-
constructor(ref, rest, routeId) {
|
|
46
|
-
super(routeId);
|
|
47
|
-
this.ref = ref;
|
|
48
|
-
this.rest = rest;
|
|
49
|
-
}
|
|
50
|
-
async writeReply(response, opts) {
|
|
51
|
-
const reply = this.serialize(response);
|
|
52
|
-
const result = await this.callback(discord_api_types_v10.InteractionResponseType.ChannelMessageWithSource, callbackData(reply, (0, _seedcord_core_internal.sendFlags)(opts)), reply.files);
|
|
53
|
-
return this.createdMessage(result);
|
|
54
|
-
}
|
|
55
|
-
async writeDefer(opts) {
|
|
56
|
-
await this.callback(discord_api_types_v10.InteractionResponseType.DeferredChannelMessageWithSource, { flags: (0, _seedcord_core_internal.deferFlags)(opts) });
|
|
57
|
-
}
|
|
58
|
-
async writeDeferUpdate() {
|
|
59
|
-
await this.callback(discord_api_types_v10.InteractionResponseType.DeferredMessageUpdate);
|
|
60
|
-
}
|
|
61
|
-
async writeUpdate(response) {
|
|
62
|
-
const reply = this.serialize(response);
|
|
63
|
-
const result = await this.callback(discord_api_types_v10.InteractionResponseType.UpdateMessage, callbackData(reply, discord_api_types_v10.MessageFlags.IsComponentsV2), reply.files);
|
|
64
|
-
return this.createdMessage(result);
|
|
65
|
-
}
|
|
66
|
-
async writeFollowUp(response, opts) {
|
|
67
|
-
const reply = this.serialize(response);
|
|
68
|
-
return await this.rest.post(discord_api_types_v10.Routes.webhook(this.ref.application_id, this.ref.token), {
|
|
69
|
-
body: callbackData(reply, (0, _seedcord_core_internal.sendFlags)(opts)),
|
|
70
|
-
query: new URLSearchParams({ wait: "true" }),
|
|
71
|
-
...reply.files && { files: this.rawFiles(reply.files) }
|
|
72
|
-
});
|
|
73
|
-
}
|
|
74
|
-
writeEditOriginal(response) {
|
|
75
|
-
return this.editMessage(discord_api_types_v10.Routes.webhookMessage(this.ref.application_id, this.ref.token), this.serialize(response));
|
|
76
|
-
}
|
|
77
|
-
writeEditTarget(targetId, response) {
|
|
78
|
-
const route = discord_api_types_v10.Routes.webhookMessage(this.ref.application_id, this.ref.token, targetId);
|
|
79
|
-
return this.editMessage(route, this.serialize(response));
|
|
80
|
-
}
|
|
81
|
-
async writeDeleteOriginal() {
|
|
82
|
-
await this.rest.delete(discord_api_types_v10.Routes.webhookMessage(this.ref.application_id, this.ref.token));
|
|
83
|
-
}
|
|
84
|
-
async writeDeleteTarget(targetId) {
|
|
85
|
-
await this.rest.delete(discord_api_types_v10.Routes.webhookMessage(this.ref.application_id, this.ref.token, targetId));
|
|
86
|
-
}
|
|
87
|
-
async writeModal(data) {
|
|
88
|
-
await this.callback(discord_api_types_v10.InteractionResponseType.Modal, data);
|
|
89
|
-
}
|
|
90
|
-
async callback(type, data, files) {
|
|
91
|
-
const withResponse = type === discord_api_types_v10.InteractionResponseType.ChannelMessageWithSource || type === discord_api_types_v10.InteractionResponseType.UpdateMessage;
|
|
92
|
-
return await this.rest.post(discord_api_types_v10.Routes.interactionCallback(this.ref.id, this.ref.token), {
|
|
93
|
-
body: {
|
|
94
|
-
type,
|
|
95
|
-
...data !== void 0 && { data }
|
|
96
|
-
},
|
|
97
|
-
...withResponse && { query: new URLSearchParams({ with_response: "true" }) },
|
|
98
|
-
...files && { files: this.rawFiles(files) }
|
|
99
|
-
});
|
|
100
|
-
}
|
|
101
|
-
async editMessage(route, reply) {
|
|
102
|
-
return await this.rest.patch(route, {
|
|
103
|
-
body: callbackData(reply, discord_api_types_v10.MessageFlags.IsComponentsV2),
|
|
104
|
-
...reply.files && { files: this.rawFiles(reply.files) }
|
|
105
|
-
});
|
|
106
|
-
}
|
|
107
|
-
rawFiles(files) {
|
|
108
|
-
return files.map((file, index) => ({
|
|
109
|
-
name: file.name ?? `file-${index}`,
|
|
110
|
-
data: file.attachment
|
|
111
|
-
}));
|
|
112
|
-
}
|
|
113
|
-
createdMessage(result) {
|
|
114
|
-
return result.resource?.message;
|
|
115
|
-
}
|
|
20
|
+
//#region src/manifest/RouteManifest.ts
|
|
21
|
+
/** @internal */
|
|
22
|
+
const EMPTY_MANIFEST = {
|
|
23
|
+
commands: [],
|
|
24
|
+
components: [],
|
|
25
|
+
autocomplete: [],
|
|
26
|
+
subscribers: []
|
|
116
27
|
};
|
|
117
28
|
|
|
118
29
|
//#endregion
|
|
119
|
-
//#region src/
|
|
30
|
+
//#region src/node/InteractionDispatcher.ts
|
|
120
31
|
/**
|
|
121
|
-
*
|
|
32
|
+
* Discovers interaction handlers from the filesystem into the engine's live route maps.
|
|
122
33
|
*
|
|
123
|
-
*
|
|
124
|
-
*
|
|
125
|
-
* to the http sender.
|
|
126
|
-
*
|
|
127
|
-
* @typeParam Event - The repliable interaction type this handler processes
|
|
128
|
-
*/
|
|
129
|
-
var RepliableHandler = class extends _seedcord_core.RepliableHandler {
|
|
130
|
-
buildSender(event, core, routeId) {
|
|
131
|
-
return new ReplySender({
|
|
132
|
-
application_id: event.application_id,
|
|
133
|
-
id: event.id,
|
|
134
|
-
token: event.token
|
|
135
|
-
}, core.rest, routeId);
|
|
136
|
-
}
|
|
137
|
-
};
|
|
138
|
-
|
|
139
|
-
//#endregion
|
|
140
|
-
//#region src/gates/context.ts
|
|
141
|
-
function interactionGateContext(payload, core, routeId) {
|
|
142
|
-
const member = payload.member ?? null;
|
|
143
|
-
const resolved = member?.user ?? payload.user;
|
|
144
|
-
return {
|
|
145
|
-
kind: "interaction",
|
|
146
|
-
core,
|
|
147
|
-
interaction: payload,
|
|
148
|
-
user: resolved,
|
|
149
|
-
member,
|
|
150
|
-
userId: resolved?.id ?? null,
|
|
151
|
-
guildId: payload.guild_id ?? null,
|
|
152
|
-
channelId: payload.channel?.id ?? null,
|
|
153
|
-
memberRoleIds: member?.roles ?? [],
|
|
154
|
-
memberPermissions: member ? BigInt(member.permissions) : null,
|
|
155
|
-
appPermissions: BigInt(payload.app_permissions),
|
|
156
|
-
routeId
|
|
157
|
-
};
|
|
158
|
-
}
|
|
159
|
-
|
|
160
|
-
//#endregion
|
|
161
|
-
//#region src/dispatch/dispatchInteraction.ts
|
|
162
|
-
let dispatchLogger;
|
|
163
|
-
function logger() {
|
|
164
|
-
dispatchLogger ??= new _seedcord_logger.Logger("Dispatcher");
|
|
165
|
-
return dispatchLogger;
|
|
166
|
-
}
|
|
167
|
-
function createCore(config, token) {
|
|
168
|
-
return {
|
|
169
|
-
config,
|
|
170
|
-
rateLimiter: config.store ?? new _seedcord_rate_limiter.MemoryRateLimiter(),
|
|
171
|
-
rest: new _discordjs_rest.REST().setToken(token),
|
|
172
|
-
version: "0.1.0-next.0",
|
|
173
|
-
username: void 0,
|
|
174
|
-
augmentTarget: "@seedcord/http"
|
|
175
|
-
};
|
|
176
|
-
}
|
|
177
|
-
function isHandlerCtor(value) {
|
|
178
|
-
return typeof value === "function" && value.prototype instanceof _seedcord_core.BaseHandler;
|
|
179
|
-
}
|
|
180
|
-
function handlerCtorOf(moduleExports) {
|
|
181
|
-
if (typeof moduleExports !== "object" || moduleExports === null) return null;
|
|
182
|
-
for (const value of Object.values(moduleExports)) if (isHandlerCtor(value)) return value;
|
|
183
|
-
return null;
|
|
184
|
-
}
|
|
185
|
-
const HARMLESS_API_CODES = new Set([
|
|
186
|
-
discord_api_types_v10.RESTJSONErrorCodes.UnknownInteraction,
|
|
187
|
-
discord_api_types_v10.RESTJSONErrorCodes.InteractionHasAlreadyBeenAcknowledged,
|
|
188
|
-
discord_api_types_v10.RESTJSONErrorCodes.UnknownMessage
|
|
189
|
-
]);
|
|
190
|
-
async function sendGuarded(routeId, send) {
|
|
191
|
-
try {
|
|
192
|
-
await send();
|
|
193
|
-
} catch (error) {
|
|
194
|
-
if (error instanceof _discordjs_rest.DiscordAPIError && HARMLESS_API_CODES.has(error.code)) {
|
|
195
|
-
logger().debug(`boundary send hit harmless code ${_seedcord_logger.paint.amber(String(error.code))}`);
|
|
196
|
-
return;
|
|
197
|
-
}
|
|
198
|
-
logger().error(`boundary send failed for route ${_seedcord_logger.paint.sky.bold(routeId)}`, error);
|
|
199
|
-
}
|
|
200
|
-
}
|
|
201
|
-
async function respondEmptyChoices(scope) {
|
|
202
|
-
await scope.core.rest.post(discord_api_types_v10.Routes.interactionCallback(scope.payload.id, scope.payload.token), { body: {
|
|
203
|
-
type: discord_api_types_v10.InteractionResponseType.ApplicationCommandAutocompleteResult,
|
|
204
|
-
data: { choices: [] }
|
|
205
|
-
} });
|
|
206
|
-
}
|
|
207
|
-
function renderContext(core, uuid) {
|
|
208
|
-
const developerUsername = core.config.notifications?.developerUsername;
|
|
209
|
-
return developerUsername === void 0 ? { uuid } : {
|
|
210
|
-
uuid,
|
|
211
|
-
developerUsername
|
|
212
|
-
};
|
|
213
|
-
}
|
|
214
|
-
async function handleNotice(notice, uuid, scope) {
|
|
215
|
-
if (notice.report) logger().error(`${notice.name}: ${_seedcord_logger.paint.mute(uuid)}`, notice);
|
|
216
|
-
const { sender } = scope;
|
|
217
|
-
if (!sender) {
|
|
218
|
-
await sendGuarded(scope.routeId, () => respondEmptyChoices(scope));
|
|
219
|
-
return;
|
|
220
|
-
}
|
|
221
|
-
const response = notice.render(renderContext(scope.core, uuid));
|
|
222
|
-
await sendGuarded(scope.routeId, () => sender.send(response, { ephemeral: notice.ephemeral }));
|
|
223
|
-
}
|
|
224
|
-
async function handleRawFault(error, uuid, scope) {
|
|
225
|
-
const { core, sender } = scope;
|
|
226
|
-
if (core.config.errors?.errorStack ?? false) logger().error(_seedcord_logger.paint.mute(uuid), error);
|
|
227
|
-
else logger().error(`${_seedcord_logger.paint.mute(uuid)} | ${error.message}`);
|
|
228
|
-
if (!sender) {
|
|
229
|
-
await sendGuarded(scope.routeId, () => respondEmptyChoices(scope));
|
|
230
|
-
return;
|
|
231
|
-
}
|
|
232
|
-
const override = core.config.errors?.defaultError;
|
|
233
|
-
const response = (override ? new override(uuid) : new _seedcord_core.Fault()).render(renderContext(core, uuid));
|
|
234
|
-
await sendGuarded(scope.routeId, () => sender.send(response, { ephemeral: true }));
|
|
235
|
-
}
|
|
236
|
-
async function handleFault(caught, scope) {
|
|
237
|
-
if (caught instanceof _seedcord_core.Silence) {
|
|
238
|
-
if (caught.reason !== void 0) logger().debug(`Silence: ${caught.reason}`);
|
|
239
|
-
return;
|
|
240
|
-
}
|
|
241
|
-
const uuid = crypto.randomUUID();
|
|
242
|
-
if (caught instanceof _seedcord_core.Notice) {
|
|
243
|
-
await handleNotice(caught, uuid, scope);
|
|
244
|
-
return;
|
|
245
|
-
}
|
|
246
|
-
const error = Error.isError(caught) ? caught : new Error(String(caught));
|
|
247
|
-
const ignore = new Set(scope.core.config.errors?.ignoreApiCodes ?? []);
|
|
248
|
-
if (error instanceof _discordjs_rest.DiscordAPIError && ignore.has(error.code)) {
|
|
249
|
-
logger().debug(`swallowed api code ${_seedcord_logger.paint.amber(String(error.code))}`);
|
|
250
|
-
return;
|
|
251
|
-
}
|
|
252
|
-
await handleRawFault(error, uuid, scope);
|
|
253
|
-
}
|
|
254
|
-
function freshScope(match, payload, core) {
|
|
255
|
-
const ref = {
|
|
256
|
-
application_id: payload.application_id,
|
|
257
|
-
id: payload.id,
|
|
258
|
-
token: payload.token
|
|
259
|
-
};
|
|
260
|
-
const routeId = match.routeId ?? "unhandled";
|
|
261
|
-
return {
|
|
262
|
-
core,
|
|
263
|
-
payload,
|
|
264
|
-
routeId,
|
|
265
|
-
sender: match.kind === "autocomplete" ? null : new ReplySender(ref, core.rest, routeId)
|
|
266
|
-
};
|
|
267
|
-
}
|
|
268
|
-
/**
|
|
269
|
-
* Runs the pre-ack phase for a matched interaction. Loads the route module, constructs the handler, and
|
|
270
|
-
* runs its gates, and the sender posts any refusal. Returns the post-ack execute continuation, or null
|
|
271
|
-
* when a gate refuses or nothing can run.
|
|
34
|
+
* The node host runs it at startup and dev HMR swaps map entries in place. The engine's `resolve`
|
|
35
|
+
* reads `maps` per request. The edge path builds its maps from the generated manifest.
|
|
272
36
|
*/
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
return
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
37
|
+
var InteractionDispatcher = class {
|
|
38
|
+
handlersDir;
|
|
39
|
+
maps;
|
|
40
|
+
targets;
|
|
41
|
+
/** @internal */
|
|
42
|
+
logger = new _seedcord_logger.Logger("Interactions");
|
|
43
|
+
isInitialized = false;
|
|
44
|
+
hmrHandler;
|
|
45
|
+
rowOwners = /* @__PURE__ */ new Map();
|
|
46
|
+
loading = false;
|
|
47
|
+
loadedHandlers = [];
|
|
48
|
+
constructor(handlersDir) {
|
|
49
|
+
this.handlersDir = handlersDir;
|
|
50
|
+
this.maps = require_edge_index.buildRouteMaps(EMPTY_MANIFEST);
|
|
51
|
+
this.targets = this.buildTargets();
|
|
52
|
+
if (!envapt.Envapter.isDevelopment && !envapt.Envapter.isTest) return;
|
|
53
|
+
this.hmrHandler = new _seedcord_core_hmr.HmrModuleHandler({
|
|
54
|
+
handlersDir,
|
|
55
|
+
isHandler: this.isHandler.bind(this),
|
|
56
|
+
registerHandler: this.registerHandler.bind(this),
|
|
57
|
+
unregisterHandler: this.unregisterHandler.bind(this),
|
|
58
|
+
getArtifacts: this.getArtifacts.bind(this),
|
|
59
|
+
logger: this.logger
|
|
60
|
+
});
|
|
297
61
|
}
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
if (!await passedGates(ctor, match, payload, core, scope)) return null;
|
|
305
|
-
return async () => {
|
|
62
|
+
/** @internal */
|
|
63
|
+
async init() {
|
|
64
|
+
if (this.isInitialized) return;
|
|
65
|
+
this.isInitialized = true;
|
|
66
|
+
this.loading = true;
|
|
67
|
+
this.loadedHandlers.length = 0;
|
|
306
68
|
try {
|
|
307
|
-
await
|
|
308
|
-
|
|
309
|
-
|
|
69
|
+
await (0, _seedcord_utils_node.traverseDirectory)(this.handlersDir, (fullPath, relativePath, imported) => {
|
|
70
|
+
for (const value of Object.values(imported)) {
|
|
71
|
+
if (!this.isHandler(value)) continue;
|
|
72
|
+
this.registerHandler(value, relativePath);
|
|
73
|
+
this.hmrHandler?.trackHandler(fullPath, value);
|
|
74
|
+
}
|
|
75
|
+
}, this.logger);
|
|
76
|
+
} finally {
|
|
77
|
+
this.loading = false;
|
|
310
78
|
}
|
|
311
|
-
|
|
312
|
-
}
|
|
313
|
-
async function passedGates(ctor, match, payload, core, scope) {
|
|
314
|
-
if (match.kind === "autocomplete" || payload.type === discord_api_types_v10.InteractionType.ApplicationCommandAutocomplete) return true;
|
|
315
|
-
const monitor = (0, _seedcord_core_internal.slowGateMonitor)();
|
|
316
|
-
try {
|
|
317
|
-
await (0, _seedcord_core_internal.runHandlerGates)(ctor, interactionGateContext(payload, core, match.routeId), match.routeId ?? void 0, monitor?.observe);
|
|
318
|
-
return true;
|
|
319
|
-
} catch (caught) {
|
|
320
|
-
await handleFault(caught, scope);
|
|
321
|
-
return false;
|
|
322
|
-
} finally {
|
|
323
|
-
monitor?.report(match.routeId);
|
|
79
|
+
this.logger.utils.block("Loaded handlers", [...this.logger.utils.entries(this.loadedHandlers), ...this.logger.utils.counts({ routes: this.rowOwners.size })]);
|
|
324
80
|
}
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
//#region src/inputs/HttpSlashOptions.ts
|
|
329
|
-
var HttpSlashOptions = class {
|
|
330
|
-
leaves = /* @__PURE__ */ new Map();
|
|
331
|
-
resolved;
|
|
332
|
-
constructor(data) {
|
|
333
|
-
this.resolved = data.resolved;
|
|
334
|
-
let options = data.options ?? [];
|
|
335
|
-
const first = options[0];
|
|
336
|
-
if (first?.type === discord_api_types_v10.ApplicationCommandOptionType.SubcommandGroup) options = first.options;
|
|
337
|
-
const second = options[0];
|
|
338
|
-
if (second?.type === discord_api_types_v10.ApplicationCommandOptionType.Subcommand) options = second.options ?? [];
|
|
339
|
-
for (const option of options) if (option.type !== discord_api_types_v10.ApplicationCommandOptionType.Subcommand && option.type !== discord_api_types_v10.ApplicationCommandOptionType.SubcommandGroup) this.leaves.set(option.name, option);
|
|
340
|
-
}
|
|
341
|
-
getString(name) {
|
|
342
|
-
const leaf = this.leaves.get(name);
|
|
343
|
-
return leaf?.type === discord_api_types_v10.ApplicationCommandOptionType.String ? leaf.value : null;
|
|
344
|
-
}
|
|
345
|
-
getInteger(name) {
|
|
346
|
-
const leaf = this.leaves.get(name);
|
|
347
|
-
return leaf?.type === discord_api_types_v10.ApplicationCommandOptionType.Integer ? numeric(leaf.value) : null;
|
|
348
|
-
}
|
|
349
|
-
getNumber(name) {
|
|
350
|
-
const leaf = this.leaves.get(name);
|
|
351
|
-
return leaf?.type === discord_api_types_v10.ApplicationCommandOptionType.Number ? numeric(leaf.value) : null;
|
|
352
|
-
}
|
|
353
|
-
getBoolean(name) {
|
|
354
|
-
const leaf = this.leaves.get(name);
|
|
355
|
-
return leaf?.type === discord_api_types_v10.ApplicationCommandOptionType.Boolean ? leaf.value : null;
|
|
356
|
-
}
|
|
357
|
-
getUser(name) {
|
|
358
|
-
const leaf = this.leaves.get(name);
|
|
359
|
-
if (leaf?.type !== discord_api_types_v10.ApplicationCommandOptionType.User) return null;
|
|
360
|
-
return this.resolved?.users?.[leaf.value] ?? null;
|
|
361
|
-
}
|
|
362
|
-
getMember(name) {
|
|
363
|
-
const leaf = this.leaves.get(name);
|
|
364
|
-
if (leaf?.type !== discord_api_types_v10.ApplicationCommandOptionType.User) return null;
|
|
365
|
-
return this.resolved?.members?.[leaf.value] ?? null;
|
|
81
|
+
/** @internal */
|
|
82
|
+
async onHmr(event) {
|
|
83
|
+
await this.hmrHandler?.handle(event);
|
|
366
84
|
}
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
return this.resolved?.channels?.[leaf.value] ?? null;
|
|
85
|
+
isHandler(value) {
|
|
86
|
+
if (typeof value !== "function") return false;
|
|
87
|
+
return (value.prototype instanceof require_edge_index.InteractionHandler || value.prototype instanceof require_edge_index.AutocompleteHandler) && Reflect.hasMetadata(_seedcord_core_internal.InteractionMetadataKey, value);
|
|
371
88
|
}
|
|
372
|
-
|
|
373
|
-
const
|
|
374
|
-
|
|
375
|
-
return
|
|
89
|
+
getArtifacts(ctor) {
|
|
90
|
+
const routeIds = [];
|
|
91
|
+
for (const [routeId, owner] of this.rowOwners) if (owner.ctor === ctor) routeIds.push(routeId);
|
|
92
|
+
return routeIds;
|
|
376
93
|
}
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
if (leaf?.type !== discord_api_types_v10.ApplicationCommandOptionType.Attachment) return null;
|
|
380
|
-
return this.resolved?.attachments?.[leaf.value] ?? null;
|
|
94
|
+
targetFor(route) {
|
|
95
|
+
return this.targets[route];
|
|
381
96
|
}
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
97
|
+
buildTargets() {
|
|
98
|
+
return {
|
|
99
|
+
[_seedcord_core_internal.InteractionRoutes.Slash]: {
|
|
100
|
+
map: this.maps.slash,
|
|
101
|
+
kind: "slash"
|
|
102
|
+
},
|
|
103
|
+
[_seedcord_core_internal.InteractionRoutes.UserContextMenu]: {
|
|
104
|
+
map: this.maps.userContextMenu,
|
|
105
|
+
kind: "userContextMenu"
|
|
106
|
+
},
|
|
107
|
+
[_seedcord_core_internal.InteractionRoutes.MessageContextMenu]: {
|
|
108
|
+
map: this.maps.messageContextMenu,
|
|
109
|
+
kind: "messageContextMenu"
|
|
110
|
+
},
|
|
111
|
+
[_seedcord_core_internal.InteractionRoutes.Autocomplete]: {
|
|
112
|
+
map: this.maps.autocomplete,
|
|
113
|
+
kind: "autocomplete"
|
|
114
|
+
},
|
|
115
|
+
[_seedcord_core_internal.InteractionRoutes.Button]: {
|
|
116
|
+
map: this.maps.components.button,
|
|
117
|
+
kind: "button"
|
|
118
|
+
},
|
|
119
|
+
[_seedcord_core_internal.InteractionRoutes.StringMenu]: {
|
|
120
|
+
map: this.maps.components.stringSelect,
|
|
121
|
+
kind: "stringMenu"
|
|
122
|
+
},
|
|
123
|
+
[_seedcord_core_internal.InteractionRoutes.UserMenu]: {
|
|
124
|
+
map: this.maps.components.userSelect,
|
|
125
|
+
kind: "userMenu"
|
|
126
|
+
},
|
|
127
|
+
[_seedcord_core_internal.InteractionRoutes.RoleMenu]: {
|
|
128
|
+
map: this.maps.components.roleSelect,
|
|
129
|
+
kind: "roleMenu"
|
|
130
|
+
},
|
|
131
|
+
[_seedcord_core_internal.InteractionRoutes.ChannelMenu]: {
|
|
132
|
+
map: this.maps.components.channelSelect,
|
|
133
|
+
kind: "channelMenu"
|
|
134
|
+
},
|
|
135
|
+
[_seedcord_core_internal.InteractionRoutes.MentionableMenu]: {
|
|
136
|
+
map: this.maps.components.mentionableSelect,
|
|
137
|
+
kind: "mentionableMenu"
|
|
138
|
+
},
|
|
139
|
+
[_seedcord_core_internal.InteractionRoutes.Modal]: {
|
|
140
|
+
map: this.maps.components.modal,
|
|
141
|
+
kind: "modal"
|
|
142
|
+
}
|
|
392
143
|
};
|
|
393
|
-
|
|
144
|
+
}
|
|
145
|
+
registerHandler(ctor, relativePath) {
|
|
146
|
+
const writes = [];
|
|
147
|
+
for (const [route, keys] of (0, _seedcord_core_internal.interactionRoutesOf)(ctor)) {
|
|
148
|
+
const target = this.targetFor(route);
|
|
149
|
+
for (const key of keys) {
|
|
150
|
+
const existing = this.rowOwners.get(`${target.kind}:${key}`);
|
|
151
|
+
if (existing && existing.ctor !== ctor) throw new _seedcord_errors_internal.SeedcordError(_seedcord_errors.SeedcordErrorCode.InteractionDuplicateRoute, [
|
|
152
|
+
key,
|
|
153
|
+
existing.ctor.name,
|
|
154
|
+
ctor.name
|
|
155
|
+
]);
|
|
156
|
+
writes.push([target, key]);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
if (writes.length === 0) return;
|
|
160
|
+
for (const [target, key] of writes) {
|
|
161
|
+
const routeId = `${target.kind}:${key}`;
|
|
162
|
+
target.map.set(key, {
|
|
163
|
+
kind: target.kind,
|
|
164
|
+
routeId,
|
|
165
|
+
load: () => Promise.resolve({ [ctor.name]: ctor })
|
|
166
|
+
});
|
|
167
|
+
this.rowOwners.set(routeId, {
|
|
168
|
+
ctor,
|
|
169
|
+
target,
|
|
170
|
+
key
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
const from = (0, _seedcord_utils.formatFilePath)(relativePath);
|
|
174
|
+
if (this.loading) this.loadedHandlers.push({
|
|
175
|
+
name: ctor.name,
|
|
176
|
+
from
|
|
177
|
+
});
|
|
178
|
+
else this.logger.utils.registration(ctor.name, from);
|
|
179
|
+
}
|
|
180
|
+
unregisterHandler(ctor, artifacts) {
|
|
181
|
+
const routeIds = artifacts ?? this.getArtifacts(ctor);
|
|
182
|
+
for (const routeId of routeIds) {
|
|
183
|
+
const owner = this.rowOwners.get(routeId);
|
|
184
|
+
if (owner?.ctor !== ctor) continue;
|
|
185
|
+
this.rowOwners.delete(routeId);
|
|
186
|
+
owner.target.map.delete(owner.key);
|
|
187
|
+
}
|
|
394
188
|
}
|
|
395
189
|
};
|
|
396
|
-
function numeric(value) {
|
|
397
|
-
if (typeof value === "number") return value;
|
|
398
|
-
if (value.trim() === "") return null;
|
|
399
|
-
const parsed = Number(value);
|
|
400
|
-
return Number.isNaN(parsed) ? null : parsed;
|
|
401
|
-
}
|
|
402
190
|
|
|
403
191
|
//#endregion
|
|
404
|
-
//#region src/
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
192
|
+
//#region src/node/webBridge.ts
|
|
193
|
+
function toHeaders(raw) {
|
|
194
|
+
const headers = new Headers();
|
|
195
|
+
for (const [name, value] of Object.entries(raw)) {
|
|
196
|
+
if (value === void 0) continue;
|
|
197
|
+
if (Array.isArray(value)) for (const item of value) headers.append(name, item);
|
|
198
|
+
else headers.set(name, value);
|
|
199
|
+
}
|
|
200
|
+
return headers;
|
|
201
|
+
}
|
|
202
|
+
async function toWebRequest(request) {
|
|
203
|
+
const chunks = [];
|
|
204
|
+
for await (const chunk of request) chunks.push(chunk);
|
|
205
|
+
const method = request.method ?? "GET";
|
|
206
|
+
const body = method === "GET" || method === "HEAD" ? void 0 : new Uint8Array(Buffer.concat(chunks));
|
|
207
|
+
return new Request(`http://${request.headers.host ?? "localhost"}${request.url ?? "/"}`, {
|
|
208
|
+
method,
|
|
209
|
+
headers: toHeaders(request.headers),
|
|
210
|
+
...body !== void 0 && { body }
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
async function writeWebResponse(response, out) {
|
|
214
|
+
const headers = Object.fromEntries(response.headers);
|
|
215
|
+
const cookies = response.headers.getSetCookie();
|
|
216
|
+
if (cookies.length > 0) headers["set-cookie"] = cookies;
|
|
217
|
+
out.writeHead(response.status, headers);
|
|
218
|
+
out.end(response.body === null ? void 0 : Buffer.from(await response.arrayBuffer()));
|
|
415
219
|
}
|
|
416
220
|
|
|
417
221
|
//#endregion
|
|
418
|
-
//#region src/
|
|
222
|
+
//#region src/node/Seedcord.ts
|
|
223
|
+
const DEFAULT_PORT = 3e3;
|
|
224
|
+
const SERVER_SHUTDOWN_TIMEOUT_MS = 5e3;
|
|
225
|
+
const DRAIN_TIMEOUT_MS = 1e4;
|
|
419
226
|
/**
|
|
420
|
-
*
|
|
227
|
+
* The HTTP-interactions bot host, a long-running node server around the engine.
|
|
421
228
|
*
|
|
422
|
-
*
|
|
423
|
-
* `
|
|
424
|
-
*
|
|
425
|
-
*
|
|
426
|
-
* @typeParam Route - One or more route keys from {@link SlashOptionRegistry}, e.g. `'search'`.
|
|
229
|
+
* Discovers handlers from `config.bot.interactions.path`, verifies and dispatches interactions on
|
|
230
|
+
* `start(port)`, and runs coordinated shutdown with an in-flight drain. The edge deploy path calls
|
|
231
|
+
* `createSeedcord` from a generated entry.
|
|
427
232
|
*/
|
|
428
|
-
var
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
*/
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
233
|
+
var Seedcord = class Seedcord extends _seedcord_core_node_internal.Pluggable {
|
|
234
|
+
config;
|
|
235
|
+
/** @internal */
|
|
236
|
+
[_seedcord_types_internal.SeedcordBrand] = true;
|
|
237
|
+
/** @internal */
|
|
238
|
+
augmentTarget = "@seedcord/http";
|
|
239
|
+
/** @internal */
|
|
240
|
+
version = require_edge_index.version;
|
|
241
|
+
/** Workerd-compatible Discord REST client. `start()` sets the token. */
|
|
242
|
+
rest = new _discordjs_rest.REST();
|
|
243
|
+
/** @see {@link IRateLimiter} */
|
|
244
|
+
rateLimiter;
|
|
245
|
+
/** @see {@link CoordinatedShutdown} */
|
|
246
|
+
shutdown;
|
|
247
|
+
/** @see {@link CoordinatedStartup} */
|
|
248
|
+
startup;
|
|
249
|
+
interactions;
|
|
250
|
+
healthCheck;
|
|
251
|
+
hmrManager;
|
|
252
|
+
logger = new _seedcord_logger.Logger("Server");
|
|
253
|
+
server;
|
|
254
|
+
boundPort;
|
|
255
|
+
requestedPort = DEFAULT_PORT;
|
|
256
|
+
fetchedUsername;
|
|
257
|
+
constructor(config) {
|
|
258
|
+
const shutdown = new _seedcord_core_node_internal.CoordinatedShutdown();
|
|
259
|
+
const startup = new _seedcord_core_node_internal.CoordinatedStartup();
|
|
260
|
+
super(shutdown, startup);
|
|
261
|
+
this.config = config;
|
|
262
|
+
(0, _seedcord_logger_node.installNodeDefaults)(config.logger);
|
|
263
|
+
(0, _seedcord_core_internal.setBotColor)(config.botColor);
|
|
264
|
+
this.shutdown = shutdown;
|
|
265
|
+
this.startup = startup;
|
|
266
|
+
this.hmrManager = new _seedcord_core_internal.HmrManager();
|
|
267
|
+
this.hmrManager.init();
|
|
268
|
+
if (this.config.bot.interactions.path) this.interactions = new InteractionDispatcher(this.config.bot.interactions.path);
|
|
269
|
+
this.rateLimiter = config.store ?? new _seedcord_rate_limiter.MemoryRateLimiter();
|
|
270
|
+
this.healthCheck = config.runtime === "edge" ? void 0 : _seedcord_core_node_internal.HealthCheck.fromOption(this.shutdown, config.healthCheck);
|
|
271
|
+
this.registerStartupTasks();
|
|
272
|
+
}
|
|
273
|
+
/** The bot's discord username, populated by the ready fetch. */
|
|
274
|
+
get username() {
|
|
275
|
+
return this.fetchedUsername;
|
|
276
|
+
}
|
|
277
|
+
/** The bound server port, populated once `start()` is listening. */
|
|
278
|
+
get port() {
|
|
279
|
+
return this.boundPort;
|
|
280
|
+
}
|
|
281
|
+
pluginCapabilities() {
|
|
282
|
+
const token = envapt.Envapter.get("DISCORD_BOT_TOKEN");
|
|
283
|
+
return {
|
|
284
|
+
rest: this.rest,
|
|
285
|
+
...token !== void 0 && { token }
|
|
286
|
+
};
|
|
445
287
|
}
|
|
446
288
|
/**
|
|
447
|
-
*
|
|
448
|
-
* match is how you read it.
|
|
289
|
+
* Starts the host and runs the startup tasks.
|
|
449
290
|
*
|
|
450
|
-
*
|
|
451
|
-
* arm receives the focused partial value and a `respond` typed to that field's choice value. The
|
|
452
|
-
* arms must cover every autocompletable field, a missing field or an unknown key is a compile error. A
|
|
453
|
-
* focused field with no arm, only reachable from a stale-deployed command, throws at runtime.
|
|
454
|
-
*
|
|
455
|
-
* @param arms - One handler per autocompletable field, keyed by field name.
|
|
456
|
-
* @returns The result of the arm that ran.
|
|
457
|
-
*/
|
|
458
|
-
async match(arms) {
|
|
459
|
-
const { name, value } = this.focused;
|
|
460
|
-
const respond = (choices) => this.respond(choices);
|
|
461
|
-
const arm = Object.hasOwn(arms, name) ? arms[name] : void 0;
|
|
462
|
-
if (!arm) throw new _seedcord_errors_internal.SeedcordError(_seedcord_errors.SeedcordErrorCode.AutocompleteMatchArmMissing, [name]);
|
|
463
|
-
return await arm(value, respond);
|
|
464
|
-
}
|
|
465
|
-
/** Send autocomplete suggestions, callback type 8. Prefer {@link match}, which restricts each field's choices to its declared type. */
|
|
466
|
-
async respond(choices) {
|
|
467
|
-
await this.core.rest.post(discord_api_types_v10.Routes.interactionCallback(this.event.id, this.event.token), { body: {
|
|
468
|
-
type: discord_api_types_v10.InteractionResponseType.ApplicationCommandAutocompleteResult,
|
|
469
|
-
data: { choices }
|
|
470
|
-
} });
|
|
471
|
-
}
|
|
472
|
-
/** The firing command route, for a field whose completion differs per registered command. */
|
|
473
|
-
get route() {
|
|
474
|
-
return slashRouteOf(this.event.data);
|
|
475
|
-
}
|
|
476
|
-
/**
|
|
477
|
-
* The already-entered options on this command, restricted to the kinds Discord resolves during autocomplete
|
|
478
|
-
* (string, integer, number, boolean) with every read nullable, since a sibling is partial while the user
|
|
479
|
-
* types the focused field. The focused field is on `this.focused`.
|
|
291
|
+
* @param port - The port the interaction server binds. {@default `3000`}
|
|
480
292
|
*/
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
* Default handler for autocomplete no manifest row matches.
|
|
490
|
-
* Empty choices are the only legal answer, they clear the pending state.
|
|
491
|
-
*
|
|
492
|
-
* @internal
|
|
493
|
-
*/
|
|
494
|
-
var UnhandledAutocomplete = class extends AutocompleteHandler {
|
|
495
|
-
async execute() {
|
|
496
|
-
await this.respond([]);
|
|
497
|
-
}
|
|
498
|
-
};
|
|
499
|
-
|
|
500
|
-
//#endregion
|
|
501
|
-
//#region src/handlers/interaction/InteractionHandler.ts
|
|
502
|
-
/**
|
|
503
|
-
* Shared base the repliable interaction handlers extend.
|
|
504
|
-
*
|
|
505
|
-
* Not a public entry point. Extend {@link SlashHandler}, {@link ContextMenuHandler}, {@link ButtonHandler},
|
|
506
|
-
* {@link SelectMenuHandler}, or {@link ModalHandler} instead. This class adds `showModal` on top of the
|
|
507
|
-
* reply members.
|
|
508
|
-
*
|
|
509
|
-
* @typeParam Event - The repliable interaction type this handler processes
|
|
510
|
-
*/
|
|
511
|
-
var InteractionHandler = class extends RepliableHandler {
|
|
512
|
-
constructor(event, core, dispatch) {
|
|
513
|
-
super(event, core, dispatch);
|
|
514
|
-
}
|
|
515
|
-
/**
|
|
516
|
-
* Open a modal. Must be the initial response to this interaction. The modal kind rejects this call at
|
|
517
|
-
* compile time (Discord forbids a modal in response to a modal).
|
|
518
|
-
*/
|
|
519
|
-
showModal(modal) {
|
|
520
|
-
return this.sender.showModal(modal);
|
|
521
|
-
}
|
|
522
|
-
};
|
|
523
|
-
|
|
524
|
-
//#endregion
|
|
525
|
-
//#region src/handlers/defaults/UnhandledRepliable.ts
|
|
526
|
-
/**
|
|
527
|
-
* Default handler for interactions no manifest row matches. A reply failure here
|
|
528
|
-
* goes directly to the dispatch fault boundary, so it needs no guard of its own.
|
|
529
|
-
*
|
|
530
|
-
* @internal
|
|
531
|
-
*/
|
|
532
|
-
var UnhandledRepliable = class extends InteractionHandler {
|
|
533
|
-
async execute() {
|
|
534
|
-
await this.reply("Feature not implemented yet.");
|
|
535
|
-
}
|
|
536
|
-
};
|
|
537
|
-
|
|
538
|
-
//#endregion
|
|
539
|
-
//#region src/dispatch/resolve.ts
|
|
540
|
-
const COMPONENT_KIND = {
|
|
541
|
-
button: "button",
|
|
542
|
-
stringSelect: "stringMenu",
|
|
543
|
-
userSelect: "userMenu",
|
|
544
|
-
roleSelect: "roleMenu",
|
|
545
|
-
channelSelect: "channelMenu",
|
|
546
|
-
mentionableSelect: "mentionableMenu",
|
|
547
|
-
modal: "modal"
|
|
548
|
-
};
|
|
549
|
-
function commandKind(type) {
|
|
550
|
-
switch (type) {
|
|
551
|
-
case discord_api_types_v10.ApplicationCommandType.ChatInput: return "slash";
|
|
552
|
-
case discord_api_types_v10.ApplicationCommandType.User: return "userContextMenu";
|
|
553
|
-
case discord_api_types_v10.ApplicationCommandType.Message: return "messageContextMenu";
|
|
554
|
-
default: return null;
|
|
555
|
-
}
|
|
556
|
-
}
|
|
557
|
-
function componentMapKey(type) {
|
|
558
|
-
switch (type) {
|
|
559
|
-
case discord_api_types_v10.ComponentType.Button: return "button";
|
|
560
|
-
case discord_api_types_v10.ComponentType.StringSelect: return "stringSelect";
|
|
561
|
-
case discord_api_types_v10.ComponentType.UserSelect: return "userSelect";
|
|
562
|
-
case discord_api_types_v10.ComponentType.RoleSelect: return "roleSelect";
|
|
563
|
-
case discord_api_types_v10.ComponentType.ChannelSelect: return "channelSelect";
|
|
564
|
-
case discord_api_types_v10.ComponentType.MentionableSelect: return "mentionableSelect";
|
|
565
|
-
default: return null;
|
|
566
|
-
}
|
|
567
|
-
}
|
|
568
|
-
function set(map, kind, key, load) {
|
|
569
|
-
map.set(key, {
|
|
570
|
-
kind,
|
|
571
|
-
routeId: `${kind}:${key}`,
|
|
572
|
-
load
|
|
573
|
-
});
|
|
574
|
-
}
|
|
575
|
-
/** Builds the per-kind lookup maps. */
|
|
576
|
-
function buildRouteMaps(manifest) {
|
|
577
|
-
const maps = {
|
|
578
|
-
slash: /* @__PURE__ */ new Map(),
|
|
579
|
-
userContextMenu: /* @__PURE__ */ new Map(),
|
|
580
|
-
messageContextMenu: /* @__PURE__ */ new Map(),
|
|
581
|
-
autocomplete: /* @__PURE__ */ new Map(),
|
|
582
|
-
components: {
|
|
583
|
-
button: /* @__PURE__ */ new Map(),
|
|
584
|
-
stringSelect: /* @__PURE__ */ new Map(),
|
|
585
|
-
userSelect: /* @__PURE__ */ new Map(),
|
|
586
|
-
roleSelect: /* @__PURE__ */ new Map(),
|
|
587
|
-
channelSelect: /* @__PURE__ */ new Map(),
|
|
588
|
-
mentionableSelect: /* @__PURE__ */ new Map(),
|
|
589
|
-
modal: /* @__PURE__ */ new Map()
|
|
590
|
-
}
|
|
591
|
-
};
|
|
592
|
-
for (const row of manifest.commands) {
|
|
593
|
-
const kind = commandKind(row.type);
|
|
594
|
-
if (kind) set(maps[kind], kind, row.name, row.load);
|
|
595
|
-
}
|
|
596
|
-
for (const row of manifest.autocomplete) set(maps.autocomplete, "autocomplete", row.name, row.load);
|
|
597
|
-
for (const row of manifest.components) set(maps.components[row.kind], COMPONENT_KIND[row.kind], row.prefix, row.load);
|
|
598
|
-
return maps;
|
|
599
|
-
}
|
|
600
|
-
function unhandled(kind) {
|
|
601
|
-
return {
|
|
602
|
-
kind,
|
|
603
|
-
routeId: null,
|
|
604
|
-
load: () => Promise.resolve(kind === "autocomplete" ? { UnhandledAutocomplete } : { UnhandledRepliable })
|
|
605
|
-
};
|
|
606
|
-
}
|
|
607
|
-
/**
|
|
608
|
-
* Matches a verified non-PING interaction to its manifest row. A known kind with no row resolves to the
|
|
609
|
-
* unhandled default, whose handler replies "Feature not implemented yet." (empty choices on autocomplete).
|
|
610
|
-
* Null is an unrecognized payload shape, which the engine acks with a 202 without dispatching.
|
|
611
|
-
* Components and modals route by the stable customId prefix, so a wire whose layout hash drifted still
|
|
612
|
-
* routes to its handler, where decode refuses with `StaleCustomId`.
|
|
613
|
-
*/
|
|
614
|
-
function resolve(maps, interaction) {
|
|
615
|
-
switch (interaction.type) {
|
|
616
|
-
case discord_api_types_v10.InteractionType.ApplicationCommand: {
|
|
617
|
-
if (interaction.data.type === discord_api_types_v10.ApplicationCommandType.ChatInput) return maps.slash.get(slashRouteOf(interaction.data)) ?? unhandled("slash");
|
|
618
|
-
const kind = commandKind(interaction.data.type);
|
|
619
|
-
return kind ? maps[kind].get(interaction.data.name) ?? unhandled(kind) : null;
|
|
620
|
-
}
|
|
621
|
-
case discord_api_types_v10.InteractionType.ApplicationCommandAutocomplete: return maps.autocomplete.get(slashRouteOf(interaction.data)) ?? unhandled("autocomplete");
|
|
622
|
-
case discord_api_types_v10.InteractionType.MessageComponent: {
|
|
623
|
-
const key = componentMapKey(interaction.data.component_type);
|
|
624
|
-
if (!key) return null;
|
|
625
|
-
return maps.components[key].get((0, _seedcord_core_internal.prefixOf)(interaction.data.custom_id)) ?? unhandled(COMPONENT_KIND[key]);
|
|
293
|
+
async start(port = DEFAULT_PORT) {
|
|
294
|
+
this.requestedPort = port;
|
|
295
|
+
try {
|
|
296
|
+
await super.init();
|
|
297
|
+
} catch (caught) {
|
|
298
|
+
await this.shutdown.run(1, false);
|
|
299
|
+
Seedcord.reset();
|
|
300
|
+
throw caught;
|
|
626
301
|
}
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
const
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
}
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
if (!publicKey) throw new _seedcord_errors_internal.SeedcordError(_seedcord_errors.SeedcordErrorCode.ConfigIncorrectPublicKey);
|
|
650
|
-
this.key = crypto.subtle.importKey("raw", publicKey, "Ed25519", false, ["verify"]);
|
|
651
|
-
}
|
|
652
|
-
async verify(signatureHex, timestamp, body) {
|
|
653
|
-
const signature = hexToBytes(signatureHex, SIGNATURE_BYTES);
|
|
654
|
-
if (!signature) return false;
|
|
655
|
-
const timestampBytes = encoder.encode(timestamp);
|
|
656
|
-
const message = new Uint8Array(timestampBytes.length + body.length);
|
|
657
|
-
message.set(timestampBytes, 0);
|
|
658
|
-
message.set(body, timestampBytes.length);
|
|
659
|
-
return crypto.subtle.verify("Ed25519", await this.key, signature, message);
|
|
660
|
-
}
|
|
661
|
-
};
|
|
662
|
-
|
|
663
|
-
//#endregion
|
|
664
|
-
//#region src/receiver/ReplayGuard.ts
|
|
665
|
-
const REPLAY_WINDOW_MS = 3e5;
|
|
666
|
-
const SWEEP_GAP_MS = 6e4;
|
|
667
|
-
const MS_PER_SECOND = 1e3;
|
|
668
|
-
const TIMESTAMP_PATTERN = /^\d+$/;
|
|
669
|
-
var ReplayGuard = class {
|
|
670
|
-
seen = /* @__PURE__ */ new Map();
|
|
671
|
-
lastSweep = Date.now();
|
|
672
|
-
accepts(signatureHex, timestampHeader) {
|
|
673
|
-
const now = Date.now();
|
|
674
|
-
this.maybeSweep(now);
|
|
675
|
-
if (!TIMESTAMP_PATTERN.test(timestampHeader)) return false;
|
|
676
|
-
const timestampMs = Number(timestampHeader) * MS_PER_SECOND;
|
|
677
|
-
if (Math.abs(now - timestampMs) > REPLAY_WINDOW_MS) return false;
|
|
678
|
-
const rejectUntil = this.seen.get(signatureHex);
|
|
679
|
-
if (rejectUntil !== void 0 && rejectUntil >= now) return false;
|
|
680
|
-
this.seen.set(signatureHex, timestampMs + REPLAY_WINDOW_MS);
|
|
681
|
-
return true;
|
|
682
|
-
}
|
|
683
|
-
maybeSweep(now) {
|
|
684
|
-
if (now - this.lastSweep < SWEEP_GAP_MS) return;
|
|
685
|
-
this.lastSweep = now;
|
|
686
|
-
for (const [signature, rejectUntil] of this.seen) if (rejectUntil < now) this.seen.delete(signature);
|
|
302
|
+
return this;
|
|
303
|
+
}
|
|
304
|
+
static reset() {
|
|
305
|
+
super.reset();
|
|
306
|
+
_seedcord_logger.LoggerChannelRegistry.instance.reset();
|
|
307
|
+
}
|
|
308
|
+
registerStartupTasks() {
|
|
309
|
+
if (envapt.Envapter.isDevelopment || envapt.Envapter.isTest) this.registerHmrAwareModules();
|
|
310
|
+
const { interactions } = this;
|
|
311
|
+
if (interactions) this.startup.addTask(_seedcord_core_node_internal.StartupPhase.Configuration, "Interactions Initialization", async () => {
|
|
312
|
+
interactions.logger.utils.initialization("Interactions", "start");
|
|
313
|
+
await interactions.init();
|
|
314
|
+
interactions.logger.utils.initialization("Interactions", "end");
|
|
315
|
+
});
|
|
316
|
+
this.startup.addTask(_seedcord_core_node_internal.StartupPhase.Ready, "Http Server", () => this.listen());
|
|
317
|
+
if (!envapt.Envapter.isTest) this.startup.addTask(_seedcord_core_node_internal.StartupPhase.Ready, "Identity", () => this.fetchUsername());
|
|
318
|
+
const { healthCheck } = this;
|
|
319
|
+
if (healthCheck) this.startup.addTask(_seedcord_core_node_internal.StartupPhase.Ready, "Health Check", async () => {
|
|
320
|
+
healthCheck.logger.utils.initialization("HealthCheck", "start");
|
|
321
|
+
await healthCheck.init();
|
|
322
|
+
healthCheck.logger.utils.initialization("HealthCheck", "end");
|
|
323
|
+
});
|
|
687
324
|
}
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
const TIMESTAMP_HEADER = "x-signature-timestamp";
|
|
694
|
-
const ACCEPTED = 202;
|
|
695
|
-
const BAD_REQUEST = 400;
|
|
696
|
-
const UNAUTHORIZED = 401;
|
|
697
|
-
const METHOD_NOT_ALLOWED = 405;
|
|
698
|
-
const PING = discord_api_types_v10.InteractionType.Ping;
|
|
699
|
-
const decoder = new TextDecoder();
|
|
700
|
-
function hasInteractionType(payload) {
|
|
701
|
-
return typeof payload === "object" && payload !== null && "type" in payload && typeof payload.type === "number";
|
|
702
|
-
}
|
|
703
|
-
/**
|
|
704
|
-
* Builds the HTTP-interactions engine, a `(request, ctx?) => Promise<Response>` handler.
|
|
705
|
-
*
|
|
706
|
-
* The handler verifies the Ed25519 signature over the raw request bytes, rejects stale or replayed
|
|
707
|
-
* requests, answers a PING with an in-body PONG, and acks every other interaction with an empty 202.
|
|
708
|
-
* The engine dispatches a matched interaction through the manifest before the 202 goes out. Gates run
|
|
709
|
-
* first and the sender posts any refusal over the REST callback. `execute()` continues past the 202 under
|
|
710
|
-
* `ctx.waitUntil` when the caller passes one (the edge entry), and an engine-held in-flight set tracks
|
|
711
|
-
* it otherwise (node paths). It reads only the method, headers, and body. Mount it at any path.
|
|
712
|
-
*
|
|
713
|
-
* Reads `DISCORD_PUBLIC_KEY` and `DISCORD_BOT_TOKEN` from the environment through envapt and throws a
|
|
714
|
-
* `SeedcordError` when either is missing or malformed.
|
|
715
|
-
*/
|
|
716
|
-
function createSeedcord(config, manifest) {
|
|
717
|
-
if (!envapt.Envapter.has("DISCORD_PUBLIC_KEY")) throw new _seedcord_errors_internal.SeedcordError(_seedcord_errors.SeedcordErrorCode.ConfigMissingPublicKey);
|
|
718
|
-
const publicKey = envapt.Envapter.getRequired("DISCORD_PUBLIC_KEY", envapt.Converters.String);
|
|
719
|
-
const token = (0, _seedcord_errors_internal.validateDiscordToken)(envapt.Envapter.get("DISCORD_BOT_TOKEN"));
|
|
720
|
-
const verifier = new Ed25519Verifier(publicKey);
|
|
721
|
-
const replays = new ReplayGuard();
|
|
722
|
-
const maps = buildRouteMaps(manifest);
|
|
723
|
-
const inFlight = /* @__PURE__ */ new Set();
|
|
724
|
-
const core = createCore(config, token);
|
|
725
|
-
const logger = new _seedcord_logger.Logger("Engine");
|
|
726
|
-
async function dispatchMatched(match, payload, ctx) {
|
|
727
|
-
const start = await dispatchInteraction({
|
|
728
|
-
match,
|
|
729
|
-
payload,
|
|
730
|
-
core
|
|
325
|
+
registerHmrAwareModules() {
|
|
326
|
+
this.startup.addTask(_seedcord_core_node_internal.StartupPhase.Configuration, "HMR Registration", async () => {
|
|
327
|
+
if (this.interactions) this.hmrManager.register(this.interactions);
|
|
328
|
+
for (const plugin of this.plugins) this.hmrManager.register(plugin);
|
|
329
|
+
await Promise.resolve();
|
|
731
330
|
});
|
|
732
|
-
if (!start) return;
|
|
733
|
-
const work = start();
|
|
734
|
-
if (ctx) ctx.waitUntil(work);
|
|
735
|
-
else {
|
|
736
|
-
inFlight.add(work);
|
|
737
|
-
work.finally(() => inFlight.delete(work));
|
|
738
|
-
}
|
|
739
331
|
}
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
332
|
+
async listen() {
|
|
333
|
+
const token = (0, _seedcord_errors_internal.validateDiscordToken)(envapt.Envapter.get("DISCORD_BOT_TOKEN"));
|
|
334
|
+
this.rest.setToken(token);
|
|
335
|
+
const maps = this.interactions?.maps ?? require_edge_index.buildRouteMaps(EMPTY_MANIFEST);
|
|
336
|
+
const { handle, inFlight } = require_edge_index.buildEngine(this, maps);
|
|
337
|
+
const server = (0, node_http.createServer)((incoming, outgoing) => {
|
|
338
|
+
(async () => {
|
|
339
|
+
await writeWebResponse(await handle(await toWebRequest(incoming)), outgoing);
|
|
340
|
+
})().catch((error) => {
|
|
341
|
+
outgoing.destroy(Error.isError(error) ? error : new Error(String(error)));
|
|
342
|
+
});
|
|
744
343
|
});
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
}
|
|
757
|
-
if (!hasInteractionType(payload)) return new Response(null, { status: BAD_REQUEST });
|
|
758
|
-
if (payload.type === PING) return Response.json({ type: discord_api_types_v10.InteractionResponseType.Pong });
|
|
344
|
+
this.server = server;
|
|
345
|
+
server.listen(this.requestedPort);
|
|
346
|
+
await (0, node_events.once)(server, "listening");
|
|
347
|
+
this.boundPort = server.address().port;
|
|
348
|
+
this.logger.info(`Interactions server listening on port ${_seedcord_logger.paint.sky.bold(String(this.boundPort))}`);
|
|
349
|
+
this.shutdown.addTask(_seedcord_core_node_internal.ShutdownPhase.Unbind, "stop-http-server", () => this.stopServer(), SERVER_SHUTDOWN_TIMEOUT_MS);
|
|
350
|
+
this.shutdown.addTask(_seedcord_core_node_internal.ShutdownPhase.Drain, "drain-inflight", async () => {
|
|
351
|
+
await Promise.allSettled(inFlight);
|
|
352
|
+
}, DRAIN_TIMEOUT_MS);
|
|
353
|
+
}
|
|
354
|
+
async fetchUsername() {
|
|
759
355
|
try {
|
|
760
|
-
const
|
|
761
|
-
|
|
356
|
+
const me = await this.rest.get(discord_api_types_v10.Routes.user("@me"));
|
|
357
|
+
this.fetchedUsername = me.username;
|
|
762
358
|
} catch (caught) {
|
|
763
|
-
logger.
|
|
359
|
+
this.logger.warn("could not fetch the bot identity", caught);
|
|
764
360
|
}
|
|
765
|
-
return new Response(null, { status: ACCEPTED });
|
|
766
|
-
};
|
|
767
|
-
}
|
|
768
|
-
|
|
769
|
-
//#endregion
|
|
770
|
-
//#region src/handlers/interaction/SlashHandler.ts
|
|
771
|
-
/**
|
|
772
|
-
* Base class for a chat-input (slash) command handler on the HTTP transport.
|
|
773
|
-
*
|
|
774
|
-
* Pass the route from the generated registry as the generic, then read `this.options` for a single
|
|
775
|
-
* command or `this.match` for several. Command authoring stays plain discord.js, `seedcord codegen`
|
|
776
|
-
* reads its `toJSON()` to type these options.
|
|
777
|
-
*
|
|
778
|
-
* @typeParam Route - One or more route keys from {@link SlashOptionRegistry}, e.g. `'ban'` or `'ban' | 'kick'`.
|
|
779
|
-
*/
|
|
780
|
-
var SlashHandler = class extends InteractionHandler {
|
|
781
|
-
resolver;
|
|
782
|
-
/**
|
|
783
|
-
* The typed options for this command's route. Required options drop the null, choices narrow to their
|
|
784
|
-
* literal union, and only the getters for kinds this command actually uses appear. Rich kinds resolve
|
|
785
|
-
* from the interaction's `resolved` data.
|
|
786
|
-
*/
|
|
787
|
-
get options() {
|
|
788
|
-
this.resolver ??= new HttpSlashOptions(this.event.data);
|
|
789
|
-
return this.resolver;
|
|
790
|
-
}
|
|
791
|
-
/**
|
|
792
|
-
* Run the arm for whichever command fired. Use this only when the handler is registered for several
|
|
793
|
-
* routes.
|
|
794
|
-
*
|
|
795
|
-
* Provide one arm per registered route, keyed by its route string, and each arm receives that route's
|
|
796
|
-
* own narrowed options. The arms must cover every route in the generic, a missing route or an unknown
|
|
797
|
-
* key is a compile error.
|
|
798
|
-
*
|
|
799
|
-
* @param arms - One handler per registered route, keyed by route string.
|
|
800
|
-
* @returns The result of the arm that ran.
|
|
801
|
-
*/
|
|
802
|
-
async match(arms) {
|
|
803
|
-
const route = slashRouteOf(this.event.data);
|
|
804
|
-
const arm = Object.hasOwn(arms, route) ? arms[route] : void 0;
|
|
805
|
-
if (!arm) throw new _seedcord_errors_internal.SeedcordError(_seedcord_errors.SeedcordErrorCode.SlashMatchArmMissing, [route]);
|
|
806
|
-
return await arm(this.options);
|
|
807
|
-
}
|
|
808
|
-
};
|
|
809
|
-
|
|
810
|
-
//#endregion
|
|
811
|
-
//#region src/handlers/interaction/ContextMenuHandler.ts
|
|
812
|
-
/**
|
|
813
|
-
* Base class for a context-menu command handler on the HTTP transport (right-click a user or a message).
|
|
814
|
-
*
|
|
815
|
-
* Pass the kind from {@link ApplicationCommandType} as the generic. Read the right-clicked entity from
|
|
816
|
-
* `this.target`, an `APIUser` for a user menu and an `APIMessage` for a message menu. Context menus carry
|
|
817
|
-
* no options, so a handler registered for several names reads `this.target` uniformly with no per-name
|
|
818
|
-
* branch.
|
|
819
|
-
*
|
|
820
|
-
* @typeParam Kind - `ApplicationCommandType.User` or `ApplicationCommandType.Message`.
|
|
821
|
-
*/
|
|
822
|
-
var ContextMenuHandler = class extends InteractionHandler {
|
|
823
|
-
get target() {
|
|
824
|
-
const data = this.event.data;
|
|
825
|
-
return data.type === discord_api_types_v10.ApplicationCommandType.User ? data.resolved.users[data.target_id] : data.resolved.messages[data.target_id];
|
|
826
|
-
}
|
|
827
|
-
/**
|
|
828
|
-
* The right-clicked user's guild member, resolved only on user menus fired in a guild. Reading it on a
|
|
829
|
-
* message menu is a compile error.
|
|
830
|
-
*/
|
|
831
|
-
get targetMember() {
|
|
832
|
-
const data = this.event.data;
|
|
833
|
-
return data.type === discord_api_types_v10.ApplicationCommandType.User ? data.resolved.members?.[data.target_id] ?? null : null;
|
|
834
|
-
}
|
|
835
|
-
};
|
|
836
|
-
|
|
837
|
-
//#endregion
|
|
838
|
-
//#region src/handlers/interaction/components/ComponentHandler.ts
|
|
839
|
-
/**
|
|
840
|
-
* Shared base the customId-routed component handlers extend on the HTTP transport.
|
|
841
|
-
*
|
|
842
|
-
* Not a public entry point. Extend {@link ButtonHandler}, {@link SelectMenuHandler}, or {@link ModalHandler}
|
|
843
|
-
* instead. This class defines the customId decode, the route matching, and the source-message verbs
|
|
844
|
-
* `update` and `deferUpdate`.
|
|
845
|
-
*
|
|
846
|
-
* @typeParam Event - The component or modal interaction type this handler processes
|
|
847
|
-
* @typeParam Defs - The customId route definitions registered on the concrete handler
|
|
848
|
-
*/
|
|
849
|
-
var ComponentHandler = class extends InteractionHandler {
|
|
850
|
-
/** Rewrite the source message this component interaction came from. */
|
|
851
|
-
update(response) {
|
|
852
|
-
return this.sender.update(response);
|
|
853
|
-
}
|
|
854
|
-
/** Acknowledge the component without changing the source message. */
|
|
855
|
-
deferUpdate() {
|
|
856
|
-
return this.sender.deferUpdate();
|
|
857
|
-
}
|
|
858
|
-
decoded;
|
|
859
|
-
get route() {
|
|
860
|
-
this.decoded ??= (0, _seedcord_core_internal.decodeComponentRoute)(this.constructor, this.event.data.custom_id);
|
|
861
|
-
return this.decoded;
|
|
862
|
-
}
|
|
863
|
-
/**
|
|
864
|
-
* The decoded params of the single route this handler is registered for.
|
|
865
|
-
*
|
|
866
|
-
* Reading this decodes `this.event.data.custom_id` once (cached after the first read) and throws
|
|
867
|
-
* `StaleCustomId` or `InvalidCustomId` when the wire no longer matches the current shape, which the
|
|
868
|
-
* dispatcher boundary turns into a reply. On a handler registered for several routes this is
|
|
869
|
-
* `never`, so use {@link match} instead.
|
|
870
|
-
*/
|
|
871
|
-
get params() {
|
|
872
|
-
return this.route.params;
|
|
873
361
|
}
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
* ```ts
|
|
889
|
-
* \@ButtonRoute(Approve, Reject)
|
|
890
|
-
* class ReviewButtons extends ButtonHandler<[typeof Approve, typeof Reject]> {
|
|
891
|
-
* async execute() {
|
|
892
|
-
* await this.match({
|
|
893
|
-
* approve: ({ userId }) => this.reply(`approved <@${userId}>`),
|
|
894
|
-
* reject: ({ userId }) => this.reply(`rejected <@${userId}>`)
|
|
895
|
-
* });
|
|
896
|
-
* }
|
|
897
|
-
* }
|
|
898
|
-
* ```
|
|
899
|
-
*/
|
|
900
|
-
async match(arms) {
|
|
901
|
-
const { prefix, params } = this.route;
|
|
902
|
-
const arm = Object.hasOwn(arms, prefix) ? arms[prefix] : void 0;
|
|
903
|
-
if (!arm) throw new _seedcord_errors_internal.SeedcordError(_seedcord_errors.SeedcordErrorCode.CustomIdMatchArmMissing, [prefix]);
|
|
904
|
-
return await arm(params);
|
|
905
|
-
}
|
|
906
|
-
};
|
|
907
|
-
|
|
908
|
-
//#endregion
|
|
909
|
-
//#region src/handlers/interaction/components/ButtonHandler.ts
|
|
910
|
-
/**
|
|
911
|
-
* Base class for a button interaction handler on the HTTP transport.
|
|
912
|
-
*
|
|
913
|
-
* Register the customId definitions this handler decodes with `@ButtonRoute`, list the same ones in the
|
|
914
|
-
* generic, then read `this.params` for a single route or `this.match` for several. Reply through the
|
|
915
|
-
* handler members, or rewrite the source message with `this.update`. Passing different definitions to the
|
|
916
|
-
* decorator and the generic is a compile error.
|
|
917
|
-
*
|
|
918
|
-
* @typeParam Defs - The customId definitions this handler decodes, e.g. `[typeof ApproveId]`.
|
|
919
|
-
*/
|
|
920
|
-
var ButtonHandler = class extends ComponentHandler {};
|
|
921
|
-
|
|
922
|
-
//#endregion
|
|
923
|
-
//#region src/handlers/interaction/components/SelectMenuHandler.ts
|
|
924
|
-
/**
|
|
925
|
-
* Base class for a select menu handler on the HTTP transport.
|
|
926
|
-
*
|
|
927
|
-
* Pass the select kind first and the customId definitions second, the same order as `@SelectMenuRoute`,
|
|
928
|
-
* so `this.event.data` and its `values`/`resolved` are narrowed to that kind. Read `this.params` for a
|
|
929
|
-
* single route or `this.match` for several, and reply through the handler members or rewrite the source
|
|
930
|
-
* message with `this.update`.
|
|
931
|
-
*
|
|
932
|
-
* @typeParam Kind - The select kind from {@link SelectMenuKind}, e.g. `SelectMenuKind.User`.
|
|
933
|
-
* @typeParam Defs - The customId definitions this handler decodes, e.g. `[typeof AssignId]`.
|
|
934
|
-
*/
|
|
935
|
-
var SelectMenuHandler = class extends ComponentHandler {};
|
|
936
|
-
|
|
937
|
-
//#endregion
|
|
938
|
-
//#region src/handlers/interaction/components/ModalHandler.ts
|
|
939
|
-
/**
|
|
940
|
-
* Base class for a modal submit handler on the HTTP transport.
|
|
941
|
-
*
|
|
942
|
-
* Register the customId definitions this handler decodes with `@ModalRoute` and list the same ones in the
|
|
943
|
-
* generic. Read the submitted inputs off `this.event.data.components`. Reply through the handler members.
|
|
944
|
-
* Discord forbids opening a modal in response to a modal, so `showModal` fails compilation on this kind.
|
|
945
|
-
*
|
|
946
|
-
* @typeParam Defs - The customId definitions this handler decodes, e.g. `[typeof ConfigId]`.
|
|
947
|
-
*/
|
|
948
|
-
var ModalHandler = class extends ComponentHandler {
|
|
949
|
-
/** Rewrite the message this modal was opened from (only when a component opened it). */
|
|
950
|
-
update(response) {
|
|
951
|
-
this.ensureSourceMessage("update");
|
|
952
|
-
return super.update(response);
|
|
953
|
-
}
|
|
954
|
-
/** Silently acknowledge, leaving the source message untouched. */
|
|
955
|
-
deferUpdate() {
|
|
956
|
-
this.ensureSourceMessage("deferUpdate");
|
|
957
|
-
return super.deferUpdate();
|
|
958
|
-
}
|
|
959
|
-
ensureSourceMessage(method) {
|
|
960
|
-
if (this.event.message) return;
|
|
961
|
-
throw new _seedcord_errors_internal.SeedcordError(_seedcord_errors.SeedcordErrorCode.ReplyUpdateWithoutSource, [method, this.routeId]);
|
|
362
|
+
stopServer() {
|
|
363
|
+
const server = this.server;
|
|
364
|
+
if (!server?.listening) return Promise.resolve();
|
|
365
|
+
return new Promise((resolveClose, rejectClose) => {
|
|
366
|
+
server.close((err) => {
|
|
367
|
+
if (err) {
|
|
368
|
+
rejectClose(err);
|
|
369
|
+
return;
|
|
370
|
+
}
|
|
371
|
+
this.logger.info(_seedcord_logger.paint.coral.bold("Interactions server stopped"));
|
|
372
|
+
resolveClose();
|
|
373
|
+
});
|
|
374
|
+
server.closeIdleConnections();
|
|
375
|
+
});
|
|
962
376
|
}
|
|
963
377
|
};
|
|
964
378
|
|
|
965
|
-
//#endregion
|
|
966
|
-
//#region src/gates/Gated.ts
|
|
967
|
-
/**
|
|
968
|
-
* Attaches gates to an HTTP interaction handler. The gates run before `execute`, and a gate refusing stops
|
|
969
|
-
* the handler with the reply or drop the gate threw. Multiple gates are ANDed, so each must pass. A gate
|
|
970
|
-
* that requires a context the handler does not provide (a button gate on a slash handler, a gate on an
|
|
971
|
-
* autocomplete handler, or a `RequirePermissions([...], { in: 'guild' })` gate the http transport cannot
|
|
972
|
-
* satisfy) is a compile error at this line, and the error names the gate and the handler kind. Place it
|
|
973
|
-
* above the route decorator.
|
|
974
|
-
*
|
|
975
|
-
* Combine gates with {@link and} or {@link or} to build a single gate from multiple arms.
|
|
976
|
-
*
|
|
977
|
-
* @example
|
|
978
|
-
* ```ts
|
|
979
|
-
* import { PermissionFlagsBits } from 'discord-api-types/v10';
|
|
980
|
-
*
|
|
981
|
-
* \@Gated(GuildOnly(), RequirePermissions([PermissionFlagsBits.ManageMessages]))
|
|
982
|
-
* \@SlashRoute('purge')
|
|
983
|
-
* class Purge extends SlashHandler<'purge'> {
|
|
984
|
-
* async execute() {
|
|
985
|
-
* // both gates passed, so this runs in a guild with a caller who can moderate this channel
|
|
986
|
-
* }
|
|
987
|
-
* }
|
|
988
|
-
* ```
|
|
989
|
-
*
|
|
990
|
-
* @typeParam Gates - The non-empty tuple of gates to run, in order, against the handler's context.
|
|
991
|
-
* @typeParam TCtor - The decorated handler's constructor, checked against every gate's required context.
|
|
992
|
-
* @param gates - One or more gates to attach, each ANDed so the handler runs only when all pass.
|
|
993
|
-
* @param ctor - The handler class being decorated, rejected at compile time when a gate requires a context it lacks.
|
|
994
|
-
*
|
|
995
|
-
* @see {@link defineGate}
|
|
996
|
-
* @see {@link defineEffectGate}
|
|
997
|
-
* @decorator
|
|
998
|
-
*/
|
|
999
|
-
function Gated(...gates) {
|
|
1000
|
-
return function(ctor) {
|
|
1001
|
-
const existing = Reflect.getMetadata(_seedcord_core_internal.GatedMetadataKey, ctor) ?? [];
|
|
1002
|
-
Reflect.defineMetadata(_seedcord_core_internal.GatedMetadataKey, [...existing, ...gates], ctor);
|
|
1003
|
-
};
|
|
1004
|
-
}
|
|
1005
|
-
|
|
1006
379
|
//#endregion
|
|
1007
380
|
//#region src/index.ts
|
|
1008
|
-
|
|
1009
|
-
|
|
381
|
+
var src_exports = /* @__PURE__ */ require_edge_index.__exportAll({
|
|
382
|
+
AutocompleteHandler: () => require_edge_index.AutocompleteHandler,
|
|
383
|
+
ButtonHandler: () => require_edge_index.ButtonHandler,
|
|
384
|
+
ComponentHandler: () => require_edge_index.ComponentHandler,
|
|
385
|
+
ContextMenuHandler: () => require_edge_index.ContextMenuHandler,
|
|
386
|
+
Gated: () => require_edge_index.Gated,
|
|
387
|
+
InteractionHandler: () => require_edge_index.InteractionHandler,
|
|
388
|
+
ModalHandler: () => require_edge_index.ModalHandler,
|
|
389
|
+
RepliableHandler: () => require_edge_index.RepliableHandler,
|
|
390
|
+
Seedcord: () => Seedcord,
|
|
391
|
+
SelectMenuHandler: () => require_edge_index.SelectMenuHandler,
|
|
392
|
+
SlashHandler: () => require_edge_index.SlashHandler,
|
|
393
|
+
createSeedcord: () => require_edge_index.createSeedcord,
|
|
394
|
+
version: () => require_edge_index.version
|
|
395
|
+
});
|
|
1010
396
|
|
|
1011
397
|
//#endregion
|
|
1012
|
-
exports.AutocompleteHandler = AutocompleteHandler;
|
|
1013
|
-
exports.ButtonHandler = ButtonHandler;
|
|
1014
|
-
exports.ComponentHandler = ComponentHandler;
|
|
1015
|
-
exports.ContextMenuHandler = ContextMenuHandler;
|
|
1016
|
-
exports.Gated = Gated;
|
|
1017
|
-
exports.InteractionHandler = InteractionHandler;
|
|
1018
|
-
exports.ModalHandler = ModalHandler;
|
|
1019
|
-
exports.RepliableHandler = RepliableHandler;
|
|
1020
|
-
exports.
|
|
1021
|
-
exports.
|
|
1022
|
-
exports.
|
|
1023
|
-
exports.
|
|
398
|
+
exports.AutocompleteHandler = require_edge_index.AutocompleteHandler;
|
|
399
|
+
exports.ButtonHandler = require_edge_index.ButtonHandler;
|
|
400
|
+
exports.ComponentHandler = require_edge_index.ComponentHandler;
|
|
401
|
+
exports.ContextMenuHandler = require_edge_index.ContextMenuHandler;
|
|
402
|
+
exports.Gated = require_edge_index.Gated;
|
|
403
|
+
exports.InteractionHandler = require_edge_index.InteractionHandler;
|
|
404
|
+
exports.ModalHandler = require_edge_index.ModalHandler;
|
|
405
|
+
exports.RepliableHandler = require_edge_index.RepliableHandler;
|
|
406
|
+
exports.Seedcord = Seedcord;
|
|
407
|
+
exports.SelectMenuHandler = require_edge_index.SelectMenuHandler;
|
|
408
|
+
exports.SlashHandler = require_edge_index.SlashHandler;
|
|
409
|
+
exports.createSeedcord = require_edge_index.createSeedcord;
|
|
410
|
+
exports.version = require_edge_index.version;
|
|
411
|
+
var _seedcord_core = require("@seedcord/core");
|
|
1024
412
|
Object.keys(_seedcord_core).forEach(function (k) {
|
|
1025
413
|
if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
|
|
1026
414
|
enumerable: true,
|