@seedcord/http 0.1.0-next.0 → 0.1.0-next.2

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.
@@ -0,0 +1,1426 @@
1
+ //#region \0rolldown/runtime.js
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __exportAll = (all, no_symbols) => {
7
+ let target = {};
8
+ for (var name in all) {
9
+ __defProp(target, name, {
10
+ get: all[name],
11
+ enumerable: true
12
+ });
13
+ }
14
+ if (!no_symbols) {
15
+ __defProp(target, Symbol.toStringTag, { value: "Module" });
16
+ }
17
+ return target;
18
+ };
19
+ var __copyProps = (to, from, except, desc) => {
20
+ if (from && typeof from === "object" || typeof from === "function") {
21
+ for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
22
+ key = keys[i];
23
+ if (!__hasOwnProp.call(to, key) && key !== except) {
24
+ __defProp(to, key, {
25
+ get: ((k) => from[k]).bind(null, key),
26
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
27
+ });
28
+ }
29
+ }
30
+ }
31
+ return to;
32
+ };
33
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
34
+
35
+ //#endregion
36
+ let _seedcord_errors_internal = require("@seedcord/errors/internal");
37
+ let envapt = require("envapt");
38
+ let _discordjs_rest = require("@discordjs/rest");
39
+ let _seedcord_core = require("@seedcord/core");
40
+ let _seedcord_core_internal = require("@seedcord/core/internal");
41
+ let _seedcord_logger = require("@seedcord/logger");
42
+ let _seedcord_rate_limiter = require("@seedcord/rate-limiter");
43
+ let discord_api_types_v10 = require("discord-api-types/v10");
44
+ let _discordjs_core_http_only = require("@discordjs/core/http-only");
45
+ let _seedcord_utils_internal = require("@seedcord/utils/internal");
46
+ let _seedcord_errors = require("@seedcord/errors");
47
+
48
+ //#region src/reply/ReplySender.ts
49
+ function wireAllowedMentions(mentions) {
50
+ const { repliedUser, ...wire } = mentions;
51
+ return {
52
+ ...wire,
53
+ ...repliedUser !== void 0 && { replied_user: repliedUser }
54
+ };
55
+ }
56
+ function wireAttachments(files) {
57
+ if (!files?.some((file) => file.description)) return null;
58
+ return files.map((file, index) => ({
59
+ id: index,
60
+ ...file.name && { filename: file.name },
61
+ ...file.description && { description: file.description }
62
+ }));
63
+ }
64
+ function callbackData(reply, flags) {
65
+ const attachments = wireAttachments(reply.files);
66
+ return {
67
+ flags,
68
+ components: reply.components,
69
+ ...reply.allowedMentions && { allowed_mentions: wireAllowedMentions(reply.allowedMentions) },
70
+ ...attachments && { attachments }
71
+ };
72
+ }
73
+ /**
74
+ * Writes interaction responses over the Discord REST callback and webhook endpoints. Construction is
75
+ * internal to the repliable handler bases and the dispatcher.
76
+ */
77
+ var ReplySender = class extends _seedcord_core_internal.BaseReplySender {
78
+ ref;
79
+ rest;
80
+ constructor(ref, rest, routeId, bus) {
81
+ super(routeId, "unacked", bus && {
82
+ bus,
83
+ interactionId: ref.id
84
+ });
85
+ this.ref = ref;
86
+ this.rest = rest;
87
+ }
88
+ async writeReply(response, opts) {
89
+ const reply = this.serialize(response);
90
+ const result = await this.callback(discord_api_types_v10.InteractionResponseType.ChannelMessageWithSource, callbackData(reply, (0, _seedcord_core_internal.sendFlags)(opts)), reply.files);
91
+ return this.createdMessage(result);
92
+ }
93
+ async writeDefer(opts) {
94
+ await this.callback(discord_api_types_v10.InteractionResponseType.DeferredChannelMessageWithSource, { flags: (0, _seedcord_core_internal.deferFlags)(opts) });
95
+ }
96
+ async writeDeferUpdate() {
97
+ await this.callback(discord_api_types_v10.InteractionResponseType.DeferredMessageUpdate);
98
+ }
99
+ async writeUpdate(response) {
100
+ const reply = this.serialize(response);
101
+ const result = await this.callback(discord_api_types_v10.InteractionResponseType.UpdateMessage, callbackData(reply, discord_api_types_v10.MessageFlags.IsComponentsV2), reply.files);
102
+ return this.createdMessage(result);
103
+ }
104
+ async writeFollowUp(response, opts) {
105
+ const reply = this.serialize(response);
106
+ return await this.rest.post(discord_api_types_v10.Routes.webhook(this.ref.application_id, this.ref.token), {
107
+ body: callbackData(reply, (0, _seedcord_core_internal.sendFlags)(opts)),
108
+ query: new URLSearchParams({ wait: "true" }),
109
+ ...reply.files && { files: this.rawFiles(reply.files) }
110
+ });
111
+ }
112
+ writeEditOriginal(response) {
113
+ return this.editMessage(discord_api_types_v10.Routes.webhookMessage(this.ref.application_id, this.ref.token), this.serialize(response));
114
+ }
115
+ writeEditTarget(targetId, response) {
116
+ const route = discord_api_types_v10.Routes.webhookMessage(this.ref.application_id, this.ref.token, targetId);
117
+ return this.editMessage(route, this.serialize(response));
118
+ }
119
+ async writeDeleteOriginal() {
120
+ await this.rest.delete(discord_api_types_v10.Routes.webhookMessage(this.ref.application_id, this.ref.token));
121
+ }
122
+ async writeDeleteTarget(targetId) {
123
+ await this.rest.delete(discord_api_types_v10.Routes.webhookMessage(this.ref.application_id, this.ref.token, targetId));
124
+ }
125
+ async writeModal(data) {
126
+ await this.callback(discord_api_types_v10.InteractionResponseType.Modal, data);
127
+ }
128
+ async callback(type, data, files) {
129
+ const withResponse = type === discord_api_types_v10.InteractionResponseType.ChannelMessageWithSource || type === discord_api_types_v10.InteractionResponseType.UpdateMessage;
130
+ return await this.rest.post(discord_api_types_v10.Routes.interactionCallback(this.ref.id, this.ref.token), {
131
+ body: {
132
+ type,
133
+ ...data !== void 0 && { data }
134
+ },
135
+ ...withResponse && { query: new URLSearchParams({ with_response: "true" }) },
136
+ ...files && { files: this.rawFiles(files) }
137
+ });
138
+ }
139
+ async editMessage(route, reply) {
140
+ return await this.rest.patch(route, {
141
+ body: callbackData(reply, discord_api_types_v10.MessageFlags.IsComponentsV2),
142
+ ...reply.files && { files: this.rawFiles(reply.files) }
143
+ });
144
+ }
145
+ rawFiles(files) {
146
+ return files.map((file, index) => ({
147
+ name: file.name ?? `file-${index}`,
148
+ data: file.attachment
149
+ }));
150
+ }
151
+ createdMessage(result) {
152
+ return result.resource?.message;
153
+ }
154
+ };
155
+
156
+ //#endregion
157
+ //#region src/api.ts
158
+ const apis = /* @__PURE__ */ new WeakMap();
159
+ function apiFor(rest) {
160
+ let api = apis.get(rest);
161
+ if (!api) {
162
+ api = new _discordjs_core_http_only.API(rest);
163
+ apis.set(rest, api);
164
+ }
165
+ return api;
166
+ }
167
+
168
+ //#endregion
169
+ //#region src/handlers/RepliableHandler.ts
170
+ /**
171
+ * Shared base the repliable HTTP interaction handlers extend.
172
+ *
173
+ * Not a public entry point. Extend {@link SlashHandler}, {@link ButtonHandler}, {@link ModalHandler},
174
+ * {@link SelectMenuHandler}, or {@link ContextMenuHandler} instead. This class binds the core reply base
175
+ * to the http sender.
176
+ *
177
+ * @typeParam Event - The repliable interaction type this handler processes
178
+ */
179
+ var RepliableHandler = class extends _seedcord_core.RepliableHandler {
180
+ buildSender(event, core, routeId) {
181
+ return new ReplySender({
182
+ application_id: event.application_id,
183
+ id: event.id,
184
+ token: event.token
185
+ }, core.rest, routeId, core.bus);
186
+ }
187
+ /**
188
+ * Typed Discord REST API (`@discordjs/core/http-only`) over `core.rest`, one instance per core.
189
+ * The interaction callbacks on `api.interactions` bypass the reply surface. The
190
+ * `no-raw-interaction-acks` rule flags them in handler classes.
191
+ */
192
+ get api() {
193
+ return apiFor(this.core.rest);
194
+ }
195
+ };
196
+
197
+ //#endregion
198
+ //#region src/gates/context.ts
199
+ function interactionGateContext(payload, core, routeId) {
200
+ const member = payload.member ?? null;
201
+ const resolved = member?.user ?? payload.user;
202
+ return {
203
+ kind: "interaction",
204
+ core,
205
+ interaction: payload,
206
+ user: resolved,
207
+ member,
208
+ userId: resolved?.id ?? null,
209
+ guildId: payload.guild_id ?? null,
210
+ channelId: payload.channel?.id ?? null,
211
+ memberRoleIds: member?.roles ?? [],
212
+ memberPermissions: member ? BigInt(member.permissions) : null,
213
+ appPermissions: BigInt(payload.app_permissions),
214
+ routeId
215
+ };
216
+ }
217
+
218
+ //#endregion
219
+ //#region src/dispatch/slashRouteOf.ts
220
+ /**
221
+ * Computes the dispatch route for a chat-input or autocomplete payload, the raw-payload port of the
222
+ * gateway's `slashRouteOf`. Both assemble keys through `buildSlashRoute`, so a dispatched interaction
223
+ * and a generated registry key always match.
224
+ */
225
+ function slashRouteOf(data) {
226
+ const first = data.options?.[0];
227
+ if (first?.type === discord_api_types_v10.ApplicationCommandOptionType.SubcommandGroup) return (0, _seedcord_utils_internal.buildSlashRoute)(data.name, first.options[0]?.name, first.name);
228
+ if (first?.type === discord_api_types_v10.ApplicationCommandOptionType.Subcommand) return (0, _seedcord_utils_internal.buildSlashRoute)(data.name, first.name);
229
+ return data.name;
230
+ }
231
+
232
+ //#endregion
233
+ //#region src/dispatch/reportFault.ts
234
+ let faultLogger;
235
+ function logger$1() {
236
+ faultLogger ??= new _seedcord_logger.Logger("Faults", { channel: "errors" });
237
+ return faultLogger;
238
+ }
239
+ /**
240
+ * Publishes a fault on the bus, the raw-payload equivalent of the reporting half of gateway's
241
+ * `extractErrorResponse`. A reported {@link Notice} publishes `handledException`, everything else
242
+ * publishes `unknownException`.
243
+ *
244
+ * @internal
245
+ */
246
+ function reportFault(error, uuid, payload, core) {
247
+ const throttle = _seedcord_core_internal.FaultThrottle.for(core);
248
+ const key = `${routeKeyOf(payload)}:${nameOf(error)}`;
249
+ if (!throttle.shouldReport(key)) {
250
+ logger$1().debug(`throttled duplicate fault ${_seedcord_logger.paint.mute(key)}`);
251
+ return;
252
+ }
253
+ const source = interactionSource(payload);
254
+ if (error instanceof _seedcord_core.Notice && source) core.bus[_seedcord_core_internal.PublishDefault]("handledException", {
255
+ denial: error,
256
+ uuid,
257
+ source
258
+ });
259
+ else core.bus[_seedcord_core_internal.PublishDefault]("unknownException", {
260
+ uuid,
261
+ error,
262
+ ...actors(payload),
263
+ metadata: payload
264
+ });
265
+ throttle.markReported(key);
266
+ }
267
+ function routeKeyOf(payload) {
268
+ if (payload.type === discord_api_types_v10.InteractionType.ApplicationCommandAutocomplete) return `autocomplete:${slashRouteOf(payload.data)}`;
269
+ if (payload.type === discord_api_types_v10.InteractionType.ApplicationCommand) return payload.data.type === discord_api_types_v10.ApplicationCommandType.ChatInput ? slashRouteOf(payload.data) : payload.data.name;
270
+ return (0, _seedcord_core_internal.prefixOf)(payload.data.custom_id) || payload.data.custom_id;
271
+ }
272
+ function nameOf(error) {
273
+ if (error instanceof _seedcord_core.Notice) return error.name;
274
+ if (error instanceof _discordjs_rest.DiscordAPIError) return String(error.code);
275
+ return error.constructor.name;
276
+ }
277
+ function actors(payload) {
278
+ const user = payload.member?.user ?? payload.user;
279
+ return {
280
+ guild: void 0,
281
+ user: user ? {
282
+ id: user.id,
283
+ username: user.username
284
+ } : void 0
285
+ };
286
+ }
287
+ function interactionSource(payload) {
288
+ const user = payload.member?.user ?? payload.user;
289
+ if (!user) return null;
290
+ const common = {
291
+ kind: "interaction",
292
+ userId: user.id,
293
+ guildId: payload.guild_id ?? null,
294
+ channelId: payload.channel?.id ?? null,
295
+ interactionId: payload.id,
296
+ raw: payload
297
+ };
298
+ if (payload.type === discord_api_types_v10.InteractionType.ApplicationCommand) {
299
+ const isSlash = payload.data.type === discord_api_types_v10.ApplicationCommandType.ChatInput;
300
+ return {
301
+ ...common,
302
+ interactionKind: isSlash ? "slash" : "context-menu",
303
+ command: routeKeyOf(payload),
304
+ customId: null
305
+ };
306
+ }
307
+ if (payload.type === discord_api_types_v10.InteractionType.ModalSubmit) return {
308
+ ...common,
309
+ interactionKind: "modal",
310
+ command: null,
311
+ customId: payload.data.custom_id
312
+ };
313
+ if (payload.type === discord_api_types_v10.InteractionType.MessageComponent) {
314
+ const isButton = payload.data.component_type === discord_api_types_v10.ComponentType.Button;
315
+ return {
316
+ ...common,
317
+ interactionKind: isButton ? "button" : "select",
318
+ command: null,
319
+ customId: payload.data.custom_id
320
+ };
321
+ }
322
+ return null;
323
+ }
324
+
325
+ //#endregion
326
+ //#region src/dispatch/dispatchInteraction.ts
327
+ let dispatchLogger;
328
+ function logger() {
329
+ dispatchLogger ??= new _seedcord_logger.Logger("Dispatcher", { channel: "interactions" });
330
+ return dispatchLogger;
331
+ }
332
+ function createCore(config, token) {
333
+ const draft = {
334
+ config,
335
+ rateLimiter: config.store ?? new _seedcord_rate_limiter.MemoryRateLimiter(),
336
+ rest: new _discordjs_rest.REST().setToken(token)
337
+ };
338
+ draft.bus = new _seedcord_core.Bus(draft);
339
+ return draft;
340
+ }
341
+ function isHandlerCtor(value) {
342
+ return typeof value === "function" && value.prototype instanceof _seedcord_core.BaseHandler;
343
+ }
344
+ const HARMLESS_API_CODES = new Set([
345
+ discord_api_types_v10.RESTJSONErrorCodes.UnknownInteraction,
346
+ discord_api_types_v10.RESTJSONErrorCodes.InteractionHasAlreadyBeenAcknowledged,
347
+ discord_api_types_v10.RESTJSONErrorCodes.UnknownMessage
348
+ ]);
349
+ async function sendGuarded(routeId, send) {
350
+ try {
351
+ await send();
352
+ } catch (error) {
353
+ if (error instanceof _discordjs_rest.DiscordAPIError && HARMLESS_API_CODES.has(error.code)) {
354
+ logger().debug(`boundary send hit harmless code ${_seedcord_logger.paint.amber(String(error.code))}`);
355
+ return;
356
+ }
357
+ logger().error(`boundary send failed for route ${_seedcord_logger.paint.sky.bold(routeId)}`, error);
358
+ }
359
+ }
360
+ async function respondEmptyChoices(scope) {
361
+ await (0, _seedcord_core_internal.reportedWrite)({
362
+ bus: scope.core.bus,
363
+ interactionId: scope.payload.id
364
+ }, scope.routeId, "respond", () => scope.core.rest.post(discord_api_types_v10.Routes.interactionCallback(scope.payload.id, scope.payload.token), { body: {
365
+ type: discord_api_types_v10.InteractionResponseType.ApplicationCommandAutocompleteResult,
366
+ data: { choices: [] }
367
+ } }));
368
+ }
369
+ function renderContext(core, uuid) {
370
+ const developerUsername = core.config.notifications?.developerUsername;
371
+ return developerUsername === void 0 ? { uuid } : {
372
+ uuid,
373
+ developerUsername
374
+ };
375
+ }
376
+ async function handleNotice(notice, uuid, scope) {
377
+ if (notice.report) {
378
+ logger().error(`${notice.name}: ${_seedcord_logger.paint.mute(uuid)}`, notice);
379
+ reportFault(notice, uuid, scope.payload, scope.core);
380
+ }
381
+ const { sender } = scope;
382
+ if (!sender) {
383
+ await sendGuarded(scope.routeId, () => respondEmptyChoices(scope));
384
+ return;
385
+ }
386
+ const response = notice.render(renderContext(scope.core, uuid));
387
+ await sendGuarded(scope.routeId, () => sender.send(response, { ephemeral: notice.ephemeral }));
388
+ }
389
+ async function handleRawFault(error, uuid, scope) {
390
+ const { core, sender } = scope;
391
+ if (core.config.errors?.errorStack ?? false) logger().error(_seedcord_logger.paint.mute(uuid), error);
392
+ else logger().error(`${_seedcord_logger.paint.mute(uuid)} | ${error.message}`);
393
+ reportFault(error, uuid, scope.payload, core);
394
+ if (!sender) {
395
+ await sendGuarded(scope.routeId, () => respondEmptyChoices(scope));
396
+ return;
397
+ }
398
+ const override = core.config.errors?.defaultError;
399
+ const response = (override ? new override(uuid) : new _seedcord_core.Fault()).render(renderContext(core, uuid));
400
+ await sendGuarded(scope.routeId, () => sender.send(response, { ephemeral: true }));
401
+ }
402
+ async function handleFault(caught, scope) {
403
+ if (caught instanceof _seedcord_core.Silence) {
404
+ if (caught.reason !== void 0) logger().debug(`Silence: ${caught.reason}`);
405
+ return;
406
+ }
407
+ const uuid = crypto.randomUUID();
408
+ if (caught instanceof _seedcord_core.Notice) {
409
+ await handleNotice(caught, uuid, scope);
410
+ return;
411
+ }
412
+ const error = (0, _seedcord_core_internal.asError)(caught);
413
+ const ignore = new Set(scope.core.config.errors?.ignoreApiCodes ?? []);
414
+ if (error instanceof _discordjs_rest.DiscordAPIError && ignore.has(error.code)) {
415
+ logger().debug(`swallowed api code ${_seedcord_logger.paint.amber(String(error.code))}`);
416
+ return;
417
+ }
418
+ await handleRawFault(error, uuid, scope);
419
+ }
420
+ function unhandledRouteId(match) {
421
+ if (match.routeId) return match.routeId;
422
+ const key = match.attemptedKey ?? "";
423
+ return `${match.kind}:${key.length > 0 ? key : "unrouted"}`;
424
+ }
425
+ function freshScope(match, payload, core) {
426
+ const ref = {
427
+ application_id: payload.application_id,
428
+ id: payload.id,
429
+ token: payload.token
430
+ };
431
+ const routeId = unhandledRouteId(match);
432
+ return {
433
+ core,
434
+ payload,
435
+ routeId,
436
+ sender: match.kind === "autocomplete" ? null : new ReplySender(ref, core.rest, routeId, core.bus)
437
+ };
438
+ }
439
+ function dispatchReporter(match, payload, core) {
440
+ const startedAt = performance.now();
441
+ const queuedMs = (0, _seedcord_core_internal.queuedMsFor)(payload.id);
442
+ return (outcome) => {
443
+ core.bus[_seedcord_core_internal.PublishDefault]("interactionDispatched", (0, _seedcord_core_internal.dispatchedPayload)({
444
+ routeId: unhandledRouteId(match),
445
+ interactionId: payload.id,
446
+ kind: match.kind,
447
+ outcome,
448
+ fallback: match.routeId === null,
449
+ startedAt,
450
+ queuedMs
451
+ }));
452
+ };
453
+ }
454
+ async function answer(caught, scope, report, outcome = (0, _seedcord_core_internal.outcomeFor)(caught)) {
455
+ try {
456
+ await handleFault(caught, scope);
457
+ } finally {
458
+ report(outcome);
459
+ }
460
+ }
461
+ async function loadHandlerCtor(match, payload, core, report) {
462
+ const routeId = unhandledRouteId(match);
463
+ let exported;
464
+ try {
465
+ exported = await match.load();
466
+ } catch (caught) {
467
+ logger().error(`Route ${_seedcord_logger.paint.sky.bold(routeId)} failed to load its handler.`, caught);
468
+ await answer(caught, freshScope(match, payload, core), report, "failed");
469
+ return null;
470
+ }
471
+ if (isHandlerCtor(exported)) return exported;
472
+ logger().error(`Route ${_seedcord_logger.paint.sky.bold(routeId)} loaded an export that is not a handler class.`);
473
+ await answer(/* @__PURE__ */ new Error(`route ${routeId} loaded an export that is not a handler class`), freshScope(match, payload, core), report, "failed");
474
+ return null;
475
+ }
476
+ /**
477
+ * Runs the pre-ack phase for a matched interaction. Loads the route's handler class, constructs it, and
478
+ * runs its gates, and the sender posts any refusal. Returns the post-ack execute continuation, or null
479
+ * when a gate refuses or nothing can run.
480
+ */
481
+ async function dispatchInteraction(args) {
482
+ const { match, payload, core } = args;
483
+ const report = dispatchReporter(match, payload, core);
484
+ const ctor = await loadHandlerCtor(match, payload, core, report);
485
+ if (!ctor) return null;
486
+ const dispatch = new _seedcord_core.DispatchContext(unhandledRouteId(match));
487
+ let handler;
488
+ try {
489
+ handler = new ctor(payload, core, dispatch);
490
+ } catch (caught) {
491
+ await answer(caught, freshScope(match, payload, core), report);
492
+ return null;
493
+ }
494
+ const scope = {
495
+ core,
496
+ payload,
497
+ routeId: unhandledRouteId(match),
498
+ sender: handler instanceof RepliableHandler ? handler.getSender() : null
499
+ };
500
+ const refusal = await gateRefusal(ctor, match, payload, core);
501
+ if (refusal) {
502
+ await answer(refusal.caught, scope, report);
503
+ return null;
504
+ }
505
+ return async () => {
506
+ try {
507
+ await handler.execute();
508
+ report("handled");
509
+ } catch (caught) {
510
+ await answer(caught, scope, report);
511
+ }
512
+ };
513
+ }
514
+ async function gateRefusal(ctor, match, payload, core) {
515
+ if (match.kind === "autocomplete" || payload.type === discord_api_types_v10.InteractionType.ApplicationCommandAutocomplete) return null;
516
+ const monitor = (0, _seedcord_core_internal.slowGateMonitor)();
517
+ try {
518
+ await (0, _seedcord_core_internal.runHandlerGates)(ctor, interactionGateContext(payload, core, match.routeId), match.routeId ?? void 0, monitor?.observe);
519
+ return null;
520
+ } catch (caught) {
521
+ return { caught };
522
+ } finally {
523
+ monitor?.report(match.routeId);
524
+ }
525
+ }
526
+
527
+ //#endregion
528
+ //#region src/dispatch/registerSubscribers.ts
529
+ /**
530
+ * Registers a manifest's subscribers on the bus without importing them. Each row's module loads on
531
+ * the first publish of one of its keys, which keeps an isolate that never publishes free of the cost.
532
+ *
533
+ * @internal
534
+ */
535
+ function registerSubscribers(bus, manifest) {
536
+ for (const row of manifest.subscriberRoutes) bus.register({
537
+ keys: row.keys,
538
+ frequency: row.frequency,
539
+ resolve: async () => {
540
+ const keys = row.keys.join(", ");
541
+ let module;
542
+ try {
543
+ module = await row.load();
544
+ } catch (caught) {
545
+ throw new _seedcord_errors_internal.SeedcordError(_seedcord_errors.SeedcordErrorCode.RouteModuleLoadFailed, [keys, row.from], { cause: caught });
546
+ }
547
+ if (!Object.hasOwn(module, row.exportName)) throw new _seedcord_errors_internal.SeedcordError(_seedcord_errors.SeedcordErrorCode.InteractionRouteExportMissing, [
548
+ keys,
549
+ row.exportName,
550
+ row.from
551
+ ]);
552
+ const exported = module[row.exportName];
553
+ if (typeof exported !== "function" || !(exported.prototype instanceof _seedcord_core.Subscriber)) throw new _seedcord_errors_internal.SeedcordError(_seedcord_errors.SeedcordErrorCode.SubscriberRouteNotASubscriber, [
554
+ keys,
555
+ row.exportName,
556
+ row.from
557
+ ]);
558
+ return exported;
559
+ }
560
+ });
561
+ }
562
+
563
+ //#endregion
564
+ //#region src/inputs/HttpSlashOptions.ts
565
+ var HttpSlashOptions = class {
566
+ leaves = /* @__PURE__ */ new Map();
567
+ resolved;
568
+ constructor(data) {
569
+ this.resolved = data.resolved;
570
+ let options = data.options ?? [];
571
+ const first = options[0];
572
+ if (first?.type === discord_api_types_v10.ApplicationCommandOptionType.SubcommandGroup) options = first.options;
573
+ const second = options[0];
574
+ if (second?.type === discord_api_types_v10.ApplicationCommandOptionType.Subcommand) options = second.options ?? [];
575
+ 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);
576
+ }
577
+ getString(name) {
578
+ const leaf = this.leaves.get(name);
579
+ return leaf?.type === discord_api_types_v10.ApplicationCommandOptionType.String ? leaf.value : null;
580
+ }
581
+ getInteger(name) {
582
+ const leaf = this.leaves.get(name);
583
+ return leaf?.type === discord_api_types_v10.ApplicationCommandOptionType.Integer ? numeric(leaf.value) : null;
584
+ }
585
+ getNumber(name) {
586
+ const leaf = this.leaves.get(name);
587
+ return leaf?.type === discord_api_types_v10.ApplicationCommandOptionType.Number ? numeric(leaf.value) : null;
588
+ }
589
+ getBoolean(name) {
590
+ const leaf = this.leaves.get(name);
591
+ return leaf?.type === discord_api_types_v10.ApplicationCommandOptionType.Boolean ? leaf.value : null;
592
+ }
593
+ getUser(name) {
594
+ const leaf = this.leaves.get(name);
595
+ if (leaf?.type !== discord_api_types_v10.ApplicationCommandOptionType.User) return null;
596
+ return this.resolved?.users?.[leaf.value] ?? null;
597
+ }
598
+ getMember(name) {
599
+ const leaf = this.leaves.get(name);
600
+ if (leaf?.type !== discord_api_types_v10.ApplicationCommandOptionType.User) return null;
601
+ return this.resolved?.members?.[leaf.value] ?? null;
602
+ }
603
+ getChannel(name) {
604
+ const leaf = this.leaves.get(name);
605
+ if (leaf?.type !== discord_api_types_v10.ApplicationCommandOptionType.Channel) return null;
606
+ return this.resolved?.channels?.[leaf.value] ?? null;
607
+ }
608
+ getRole(name) {
609
+ const leaf = this.leaves.get(name);
610
+ if (leaf?.type !== discord_api_types_v10.ApplicationCommandOptionType.Role) return null;
611
+ return this.resolved?.roles?.[leaf.value] ?? null;
612
+ }
613
+ getAttachment(name) {
614
+ const leaf = this.leaves.get(name);
615
+ if (leaf?.type !== discord_api_types_v10.ApplicationCommandOptionType.Attachment) return null;
616
+ return this.resolved?.attachments?.[leaf.value] ?? null;
617
+ }
618
+ getMentionable(name) {
619
+ const leaf = this.leaves.get(name);
620
+ if (leaf?.type !== discord_api_types_v10.ApplicationCommandOptionType.Mentionable) return null;
621
+ const resolved = this.resolved;
622
+ return resolved?.members?.[leaf.value] ?? resolved?.users?.[leaf.value] ?? resolved?.roles?.[leaf.value] ?? null;
623
+ }
624
+ getFocused() {
625
+ for (const leaf of this.leaves.values()) if ("focused" in leaf && leaf.focused === true) return {
626
+ name: leaf.name,
627
+ value: String(leaf.value)
628
+ };
629
+ return null;
630
+ }
631
+ };
632
+ function numeric(value) {
633
+ if (typeof value === "number") return value;
634
+ if (value.trim() === "") return null;
635
+ const parsed = Number(value);
636
+ return Number.isNaN(parsed) ? null : parsed;
637
+ }
638
+
639
+ //#endregion
640
+ //#region src/handlers/interaction/AutocompleteHandler.ts
641
+ /**
642
+ * Base class for an autocomplete handler on the HTTP transport.
643
+ *
644
+ * Pass the command route(s) from the generated registry as the generic. Branch on the focused field with
645
+ * `this.match`, read already-entered sibling options with `this.options`, and find which command fired
646
+ * with `this.route`.
647
+ *
648
+ * @typeParam Route - One or more route keys from {@link SlashOptionRegistry}, e.g. `'search'`.
649
+ */
650
+ var AutocompleteHandler = class extends _seedcord_core.BaseHandler {
651
+ constructor(event, core, dispatch) {
652
+ super(event, core, dispatch, "interactions");
653
+ }
654
+ /**
655
+ * Typed Discord REST API (`@discordjs/core/http-only`) over `core.rest`, one instance per core.
656
+ */
657
+ get api() {
658
+ return apiFor(this.core.rest);
659
+ }
660
+ resolver;
661
+ get reader() {
662
+ this.resolver ??= new HttpSlashOptions(this.event.data);
663
+ return this.resolver;
664
+ }
665
+ /**
666
+ * The focused option for this interaction. `value` is always the raw partial string the user is typing,
667
+ * even for an integer or number option, so coerce it yourself when you need a number.
668
+ */
669
+ get focused() {
670
+ const focused = this.reader.getFocused();
671
+ if (!focused) throw new _seedcord_errors_internal.SeedcordError(_seedcord_errors.SeedcordErrorCode.AutocompleteNoFocusedOption);
672
+ return focused;
673
+ }
674
+ /**
675
+ * Run the arm for the focused field. An autocomplete always dispatches by which field is focused, so
676
+ * match is how you read it.
677
+ *
678
+ * Provide one arm per autocompletable field across the registered commands, keyed by field name. Each
679
+ * arm receives the focused partial value and a `respond` typed to that field's choice value. The
680
+ * arms must cover every autocompletable field, a missing field or an unknown key is a compile error. A
681
+ * focused field with no arm, only reachable from a stale-deployed command, throws at runtime.
682
+ *
683
+ * @param arms - One handler per autocompletable field, keyed by field name.
684
+ * @returns The result of the arm that ran.
685
+ */
686
+ async match(arms) {
687
+ const { name, value } = this.focused;
688
+ const respond = (choices) => this.respond(choices);
689
+ const arm = Object.hasOwn(arms, name) ? arms[name] : void 0;
690
+ if (!arm) throw new _seedcord_errors_internal.SeedcordError(_seedcord_errors.SeedcordErrorCode.AutocompleteMatchArmMissing, [name]);
691
+ return await arm(value, respond);
692
+ }
693
+ /** Send autocomplete suggestions, callback type 8. Prefer {@link match}, which restricts each field's choices to its declared type. */
694
+ async respond(choices) {
695
+ const routeId = this.dispatch?.routeId ?? "autocomplete";
696
+ await (0, _seedcord_core_internal.reportedWrite)({
697
+ bus: this.core.bus,
698
+ interactionId: this.event.id
699
+ }, routeId, "respond", () => this.core.rest.post(discord_api_types_v10.Routes.interactionCallback(this.event.id, this.event.token), { body: {
700
+ type: discord_api_types_v10.InteractionResponseType.ApplicationCommandAutocompleteResult,
701
+ data: { choices }
702
+ } }));
703
+ }
704
+ /** The firing command route, for a field whose completion differs per registered command. */
705
+ get route() {
706
+ return slashRouteOf(this.event.data);
707
+ }
708
+ /**
709
+ * The already-entered options on this command, restricted to the kinds Discord resolves during autocomplete
710
+ * (string, integer, number, boolean) with every read nullable, since a sibling is partial while the user
711
+ * types the focused field. The focused field is on `this.focused`.
712
+ */
713
+ get options() {
714
+ return this.reader;
715
+ }
716
+ };
717
+
718
+ //#endregion
719
+ //#region src/handlers/defaults/UnhandledAutocomplete.ts
720
+ /**
721
+ * Default handler for autocomplete no manifest row matches.
722
+ * Empty choices are the only legal answer, they clear the pending state.
723
+ *
724
+ * @internal
725
+ */
726
+ var UnhandledAutocomplete = class extends AutocompleteHandler {
727
+ async execute() {
728
+ await this.respond([]);
729
+ }
730
+ };
731
+
732
+ //#endregion
733
+ //#region src/handlers/interaction/InteractionHandler.ts
734
+ /**
735
+ * Shared base the repliable interaction handlers extend.
736
+ *
737
+ * Not a public entry point. Extend {@link SlashHandler}, {@link ContextMenuHandler}, {@link ButtonHandler},
738
+ * {@link SelectMenuHandler}, or {@link ModalHandler} instead. This class adds `showModal` on top of the
739
+ * reply members.
740
+ *
741
+ * @typeParam Event - The repliable interaction type this handler processes
742
+ */
743
+ var InteractionHandler = class extends RepliableHandler {
744
+ constructor(event, core, dispatch) {
745
+ super(event, core, dispatch);
746
+ }
747
+ /**
748
+ * Open a modal. Must be the initial response to this interaction. The modal kind rejects this call at
749
+ * compile time (Discord forbids a modal in response to a modal).
750
+ */
751
+ showModal(modal) {
752
+ return this.sender.showModal(modal);
753
+ }
754
+ };
755
+
756
+ //#endregion
757
+ //#region src/handlers/defaults/UnhandledRepliable.ts
758
+ /**
759
+ * Default handler for interactions no manifest row matches. A reply failure here
760
+ * goes directly to the dispatch fault boundary, so it needs no guard of its own.
761
+ *
762
+ * @internal
763
+ */
764
+ var UnhandledRepliable = class extends InteractionHandler {
765
+ async execute() {
766
+ await this.reply("Feature not implemented yet.");
767
+ }
768
+ };
769
+
770
+ //#endregion
771
+ //#region src/dispatch/resolve.ts
772
+ const COMPONENT_KIND = {
773
+ button: "button",
774
+ stringSelect: "stringMenu",
775
+ userSelect: "userMenu",
776
+ roleSelect: "roleMenu",
777
+ channelSelect: "channelMenu",
778
+ mentionableSelect: "mentionableMenu",
779
+ modal: "modal"
780
+ };
781
+ function commandKind(type) {
782
+ switch (type) {
783
+ case discord_api_types_v10.ApplicationCommandType.ChatInput: return "slash";
784
+ case discord_api_types_v10.ApplicationCommandType.User: return "userContextMenu";
785
+ case discord_api_types_v10.ApplicationCommandType.Message: return "messageContextMenu";
786
+ default: return null;
787
+ }
788
+ }
789
+ function componentMapKey(type) {
790
+ switch (type) {
791
+ case discord_api_types_v10.ComponentType.Button: return "button";
792
+ case discord_api_types_v10.ComponentType.StringSelect: return "stringSelect";
793
+ case discord_api_types_v10.ComponentType.UserSelect: return "userSelect";
794
+ case discord_api_types_v10.ComponentType.RoleSelect: return "roleSelect";
795
+ case discord_api_types_v10.ComponentType.ChannelSelect: return "channelSelect";
796
+ case discord_api_types_v10.ComponentType.MentionableSelect: return "mentionableSelect";
797
+ default: return null;
798
+ }
799
+ }
800
+ function namedExport(routeId, row) {
801
+ return async () => {
802
+ let moduleExports;
803
+ try {
804
+ moduleExports = await row.load();
805
+ } catch (caught) {
806
+ throw new _seedcord_errors_internal.SeedcordError(_seedcord_errors.SeedcordErrorCode.RouteModuleLoadFailed, [routeId, row.from], { cause: caught });
807
+ }
808
+ if (!Object.hasOwn(moduleExports, row.exportName)) throw new _seedcord_errors_internal.SeedcordError(_seedcord_errors.SeedcordErrorCode.InteractionRouteExportMissing, [
809
+ routeId,
810
+ row.exportName,
811
+ row.from
812
+ ]);
813
+ return moduleExports[row.exportName];
814
+ };
815
+ }
816
+ function describeRow(row) {
817
+ return `${row.exportName} (${row.from})`;
818
+ }
819
+ /**
820
+ * Builds the per-kind lookup maps.
821
+ *
822
+ * @throws A **SeedcordError** when two rows resolve to the same route.
823
+ */
824
+ function buildRouteMaps(manifest) {
825
+ const maps = {
826
+ slash: /* @__PURE__ */ new Map(),
827
+ userContextMenu: /* @__PURE__ */ new Map(),
828
+ messageContextMenu: /* @__PURE__ */ new Map(),
829
+ autocomplete: /* @__PURE__ */ new Map(),
830
+ components: {
831
+ button: /* @__PURE__ */ new Map(),
832
+ stringSelect: /* @__PURE__ */ new Map(),
833
+ userSelect: /* @__PURE__ */ new Map(),
834
+ roleSelect: /* @__PURE__ */ new Map(),
835
+ channelSelect: /* @__PURE__ */ new Map(),
836
+ mentionableSelect: /* @__PURE__ */ new Map(),
837
+ modal: /* @__PURE__ */ new Map()
838
+ }
839
+ };
840
+ const owners = /* @__PURE__ */ new Map();
841
+ function set(map, kind, key, row) {
842
+ const routeId = `${kind}:${key}`;
843
+ const owner = owners.get(routeId);
844
+ if (owner) throw new _seedcord_errors_internal.SeedcordError(_seedcord_errors.SeedcordErrorCode.InteractionDuplicateRoute, [
845
+ routeId,
846
+ describeRow(owner),
847
+ describeRow(row)
848
+ ]);
849
+ owners.set(routeId, row);
850
+ map.set(key, {
851
+ kind,
852
+ routeId,
853
+ load: namedExport(routeId, row)
854
+ });
855
+ }
856
+ for (const row of manifest.commandRoutes) {
857
+ const kind = commandKind(row.type);
858
+ if (kind) set(maps[kind], kind, row.name, row);
859
+ }
860
+ for (const row of manifest.autocompleteRoutes) set(maps.autocomplete, "autocomplete", row.name, row);
861
+ for (const row of manifest.componentRoutes) set(maps.components[row.kind], COMPONENT_KIND[row.kind], row.prefix, row);
862
+ return maps;
863
+ }
864
+ function unhandled(kind, attemptedKey) {
865
+ return {
866
+ kind,
867
+ routeId: null,
868
+ attemptedKey,
869
+ load: () => Promise.resolve(kind === "autocomplete" ? UnhandledAutocomplete : UnhandledRepliable)
870
+ };
871
+ }
872
+ /**
873
+ * Matches a verified non-PING interaction to its manifest row. A known kind with no row resolves to the
874
+ * unhandled default, whose handler replies "Feature not implemented yet." (empty choices on autocomplete).
875
+ * Null is an unrecognized payload shape, which the engine acks with a 202 without dispatching.
876
+ * Components and modals route by the stable customId prefix, so a wire whose layout hash drifted still
877
+ * routes to its handler, where decode refuses with `StaleCustomId`.
878
+ */
879
+ function resolve(maps, interaction) {
880
+ switch (interaction.type) {
881
+ case discord_api_types_v10.InteractionType.ApplicationCommand: {
882
+ if (interaction.data.type === discord_api_types_v10.ApplicationCommandType.ChatInput) {
883
+ const route = slashRouteOf(interaction.data);
884
+ return maps.slash.get(route) ?? unhandled("slash", route);
885
+ }
886
+ const kind = commandKind(interaction.data.type);
887
+ return kind ? maps[kind].get(interaction.data.name) ?? unhandled(kind, interaction.data.name) : null;
888
+ }
889
+ case discord_api_types_v10.InteractionType.ApplicationCommandAutocomplete: {
890
+ const route = slashRouteOf(interaction.data);
891
+ return maps.autocomplete.get(route) ?? unhandled("autocomplete", route);
892
+ }
893
+ case discord_api_types_v10.InteractionType.MessageComponent: {
894
+ const key = componentMapKey(interaction.data.component_type);
895
+ if (!key) return null;
896
+ const prefix = (0, _seedcord_core_internal.prefixOf)(interaction.data.custom_id);
897
+ return maps.components[key].get(prefix) ?? unhandled(COMPONENT_KIND[key], prefix);
898
+ }
899
+ case discord_api_types_v10.InteractionType.ModalSubmit: {
900
+ const prefix = (0, _seedcord_core_internal.prefixOf)(interaction.data.custom_id);
901
+ return maps.components.modal.get(prefix) ?? unhandled("modal", prefix);
902
+ }
903
+ default: return null;
904
+ }
905
+ }
906
+
907
+ //#endregion
908
+ //#region src/receiver/Ed25519Verifier.ts
909
+ const PUBLIC_KEY_BYTES = 32;
910
+ const SIGNATURE_BYTES = 64;
911
+ const HEX_RADIX = 16;
912
+ const HEX_PATTERN = /^[0-9a-f]+$/i;
913
+ function hexToBytes(hex, byteLength) {
914
+ if (hex.length !== byteLength * 2 || !HEX_PATTERN.test(hex)) return null;
915
+ const bytes = new Uint8Array(byteLength);
916
+ for (let index = 0; index < byteLength; index++) bytes[index] = Number.parseInt(hex.slice(index * 2, index * 2 + 2), HEX_RADIX);
917
+ return bytes;
918
+ }
919
+ const encoder = new TextEncoder();
920
+ var Ed25519Verifier = class {
921
+ key;
922
+ constructor(publicKeyHex) {
923
+ const publicKey = hexToBytes(publicKeyHex, PUBLIC_KEY_BYTES);
924
+ if (!publicKey) throw new _seedcord_errors_internal.SeedcordError(_seedcord_errors.SeedcordErrorCode.ConfigIncorrectPublicKey);
925
+ this.key = crypto.subtle.importKey("raw", publicKey, "Ed25519", false, ["verify"]);
926
+ }
927
+ async verify(signatureHex, timestamp, body) {
928
+ const signature = hexToBytes(signatureHex, SIGNATURE_BYTES);
929
+ if (!signature) return false;
930
+ const timestampBytes = encoder.encode(timestamp);
931
+ const message = new Uint8Array(timestampBytes.length + body.length);
932
+ message.set(timestampBytes, 0);
933
+ message.set(body, timestampBytes.length);
934
+ return crypto.subtle.verify("Ed25519", await this.key, signature, message);
935
+ }
936
+ };
937
+
938
+ //#endregion
939
+ //#region src/receiver/ReplayGuard.ts
940
+ const REPLAY_WINDOW_MS = 3e5;
941
+ const SWEEP_GAP_MS = 6e4;
942
+ const MS_PER_SECOND = 1e3;
943
+ const TIMESTAMP_PATTERN = /^\d+$/;
944
+ var ReplayGuard = class {
945
+ seen = /* @__PURE__ */ new Map();
946
+ lastSweep = Date.now();
947
+ accepts(signatureHex, timestampHeader) {
948
+ const now = Date.now();
949
+ this.maybeSweep(now);
950
+ if (!TIMESTAMP_PATTERN.test(timestampHeader)) return false;
951
+ const timestampMs = Number(timestampHeader) * MS_PER_SECOND;
952
+ if (Math.abs(now - timestampMs) > REPLAY_WINDOW_MS) return false;
953
+ const rejectUntil = this.seen.get(signatureHex);
954
+ if (rejectUntil !== void 0 && rejectUntil >= now) return false;
955
+ this.seen.set(signatureHex, timestampMs + REPLAY_WINDOW_MS);
956
+ return true;
957
+ }
958
+ maybeSweep(now) {
959
+ if (now - this.lastSweep < SWEEP_GAP_MS) return;
960
+ this.lastSweep = now;
961
+ for (const [signature, rejectUntil] of this.seen) if (rejectUntil < now) this.seen.delete(signature);
962
+ }
963
+ };
964
+
965
+ //#endregion
966
+ //#region src/engine.ts
967
+ const SIGNATURE_HEADER = "x-signature-ed25519";
968
+ const TIMESTAMP_HEADER = "x-signature-timestamp";
969
+ const ACCEPTED = 202;
970
+ const BAD_REQUEST = 400;
971
+ const UNAUTHORIZED = 401;
972
+ const METHOD_NOT_ALLOWED = 405;
973
+ const PING = discord_api_types_v10.InteractionType.Ping;
974
+ const decoder = new TextDecoder();
975
+ function hasInteractionType(payload) {
976
+ return typeof payload === "object" && payload !== null && "type" in payload && typeof payload.type === "number";
977
+ }
978
+ function buildEngine(core, maps) {
979
+ if (!envapt.Envapter.has("DISCORD_PUBLIC_KEY")) throw new _seedcord_errors_internal.SeedcordError(_seedcord_errors.SeedcordErrorCode.ConfigMissingPublicKey);
980
+ const verifier = new Ed25519Verifier(envapt.Envapter.getRequired("DISCORD_PUBLIC_KEY", envapt.Converters.String));
981
+ const replays = new ReplayGuard();
982
+ const inFlight = /* @__PURE__ */ new Set();
983
+ const logger = new _seedcord_logger.Logger("Engine", { channel: "bot" });
984
+ async function dispatchMatched(match, payload, ctx) {
985
+ const start = await dispatchInteraction({
986
+ match,
987
+ payload,
988
+ core
989
+ });
990
+ if (!start) return;
991
+ const work = start().catch(rootFault);
992
+ if (ctx) ctx.waitUntil(work);
993
+ else {
994
+ inFlight.add(work);
995
+ work.finally(() => inFlight.delete(work));
996
+ }
997
+ }
998
+ function rootFault(caught) {
999
+ const error = (0, _seedcord_core_internal.asError)(caught);
1000
+ logger.error("dispatch failed past the boundary", error);
1001
+ core.bus[_seedcord_core_internal.PublishDefault]("unhandledInteractionError", { error });
1002
+ }
1003
+ const handle = async (request, ctx) => {
1004
+ if (request.method !== "POST") return new Response(null, {
1005
+ status: METHOD_NOT_ALLOWED,
1006
+ headers: { allow: "POST" }
1007
+ });
1008
+ const signature = request.headers.get(SIGNATURE_HEADER);
1009
+ const timestamp = request.headers.get(TIMESTAMP_HEADER);
1010
+ if (signature === null || timestamp === null) return new Response(null, { status: UNAUTHORIZED });
1011
+ const body = new Uint8Array(await request.arrayBuffer());
1012
+ if (!await verifier.verify(signature, timestamp, body)) return new Response(null, { status: UNAUTHORIZED });
1013
+ if (!replays.accepts(signature, timestamp)) return new Response(null, { status: UNAUTHORIZED });
1014
+ let payload;
1015
+ try {
1016
+ payload = JSON.parse(decoder.decode(body));
1017
+ } catch {
1018
+ return new Response(null, { status: BAD_REQUEST });
1019
+ }
1020
+ if (!hasInteractionType(payload)) return new Response(null, { status: BAD_REQUEST });
1021
+ if (payload.type === PING) return Response.json({ type: discord_api_types_v10.InteractionResponseType.Pong });
1022
+ try {
1023
+ core.bus[_seedcord_core_internal.PublishDefault]("anyInteraction", { interaction: payload });
1024
+ const match = resolve(maps, payload);
1025
+ if (match) await dispatchMatched(match, payload, ctx);
1026
+ } catch (caught) {
1027
+ rootFault(caught);
1028
+ }
1029
+ return new Response(null, { status: ACCEPTED });
1030
+ };
1031
+ return {
1032
+ handle,
1033
+ inFlight
1034
+ };
1035
+ }
1036
+
1037
+ //#endregion
1038
+ //#region src/createSeedcord.ts
1039
+ /**
1040
+ * Builds the HTTP-interactions engine, a `(request, ctx?) => Promise<Response>` handler.
1041
+ *
1042
+ * The handler verifies the Ed25519 signature over the raw request bytes, rejects stale or replayed
1043
+ * requests, answers a PING with an in-body PONG, and acks every other interaction with an empty 202.
1044
+ * The engine dispatches a matched interaction through the manifest before the 202 goes out. Gates run
1045
+ * first and the sender posts any refusal over the REST callback. `execute()` continues past the 202 under
1046
+ * `ctx.waitUntil` when the caller passes one (the edge entry), and an engine-held in-flight set tracks
1047
+ * it otherwise (node paths). It reads only the method, headers, and body. Mount it at any path.
1048
+ *
1049
+ * Reads `DISCORD_PUBLIC_KEY` and `DISCORD_BOT_TOKEN` from the environment through envapt and throws a
1050
+ * `SeedcordError` when either is missing or malformed.
1051
+ */
1052
+ function createSeedcord(config, manifest) {
1053
+ const core = createCore(config, (0, _seedcord_errors_internal.validateDiscordToken)(envapt.Envapter.get("DISCORD_BOT_TOKEN")));
1054
+ core.bus.registerDefaults();
1055
+ registerSubscribers(core.bus, manifest);
1056
+ return buildEngine(core, buildRouteMaps(manifest)).handle;
1057
+ }
1058
+
1059
+ //#endregion
1060
+ //#region src/handlers/interaction/SlashHandler.ts
1061
+ /**
1062
+ * Base class for a chat-input (slash) command handler on the HTTP transport.
1063
+ *
1064
+ * Pass the route from the generated registry as the generic, then read `this.options` for a single
1065
+ * command or `this.match` for several. Command authoring stays plain discord.js, `seedcord codegen`
1066
+ * reads its `toJSON()` to type these options.
1067
+ *
1068
+ * @typeParam Route - One or more route keys from {@link SlashOptionRegistry}, e.g. `'ban'` or `'ban' | 'kick'`.
1069
+ */
1070
+ var SlashHandler = class extends InteractionHandler {
1071
+ resolver;
1072
+ /**
1073
+ * The typed options for this command's route. Required options drop the null, choices narrow to their
1074
+ * literal union, and only the getters for kinds this command actually uses appear. Rich kinds resolve
1075
+ * from the interaction's `resolved` data.
1076
+ */
1077
+ get options() {
1078
+ this.resolver ??= new HttpSlashOptions(this.event.data);
1079
+ return this.resolver;
1080
+ }
1081
+ /**
1082
+ * Run the arm for whichever command fired. Use this only when the handler is registered for several
1083
+ * routes.
1084
+ *
1085
+ * Provide one arm per registered route, keyed by its route string, and each arm receives that route's
1086
+ * own narrowed options. The arms must cover every route in the generic, a missing route or an unknown
1087
+ * key is a compile error.
1088
+ *
1089
+ * @param arms - One handler per registered route, keyed by route string.
1090
+ * @returns The result of the arm that ran.
1091
+ */
1092
+ async match(arms) {
1093
+ const route = slashRouteOf(this.event.data);
1094
+ const arm = Object.hasOwn(arms, route) ? arms[route] : void 0;
1095
+ if (!arm) throw new _seedcord_errors_internal.SeedcordError(_seedcord_errors.SeedcordErrorCode.SlashMatchArmMissing, [route]);
1096
+ return await arm(this.options);
1097
+ }
1098
+ };
1099
+
1100
+ //#endregion
1101
+ //#region src/handlers/interaction/ContextMenuHandler.ts
1102
+ /**
1103
+ * Base class for a context-menu command handler on the HTTP transport (right-click a user or a message).
1104
+ *
1105
+ * Pass the kind from {@link ApplicationCommandType} as the generic. Read the right-clicked entity from
1106
+ * `this.target`, an `APIUser` for a user menu and an `APIMessage` for a message menu. Context menus carry
1107
+ * no options, so a handler registered for several names reads `this.target` uniformly with no per-name
1108
+ * branch.
1109
+ *
1110
+ * @typeParam Kind - `ApplicationCommandType.User` or `ApplicationCommandType.Message`.
1111
+ */
1112
+ var ContextMenuHandler = class extends InteractionHandler {
1113
+ get target() {
1114
+ const data = this.event.data;
1115
+ return data.type === discord_api_types_v10.ApplicationCommandType.User ? data.resolved.users[data.target_id] : data.resolved.messages[data.target_id];
1116
+ }
1117
+ /**
1118
+ * The right-clicked user's guild member, resolved only on user menus fired in a guild. Reading it on a
1119
+ * message menu is a compile error.
1120
+ */
1121
+ get targetMember() {
1122
+ const data = this.event.data;
1123
+ return data.type === discord_api_types_v10.ApplicationCommandType.User ? data.resolved.members?.[data.target_id] ?? null : null;
1124
+ }
1125
+ };
1126
+
1127
+ //#endregion
1128
+ //#region src/handlers/interaction/components/ComponentHandler.ts
1129
+ /**
1130
+ * Shared base the customId-routed component handlers extend on the HTTP transport.
1131
+ *
1132
+ * Not a public entry point. Extend {@link ButtonHandler}, {@link SelectMenuHandler}, or {@link ModalHandler}
1133
+ * instead. This class defines the customId decode, the route matching, and the source-message verbs
1134
+ * `update` and `deferUpdate`.
1135
+ *
1136
+ * @typeParam Event - The component or modal interaction type this handler processes
1137
+ * @typeParam Defs - The customId route definitions registered on the concrete handler
1138
+ */
1139
+ var ComponentHandler = class extends InteractionHandler {
1140
+ /** Rewrite the source message this component interaction came from. */
1141
+ update(response) {
1142
+ return this.sender.update(response);
1143
+ }
1144
+ /** Acknowledge the component without changing the source message. */
1145
+ deferUpdate() {
1146
+ return this.sender.deferUpdate();
1147
+ }
1148
+ decoded;
1149
+ get route() {
1150
+ this.decoded ??= (0, _seedcord_core_internal.decodeComponentRoute)(this.constructor, this.event.data.custom_id);
1151
+ return this.decoded;
1152
+ }
1153
+ /**
1154
+ * The decoded params of the single route this handler is registered for.
1155
+ *
1156
+ * Reading this decodes `this.event.data.custom_id` once (cached after the first read) and throws
1157
+ * `StaleCustomId` or `InvalidCustomId` when the wire no longer matches the current shape, which the
1158
+ * dispatcher boundary turns into a reply. On a handler registered for several routes this is
1159
+ * `never`, so use {@link match} instead.
1160
+ */
1161
+ get params() {
1162
+ return this.route.params;
1163
+ }
1164
+ /**
1165
+ * Run the arm for whichever route the component was minted from. Use this only when the handler is
1166
+ * registered for several routes. A single-route handler reads `this.params` directly. On a multi-route
1167
+ * handler `this.params` is `never`, so match is the only way to read the decoded params.
1168
+ *
1169
+ * Provide one arm per registered route, keyed by its prefix, and each arm receives that route's own
1170
+ * decoded params. The arms cover every registered route prefix, checked at compile time, and a prefix
1171
+ * unmatched at runtime throws `CustomIdMatchArmMissing`. Decoding runs before any arm, so a stale or
1172
+ * corrupt wire throws before an arm body executes.
1173
+ *
1174
+ * @param arms - One callback per registered route, keyed by prefix.
1175
+ * @returns The result of the arm that ran.
1176
+ *
1177
+ * @example
1178
+ * ```ts
1179
+ * \@ButtonRoute(Approve, Reject)
1180
+ * class ReviewButtons extends ButtonHandler<[typeof Approve, typeof Reject]> {
1181
+ * async execute() {
1182
+ * await this.match({
1183
+ * approve: ({ userId }) => this.reply(`approved <@${userId}>`),
1184
+ * reject: ({ userId }) => this.reply(`rejected <@${userId}>`)
1185
+ * });
1186
+ * }
1187
+ * }
1188
+ * ```
1189
+ */
1190
+ async match(arms) {
1191
+ const { prefix, params } = this.route;
1192
+ const arm = Object.hasOwn(arms, prefix) ? arms[prefix] : void 0;
1193
+ if (!arm) throw new _seedcord_errors_internal.SeedcordError(_seedcord_errors.SeedcordErrorCode.CustomIdMatchArmMissing, [prefix]);
1194
+ return await arm(params);
1195
+ }
1196
+ };
1197
+
1198
+ //#endregion
1199
+ //#region src/handlers/interaction/components/ButtonHandler.ts
1200
+ /**
1201
+ * Base class for a button interaction handler on the HTTP transport.
1202
+ *
1203
+ * Register the customId definitions this handler decodes with `@ButtonRoute`, list the same ones in the
1204
+ * generic, then read `this.params` for a single route or `this.match` for several. Reply through the
1205
+ * handler members, or rewrite the source message with `this.update`. Passing different definitions to the
1206
+ * decorator and the generic is a compile error.
1207
+ *
1208
+ * @typeParam Defs - The customId definitions this handler decodes, e.g. `[typeof ApproveId]`.
1209
+ */
1210
+ var ButtonHandler = class extends ComponentHandler {};
1211
+
1212
+ //#endregion
1213
+ //#region src/handlers/interaction/components/SelectMenuHandler.ts
1214
+ /**
1215
+ * Base class for a select menu handler on the HTTP transport.
1216
+ *
1217
+ * Pass the select kind first and the customId definitions second, the same order as `@SelectMenuRoute`,
1218
+ * so `this.event.data` and its `values`/`resolved` are narrowed to that kind. Read `this.params` for a
1219
+ * single route or `this.match` for several, and reply through the handler members or rewrite the source
1220
+ * message with `this.update`.
1221
+ *
1222
+ * @typeParam Kind - The select kind from {@link SelectMenuKind}, e.g. `SelectMenuKind.User`.
1223
+ * @typeParam Defs - The customId definitions this handler decodes, e.g. `[typeof AssignId]`.
1224
+ */
1225
+ var SelectMenuHandler = class extends ComponentHandler {};
1226
+
1227
+ //#endregion
1228
+ //#region src/handlers/interaction/components/ModalHandler.ts
1229
+ /**
1230
+ * Base class for a modal submit handler on the HTTP transport.
1231
+ *
1232
+ * Register the customId definitions this handler decodes with `@ModalRoute` and list the same ones in the
1233
+ * generic. Read the submitted inputs off `this.event.data.components`. Reply through the handler members.
1234
+ * Discord forbids opening a modal in response to a modal, so `showModal` fails compilation on this kind.
1235
+ *
1236
+ * @typeParam Defs - The customId definitions this handler decodes, e.g. `[typeof ConfigId]`.
1237
+ */
1238
+ var ModalHandler = class extends ComponentHandler {
1239
+ /** Rewrite the message this modal was opened from (only when a component opened it). */
1240
+ update(response) {
1241
+ this.ensureSourceMessage("update");
1242
+ return super.update(response);
1243
+ }
1244
+ /** Silently acknowledge, leaving the source message untouched. */
1245
+ deferUpdate() {
1246
+ this.ensureSourceMessage("deferUpdate");
1247
+ return super.deferUpdate();
1248
+ }
1249
+ ensureSourceMessage(method) {
1250
+ if (this.event.message) return;
1251
+ throw new _seedcord_errors_internal.SeedcordError(_seedcord_errors.SeedcordErrorCode.ReplyUpdateWithoutSource, [method, this.routeId]);
1252
+ }
1253
+ };
1254
+
1255
+ //#endregion
1256
+ //#region src/subscribers/index.ts
1257
+ /**
1258
+ * Base class for an HTTP subscriber, binding `this.core` to the HTTP {@link Core}.
1259
+ *
1260
+ * @typeParam KeyOfSubscribers - The subscription key this handler receives
1261
+ */
1262
+ var Subscriber = class extends _seedcord_core.Subscriber {};
1263
+ /**
1264
+ * Base class for an HTTP subscriber that delivers its event to a Discord webhook, binding
1265
+ * `this.core` to the HTTP {@link Core}.
1266
+ *
1267
+ * @typeParam KeyOfSubscribers - The subscription key this reporter receives
1268
+ */
1269
+ var WebhookLog = class extends _seedcord_core.WebhookLog {};
1270
+
1271
+ //#endregion
1272
+ //#region src/gates/Gated.ts
1273
+ /**
1274
+ * Attaches gates to an HTTP interaction handler. The gates run before `execute`, and a gate refusing stops
1275
+ * the handler with the reply or drop the gate threw. Multiple gates are ANDed, so each must pass. A gate
1276
+ * that requires a context the handler does not provide (a button gate on a slash handler, a gate on an
1277
+ * autocomplete handler, or a `RequirePermissions([...], { in: 'guild' })` gate the http transport cannot
1278
+ * satisfy) is a compile error at this line, and the error names the gate and the handler kind. Place it
1279
+ * above the route decorator.
1280
+ *
1281
+ * Combine gates with {@link and} or {@link or} to build a single gate from multiple arms.
1282
+ *
1283
+ * @example
1284
+ * ```ts
1285
+ * import { PermissionFlagsBits } from 'discord-api-types/v10';
1286
+ *
1287
+ * \@Gated(GuildOnly(), RequirePermissions([PermissionFlagsBits.ManageMessages]))
1288
+ * \@SlashRoute('purge')
1289
+ * class Purge extends SlashHandler<'purge'> {
1290
+ * async execute() {
1291
+ * // both gates passed, so this runs in a guild with a caller who can moderate this channel
1292
+ * }
1293
+ * }
1294
+ * ```
1295
+ *
1296
+ * @typeParam Gates - The non-empty tuple of gates to run, in order, against the handler's context.
1297
+ * @typeParam TCtor - The decorated handler's constructor, checked against every gate's required context.
1298
+ * @param gates - One or more gates to attach, each ANDed so the handler runs only when all pass.
1299
+ * @param ctor - The handler class being decorated, rejected at compile time when a gate requires a context it lacks.
1300
+ *
1301
+ * @see {@link defineGate}
1302
+ * @see {@link defineEffectGate}
1303
+ * @decorator
1304
+ */
1305
+ function Gated(...gates) {
1306
+ return function(ctor) {
1307
+ const existing = Reflect.getMetadata(_seedcord_core_internal.GatedMetadataKey, ctor) ?? [];
1308
+ Reflect.defineMetadata(_seedcord_core_internal.GatedMetadataKey, [...existing, ...gates], ctor);
1309
+ };
1310
+ }
1311
+
1312
+ //#endregion
1313
+ //#region src/version.ts
1314
+ /** Package version */
1315
+ const version = "0.1.0-next.2";
1316
+
1317
+ //#endregion
1318
+ Object.defineProperty(exports, 'AutocompleteHandler', {
1319
+ enumerable: true,
1320
+ get: function () {
1321
+ return AutocompleteHandler;
1322
+ }
1323
+ });
1324
+ Object.defineProperty(exports, 'ButtonHandler', {
1325
+ enumerable: true,
1326
+ get: function () {
1327
+ return ButtonHandler;
1328
+ }
1329
+ });
1330
+ Object.defineProperty(exports, 'ComponentHandler', {
1331
+ enumerable: true,
1332
+ get: function () {
1333
+ return ComponentHandler;
1334
+ }
1335
+ });
1336
+ Object.defineProperty(exports, 'ContextMenuHandler', {
1337
+ enumerable: true,
1338
+ get: function () {
1339
+ return ContextMenuHandler;
1340
+ }
1341
+ });
1342
+ Object.defineProperty(exports, 'Gated', {
1343
+ enumerable: true,
1344
+ get: function () {
1345
+ return Gated;
1346
+ }
1347
+ });
1348
+ Object.defineProperty(exports, 'InteractionHandler', {
1349
+ enumerable: true,
1350
+ get: function () {
1351
+ return InteractionHandler;
1352
+ }
1353
+ });
1354
+ Object.defineProperty(exports, 'ModalHandler', {
1355
+ enumerable: true,
1356
+ get: function () {
1357
+ return ModalHandler;
1358
+ }
1359
+ });
1360
+ Object.defineProperty(exports, 'RepliableHandler', {
1361
+ enumerable: true,
1362
+ get: function () {
1363
+ return RepliableHandler;
1364
+ }
1365
+ });
1366
+ Object.defineProperty(exports, 'SelectMenuHandler', {
1367
+ enumerable: true,
1368
+ get: function () {
1369
+ return SelectMenuHandler;
1370
+ }
1371
+ });
1372
+ Object.defineProperty(exports, 'SlashHandler', {
1373
+ enumerable: true,
1374
+ get: function () {
1375
+ return SlashHandler;
1376
+ }
1377
+ });
1378
+ Object.defineProperty(exports, 'Subscriber', {
1379
+ enumerable: true,
1380
+ get: function () {
1381
+ return Subscriber;
1382
+ }
1383
+ });
1384
+ Object.defineProperty(exports, 'WebhookLog', {
1385
+ enumerable: true,
1386
+ get: function () {
1387
+ return WebhookLog;
1388
+ }
1389
+ });
1390
+ Object.defineProperty(exports, '__exportAll', {
1391
+ enumerable: true,
1392
+ get: function () {
1393
+ return __exportAll;
1394
+ }
1395
+ });
1396
+ Object.defineProperty(exports, '__reExport', {
1397
+ enumerable: true,
1398
+ get: function () {
1399
+ return __reExport;
1400
+ }
1401
+ });
1402
+ Object.defineProperty(exports, 'buildEngine', {
1403
+ enumerable: true,
1404
+ get: function () {
1405
+ return buildEngine;
1406
+ }
1407
+ });
1408
+ Object.defineProperty(exports, 'buildRouteMaps', {
1409
+ enumerable: true,
1410
+ get: function () {
1411
+ return buildRouteMaps;
1412
+ }
1413
+ });
1414
+ Object.defineProperty(exports, 'createSeedcord', {
1415
+ enumerable: true,
1416
+ get: function () {
1417
+ return createSeedcord;
1418
+ }
1419
+ });
1420
+ Object.defineProperty(exports, 'version', {
1421
+ enumerable: true,
1422
+ get: function () {
1423
+ return version;
1424
+ }
1425
+ });
1426
+ //# sourceMappingURL=edge.index-joDL39cK.cjs.map