@seedcord/gateway 0.0.1 → 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/index.mjs CHANGED
@@ -1,7 +1,3924 @@
1
- //#region src/index.ts
1
+ import "reflect-metadata";
2
+ import { BuilderComponent, CustomId, DispatchContext, Fault, Notice, RegisterCommand, RowComponent, Silence, defineGate, paginate } from "@seedcord/core";
3
+ import { CommandMetadataKey, ComponentDefsKey, EventMetadataKey, GateNotice, GatedMetadataKey, InteractionMetadataKey, InteractionRouteKeys, InteractionRoutes, MiddlewareMetadataKey, NotInGuild, NoticeCard, PAGE_MAX, SubscribeMetadataKey, decodeFor, pageCursor, pickNotice, prefixOf, routeIdOf, runHandlerGates, setBotColor } from "@seedcord/core/internal";
4
+ import { ApplicationCommandType, AttachmentBuilder, ButtonStyle, Client, Collection, ComponentType, DiscordAPIError, Events, Guild, GuildMember, Message, MessageFlags, PermissionFlagsBits, RESTJSONErrorCodes, Role, SeparatorSpacingSize, SnowflakeUtil, TextChannel, User, WebhookClient, chatInputApplicationCommandMention } from "discord.js";
5
+ import { SeedcordErrorCode } from "@seedcord/errors";
6
+ import { SeedcordError, SeedcordRangeError, SeedcordTypeError, validateDiscordToken } from "@seedcord/errors/internal";
7
+ import { filterCirculars, formatFilePath, hasKeys, prettify, traverseDirectory } from "@seedcord/utils";
8
+ import { CoordinatedShutdown, CoordinatedStartup, HealthCheck, Logger, ShutdownPhase, StartupPhase } from "@seedcord/services";
9
+ import chalk from "chalk";
10
+ import { ActionRowBuilder, ButtonBuilder, ContextMenuCommandBuilder, SlashCommandBuilder, TextDisplayBuilder } from "@discordjs/builders";
11
+ import { buildSlashRoute, routeLeavesOf } from "@seedcord/utils/internal";
12
+ import { TypedEventEmitter } from "@seedcord/event-emitter";
13
+ import { existsSync } from "node:fs";
14
+ import { resolve } from "node:path";
15
+ import { pathToFileURL } from "node:url";
16
+ import { MemoryRateLimiter } from "@seedcord/rate-limiter";
17
+ import { SeedcordBrand, wrapHot } from "@seedcord/types/internal";
18
+ import { Envapt, Envapter } from "envapt";
19
+ import * as crypto from "node:crypto";
20
+
21
+ export * from "@seedcord/core"
22
+
23
+ export * from "@seedcord/errors"
24
+
25
+ export * from "@seedcord/utils"
26
+
27
+ export * from "@seedcord/services"
28
+
29
+ export * from "@seedcord/event-emitter"
30
+
31
+ export * from "@seedcord/rate-limiter"
32
+
33
+ //#region src/bot/decorators/Events.ts
34
+ /**
35
+ * Registers an event handler class with one or more Discord.js events.
36
+ *
37
+ * Associates the decorated class with the provided Discord client events for automatic registration and execution when those events are emitted.
38
+ *
39
+ * Supply any number of event tuples. Each tuple can include per event options.
40
+ *
41
+ * @typeParam EventKey - Union of Discord.js ClientEvents keys to register for
42
+ * @param defs - One or more tuples of [event, options]
43
+ * @decorator
44
+ * @example
45
+ * ```ts
46
+ * \@RegisterEvent([Events.MessageCreate])
47
+ * class MessageHandler extends EventHandler<Events.MessageCreate> {
48
+ * async execute() {
49
+ * // Handle message creation
50
+ * }
51
+ * }
52
+ * ```
53
+ *
54
+ * @example
55
+ * ```ts
56
+ * \@RegisterEvent([Events.MessageCreate], [Events.MessageUpdate])
57
+ * class MessageHandler extends EventHandler<Events.MessageCreate | Events.MessageUpdate> {
58
+ * async execute() {
59
+ * // Handle message creation or update
60
+ * }
61
+ * }
62
+ * ```
63
+ *
64
+ * @example
65
+ * ```ts
66
+ * \@RegisterEvent([Events.MessageCreate, { frequency: 'once' }], [Events.MessageUpdate])
67
+ * class OneTimeMessageHandler extends EventHandler<Events.MessageCreate | Events.MessageUpdate> {
68
+ * async execute() {
69
+ * // Handle only the first message creation, and message update normally
70
+ * }
71
+ * }
72
+ * ```
73
+ */
74
+ function RegisterEvent(...defs) {
75
+ return function(constructor) {
76
+ const existing = Reflect.getMetadata(EventMetadataKey, constructor) ?? [];
77
+ const entries = defs.map(([event, options]) => ({
78
+ event,
79
+ frequency: options?.frequency ?? "on"
80
+ }));
81
+ Reflect.defineMetadata(EventMetadataKey, [...existing, ...entries], constructor);
82
+ };
83
+ }
84
+
85
+ //#endregion
86
+ //#region src/bot/decorators/Gated.ts
87
+ /**
88
+ * Attaches gates to a handler. The gates run before `execute`, and a gate refusing stops the handler with
89
+ * the reply or drop the gate threw. Multiple gates are ANDed, so each must pass. A gate that requires a
90
+ * context the handler does not provide (a button gate on a slash handler, an interaction gate on an event
91
+ * handler) is a compile error at this line, and the error names the gate and the handler kind. Place it
92
+ * above the route decorator.
93
+ *
94
+ * Combine gates with {@link and} or {@link or} to build a single gate from multiple arms.
95
+ *
96
+ * @example
97
+ * ```ts
98
+ * import { PermissionFlagsBits } from 'discord.js';
99
+ *
100
+ * \@Gated(GuildOnly(), RequirePermissions([PermissionFlagsBits.Administrator]))
101
+ * \@SlashRoute('maintenance')
102
+ * class Maintenance extends SlashHandler<'maintenance'> {
103
+ * async execute() {
104
+ * // both gates passed, so this runs in a guild with an admin caller
105
+ * }
106
+ * }
107
+ * ```
108
+ *
109
+ * @typeParam Gates - The non-empty tuple of gates to run, in order, against the handler's context.
110
+ * @typeParam TCtor - The decorated handler's constructor, checked against every gate's required context.
111
+ * @param gates - One or more gates to attach, each ANDed so the handler runs only when all pass.
112
+ * @param ctor - The handler class being decorated, rejected at compile time when a gate needs a context it lacks.
113
+ *
114
+ * @see {@link defineGate}
115
+ * @see {@link defineEffectGate}
116
+ * @decorator
117
+ */
118
+ function Gated(...gates) {
119
+ return function(ctor) {
120
+ const existing = Reflect.getMetadata(GatedMetadataKey, ctor) ?? [];
121
+ Reflect.defineMetadata(GatedMetadataKey, [...existing, ...gates], ctor);
122
+ };
123
+ }
124
+
125
+ //#endregion
126
+ //#region src/miscellaneous/areRoutes.ts
127
+ /**
128
+ * Checks if the provided value is an array of strings.
129
+ *
130
+ * @internal
131
+ */
132
+ function areRoutes(routes) {
133
+ return Array.isArray(routes) && routes.every((r) => typeof r === "string");
134
+ }
135
+
136
+ //#endregion
137
+ //#region src/bot/decorators/Interactions.ts
138
+ /**
139
+ * Types of select menus supported for routing
140
+ */
141
+ let SelectMenuKind = /* @__PURE__ */ function(SelectMenuKind) {
142
+ SelectMenuKind["String"] = "string";
143
+ SelectMenuKind["User"] = "user";
144
+ SelectMenuKind["Role"] = "role";
145
+ SelectMenuKind["Channel"] = "channel";
146
+ SelectMenuKind["Mentionable"] = "mentionable";
147
+ return SelectMenuKind;
148
+ }({});
149
+ /**
150
+ * Routes one or more slash commands to a {@link SlashHandler}.
151
+ *
152
+ * Pass the same route string(s) as the handler's generic. A single command reads `this.options`, several
153
+ * commands branch with `this.match`. The decorator routes and the generic must match exactly, so listing
154
+ * fewer or more than the handler declares is a compile error. Subcommands use a slash path.
155
+ *
156
+ * @param routes - The route string(s) this handler serves, e.g. `'ban'`, `'ban', 'kick'`, or `'demo/setup'`.
157
+ * @decorator
158
+ * @example
159
+ * ```ts
160
+ * \@SlashRoute('ban')
161
+ * class BanHandler extends SlashHandler<'ban'> {
162
+ * async execute() {
163
+ * const target = this.options.getUser('target');
164
+ * }
165
+ * }
166
+ * ```
167
+ *
168
+ * @example
169
+ * ```ts
170
+ * \@SlashRoute('ban', 'kick')
171
+ * class ModerationHandler extends SlashHandler<'ban' | 'kick'> {
172
+ * async execute() {
173
+ * await this.match({ ban: (o) => o.getUser('target'), kick: (o) => o.getUser('member') });
174
+ * }
175
+ * }
176
+ * ```
177
+ */
178
+ function SlashRoute(...routes) {
179
+ return function(constructor) {
180
+ storeMetadata(InteractionRoutes.Slash, routes, constructor);
181
+ };
182
+ }
183
+ /**
184
+ * Routes button interactions to handler classes.
185
+ *
186
+ * Pass the {@link CustomId} definition(s) this handler decodes and list the same ones in the handler's
187
+ * generic. Passing different definitions to the decorator and the generic is a compile error. Routing
188
+ * matches the stable prefix, so a wire minted from an older shape still reaches the handler, where
189
+ * reading this.params throws StaleCustomId and the controller boundary turns it into a reply.
190
+ *
191
+ * @param defs - The customId definition(s) this handler decodes, one per route.
192
+ * @decorator
193
+ */
194
+ function ButtonRoute(...defs) {
195
+ return function(constructor) {
196
+ storeComponentRoute(InteractionRoutes.Button, defs, constructor);
197
+ };
198
+ }
199
+ /**
200
+ * Routes modal submissions to handler classes.
201
+ *
202
+ * Pass the {@link CustomId} definition(s) this handler decodes and list the same ones in the handler's
203
+ * generic. Passing different definitions to the decorator and the generic is a compile error. Routing
204
+ * matches the stable prefix, so an older-shape wire still reaches the handler and throws StaleCustomId
205
+ * on read, the same as a button route.
206
+ *
207
+ * @param defs - The customId definition(s) this handler decodes, one per route.
208
+ * @decorator
209
+ */
210
+ function ModalRoute(...defs) {
211
+ return function(constructor) {
212
+ storeComponentRoute(InteractionRoutes.Modal, defs, constructor);
213
+ };
214
+ }
215
+ /**
216
+ * Routes one or more context-menu commands to a {@link ContextMenuHandler}.
217
+ *
218
+ * Pass the kind (`ApplicationCommandType.User` or `ApplicationCommandType.Message`) and the command name(s),
219
+ * each checked against that kind's registry, so a typo is a compile error. The same kind must sit on the
220
+ * handler's generic, cross-checked both directions. Context menus carry no options, so a multi-name handler
221
+ * reads `this.target` uniformly with no branch.
222
+ *
223
+ * @param kind - The context-menu kind, `ApplicationCommandType.User` or `ApplicationCommandType.Message`.
224
+ * @param names - The command name(s) this handler serves, keyed off the matching registry.
225
+ * @decorator
226
+ * @example
227
+ * ```ts
228
+ * \@ContextMenuRoute(ApplicationCommandType.User, 'View Profile')
229
+ * class ViewProfile extends ContextMenuHandler<ApplicationCommandType.User> {
230
+ * async execute() {
231
+ * const user = this.target;
232
+ * }
233
+ * }
234
+ * ```
235
+ */
236
+ function ContextMenuRoute(kind, ...names) {
237
+ return function(constructor) {
238
+ storeMetadata(kind === ApplicationCommandType.User ? InteractionRoutes.UserContextMenu : InteractionRoutes.MessageContextMenu, names, constructor);
239
+ };
240
+ }
241
+ /**
242
+ * Routes one or more commands' autocomplete to an {@link AutocompleteHandler}.
243
+ *
244
+ * Pass the same command route string(s) as the handler's generic. One command branches with `this.match`
245
+ * over its autocompletable fields, several commands share one handler whose arms span every command's
246
+ * fields. The decorator routes and the generic must match exactly, so listing fewer or more than the
247
+ * handler declares is a compile error.
248
+ *
249
+ * @param routes - The command route string(s) this handler serves, e.g. `'search'` or `'search', 'find'`.
250
+ * @decorator
251
+ * @example
252
+ * ```ts
253
+ * \@AutocompleteRoute('search')
254
+ * class SearchAutocomplete extends AutocompleteHandler<'search'> {
255
+ * async execute() {
256
+ * await this.match({ query: (value, respond) => respond([{ name: value, value }]) });
257
+ * }
258
+ * }
259
+ * ```
260
+ */
261
+ function AutocompleteRoute(...routes) {
262
+ return function(constructor) {
263
+ storeMetadata(InteractionRoutes.Autocomplete, routes, constructor);
264
+ };
265
+ }
266
+ /**
267
+ * Routes select menu interactions to handler classes.
268
+ *
269
+ * Pass the select kind and the {@link CustomId} definition(s) this handler decodes. The handler's
270
+ * generic must list the same definitions, and its second generic argument must be the matching select
271
+ * interaction type, or it is a compile error.
272
+ *
273
+ * @param type - Select menu kind from {@link SelectMenuKind}.
274
+ * @param defs - The customId definition(s) this handler decodes, one per route.
275
+ * @decorator
276
+ *
277
+ * @example
278
+ * ```typescript
279
+ * \@SelectMenuRoute(SelectMenuKind.User, AssignId)
280
+ * class AssignSelect extends SelectMenuHandler<SelectMenuKind.User, [typeof AssignId]> {
281
+ * // handles user select menus minted from AssignId
282
+ * }
283
+ * ```
284
+ */
285
+ function SelectMenuRoute(type, ...defs) {
286
+ return function(constructor) {
287
+ storeComponentRoute({
288
+ ["string"]: InteractionRoutes.StringMenu,
289
+ ["user"]: InteractionRoutes.UserMenu,
290
+ ["role"]: InteractionRoutes.RoleMenu,
291
+ ["channel"]: InteractionRoutes.ChannelMenu,
292
+ ["mentionable"]: InteractionRoutes.MentionableMenu
293
+ }[type], defs, constructor);
294
+ };
295
+ }
296
+ function storeComponentRoute(route, defs, constructor) {
297
+ storeMetadata(route, defs.map((def) => def.prefix), constructor);
298
+ Reflect.defineMetadata(ComponentDefsKey, defs, constructor);
299
+ }
300
+ function storeMetadata(route, routes, constructor) {
301
+ const key = InteractionRouteKeys[route];
302
+ const savedRoutes = Reflect.getMetadata(key, constructor);
303
+ const existing = areRoutes(savedRoutes) ? savedRoutes : [];
304
+ const toStore = Array.isArray(routes) ? routes : [routes];
305
+ Reflect.defineMetadata(key, [...existing, ...toStore], constructor);
306
+ Reflect.defineMetadata(InteractionMetadataKey, true, constructor);
307
+ }
308
+
309
+ //#endregion
310
+ //#region src/bot/decorators/Middlewares.ts
311
+ /**
312
+ * Middleware types supported by Seedcord
313
+ */
314
+ let MiddlewareType = /* @__PURE__ */ function(MiddlewareType) {
315
+ MiddlewareType["Interaction"] = "interaction";
316
+ MiddlewareType["Event"] = "event";
317
+ return MiddlewareType;
318
+ }({});
319
+ /**
320
+ * Decorator used to register middleware with priority ordering. The lower the priority number, the earlier it runs.
321
+ *
322
+ * Interaction middleware cannot specify event filters.
323
+ *
324
+ * @param type - Middleware kind from {@link MiddlewareType}
325
+ * @param priority - Ordering value where lower runs earlier. {@default `0`}
326
+ * @param options - Additional registration options
327
+ *
328
+ * @decorator
329
+ *
330
+ * @example
331
+ * ```ts
332
+ * \@Middleware(MiddlewareType.Event, 10, { events: [Events.MessageCreate, Events.MessageUpdate] })
333
+ * class MyEventMiddleware extends EventMiddleware {}
334
+ * ```
335
+ * @throws A **SeedcordTypeError** If priority is not a finite number
336
+ * @throws A **SeedcordError** If interaction middleware specifies event filters
337
+ */
338
+ function Middleware(type, priority = 0, options = {}) {
339
+ return (ctor) => {
340
+ const normalizedPriority = Number(priority);
341
+ if (!Number.isFinite(normalizedPriority)) throw new SeedcordTypeError(SeedcordErrorCode.DecoratorInvalidMiddlewarePriority);
342
+ if (type === "interaction" && Array.isArray(options.events) && options.events.length > 0) throw new SeedcordError(SeedcordErrorCode.DecoratorInteractionEventFilter);
343
+ const metadata = {
344
+ priority: normalizedPriority,
345
+ type,
346
+ ...options.events && options.events.length > 0 && { events: options.events }
347
+ };
348
+ Reflect.defineMetadata(MiddlewareMetadataKey, metadata, ctor);
349
+ };
350
+ }
351
+
352
+ //#endregion
353
+ //#region src/bot/gates/catalog/IgnoreBots.ts
354
+ /**
355
+ * Drops a client event whose actor is a bot, with a {@link Silence} so nothing is replied. Event-only, because a
356
+ * Silence on an interaction would leave Discord's failed-interaction state. It rejects an interaction handler at
357
+ * the decorator line. Takes no options, so attach it directly without calling it.
358
+ *
359
+ * @see {@link Gated}
360
+ *
361
+ * @example
362
+ * ```ts
363
+ * import { Events } from 'discord.js';
364
+ *
365
+ * \@Gated(IgnoreBots)
366
+ * class OnMessage extends EventHandler<Events.MessageCreate> {
367
+ * async execute() {
368
+ * // ...
369
+ * }
370
+ * }
371
+ * ```
372
+ */
373
+ const IgnoreBots = defineGate("IgnoreBots", (ctx) => {
374
+ if (ctx.user?.bot) throw new Silence("actor is a bot");
375
+ });
376
+
377
+ //#endregion
378
+ //#region src/bot/notices/utils.ts
379
+ function mentionFor(subject) {
380
+ if (subject instanceof Role) return `<@&${subject.id}>`;
381
+ if (subject instanceof TextChannel) return `<#${subject.id}>`;
382
+ if (subject instanceof GuildMember) return `<@${subject.id}>`;
383
+ return `\`${subject.name}\``;
384
+ }
385
+ function labelFor(subject) {
386
+ if (subject instanceof Role) return "role";
387
+ if (subject instanceof TextChannel) return "channel";
388
+ if (subject instanceof GuildMember) return "member";
389
+ return "guild";
390
+ }
391
+
392
+ //#endregion
393
+ //#region src/bot/notices/index.ts
394
+ var NotNsfw = class extends GateNotice {
395
+ constructor(message = "This can only be used in an age-restricted channel.") {
396
+ super(message);
397
+ }
398
+ };
399
+ var MissingRole = class extends GateNotice {
400
+ role;
401
+ constructor(message, role) {
402
+ super(message ?? (role ? `You need the ${role.name} role to use this.` : "You do not have the required role."));
403
+ this.role = role;
404
+ }
405
+ };
406
+ var RoleHigherThanMe = class extends Notice {
407
+ role;
408
+ botRole;
409
+ constructor(message, role, botRole) {
410
+ super(message);
411
+ this.role = role;
412
+ this.botRole = botRole;
413
+ }
414
+ render() {
415
+ return { components: [new NoticeCard(`I cannot assign a role that is higher than me.\n\nThe role <@&${this.role.id}> is higher than my role <@&${this.botRole.id}> in the hierarchy.`).component] };
416
+ }
417
+ };
418
+ var CannotAssignBotRole = class extends Notice {
419
+ constructor(message = "I cannot assign a managed role.") {
420
+ super(message);
421
+ }
422
+ render() {
423
+ return { components: [new NoticeCard("I cannot assign a managed role.").component] };
424
+ }
425
+ };
426
+ var MissingPermissions = class extends Notice {
427
+ where;
428
+ missingPerms;
429
+ constructor(message, where, missingPerms) {
430
+ super(message);
431
+ this.where = where;
432
+ this.missingPerms = missingPerms;
433
+ }
434
+ render() {
435
+ const bullets = this.missingPerms.map((perm) => `• ${perm}`).join("\n");
436
+ return { components: [new NoticeCard(`The ${labelFor(this.where)} ${mentionFor(this.where)} is missing the following permission entries:\n\n${bullets}`).component] };
437
+ }
438
+ };
439
+ var HasDangerousPermissions = class extends Notice {
440
+ target;
441
+ dangerousPerms;
442
+ constructor(message, target, dangerousPerms) {
443
+ super(message);
444
+ this.target = target;
445
+ this.dangerousPerms = dangerousPerms;
446
+ }
447
+ render() {
448
+ const bullets = this.dangerousPerms.map((perm) => `• ${perm}`).join("\n");
449
+ return { components: [new NoticeCard(`The ${labelFor(this.target)} ${mentionFor(this.target)} has the following permission entries that must not be enabled:\n\n${bullets}`).component] };
450
+ }
451
+ };
452
+ var UserNotFound = class extends Notice {
453
+ userArg;
454
+ constructor(userArg) {
455
+ super(`User not found: ${userArg}`);
456
+ this.userArg = userArg;
457
+ }
458
+ render() {
459
+ return { components: [new NoticeCard(`User probably doesn't exist or was deleted.\n**User Argument:** \`${this.userArg}\`\nPlease check the user ID and try again. Only pass valid user IDs as the argument.`, "User Not Found").component] };
460
+ }
461
+ };
462
+ var UserNotInGuild = class extends Notice {
463
+ constructor(message = "User is not in the guild.") {
464
+ super(message);
465
+ }
466
+ render() {
467
+ return { components: [new NoticeCard(this.message).component] };
468
+ }
469
+ };
470
+ var RoleDoesNotExist = class extends Notice {
471
+ roleId;
472
+ constructor(message, roleId) {
473
+ super(message);
474
+ this.roleId = roleId;
475
+ }
476
+ render() {
477
+ return { components: [new NoticeCard(`The role with ID \`${this.roleId}\` does not exist.`).component] };
478
+ }
479
+ };
480
+ var CouldNotFindChannel = class extends Notice {
481
+ channelId;
482
+ constructor(message, channelId) {
483
+ super(message);
484
+ this.channelId = channelId;
485
+ }
486
+ render() {
487
+ return { components: [new NoticeCard(`Could not find channel with ID \`${this.channelId}\`. It could also be that the channel is not a text channel.`).component] };
488
+ }
489
+ };
490
+
491
+ //#endregion
492
+ //#region src/bot/gates/catalog/Nsfw.ts
493
+ function channelIsNsfw(channel) {
494
+ if (!channel) return false;
495
+ if (channel.isThread()) return channel.parent?.nsfw ?? false;
496
+ return "nsfw" in channel ? channel.nsfw : false;
497
+ }
498
+ /**
499
+ * Requires an age-restricted channel, else refuses. Pass {@link GateNoticeOptions} to reword or replace the refusal.
500
+ *
501
+ * A thread inherits its parent channel's nsfw flag. ModalSubmit has no reliable channel, so it is excluded.
502
+ *
503
+ * @param options - Reword the default refusal with `message`, or replace it with `notice`.
504
+ *
505
+ * @see {@link Gated}
506
+ *
507
+ * @example
508
+ * ```ts
509
+ * \@Gated(Nsfw())
510
+ * \@SlashRoute('nsfwcmd')
511
+ * class NsfwHandler extends SlashHandler<'nsfwcmd'> {
512
+ * async execute() {
513
+ * // ...
514
+ * }
515
+ * }
516
+ * ```
517
+ */
518
+ function Nsfw(options) {
519
+ return defineGate("Nsfw", (ctx) => {
520
+ if (channelIsNsfw(ctx.interaction.channel)) return;
521
+ throw pickNotice(options, (message) => new NotNsfw(message));
522
+ });
523
+ }
524
+
525
+ //#endregion
526
+ //#region src/bot/utilities/permissions/checkPermissions.ts
527
+ /**
528
+ * Map of permission bits to their prettified human readable names.
529
+ */
530
+ const PermissionNames = new Map(Object.entries(PermissionFlagsBits).map(([key, bit]) => [bit, prettify(key)]));
531
+ function checkPermissions(a, b, c, d, e) {
532
+ const { for: pFor, in: pIn, scope, inverse = false, missing: missingCtor, dangerous: dangerousCtor } = a instanceof Role || a instanceof GuildMember ? {
533
+ for: a,
534
+ in: b,
535
+ scope: c,
536
+ inverse: d ?? false,
537
+ ...e
538
+ } : a;
539
+ const Missing = missingCtor ?? MissingPermissions;
540
+ const Dangerous = dangerousCtor ?? HasDangerousPermissions;
541
+ const perms = pIn instanceof Guild ? pFor.permissions : pIn.permissionsFor(pFor, true);
542
+ const names = (bits) => bits.map((bit) => PermissionNames.get(bit) ?? String(bit));
543
+ const present = scope.filter((bit) => perms.has(bit, true));
544
+ const presentNames = names(present);
545
+ if (inverse) {
546
+ if (present.length > 0) throw new Dangerous(`${pFor instanceof Role ? "Role" : "Member"} has dangerous permissions in this ${pIn instanceof Guild ? "guild" : "channel"}`, pFor, presentNames);
547
+ return;
548
+ }
549
+ const missingBits = scope.filter((bit) => !perms.has(bit, true));
550
+ if (missingBits.length > 0) throw new Missing("Missing Any/All/No Permissions", pFor, names(missingBits));
551
+ }
552
+
553
+ //#endregion
554
+ //#region src/bot/gates/catalog/permissions.ts
555
+ const UNCACHED_MEMBER = "Your server member data could not be resolved. Try again.";
556
+ /**
557
+ * Requires the caller to hold every permission in `scope`, via `checkPermissions`. Refuses outside a guild.
558
+ *
559
+ * Interaction-only and excludes ModalSubmit, since a modal lacks a reliable cached caller member.
560
+ *
561
+ * @param scope - The permission flag bits the caller must all hold.
562
+ * @param options - Override each refusal, the outside-guild one with `notInGuild` and the missing-permissions one with `missing`.
563
+ *
564
+ * @see {@link Gated}
565
+ *
566
+ * @example
567
+ * ```ts
568
+ * import { PermissionFlagsBits } from 'discord.js';
569
+ *
570
+ * \@Gated(RequirePermissions([PermissionFlagsBits.BanMembers]))
571
+ * \@SlashRoute('ban')
572
+ * class BanHandler extends SlashHandler<'ban'> {
573
+ * async execute() {
574
+ * const target = this.options.getUser('target');
575
+ * }
576
+ * }
577
+ * ```
578
+ */
579
+ function RequirePermissions(scope, options) {
580
+ return defineGate("RequirePermissions", (ctx) => {
581
+ if (!ctx.guild) throw pickNotice(options?.notInGuild, (message) => new NotInGuild(message));
582
+ if (!ctx.member) throw pickNotice(options?.notInGuild, (message) => new NotInGuild(message ?? UNCACHED_MEMBER));
583
+ checkPermissions(ctx.member, ctx.guild, scope, false, options?.missing ? { missing: options.missing } : void 0);
584
+ });
585
+ }
586
+ /**
587
+ * Requires the bot to hold every permission in `scope`, via `checkPermissions`. Refuses outside a guild.
588
+ *
589
+ * It reads the bot's own member, so it attaches to modal handlers as well.
590
+ *
591
+ * @param scope - The permission flag bits the bot must all hold.
592
+ * @param options - Override each refusal, the outside-guild one with `notInGuild` and the missing-permissions one with `missing`.
593
+ *
594
+ * @see {@link Gated}
595
+ *
596
+ * @example
597
+ * ```ts
598
+ * import { PermissionFlagsBits } from 'discord.js';
599
+ *
600
+ * \@Gated(RequireBotPermissions([PermissionFlagsBits.BanMembers]))
601
+ * \@ModalRoute(MyModalId)
602
+ * class MyModalHandler extends ModalHandler<[typeof MyModalId]> {
603
+ * async execute() {
604
+ * // ...
605
+ * }
606
+ * }
607
+ * ```
608
+ */
609
+ function RequireBotPermissions(scope, options) {
610
+ return defineGate("RequireBotPermissions", (ctx) => {
611
+ const botMember = ctx.guild?.members.me;
612
+ if (!ctx.guild || !botMember) throw pickNotice(options?.notInGuild, (message) => new NotInGuild(message));
613
+ checkPermissions(botMember, ctx.guild, scope, false, options?.missing ? { missing: options.missing } : void 0);
614
+ });
615
+ }
616
+ /**
617
+ * Requires the caller to have `roleId`, read from the member's role cache. Refuses outside a guild first, then
618
+ * when the role is missing.
619
+ *
620
+ * Interaction-only and excludes ModalSubmit.
621
+ *
622
+ * @param roleId - The role snowflake the caller must hold, read from the member's role cache.
623
+ * @param options - Override each refusal, the outside-guild one with `notInGuild` and the missing-role one with `missingRole`.
624
+ *
625
+ * @see {@link Gated}
626
+ *
627
+ * @example
628
+ * ```ts
629
+ * \@Gated(RequireRole('123456789012345678'))
630
+ * \@SlashRoute('vip')
631
+ * class VipHandler extends SlashHandler<'vip'> {
632
+ * async execute() {
633
+ * // ...
634
+ * }
635
+ * }
636
+ * ```
637
+ */
638
+ function RequireRole(roleId, options) {
639
+ return defineGate("RequireRole", (ctx) => {
640
+ if (!ctx.guild) throw pickNotice(options?.notInGuild, (message) => new NotInGuild(message));
641
+ if (!ctx.member) throw pickNotice(options?.notInGuild, (message) => new NotInGuild(message ?? UNCACHED_MEMBER));
642
+ if (ctx.member.roles.cache.has(roleId)) return;
643
+ const role = ctx.guild.roles.cache.get(roleId) ?? null;
644
+ throw pickNotice(options?.missingRole, (message) => new MissingRole(message, role));
645
+ });
646
+ }
647
+
648
+ //#endregion
649
+ //#region src/bot/injectors/EmojiInjector.ts
650
+ const emojiStorage = {};
651
+ function isEmojiTuple(v) {
652
+ return Array.isArray(v) && v.length === 2 && typeof v[0] === "string" && typeof v[1] === "string";
653
+ }
654
+ /**
655
+ * Global emoji mappings object
656
+ *
657
+ * @see {@link EmojiMap}
658
+ */
659
+ const Emojis = emojiStorage;
660
+ /**
661
+ * Loads and injects emojis based on bot configuration.
662
+ *
663
+ * For emojis injected from specific guilds, ensure that the Guilds intent is provided in client options.
664
+ *
665
+ * @internal
666
+ */
667
+ var EmojiInjector = class {
668
+ core;
669
+ logger = new Logger("Emojis");
670
+ constructor(core) {
671
+ this.core = core;
672
+ }
673
+ async init() {
674
+ this.clearEmojis();
675
+ if (!this.core.config.bot.emojis || Object.keys(this.core.config.bot.emojis).length === 0) {
676
+ this.logger.debug(chalk.bold.yellow("No emojis configured, skipping emoji injection."));
677
+ return;
678
+ }
679
+ const configEmojis = this.core.config.bot.emojis;
680
+ await this.core.bot.client.application?.emojis.fetch();
681
+ const failures = [];
682
+ const fetchedGuilds = /* @__PURE__ */ new Set();
683
+ for (const [key, value] of Object.entries(configEmojis)) if (isEmojiTuple(value)) await this.resolveTuple(key, value, failures, fetchedGuilds);
684
+ else if (typeof value === "string") this.resolveString(key, value, failures);
685
+ else failures.push(` - "${key}" has an invalid value (expected a name or [name, guildId])`);
686
+ if (failures.length > 0) throw new SeedcordError(SeedcordErrorCode.ConfigEmojiUnresolved, [failures.length, failures.join("\n")]);
687
+ this.logger.utils.summary("Loaded emojis", { emojis: Object.keys(emojiStorage).length });
688
+ }
689
+ async resolveTuple(key, value, failures, fetchedGuilds) {
690
+ const [emojiName, guildId] = value;
691
+ const guild = this.core.bot.client.guilds.cache.get(guildId);
692
+ if (!guild) {
693
+ failures.push(` - "${emojiName}" for "${key}" targets guild ${guildId}, which is not available (check the Guilds intent)`);
694
+ return;
695
+ }
696
+ if (!fetchedGuilds.has(guildId)) {
697
+ await guild.emojis.fetch();
698
+ fetchedGuilds.add(guildId);
699
+ }
700
+ const guildEmoji = guild.emojis.cache.find((e) => e.name === emojiName);
701
+ if (!guildEmoji) {
702
+ failures.push(` - "${emojiName}" for "${key}" was not found in guild ${guildId}`);
703
+ return;
704
+ }
705
+ emojiStorage[key] = guildEmoji;
706
+ }
707
+ resolveString(key, emojiName, failures) {
708
+ const appEmoji = this.core.bot.client.application?.emojis.cache.find((e) => e.name === emojiName);
709
+ if (!appEmoji) {
710
+ failures.push(` - "${emojiName}" for "${key}" was not found among the application emojis`);
711
+ return;
712
+ }
713
+ emojiStorage[key] = appEmoji;
714
+ }
715
+ clearEmojis() {
716
+ for (const key of Object.keys(emojiStorage)) Reflect.deleteProperty(emojiStorage, key);
717
+ }
718
+ };
719
+
720
+ //#endregion
721
+ //#region src/bot/injectors/CommandMentionInjector.ts
722
+ const mentionStorage = {};
723
+ /**
724
+ * Ready-to-send command mention strings, keyed by {@link SlashOptionRegistry}.
725
+ *
726
+ * A value is a clickable `</name:id>` when the command's id resolved from the deploy, otherwise the plain
727
+ * `/name` text. Populated by {@link CommandMentionInjector} after each deploy.
728
+ */
729
+ const CommandMentions = mentionStorage;
730
+ const MULTI_GUILD = Symbol("seedcord:commandmentions:multi-guild");
731
+ /**
732
+ * Turns each deployed slash route into a clickable command mention exposed through {@link CommandMentions}.
733
+ *
734
+ * Consumes the ids {@link DeployResult} carries, so it runs after a deploy rather than resolving from a name
735
+ * cache (discord.js offers none for command ids). A global command is clickable everywhere by its app-wide id.
736
+ * A guild command deployed to one guild is clickable by that guild's id. A command deployed to two or more
737
+ * guilds mints a different id per guild, so one accessor key cannot resolve it, and it falls back to plain
738
+ * `/name` text with one warn. On a non-owning shard a guild command also falls back to plain text.
739
+ *
740
+ * @internal
741
+ */
742
+ var CommandMentionInjector = class {
743
+ core;
744
+ logger = new Logger("CommandMentions");
745
+ constructor(core) {
746
+ this.core = core;
747
+ }
748
+ inject(deploy) {
749
+ this.clear();
750
+ const globalIds = this.indexByName(deploy.global);
751
+ const guildIds = this.indexGuilds(deploy.guilds);
752
+ const warned = /* @__PURE__ */ new Set();
753
+ let clickable = 0;
754
+ for (const command of this.allSlashBuilders()) {
755
+ const id = this.resolveId(command.name, globalIds, guildIds, warned);
756
+ for (const leaf of routeLeavesOf(command.toJSON())) {
757
+ mentionStorage[leaf.route] = id ? this.toMention(leaf.route, id) : this.toPlain(leaf.route);
758
+ if (id) clickable++;
759
+ }
760
+ }
761
+ this.logger.utils.summary("Linked mentions", {
762
+ clickable,
763
+ plain: Object.keys(mentionStorage).length - clickable
764
+ });
765
+ }
766
+ allSlashBuilders() {
767
+ const registry = this.core.bot.commands;
768
+ if (!registry) return [];
769
+ const slash = [...registry.globalCommands, ...registry.guildCommands.values()].flat().filter((command) => command instanceof SlashCommandBuilder);
770
+ return [...new Set(slash)];
771
+ }
772
+ indexByName(collection) {
773
+ const map = /* @__PURE__ */ new Map();
774
+ for (const command of collection.values()) map.set(command.name, command.id);
775
+ return map;
776
+ }
777
+ indexGuilds(guilds) {
778
+ const map = /* @__PURE__ */ new Map();
779
+ for (const collection of guilds.values()) for (const command of collection.values()) {
780
+ const existing = map.get(command.name);
781
+ if (existing === void 0) map.set(command.name, command.id);
782
+ else if (existing !== command.id) map.set(command.name, MULTI_GUILD);
783
+ }
784
+ return map;
785
+ }
786
+ resolveId(name, globalIds, guildIds, warned) {
787
+ const global = globalIds.get(name);
788
+ if (global) return global;
789
+ const guild = guildIds.get(name);
790
+ if (guild === void 0) return void 0;
791
+ if (guild === MULTI_GUILD) {
792
+ if (!warned.has(name)) {
793
+ this.logger.warn(`${name} is deployed to multiple guilds, falling back to plain text (not clickable).`);
794
+ warned.add(name);
795
+ }
796
+ return;
797
+ }
798
+ return guild;
799
+ }
800
+ toMention(route, id) {
801
+ const [name, middle, sub] = route.split("/");
802
+ if (name && middle && sub) return chatInputApplicationCommandMention(name, middle, sub, id);
803
+ if (name && middle) return chatInputApplicationCommandMention(name, middle, id);
804
+ return chatInputApplicationCommandMention(name ?? route, id);
805
+ }
806
+ toPlain(route) {
807
+ return `/${route.replaceAll("/", " ")}`;
808
+ }
809
+ clear() {
810
+ for (const key of Object.keys(mentionStorage)) Reflect.deleteProperty(mentionStorage, key);
811
+ }
812
+ };
813
+
814
+ //#endregion
815
+ //#region src/bot/utilities/channels/fetchText.ts
816
+ /**
817
+ * Fetches and validates a text channel. Refuses when the channel doesn't exist or isn't a text channel.
818
+ *
819
+ * @param client - The Discord client instance
820
+ * @param channelId - Channel ID or TextChannel instance
821
+ * @returns Promise resolving to the text channel
822
+ */
823
+ async function fetchText(client, channelId) {
824
+ if (channelId instanceof TextChannel) return channelId;
825
+ let channel = client.channels.cache.get(channelId);
826
+ if (!channel) try {
827
+ channel = await client.channels.fetch(channelId);
828
+ } catch (err) {
829
+ if (err instanceof DiscordAPIError && err.code === RESTJSONErrorCodes.UnknownChannel) throw new CouldNotFindChannel("Channel not found or not a text channel", channelId);
830
+ throw err;
831
+ }
832
+ if (channel?.isTextBased()) return channel;
833
+ throw new CouldNotFindChannel("Channel not found or not a text channel", channelId);
834
+ }
835
+
836
+ //#endregion
837
+ //#region src/bot/utilities/permissions/checkBotPermissions.ts
838
+ /**
839
+ * Checks if the bot has required permissions in a {@link Guild} or {@link TextChannel}. Refuses when a
840
+ * required permission is missing.
841
+ *
842
+ * @param target - Guild or text channel to check in
843
+ * @param scope - Permission bits to validate
844
+ * @param inverse - Whether to check for absence of the given permissions
845
+ * @param errors - Optional custom error constructors
846
+ *
847
+ * @example
848
+ * ```ts
849
+ * import { PermissionFlagsBits } from 'discord.js';
850
+ * import { checkBotPermissions } from '@seedcord/gateway';
851
+ *
852
+ * // Check if the bot has SendMessages and ViewChannel permissions in a text channel
853
+ * checkBotPermissions(textChannel, [
854
+ * PermissionFlagsBits.SendMessages,
855
+ * PermissionFlagsBits.ViewChannel
856
+ * ]);
857
+ * ```
858
+ */
859
+ function checkBotPermissions(target, scope, inverse = false, errors) {
860
+ if (target instanceof Guild) {
861
+ const me = target.members.me;
862
+ if (!me) {
863
+ const names = scope.map((bit) => PermissionNames.get(bit) ?? String(bit));
864
+ throw new ((errors?.missing) ?? MissingPermissions)("Missing Permissions", target, names);
865
+ }
866
+ checkPermissions(me, target, scope, inverse, errors);
867
+ return;
868
+ }
869
+ const me = target.guild.members.me;
870
+ if (!me) {
871
+ new Logger("checkBotPermissions").warn(`Bot member is unavailable in guild ${target.guild.id} while checking permissions in channel ${target.id}`);
872
+ const names = scope.map((bit) => PermissionNames.get(bit) ?? String(bit));
873
+ throw new ((errors?.missing) ?? MissingPermissions)("Missing Permissions", target, names);
874
+ }
875
+ checkPermissions(me, target, scope, inverse, errors);
876
+ }
877
+
878
+ //#endregion
879
+ //#region src/bot/utilities/roles/getBotRole.ts
880
+ /**
881
+ * Gets the bot's managed role in a guild.
882
+ *
883
+ * @param guild - The guild to get the bot role from
884
+ * @returns The bot's managed role in the guild
885
+ * @throws A **SeedcordError** if the client user is unavailable or if the bot role is missing
886
+ */
887
+ function getBotRole(guild) {
888
+ const botRole = guild.roles.botRoleFor(guild.client.user);
889
+ if (!botRole) throw new SeedcordError(SeedcordErrorCode.CoreBotRoleMissing, [guild.id]);
890
+ return botRole;
891
+ }
892
+
893
+ //#endregion
894
+ //#region src/bot/utilities/permissions/hasPermsToAssign.ts
895
+ /**
896
+ * Validates if the bot can assign a target role. Refuses when the target role is above the bot's, is managed, or the bot lacks Manage Roles.
897
+ *
898
+ * @param roleOrOptions - Target role or complete options for the check
899
+ *
900
+ * @example
901
+ * ```ts
902
+ * import { hasPermsToAssign } from '@seedcord/gateway';
903
+ *
904
+ * // Check if the bot can assign a specific role
905
+ * hasPermsToAssign(role);
906
+ *
907
+ * // Check with custom error handling
908
+ * hasPermsToAssign({
909
+ * targetRole: role,
910
+ * errors: {
911
+ * higher: CustomHigherError,
912
+ * managed: CustomManagedError,
913
+ * missing: CustomMissingPermissionsError
914
+ * }
915
+ * });
916
+ * ```
917
+ */
918
+ function hasPermsToAssign(roleOrOptions) {
919
+ const { targetRole, errors } = roleOrOptions instanceof Role ? {
920
+ targetRole: roleOrOptions,
921
+ errors: void 0
922
+ } : roleOrOptions;
923
+ const HigherErr = errors?.higher ?? RoleHigherThanMe;
924
+ const ManagedErr = errors?.managed ?? CannotAssignBotRole;
925
+ const Missing = errors?.missing ?? MissingPermissions;
926
+ const botRole = getBotRole(targetRole.guild);
927
+ if (targetRole.comparePositionTo(botRole) >= 0) throw new HigherErr("Role is higher than me", targetRole, botRole);
928
+ if (targetRole.managed) throw new ManagedErr(`Cannot assign managed role ${targetRole.name}`);
929
+ checkBotPermissions(targetRole.guild, [PermissionFlagsBits.ManageRoles], false, { missing: Missing });
930
+ }
931
+
932
+ //#endregion
933
+ //#region src/bot/utilities/roles/fetchRole.ts
934
+ function isUnknownRole(err) {
935
+ return err instanceof DiscordAPIError && err.code === RESTJSONErrorCodes.UnknownRole;
936
+ }
937
+ async function fetchRoleInGuild(guild, roleId) {
938
+ const cached = guild.roles.cache.get(roleId);
939
+ if (cached) return cached;
940
+ try {
941
+ return await guild.roles.fetch(roleId);
942
+ } catch (err) {
943
+ if (isUnknownRole(err)) throw new RoleDoesNotExist("Role not found in specified guild", roleId);
944
+ throw err;
945
+ }
946
+ }
947
+ async function scanGuildsForRole(client, roleId) {
948
+ const cached = client.guilds.cache.map((guild) => guild.roles.cache.get(roleId)).find(Boolean);
949
+ if (cached) return cached;
950
+ for (const guild of client.guilds.cache.values()) try {
951
+ const role = await guild.roles.fetch(roleId);
952
+ if (role) return role;
953
+ } catch (err) {
954
+ if (isUnknownRole(err)) continue;
955
+ throw err;
956
+ }
957
+ return null;
958
+ }
959
+ /**
960
+ * Fetches a role by ID from a client or guild. Refuses when the role doesn't exist.
961
+ *
962
+ * @param clientOrGuild - Discord client or guild instance
963
+ * @param roleId - The role ID to fetch
964
+ * @returns Promise resolving to the role
965
+ */
966
+ async function fetchRole(clientOrGuild, roleId) {
967
+ if (!roleId) throw new RoleDoesNotExist("Role ID is null or undefined", roleId);
968
+ const role = clientOrGuild instanceof Guild ? await fetchRoleInGuild(clientOrGuild, roleId) : await scanGuildsForRole(clientOrGuild, roleId);
969
+ if (!role) throw new RoleDoesNotExist("Role not found", roleId);
970
+ return role;
971
+ }
972
+
973
+ //#endregion
974
+ //#region src/bot/utilities/users/fetchGuildMember.ts
975
+ /**
976
+ * Fetches a guild member by user ID. Refuses when the user is not in the guild.
977
+ *
978
+ * @param guild - The guild to fetch the member from
979
+ * @param userId - The Discord user ID
980
+ * @returns Promise resolving to the guild member
981
+ */
982
+ async function fetchGuildMember(guild, userId) {
983
+ let user = guild.members.cache.get(userId);
984
+ user ??= await guild.members.fetch(userId).catch((err) => {
985
+ if (err instanceof DiscordAPIError && err.code === RESTJSONErrorCodes.UnknownMember) throw new UserNotInGuild(`User with ID ${userId} not found in guild`);
986
+ throw err;
987
+ });
988
+ return user;
989
+ }
990
+
991
+ //#endregion
992
+ //#region src/bot/utilities/users/fetchManyGuildMembers.ts
993
+ /**
994
+ * Fetches multiple guild members by user IDs.
995
+ *
996
+ * @param guild - The guild to fetch members from
997
+ * @param userIds - Array of Discord user IDs
998
+ * @returns Promise resolving to array of successfully fetched members
999
+ */
1000
+ async function fetchManyGuildMembers(guild, userIds) {
1001
+ return (await Promise.allSettled(userIds.map((userId) => fetchGuildMember(guild, userId)))).filter((result) => result.status === "fulfilled").map((result) => result.value);
1002
+ }
1003
+
1004
+ //#endregion
1005
+ //#region src/bot/utilities/users/fetchUser.ts
1006
+ /**
1007
+ * Fetches a Discord user by ID. Refuses when the user doesn't exist, with `options.throwAs` or the default.
1008
+ *
1009
+ * @param client - The Discord client instance
1010
+ * @param userId - The Discord user ID
1011
+ * @param options - Optional overrides, including the {@link FetchUserOptions.throwAs} notice
1012
+ * @returns Promise resolving to the user
1013
+ */
1014
+ async function fetchUser(client, userId, options) {
1015
+ const Throw = options?.throwAs ?? UserNotFound;
1016
+ let user = client.users.cache.get(userId);
1017
+ user ??= await client.users.fetch(userId).catch((err) => {
1018
+ if (err instanceof DiscordAPIError && err.code === RESTJSONErrorCodes.UnknownUser) throw new Throw(userId);
1019
+ throw err;
1020
+ });
1021
+ return user;
1022
+ }
1023
+
1024
+ //#endregion
1025
+ //#region src/bot/utilities/users/fetchManyUsers.ts
1026
+ /**
1027
+ * Fetches multiple Discord users by IDs.
1028
+ *
1029
+ * @param client - The Discord client instance
1030
+ * @param userIds - Array of Discord user IDs
1031
+ * @param options - Optional overrides threaded to each {@link fetchUser} call
1032
+ * @returns Promise resolving to array of successfully fetched users
1033
+ */
1034
+ async function fetchManyUsers(client, userIds, options) {
1035
+ return (await Promise.allSettled(userIds.map((userId) => fetchUser(client, userId, options)))).filter((result) => result.status === "fulfilled").map((result) => result.value);
1036
+ }
1037
+
1038
+ //#endregion
1039
+ //#region src/bot/utilities/users/updateMemberRoles.ts
1040
+ /**
1041
+ * Updates a guild member's roles by adding and removing specified roles.
1042
+ *
1043
+ * @param rolesToAdd - Array of role IDs to add to the member
1044
+ * @param rolesToRemove - Array of role IDs to remove from the member
1045
+ * @param member - The guild member to update
1046
+ * @returns Promise that resolves when roles are updated
1047
+ */
1048
+ async function updateMemberRoles(rolesToAdd, rolesToRemove, member) {
1049
+ const current = new Set(member.roles.cache.map((r) => r.id));
1050
+ const toAdd = new Set(rolesToAdd);
1051
+ const toRemove = new Set(rolesToRemove);
1052
+ const updated = current.union(toAdd).difference(toRemove);
1053
+ await member.roles.set([...updated]);
1054
+ }
1055
+
1056
+ //#endregion
1057
+ //#region src/bot/harmlessApiCodes.ts
1058
+ /**
1059
+ * Discord API error codes that mean a dead end on an interaction, a dead token, a double ack, or a gone
1060
+ * message. There is nothing to show the user and no bug to report. The controller boundary drops them on
1061
+ * the original throw, and {@link ReplySender} drops them on its own send.
1062
+ *
1063
+ * @internal
1064
+ */
1065
+ const HARMLESS_API_CODES = new Set([
1066
+ RESTJSONErrorCodes.UnknownInteraction,
1067
+ RESTJSONErrorCodes.InteractionHasAlreadyBeenAcknowledged,
1068
+ RESTJSONErrorCodes.UnknownMessage
1069
+ ]);
1070
+
1071
+ //#endregion
1072
+ //#region src/miscellaneous/flagsFor.ts
1073
+ /**
1074
+ * Builds the `flags` bitfield for a framework reply. Every framework reply is ComponentsV2, so the
1075
+ * IsComponentsV2 flag is always set.
1076
+ *
1077
+ * @param ephemeral - Whether the reply is ephemeral.
1078
+ * @returns The OR'd `MessageFlags` value as a plain number.
1079
+ *
1080
+ * @internal
1081
+ */
1082
+ function flagsFor(ephemeral) {
1083
+ let flags = MessageFlags.IsComponentsV2;
1084
+ if (ephemeral) flags |= MessageFlags.Ephemeral;
1085
+ return flags;
1086
+ }
1087
+
1088
+ //#endregion
1089
+ //#region src/bot/ReplySender.ts
1090
+ /**
1091
+ * Sends a {@link ReplyResponse} to an interaction, picking reply, editReply, or followUp from the live
1092
+ * acknowledgement state. Logs and drops its own send failures so a dead token never escapes into the
1093
+ * controller.
1094
+ */
1095
+ var ReplySender = class {
1096
+ interaction;
1097
+ logger = new Logger("ReplySender");
1098
+ constructor(interaction) {
1099
+ this.interaction = interaction;
1100
+ }
1101
+ /**
1102
+ * Sends the reply and returns the sent message so a caller can attach a collector to it. Never throws,
1103
+ * a failed send is logged and dropped and resolves to `undefined`.
1104
+ *
1105
+ * @param response - The ComponentsV2 reply to show.
1106
+ * @param ephemeral - Whether the reply is ephemeral. {@default `true`}
1107
+ * @returns The sent {@link Message}, or `undefined` when the send was swallowed.
1108
+ */
1109
+ async send(response, ephemeral = true) {
1110
+ try {
1111
+ return await this.dispatch(response, ephemeral);
1112
+ } catch (error) {
1113
+ this.logSwallowed("send", error);
1114
+ return;
1115
+ }
1116
+ }
1117
+ /**
1118
+ * Edits an already-sent message to a new {@link ReplyResponse}. Used to swap a confirmation prompt for
1119
+ * its outcome. Never throws, a failed edit is logged and dropped.
1120
+ *
1121
+ * @param message - The message to edit (the handle a prior {@link send} returned).
1122
+ * @param response - The reply to replace it with.
1123
+ */
1124
+ async edit(message, response) {
1125
+ try {
1126
+ await this.interaction.webhook.editMessage(message, this.editBody(response));
1127
+ } catch (error) {
1128
+ this.logSwallowed("edit", error);
1129
+ }
1130
+ }
1131
+ async dispatch(response, ephemeral) {
1132
+ if (this.interaction.replied) return await this.interaction.followUp(this.replyOptions(response, ephemeral));
1133
+ if (this.interaction.deferred) {
1134
+ if (this.interaction.ephemeral === null) return await this.interaction.followUp(this.replyOptions(response, ephemeral));
1135
+ return await this.interaction.editReply(this.editBody(response));
1136
+ }
1137
+ await this.interaction.reply(this.replyOptions(response, ephemeral));
1138
+ return await this.interaction.fetchReply();
1139
+ }
1140
+ replyOptions(response, ephemeral) {
1141
+ return {
1142
+ components: response.components,
1143
+ flags: flagsFor(ephemeral),
1144
+ ...response.allowedMentions && { allowedMentions: response.allowedMentions },
1145
+ ...response.files && { files: response.files }
1146
+ };
1147
+ }
1148
+ editBody(response) {
1149
+ return {
1150
+ components: response.components,
1151
+ flags: MessageFlags.IsComponentsV2,
1152
+ ...response.allowedMentions && { allowedMentions: response.allowedMentions },
1153
+ ...response.files && { files: response.files }
1154
+ };
1155
+ }
1156
+ logSwallowed(action, error) {
1157
+ if (error instanceof DiscordAPIError && HARMLESS_API_CODES.has(error.code)) {
1158
+ this.logger.debug(`reply ${action} hit harmless code ${error.code}`);
1159
+ return;
1160
+ }
1161
+ this.logger.error(`reply ${action} failed`, error);
1162
+ }
1163
+ };
1164
+
1165
+ //#endregion
1166
+ //#region src/bot/confirm/reserved.ts
1167
+ const RESERVED_CONFIRM_PREFIX = "__seedcord_confirm";
1168
+ /**
1169
+ * The reserved confirm/cancel codec. It has no route, so the dispatcher ignores its clicks and only the
1170
+ * in-process collector reads them. Do not mint a real component from it.
1171
+ *
1172
+ * @internal
1173
+ */
1174
+ const CONFIRM_DEF = new CustomId(RESERVED_CONFIRM_PREFIX).oneOf("choice", ["confirm", "cancel"]);
1175
+
1176
+ //#endregion
1177
+ //#region src/bot/confirm/getConfirmation.ts
1178
+ const DEFAULT_TIMEOUT_MS = 3e4;
1179
+ const CONFIRM_IDS = {
1180
+ confirm: CONFIRM_DEF.encode({ choice: "confirm" }),
1181
+ cancel: CONFIRM_DEF.encode({ choice: "cancel" })
1182
+ };
1183
+ var ConfirmButtons = class extends RowComponent {
1184
+ constructor(options) {
1185
+ super("button");
1186
+ this.instance.addComponents(new ButtonBuilder().setCustomId(CONFIRM_IDS.confirm).setLabel(options?.confirmLabel ?? "Confirm").setStyle(options?.confirmStyle ?? ButtonStyle.Danger), new ButtonBuilder().setCustomId(CONFIRM_IDS.cancel).setLabel(options?.cancelLabel ?? "Cancel").setStyle(ButtonStyle.Secondary));
1187
+ }
1188
+ };
1189
+ var ConfirmPromptCard = class extends BuilderComponent {
1190
+ constructor(text, options) {
1191
+ super("container");
1192
+ this.instance.addTextDisplayComponents(new TextDisplayBuilder().setContent(text)).addActionRowComponents(new ConfirmButtons(options).component);
1193
+ }
1194
+ };
1195
+ function defaultPrompt(text, options) {
1196
+ return { components: [new ConfirmPromptCard(text, options).component] };
1197
+ }
1198
+ async function collectChoice(message, userId, timeoutMs) {
1199
+ try {
1200
+ return await message.awaitMessageComponent({
1201
+ componentType: ComponentType.Button,
1202
+ time: timeoutMs,
1203
+ filter: (click) => click.user.id === userId && CONFIRM_DEF.owns(click.customId)
1204
+ });
1205
+ } catch {
1206
+ return null;
1207
+ }
1208
+ }
1209
+ async function settle(sender, interaction, message, outcome) {
1210
+ if (outcome === void 0) {
1211
+ await interaction.deleteReply(message).catch(() => void 0);
1212
+ return;
1213
+ }
1214
+ await sender.edit(message, typeof outcome === "function" ? await outcome() : outcome);
1215
+ }
1216
+ async function getConfirmation(interaction, prompt, options) {
1217
+ const { ephemeral = true, timeoutMs = DEFAULT_TIMEOUT_MS } = options ?? {};
1218
+ const response = typeof prompt === "string" ? defaultPrompt(prompt, options) : await prompt(CONFIRM_IDS);
1219
+ const sender = new ReplySender(interaction);
1220
+ const message = await sender.send(response, ephemeral);
1221
+ if (!message) return false;
1222
+ const winner = await collectChoice(message, interaction.user.id, timeoutMs);
1223
+ if (!winner) {
1224
+ await settle(sender, interaction, message, options?.onTimeout);
1225
+ return false;
1226
+ }
1227
+ await winner.deferUpdate().catch(() => void 0);
1228
+ const confirmed = winner.customId === CONFIRM_IDS.confirm;
1229
+ await settle(sender, interaction, message, confirmed ? options?.onConfirm : options?.onCancel);
1230
+ return confirmed;
1231
+ }
1232
+
1233
+ //#endregion
1234
+ //#region src/hmr/devChannel.ts
1235
+ let channel;
1236
+ function setDevChannel(next) {
1237
+ channel = next;
1238
+ }
1239
+ function getDevChannel() {
1240
+ return channel;
1241
+ }
1242
+
1243
+ //#endregion
1244
+ //#region src/interfaces/Plugin.ts
1245
+ /**
1246
+ * Base class for Seedcord plugins
1247
+ *
1248
+ * Extend this class to create plugins that integrate with the Seedcord lifecycle.
1249
+ * Plugins have access to the core instance and must implement initialization logic.
1250
+ */
1251
+ var Plugin = class extends TypedEventEmitter {
1252
+ pluggable;
1253
+ name = this.constructor.name;
1254
+ constructor(pluggable) {
1255
+ super();
1256
+ this.pluggable = pluggable;
1257
+ }
1258
+ /**
1259
+ * Reloads plugin state on an HMR update. The base implementation is a no-op, override it in your plugin.
1260
+ * @virtual
1261
+ */
1262
+ onHmr(_event) {
1263
+ return Promise.resolve();
1264
+ }
1265
+ /**
1266
+ * Registers critical file patterns that should trigger a full restart when changed in Dev HMR.
1267
+ * @param patterns - Glob patterns relative to the project root
1268
+ */
1269
+ registerCriticalFiles(patterns) {
1270
+ getDevChannel()?.send("seedcord:register-critical-files", { patterns });
1271
+ }
1272
+ /** @internal */
1273
+ removeListener(event, listener) {
1274
+ return super.removeListener(event, listener);
1275
+ }
1276
+ /** @internal */
1277
+ removeAllListeners(event) {
1278
+ return super.removeAllListeners(event);
1279
+ }
1280
+ };
1281
+ /**
1282
+ * Base class for objects that can have plugins attached.
1283
+ *
1284
+ * Provides plugin attachment capabilities and lifecycle management. Plugins are attached during
1285
+ * configuration and initialized during startup. Not constructed directly, the host is a {@link Seedcord}.
1286
+ */
1287
+ var Pluggable = class Pluggable extends TypedEventEmitter {
1288
+ isInitialized = false;
1289
+ shutdown;
1290
+ startup;
1291
+ plugins = [];
1292
+ static PLUGIN_INIT_TIMEOUT_MS = 15e3;
1293
+ constructor(shutdown, startup) {
1294
+ super();
1295
+ this.shutdown = shutdown;
1296
+ this.startup = startup;
1297
+ }
1298
+ /** @internal */
1299
+ async init() {
1300
+ if (this.isInitialized) return this;
1301
+ await this.startup.run();
1302
+ this.isInitialized = true;
1303
+ return this;
1304
+ }
1305
+ /**
1306
+ * Attaches a plugin to this instance
1307
+ *
1308
+ * Plugins provide external functionality and are initialized during the specified startup phase.
1309
+ * The plugin instance becomes available as a property in `core` wherever it's available.
1310
+ *
1311
+ * Make sure to augment the {@link Core} interface with the plugin type to ensure TypeScript recognizes it and provides intellisense.
1312
+ *
1313
+ * @typeParam Key - The property name for accessing the plugin
1314
+ * @typeParam Ctor - The plugin constructor type
1315
+ * @param key - Property name to access the plugin instance
1316
+ * @param Plugin - Plugin constructor class
1317
+ * @param startupPhase - When during startup to initialize this plugin ({@link StartupPhase})
1318
+ * @param args - Additional arguments to pass to the plugin constructor
1319
+ * @returns This instance with the plugin attached as a typed property
1320
+ * @throws A **SeedcordError** When called after initialization or if key already exists
1321
+ * @example
1322
+ * ```typescript
1323
+ * seedcord.attach('db', Mongo, StartupPhase.Configuration, { uri: 'mongodb://...', name: 'seedcord', dir: ... })
1324
+ * ```
1325
+ */
1326
+ attach(key, Plugin, startupPhase, ...args) {
1327
+ if (this.isInitialized) throw new SeedcordError(SeedcordErrorCode.CorePluginAfterInit);
1328
+ if (key in this) throw new SeedcordError(SeedcordErrorCode.CorePluginKeyExists, [key]);
1329
+ const instance = new Plugin(this, ...args);
1330
+ this.plugins.push(instance);
1331
+ const entry = { [key]: instance };
1332
+ this.startup.addTask(startupPhase, `Plugin:${key}`, async () => {
1333
+ instance.logger.utils.initialization(key, "start");
1334
+ await instance.init();
1335
+ instance.logger.utils.initialization(key, "end");
1336
+ }, Pluggable.PLUGIN_INIT_TIMEOUT_MS);
1337
+ return Object.assign(this, entry);
1338
+ }
1339
+ /** @internal */
1340
+ removeListener(event, listener) {
1341
+ return super.removeListener(event, listener);
1342
+ }
1343
+ /** @internal */
1344
+ removeAllListeners(event) {
1345
+ return super.removeAllListeners(event);
1346
+ }
1347
+ };
1348
+
1349
+ //#endregion
1350
+ //#region src/handlers/BaseHandler.ts
1351
+ /**
1352
+ * Base class for a Discord event or interaction handler. Don't register handlers directly, use the more specific handler subclasses.
1353
+ */
1354
+ var BaseHandler = class {
1355
+ core;
1356
+ event;
1357
+ logger;
1358
+ dispatch;
1359
+ constructor(event, core, dispatch) {
1360
+ this.core = core;
1361
+ this.event = event;
1362
+ this.logger = new Logger(this.constructor.name);
1363
+ this.dispatch = dispatch;
1364
+ }
1365
+ /** @internal */
1366
+ getEvent() {
1367
+ return this.event;
1368
+ }
1369
+ };
1370
+
1371
+ //#endregion
1372
+ //#region src/handlers/interaction/InteractionMiddleware.ts
1373
+ /**
1374
+ * Base class for interaction middleware
1375
+ *
1376
+ * Middleware runs before interaction handlers and can modify behavior or block execution.
1377
+ * Unlike handlers, middleware should not send responses directly.
1378
+ *
1379
+ * @typeParam Repliable - The interaction type this middleware processes
1380
+ */
1381
+ var InteractionMiddleware = class extends BaseHandler {
1382
+ constructor(event, core) {
1383
+ super(event, core);
1384
+ }
1385
+ };
1386
+
1387
+ //#endregion
1388
+ //#region src/handlers/interaction/InteractionHandler.ts
1389
+ /**
1390
+ * Shared base the typed interaction handlers extend.
1391
+ *
1392
+ * Not a public entry point. You should be using {@link SlashHandler}, {@link ButtonHandler}, {@link ModalHandler},
1393
+ * or {@link SelectMenuHandler} instead. This class only carries the repliable-event plumbing those bases share,
1394
+ * so DO NOT use it directly.
1395
+ *
1396
+ * @typeParam Repliable - The interaction type this handler processes
1397
+ */
1398
+ var InteractionHandler = class extends BaseHandler {
1399
+ constructor(event, core, dispatch) {
1400
+ super(event, core, dispatch);
1401
+ }
1402
+ };
1403
+
1404
+ //#endregion
1405
+ //#region src/bot/utilities/miscellaneous/slashRouteOf.ts
1406
+ /**
1407
+ * Computes the dispatch route for a chat-input or autocomplete interaction. The controller and
1408
+ * `seedcord codegen` both assemble route keys through the same {@link buildSlashRoute}, so a dispatched
1409
+ * interaction and a generated registry key always match.
1410
+ *
1411
+ * @internal
1412
+ */
1413
+ function slashRouteOf(interaction) {
1414
+ const group = interaction.options.getSubcommandGroup(false) ?? void 0;
1415
+ const subcommand = interaction.options.getSubcommand(false) ?? void 0;
1416
+ return buildSlashRoute(interaction.commandName, subcommand, group);
1417
+ }
1418
+
1419
+ //#endregion
1420
+ //#region src/handlers/interaction/SlashHandler.ts
1421
+ /**
1422
+ * Base class for a chat-input (slash) command handler.
1423
+ *
1424
+ * Pass the route from the generated registry as the generic, the same string as `@SlashRoute`, then read
1425
+ * `this.options` for a single command or `this.match` for several. Command authoring stays plain
1426
+ * discord.js, `seedcord codegen` reads its `toJSON()` to type these options.
1427
+ *
1428
+ * @typeParam Route - One or more route keys from {@link SlashOptionRegistry}, e.g. `'ban'` or `'ban' | 'kick'`.
1429
+ * @typeParam Cache - The interaction cache state, `'cached'` by default.
1430
+ *
1431
+ * @example
1432
+ * ```ts
1433
+ * \@SlashRoute('ban')
1434
+ * class BanHandler extends SlashHandler<'ban'> {
1435
+ * async execute() {
1436
+ * const target = this.options.getUser('target'); // User
1437
+ * const reason = this.options.getString('reason'); // string | null
1438
+ * }
1439
+ * }
1440
+ * ```
1441
+ */
1442
+ var SlashHandler = class extends InteractionHandler {
1443
+ /**
1444
+ * The typed options for this command's route. Required options drop the null, choices narrow to their
1445
+ * literal union, and only the getters for kinds this command actually uses appear. Use `this.event.options`
1446
+ * directly for anything outside this view, such as narrowing a channel option by type.
1447
+ */
1448
+ get options() {
1449
+ return this.event.options;
1450
+ }
1451
+ /**
1452
+ * Run the arm for whichever command fired. Use this only when the handler is registered for several
1453
+ * routes. A single-route handler reads `this.options` directly instead, match buys nothing there.
1454
+ *
1455
+ * Provide one arm per registered route, keyed by its route string, and each arm receives that route's
1456
+ * own narrowed options. The arms must cover every route in the generic, a missing route or an unknown
1457
+ * key is a compile error.
1458
+ *
1459
+ * @param arms - One handler per registered route, keyed by route string.
1460
+ * @returns The result of the arm that ran.
1461
+ *
1462
+ * @example
1463
+ * ```ts
1464
+ * \@SlashRoute('ban', 'kick')
1465
+ * class ModHandler extends SlashHandler<'ban' | 'kick'> {
1466
+ * async execute() {
1467
+ * await this.match({
1468
+ * ban: (options) => this.event.guild?.members.ban(options.getUser('target', true).id),
1469
+ * kick: (options) => this.event.guild?.members.kick(options.getUser('member', true).id)
1470
+ * });
1471
+ * }
1472
+ * }
1473
+ * ```
1474
+ */
1475
+ async match(arms) {
1476
+ const route = slashRouteOf(this.event);
1477
+ const arm = arms[route];
1478
+ if (!arm) throw new SeedcordError(SeedcordErrorCode.SlashMatchArmMissing, [route]);
1479
+ return await arm(this.options);
1480
+ }
1481
+ };
1482
+
1483
+ //#endregion
1484
+ //#region src/handlers/interaction/ContextMenuHandler.ts
1485
+ /**
1486
+ * Base class for a context-menu command handler (right-click a user or a message).
1487
+ *
1488
+ * Pass the kind from `discord.js`'s {@link ApplicationCommandType} as the generic, the same value as
1489
+ * `@ContextMenuRoute`. Read the right-clicked entity from `this.target`, a `User` for a user menu and a
1490
+ * `Message` for a message menu. Context menus carry no options, so a handler registered for several names
1491
+ * reads `this.target` uniformly with no per-name branch.
1492
+ *
1493
+ * @typeParam Kind - `ApplicationCommandType.User` or `ApplicationCommandType.Message`.
1494
+ * @typeParam Cache - The interaction cache state, `'cached'` by default.
1495
+ *
1496
+ * @example
1497
+ * ```ts
1498
+ * \@ContextMenuRoute(ApplicationCommandType.Message, 'Report Message')
1499
+ * class ReportMessage extends ContextMenuHandler<ApplicationCommandType.Message> {
1500
+ * async execute() {
1501
+ * const message = this.target;
1502
+ * }
1503
+ * }
1504
+ * ```
1505
+ */
1506
+ var ContextMenuHandler = class extends InteractionHandler {
1507
+ get target() {
1508
+ const event = this.event;
1509
+ return "targetUser" in event ? event.targetUser : event.targetMessage;
1510
+ }
1511
+ /**
1512
+ * The invoking guild member, resolved only on user menus. Reading it on a message menu is a compile
1513
+ * error since the type is `never` there.
1514
+ */
1515
+ get targetMember() {
1516
+ return this.event.targetMember;
1517
+ }
1518
+ };
1519
+
1520
+ //#endregion
1521
+ //#region src/handlers/interaction/AutocompleteHandler.ts
1522
+ /**
1523
+ * Base class for a Discord autocomplete handler.
1524
+ *
1525
+ * Pass the command route(s) from the generated registry as the generic, the same string(s) as
1526
+ * `@AutocompleteRoute`. Branch on the focused field with `this.match`, read already-entered sibling options
1527
+ * with `this.options`, and find which command fired with `this.route`.
1528
+ *
1529
+ * @typeParam Route - One or more route keys from {@link SlashOptionRegistry}, e.g. `'search'` or `'search' | 'find'`.
1530
+ * @typeParam Cache - The interaction cache state, `'cached'` by default.
1531
+ *
1532
+ * @example
1533
+ * ```ts
1534
+ * \@AutocompleteRoute('search')
1535
+ * class SearchAutocomplete extends AutocompleteHandler<'search'> {
1536
+ * async execute() {
1537
+ * await this.match({
1538
+ * query: (value, respond) => respond([{ name: value, value }])
1539
+ * });
1540
+ * }
1541
+ * }
1542
+ * ```
1543
+ */
1544
+ var AutocompleteHandler = class extends BaseHandler {
1545
+ constructor(event, core, dispatch) {
1546
+ super(event, core, dispatch);
1547
+ }
1548
+ /**
1549
+ * The focused option for this interaction. `value` is always the raw partial string the user is typing,
1550
+ * even for an integer or number option, so coerce it yourself when you need a number.
1551
+ */
1552
+ decodedFocused;
1553
+ get focused() {
1554
+ if (this.decodedFocused) return this.decodedFocused;
1555
+ const raw = this.event.options.getFocused(true);
1556
+ const focused = {
1557
+ name: raw.name,
1558
+ value: raw.value
1559
+ };
1560
+ this.decodedFocused = focused;
1561
+ return focused;
1562
+ }
1563
+ /**
1564
+ * Run the arm for the focused field. An autocomplete always dispatches by which field is focused, so
1565
+ * match is how you read it. There is no single-field shortcut the way slash/component handlers have one.
1566
+ *
1567
+ * Provide one arm per autocompletable field across the registered commands, keyed by field name. Each
1568
+ * arm receives the focused partial value and a `respond` pinned to that field's choice value type. The
1569
+ * arms must cover every autocompletable field, a missing field or an unknown key is a compile error. A
1570
+ * focused field with no arm, only reachable from a stale-deployed command, throws at runtime.
1571
+ *
1572
+ * @param arms - One handler per autocompletable field, keyed by field name.
1573
+ * @returns The result of the arm that ran.
1574
+ *
1575
+ * @example
1576
+ * ```ts
1577
+ * \@AutocompleteRoute('search')
1578
+ * class SearchAutocomplete extends AutocompleteHandler<'search'> {
1579
+ * async execute() {
1580
+ * await this.match({
1581
+ * query: (value, respond) => respond(titles(value).map((s) => ({ name: s, value: s }))),
1582
+ * tag: (value, respond) => respond(tags(value).map((s) => ({ name: s, value: s })))
1583
+ * });
1584
+ * }
1585
+ * }
1586
+ * ```
1587
+ */
1588
+ async match(arms) {
1589
+ const { name, value } = this.focused;
1590
+ const respond = (choices) => this.event.respond(choices);
1591
+ const arm = arms[name];
1592
+ if (!arm) throw new SeedcordError(SeedcordErrorCode.AutocompleteMatchArmMissing, [name]);
1593
+ return await arm(value, respond);
1594
+ }
1595
+ /** The firing command route, for a field whose completion differs per registered command. */
1596
+ get route() {
1597
+ return slashRouteOf(this.event);
1598
+ }
1599
+ /**
1600
+ * The already-entered options on this command, restricted to the kinds Discord resolves during autocomplete
1601
+ * (string, integer, number, boolean) with every read nullable, since a sibling is partial while the user
1602
+ * types the focused field. Read the focused field from `this.focused`, not here.
1603
+ */
1604
+ get options() {
1605
+ return this.event.options;
1606
+ }
1607
+ };
1608
+
1609
+ //#endregion
1610
+ //#region src/handlers/interaction/components/ComponentHandler.ts
1611
+ /**
1612
+ * Shared base the customId-routed component handlers extend.
1613
+ *
1614
+ * Not a public entry point. You should be using {@link ButtonHandler}, {@link SelectMenuHandler}, or
1615
+ * {@link ModalHandler} instead. This class only carries the customId decode and route-matching plumbing
1616
+ * those bases share, so DO NOT use it directly.
1617
+ *
1618
+ * @typeParam Event - The component interaction type this handler processes
1619
+ * @typeParam Defs - The customId route definitions registered on the concrete handler
1620
+ */
1621
+ var ComponentHandler = class extends InteractionHandler {
1622
+ get registeredDefs() {
1623
+ const defs = Reflect.getMetadata(ComponentDefsKey, this.constructor);
1624
+ if (!defs) throw new SeedcordError(SeedcordErrorCode.CustomIdHandlerRouteMissing, [this.constructor.name]);
1625
+ return defs;
1626
+ }
1627
+ decoded;
1628
+ get route() {
1629
+ if (this.decoded) return this.decoded;
1630
+ const decoded = decodeFor(this.registeredDefs, this.event.customId);
1631
+ this.decoded = decoded;
1632
+ return decoded;
1633
+ }
1634
+ /**
1635
+ * The decoded params of the single route this handler is registered for.
1636
+ *
1637
+ * Reading this decodes `this.event.customId` once (cached after the first read) and throws
1638
+ * `StaleCustomId` or `InvalidCustomId` when the wire no longer matches the current shape, which the
1639
+ * controller boundary turns into a reply. On a handler registered for several routes this is
1640
+ * `never`, so use {@link match} instead.
1641
+ */
1642
+ get params() {
1643
+ return this.route.params;
1644
+ }
1645
+ /**
1646
+ * Run the arm for whichever route the component was minted from. Use this only when the handler is
1647
+ * registered for several routes. A single-route handler reads `this.params` directly. On a multi-route
1648
+ * handler `this.params` is `never`, so match is the only way to read the decoded params.
1649
+ *
1650
+ * Provide one arm per registered route, keyed by its prefix, and each arm receives that route's own
1651
+ * decoded params. The arms must cover every registered def, a missing prefix or an unknown key is a
1652
+ * compile error. Decoding runs before any arm, so a stale or corrupt wire throws before an arm body executes.
1653
+ *
1654
+ * @param arms - One handler per registered route, keyed by prefix.
1655
+ * @returns The result of the arm that ran.
1656
+ *
1657
+ * @example
1658
+ * ```ts
1659
+ * \@ButtonRoute(Approve, Reject)
1660
+ * class ReviewButtons extends ButtonHandler<[typeof Approve, typeof Reject]> {
1661
+ * async execute() {
1662
+ * await this.match({
1663
+ * approve: ({ userId }) => this.event.reply(`approved <@${userId}>`),
1664
+ * reject: ({ userId }) => this.event.reply(`rejected <@${userId}>`)
1665
+ * });
1666
+ * }
1667
+ * }
1668
+ * ```
1669
+ */
1670
+ async match(arms) {
1671
+ const { prefix, params } = this.route;
1672
+ const arm = arms[prefix];
1673
+ if (!arm) throw new SeedcordError(SeedcordErrorCode.CustomIdMatchArmMissing, [prefix]);
1674
+ return await arm(params);
1675
+ }
1676
+ };
1677
+
1678
+ //#endregion
1679
+ //#region src/handlers/interaction/components/ButtonHandler.ts
1680
+ /**
1681
+ * Base class for a button interaction handler.
1682
+ *
1683
+ * Register the customId definitions this handler decodes with `@ButtonRoute`, list the same ones in the
1684
+ * generic, then read `this.params` for a single route or `this.match` for several. Passing different
1685
+ * definitions to the decorator and the generic is a compile error.
1686
+ *
1687
+ * @typeParam Defs - The customId definitions this handler decodes, e.g. `[typeof ApproveId]`.
1688
+ * @typeParam Cache - The interaction cache state, `'cached'` by default.
1689
+ *
1690
+ * @example
1691
+ * ```ts
1692
+ * \@ButtonRoute(ApproveId)
1693
+ * class ApproveButton extends ButtonHandler<[typeof ApproveId]> {
1694
+ * async execute() {
1695
+ * const { userId } = this.params;
1696
+ * await this.event.reply(`approved <@${userId}>`);
1697
+ * }
1698
+ * }
1699
+ * ```
1700
+ */
1701
+ var ButtonHandler = class extends ComponentHandler {};
1702
+
1703
+ //#endregion
1704
+ //#region src/handlers/interaction/components/ModalHandler.ts
1705
+ /**
1706
+ * Base class for a modal submit handler.
1707
+ *
1708
+ * Register the customId definitions this handler decodes with `@ModalRoute`, list the same ones in the
1709
+ * generic, then read `this.params` for a single route or `this.match` for several. Read the submitted
1710
+ * inputs from `this.event.fields`.
1711
+ *
1712
+ * @typeParam Defs - The customId definitions this handler decodes, e.g. `[typeof ConfigId]`.
1713
+ * @typeParam Cache - The interaction cache state, `'cached'` by default.
1714
+ *
1715
+ * @example
1716
+ * ```ts
1717
+ * \@ModalRoute(ConfigId)
1718
+ * class ConfigModal extends ModalHandler<[typeof ConfigId]> {
1719
+ * async execute() {
1720
+ * const { guildId } = this.params;
1721
+ * const name = this.event.fields.getTextInputValue('name');
1722
+ * await this.event.reply(`saved ${name} for ${guildId}`);
1723
+ * }
1724
+ * }
1725
+ * ```
1726
+ */
1727
+ var ModalHandler = class extends ComponentHandler {};
1728
+
1729
+ //#endregion
1730
+ //#region src/handlers/interaction/components/SelectMenuHandler.ts
1731
+ /**
1732
+ * Base class for a select menu handler.
1733
+ *
1734
+ * Pass the select kind first and the customId definitions second, the same order as `@SelectMenuRoute`,
1735
+ * so `this.event` and `this.event.values` are narrowed to that kind. Read `this.params` for a single
1736
+ * route or `this.match` for several.
1737
+ *
1738
+ * @typeParam Kind - The select kind from {@link SelectMenuKind}, e.g. `SelectMenuKind.User`.
1739
+ * @typeParam Defs - The customId definitions this handler decodes, e.g. `[typeof AssignId]`.
1740
+ * @typeParam Cache - The interaction cache state, `'cached'` by default.
1741
+ *
1742
+ * @example
1743
+ * ```ts
1744
+ * \@SelectMenuRoute(SelectMenuKind.User, AssignId)
1745
+ * class AssignSelect extends SelectMenuHandler<SelectMenuKind.User, [typeof AssignId]> {
1746
+ * async execute() {
1747
+ * const { roleId } = this.params;
1748
+ * await this.event.reply(`assigning ${this.event.values.length} member(s) to <@&${roleId}>`);
1749
+ * }
1750
+ * }
1751
+ * ```
1752
+ */
1753
+ var SelectMenuHandler = class extends ComponentHandler {};
1754
+
1755
+ //#endregion
1756
+ //#region src/handlers/event/EventHandler.ts
1757
+ /**
1758
+ * Base class for a Discord client event handler.
1759
+ *
1760
+ * Pass the event name(s) as the generic, the same one(s) as `@RegisterEvent`. A single-event handler reads
1761
+ * `this.event` (the payload tuple) directly. A handler registered for several events branches with `this.match`,
1762
+ * keyed by event name, since the union of payload tuples is not directly readable.
1763
+ *
1764
+ * @typeParam Names - One or more `ClientEvents` keys, e.g. `Events.MessageCreate` or `Events.MessageCreate | Events.MessageUpdate`.
1765
+ *
1766
+ * @example
1767
+ * ```ts
1768
+ * \@RegisterEvent([Events.MessageCreate], [Events.MessageUpdate])
1769
+ * class PingPong extends EventHandler<Events.MessageCreate | Events.MessageUpdate> {
1770
+ * async execute() {
1771
+ * await this.match({
1772
+ * [Events.MessageCreate]: (message) => message.reply('pong'),
1773
+ * [Events.MessageUpdate]: (_oldMessage, edited) => edited.reply('pong')
1774
+ * });
1775
+ * }
1776
+ * }
1777
+ * ```
1778
+ */
1779
+ var EventHandler = class extends BaseHandler {
1780
+ firedEvent;
1781
+ constructor(event, core, eventName) {
1782
+ super(event, core);
1783
+ this.firedEvent = eventName;
1784
+ }
1785
+ /**
1786
+ * Run the arm for whichever event fired. Use this only when the handler is registered for several
1787
+ * events. A single-event handler reads `this.event` directly. On a multi-event handler `this.event` is
1788
+ * `never`, so match is the only way to read the payload.
1789
+ *
1790
+ * Provide one arm per registered event, keyed by its name, and each arm receives that event's own
1791
+ * payload tuple. The arms must cover every event in the generic, a missing event or an unknown key is a
1792
+ * compile error.
1793
+ *
1794
+ * @param arms - One handler per registered event, keyed by event name.
1795
+ * @returns The result of the arm that ran.
1796
+ *
1797
+ * @example
1798
+ * ```ts
1799
+ * \@RegisterEvent([Events.MessageCreate], [Events.MessageUpdate])
1800
+ * class MessageWatcher extends EventHandler<Events.MessageCreate | Events.MessageUpdate> {
1801
+ * async execute() {
1802
+ * await this.match({
1803
+ * [Events.MessageCreate]: (message) => this.scan(message),
1804
+ * [Events.MessageUpdate]: (_old, updated) => this.scan(updated)
1805
+ * });
1806
+ * }
1807
+ * }
1808
+ * ```
1809
+ */
1810
+ async match(arms) {
1811
+ const name = this.firedEvent;
1812
+ if (name === void 0) throw new SeedcordError(SeedcordErrorCode.EventMatchArmMissing, ["<no event>"]);
1813
+ const arm = arms[name];
1814
+ if (typeof arm !== "function") throw new SeedcordError(SeedcordErrorCode.EventMatchArmMissing, [name]);
1815
+ return await arm(...this.getEvent());
1816
+ }
1817
+ };
1818
+
1819
+ //#endregion
1820
+ //#region src/handlers/event/EventMiddleware.ts
1821
+ /**
1822
+ * Base class for Discord event middleware.
1823
+ *
1824
+ * Middleware runs before event handlers and can stop the event by throwing a `Silence`. Unlike `EventHandler`, it
1825
+ * runs the SAME for every event it is registered for, so it has no `match`. Specify a single event in the
1826
+ * generic and `{ events }` to read `this.event` fully typed. Span several events (or omit `{ events }` for a
1827
+ * catchall) and `this.event` narrows to `never`, read `this.eventName` and do work that does not depend on the
1828
+ * payload shape. A middleware that needs each event's payload is written one event per class.
1829
+ *
1830
+ * @typeParam EventName - One or more `ClientEvents` keys. Defaults to every event (catchall).
1831
+ */
1832
+ var EventMiddleware = class extends BaseHandler {
1833
+ firedEvent;
1834
+ constructor(event, core, eventName) {
1835
+ super(event, core);
1836
+ this.firedEvent = eventName;
1837
+ }
1838
+ /**
1839
+ * The event that fired this middleware. Read it on a catchall or multi-event middleware, where `this.event`
1840
+ * is `never`, to do work that does not depend on the payload shape. A single-event middleware reads
1841
+ * `this.event` directly and does not need this.
1842
+ */
1843
+ get eventName() {
1844
+ if (this.firedEvent === void 0) throw new SeedcordError(SeedcordErrorCode.EventMiddlewareNameUnavailable);
1845
+ return this.firedEvent;
1846
+ }
1847
+ };
1848
+
1849
+ //#endregion
1850
+ //#region src/pagination/controls.ts
1851
+ const DEFAULT_LABEL = {
1852
+ first: "First",
1853
+ prev: "Prev",
1854
+ indicator: "",
1855
+ next: "Next",
1856
+ last: "Last"
1857
+ };
1858
+ const CONTROL_SLOT = {
1859
+ first: 0,
1860
+ prev: 1,
1861
+ indicator: 2,
1862
+ next: 3,
1863
+ last: 4
1864
+ };
1865
+ const MAX_BUTTONS_PER_ROW = 5;
1866
+ var Controls = class {
1867
+ cursor;
1868
+ view;
1869
+ constructor(cursor, view) {
1870
+ this.cursor = cursor;
1871
+ this.view = view;
1872
+ }
1873
+ button(key, cosmetics) {
1874
+ const { target, disabled } = this.navState(key);
1875
+ const defaultLabel = key === "indicator" ? this.indicatorText() : DEFAULT_LABEL[key];
1876
+ const label = cosmetics?.label ?? (key === "indicator" || !cosmetics?.emoji ? defaultLabel : void 0);
1877
+ const button = new ButtonBuilder().setCustomId(this.cursor.encode({
1878
+ page: Math.min(Math.max(0, target), PAGE_MAX),
1879
+ slot: CONTROL_SLOT[key]
1880
+ })).setStyle(cosmetics?.style ?? ButtonStyle.Secondary).setDisabled(disabled);
1881
+ if (label !== void 0) button.setLabel(label);
1882
+ if (cosmetics?.emoji) button.setEmoji(cosmetics.emoji);
1883
+ return button;
1884
+ }
1885
+ navState(key) {
1886
+ const { page, totalPages, hasPrev, hasNext } = this.view;
1887
+ const knownTotal = totalPages !== void 0;
1888
+ return {
1889
+ target: {
1890
+ first: 0,
1891
+ prev: page - 1,
1892
+ indicator: page,
1893
+ next: page + 1,
1894
+ last: knownTotal ? totalPages - 1 : page
1895
+ }[key],
1896
+ disabled: {
1897
+ first: !hasPrev,
1898
+ prev: !hasPrev,
1899
+ indicator: true,
1900
+ next: !hasNext || page + 1 > PAGE_MAX,
1901
+ last: !hasNext || !knownTotal || totalPages - 1 > PAGE_MAX
1902
+ }[key]
1903
+ };
1904
+ }
1905
+ row(...keys) {
1906
+ if (keys.length === 0) throw new SeedcordRangeError(SeedcordErrorCode.PaginationEmptyControls);
1907
+ if (keys.length > MAX_BUTTONS_PER_ROW) throw new SeedcordRangeError(SeedcordErrorCode.PaginationTooManyControls, [keys.length]);
1908
+ const seen = /* @__PURE__ */ new Set();
1909
+ for (const key of keys) {
1910
+ if (seen.has(key)) throw new SeedcordTypeError(SeedcordErrorCode.PaginationDuplicateControls, [key]);
1911
+ seen.add(key);
1912
+ }
1913
+ return new ActionRowBuilder().addComponents(keys.map((key) => this.button(key)));
1914
+ }
1915
+ indicatorText() {
1916
+ const { page, totalPages } = this.view;
1917
+ return totalPages === void 0 ? `Page ${page + 1}` : `Page ${page + 1} of ${totalPages}`;
1918
+ }
1919
+ };
1920
+
1921
+ //#endregion
1922
+ //#region src/pagination/render.ts
1923
+ var PageContainer = class extends BuilderComponent {
1924
+ constructor(view, renderItem, controlRow) {
1925
+ super("container");
1926
+ const base = view.page * view.perPage;
1927
+ let lines = [];
1928
+ const flush = () => {
1929
+ if (lines.length === 0) return;
1930
+ this.instance.addTextDisplayComponents(new TextDisplayBuilder().setContent(lines.join("\n")));
1931
+ lines = [];
1932
+ };
1933
+ view.items.forEach((item, offset) => {
1934
+ const rendered = renderItem(item, base + offset);
1935
+ if (typeof rendered === "string") {
1936
+ lines.push(rendered);
1937
+ return;
1938
+ }
1939
+ flush();
1940
+ this.instance.addSectionComponents(rendered.component);
1941
+ });
1942
+ flush();
1943
+ this.instance.addActionRowComponents(controlRow);
1944
+ }
1945
+ };
1946
+ function toReplyResponse(renderable) {
1947
+ if (typeof renderable === "string") return { components: [new TextDisplayBuilder().setContent(renderable)] };
1948
+ if (Array.isArray(renderable)) return { components: renderable };
1949
+ return renderable;
1950
+ }
1951
+ const ARRAY_KEYS = [
1952
+ "first",
1953
+ "prev",
1954
+ "indicator",
1955
+ "next",
1956
+ "last"
1957
+ ];
1958
+ const CURSOR_KEYS = [
1959
+ "prev",
1960
+ "indicator",
1961
+ "next"
1962
+ ];
1963
+ /**
1964
+ * Build a page's V2 reply. A `render` override builds the whole tree, otherwise the default container lists
1965
+ * the items and appends the controls (all five for a known total, prev/indicator/next for a cursor source).
1966
+ */
1967
+ function renderPage(view, cursor, config) {
1968
+ const controls = new Controls(cursor, view);
1969
+ if (config.render) return toReplyResponse(config.render(view, controls));
1970
+ return { components: [new PageContainer(view, config.renderItem ?? String, controls.row(...view.totalPages === void 0 ? CURSOR_KEYS : ARRAY_KEYS)).component] };
1971
+ }
1972
+
1973
+ //#endregion
1974
+ //#region src/pagination/Paginator.ts
1975
+ function contextOf(interaction, core) {
1976
+ return {
1977
+ interaction,
1978
+ user: interaction.user,
1979
+ guild: interaction.guild,
1980
+ ...core && { core }
1981
+ };
1982
+ }
1983
+ /**
1984
+ * A restart-proof paginator. Each nav button's customId encodes its full target page, so clicks are
1985
+ * idempotent and survive a restart. A persistent `@ButtonRoute` on `Handler` dispatches the clicks.
1986
+ *
1987
+ * @typeParam Item - The item type, inferred from the source.
1988
+ * @typeParam Prefix - The route prefix, inferred from `config.prefix`.
1989
+ *
1990
+ * @example
1991
+ * ```ts
1992
+ * export const Bans = new Paginator({
1993
+ * prefix: 'bans',
1994
+ * source: new ArraySource((ctx) => ctx.guild.bans.fetch().then((b) => [...b.values()]), { perPage: 10 }),
1995
+ * renderItem: (ban) => ban.user.tag
1996
+ * });
1997
+ *
1998
+ * \@ButtonRoute(Bans.cursor)
1999
+ * export class BansNav extends Bans.Handler {}
2000
+ * ```
2001
+ */
2002
+ var Paginator = class {
2003
+ /** The page cursor, pass it to your `@ButtonRoute`. */
2004
+ cursor;
2005
+ /** The nav handler base. Extend it with an empty body and decorate it, `@ButtonRoute(p.cursor)`. */
2006
+ Handler;
2007
+ config;
2008
+ constructor(config) {
2009
+ this.cursor = pageCursor(config.prefix);
2010
+ this.config = config;
2011
+ const loadPage = (ctx, n) => this.page(ctx, n);
2012
+ this.Handler = class Nav extends ButtonHandler {
2013
+ async execute() {
2014
+ await this.event.deferUpdate();
2015
+ const response = await loadPage(contextOf(this.event, this.core), this.params.page);
2016
+ await new ReplySender(this.event).edit(this.event.message, response);
2017
+ }
2018
+ };
2019
+ }
2020
+ /** Render page 0 and send it, picking reply or followUp from the interaction's state. */
2021
+ async start(interaction, core) {
2022
+ const response = await this.page(contextOf(interaction, core), 0);
2023
+ return new ReplySender(interaction).send(response, this.config.ephemeral ?? false);
2024
+ }
2025
+ /** Render a page as a {@link ReplyResponse}. To post it elsewhere, add `flags: MessageFlags.IsComponentsV2`. */
2026
+ async page(ctx, n) {
2027
+ return renderPage(await this.config.source.page(ctx, n), this.cursor, this.config);
2028
+ }
2029
+ };
2030
+
2031
+ //#endregion
2032
+ //#region src/pagination/sources.ts
2033
+ const DEFAULT_PER_PAGE = 10;
2034
+ /**
2035
+ * A source for a bounded list you can load whole. It loads the full list on every click, then slices the
2036
+ * page via {@link paginate}, so the real total is known (a real last button, "Page X of Y"). Cache inside
2037
+ * your loader if the load is expensive.
2038
+ *
2039
+ * @typeParam Item - The item type, inferred from the loader's return.
2040
+ */
2041
+ var ArraySource = class {
2042
+ load;
2043
+ perPage;
2044
+ constructor(load, opts) {
2045
+ this.load = load;
2046
+ this.perPage = opts?.perPage ?? DEFAULT_PER_PAGE;
2047
+ if (!Number.isSafeInteger(this.perPage) || this.perPage <= 0) throw new SeedcordRangeError(SeedcordErrorCode.PaginationInvalidPerPage, [this.perPage]);
2048
+ }
2049
+ async page(ctx, n) {
2050
+ return paginate(await this.load(ctx), n, this.perPage);
2051
+ }
2052
+ };
2053
+ /**
2054
+ * A source for a large or unknown-length set you fetch one page at a time (SQL LIMIT/OFFSET, a paged API).
2055
+ * The fetcher receives the page index and the page size and reports whether a next page exists. A cursor
2056
+ * source has no cheap total, so `totalPages` is undefined, the last button is omitted, and the indicator
2057
+ * reads "Page X".
2058
+ *
2059
+ * @typeParam Item - The item type, inferred from the fetcher's slice.
2060
+ */
2061
+ var CursorSource = class {
2062
+ fetch;
2063
+ perPage;
2064
+ constructor(fetch, opts) {
2065
+ this.fetch = fetch;
2066
+ this.perPage = opts?.perPage ?? DEFAULT_PER_PAGE;
2067
+ if (!Number.isSafeInteger(this.perPage) || this.perPage <= 0) throw new SeedcordRangeError(SeedcordErrorCode.PaginationInvalidPerPage, [this.perPage]);
2068
+ }
2069
+ async page(ctx, n) {
2070
+ const page = Math.max(0, Math.trunc(n));
2071
+ const { items, hasNext } = await this.fetch(ctx, page, this.perPage);
2072
+ return {
2073
+ items: [...items],
2074
+ page,
2075
+ perPage: this.perPage,
2076
+ hasPrev: page > 0,
2077
+ hasNext
2078
+ };
2079
+ }
2080
+ };
2081
+
2082
+ //#endregion
2083
+ //#region src/subscribers/Subscriber.ts
2084
+ /**
2085
+ * Abstract base class for handling application subscribers.
2086
+ *
2087
+ * Provides type-safe access to subscribers data and the core framework instance.
2088
+ * Extend this class to create custom subscriber handlers.
2089
+ *
2090
+ * @typeParam KeyOfSubscribers - The specific subscriber type this handler processes
2091
+ */
2092
+ var Subscriber = class {
2093
+ data;
2094
+ core;
2095
+ logger;
2096
+ /**
2097
+ * Instantiates the subscriber with event data and core.
2098
+ *
2099
+ * @param data - The subscriber event data
2100
+ * @param core - The core framework instance
2101
+ */
2102
+ constructor(data, core) {
2103
+ this.data = data;
2104
+ this.core = core;
2105
+ this.logger = new Logger(this.constructor.name);
2106
+ }
2107
+ };
2108
+
2109
+ //#endregion
2110
+ //#region src/subscribers/decorators/Subscribe.ts
2111
+ /**
2112
+ * Registers a subscriber handler class with a specific subscriber event.
2113
+ *
2114
+ * Associates the decorated class with a subscriber event type for automatic
2115
+ * registration and execution when the subscriber is emitted.
2116
+ *
2117
+ * @typeParam TSubscriber - The subscriber event name to register for
2118
+ * @param subscriber - The subscriber event name to register for
2119
+ * @param options - Options to configure the subscriber handler registration.
2120
+ * @decorator
2121
+ * @example
2122
+ * ```typescript
2123
+ * \@Subscribe('userJoin')
2124
+ * class WelcomeHandler extends Subscriber<'userJoin'> {
2125
+ * async execute() {
2126
+ * // Handle user join event
2127
+ * }
2128
+ * }
2129
+ * ```
2130
+ * @example
2131
+ * ```ts
2132
+ * \@Subscribe('userJoin', { frequency: 'once' })
2133
+ * // or
2134
+ * \@Subscribe('userJoin')
2135
+ * ```
2136
+ */
2137
+ function Subscribe(subscriber, options) {
2138
+ return function(constructor) {
2139
+ const meta = {
2140
+ subscriber,
2141
+ frequency: options?.frequency
2142
+ };
2143
+ Reflect.defineMetadata(SubscribeMetadataKey, meta, constructor);
2144
+ };
2145
+ }
2146
+
2147
+ //#endregion
2148
+ //#region src/subscribers/bases/WebhookLog.ts
2149
+ /**
2150
+ * Abstract webhook logging handler for subscriber events.
2151
+ *
2152
+ * Extends Subscriber to provide webhook-based logging capabilities.
2153
+ * Implementations must define the webhook client to send messages to by implementing the webhook property.
2154
+ *
2155
+ * @typeParam KeyOfSubscribers - The specific subscriber type this handler processes
2156
+ */
2157
+ var WebhookLog = class extends Subscriber {
2158
+ constructor(data, core) {
2159
+ super(data, core);
2160
+ }
2161
+ };
2162
+
2163
+ //#endregion
2164
+ //#region src/hmr/HmrModuleHandler.ts
2165
+ /**
2166
+ * Reloads THandler and optional TMiddleware modules on HMR updates.
2167
+ *
2168
+ * You can either implement a custom `onHmr()` method in your class by extending `HmrAware`, or if it's a plugin, override the existing `onHmr()` with fully custom logic. Or, use this class's `handle()` method inside your `onHmr()` to get standard HMR handling for your modules based on the provided options you give to the constructor.
2169
+ *
2170
+ * This is only useful during development.
2171
+ */
2172
+ var HmrModuleHandler = class {
2173
+ store;
2174
+ options;
2175
+ constructor(options) {
2176
+ this.options = {
2177
+ ...options,
2178
+ logger: options.logger.inChannel("hmr")
2179
+ };
2180
+ this.store = {
2181
+ fileToHandlers: /* @__PURE__ */ new Map(),
2182
+ fileToMiddlewares: /* @__PURE__ */ new Map(),
2183
+ handlerArtifacts: /* @__PURE__ */ new Map()
2184
+ };
2185
+ }
2186
+ /**
2187
+ * Handles an HMR update event by reloading affected modules based on the event details and config. It receives an {@link HmrUpdateEvent}, then checks the type of update.
2188
+ *
2189
+ * - If it's a deletion, it unloads the module.
2190
+ * - If it's an update/creation, it checks if the file is tracked, unloads it if so, then reloads the file if it is in the handlers or middlewares directory and is a valid handler/middleware.
2191
+ */
2192
+ async handle(event) {
2193
+ const { file, affectedModules, type } = event;
2194
+ const { logger, handlersDir, middlewaresDir } = this.options;
2195
+ if (type === "delete" || type === "deleteDir") {
2196
+ this.unload(file);
2197
+ return;
2198
+ }
2199
+ if (type === "update" && !existsSync(file)) {
2200
+ if (this.isTracked(file)) {
2201
+ logger.info(`Received update for non-existent file: ${formatFilePath(file)}, treating as delete`);
2202
+ this.unload(file);
2203
+ }
2204
+ return;
2205
+ }
2206
+ const rollbackEnabled = event.rollback ?? true;
2207
+ const filesToReload = affectedModules && affectedModules.length > 0 ? affectedModules : [file];
2208
+ const absHandlersDir = resolve(process.cwd(), handlersDir);
2209
+ const absMiddlewaresDir = middlewaresDir ? resolve(process.cwd(), middlewaresDir) : null;
2210
+ for (const fileToReload of filesToReload) {
2211
+ const isHandler = fileToReload.startsWith(absHandlersDir);
2212
+ const isMiddleware = absMiddlewaresDir ? fileToReload.startsWith(absMiddlewaresDir) : false;
2213
+ if (!isHandler && !isMiddleware) continue;
2214
+ await this.reloadWithRollback(fileToReload, rollbackEnabled);
2215
+ }
2216
+ }
2217
+ async reloadWithRollback(file, rollbackEnabled) {
2218
+ const { logger } = this.options;
2219
+ const snapshot = this.snapshotUnits(file);
2220
+ this.unload(file);
2221
+ if (await this.reloadFile(file)) return;
2222
+ this.unload(file);
2223
+ if (!rollbackEnabled) return;
2224
+ this.restoreUnits(file, snapshot);
2225
+ logger.warn(`${chalk.yellow.bold("Rolled back")} ${chalk.gray(formatFilePath(file))} to the last-good version`);
2226
+ }
2227
+ /**
2228
+ * Tracks a handler module as being loaded from a specific file.
2229
+ * @param file - The file path the handler was loaded from.
2230
+ * @param handler - The handler module instance.
2231
+ */
2232
+ trackHandler(file, handler) {
2233
+ let set = this.store.fileToHandlers.get(file);
2234
+ if (!set) {
2235
+ set = /* @__PURE__ */ new Set();
2236
+ this.store.fileToHandlers.set(file, set);
2237
+ }
2238
+ set.add(handler);
2239
+ if (this.options.getArtifacts) {
2240
+ const artifacts = this.options.getArtifacts(handler);
2241
+ this.store.handlerArtifacts.set(handler, artifacts);
2242
+ }
2243
+ }
2244
+ /**
2245
+ * Tracks a middleware module as being loaded from a specific file.
2246
+ * @param file - The file path the middleware was loaded from.
2247
+ * @param middleware - The middleware module instance.
2248
+ */
2249
+ trackMiddleware(file, middleware) {
2250
+ let set = this.store.fileToMiddlewares.get(file);
2251
+ if (!set) {
2252
+ set = /* @__PURE__ */ new Set();
2253
+ this.store.fileToMiddlewares.set(file, set);
2254
+ }
2255
+ set.add(middleware);
2256
+ }
2257
+ isTracked(file) {
2258
+ return this.store.fileToHandlers.has(file) || this.store.fileToMiddlewares.has(file);
2259
+ }
2260
+ unload(file) {
2261
+ const { logger } = this.options;
2262
+ const handlers = this.store.fileToHandlers.get(file);
2263
+ if (handlers) {
2264
+ for (const handler of handlers) {
2265
+ const artifacts = this.store.handlerArtifacts.get(handler);
2266
+ this.options.unregisterHandler(handler, artifacts);
2267
+ this.store.handlerArtifacts.delete(handler);
2268
+ const name = handler.name ?? "Handler";
2269
+ logger.info(`${chalk.red.bold("Unloaded")} ${chalk.cyan.bold(name)} from ${chalk.gray(formatFilePath(file))}`);
2270
+ }
2271
+ this.store.fileToHandlers.delete(file);
2272
+ }
2273
+ const middlewares = this.store.fileToMiddlewares.get(file);
2274
+ if (middlewares) {
2275
+ for (const middleware of middlewares) {
2276
+ this.options.unregisterMiddleware?.(middleware);
2277
+ const name = middleware.name ?? "Middleware";
2278
+ logger.info(`${chalk.red.bold("Unloaded")} ${chalk.cyan.bold(name)} from ${chalk.gray(formatFilePath(file))}`);
2279
+ }
2280
+ this.store.fileToMiddlewares.delete(file);
2281
+ }
2282
+ }
2283
+ async reloadFile(file) {
2284
+ const { logger, isHandler, isMiddleware, registerHandler, registerMiddleware } = this.options;
2285
+ if (!existsSync(file)) {
2286
+ logger.info(`File does not exist, skipping reload: ${formatFilePath(file)}`);
2287
+ return false;
2288
+ }
2289
+ try {
2290
+ let fileUrl = pathToFileURL(file).href;
2291
+ if (process.env.VITEST === "true") fileUrl += `?update=${Date.now()}`;
2292
+ const imported = await import(fileUrl);
2293
+ for (const val of Object.values(imported)) if (isHandler(val)) {
2294
+ registerHandler(val, file);
2295
+ this.trackHandler(file, val);
2296
+ const name = val.name ?? "Handler";
2297
+ logger.info(`${chalk.blue.bold("Reloaded")} ${chalk.cyan.bold(name)} from ${chalk.gray(formatFilePath(file))}`);
2298
+ } else if (isMiddleware && registerMiddleware && isMiddleware(val)) {
2299
+ registerMiddleware(val, file);
2300
+ this.trackMiddleware(file, val);
2301
+ const name = val.name ?? "Middleware";
2302
+ logger.info(`${chalk.blue.bold("Reloaded")} ${chalk.cyan.bold(name)} from ${chalk.gray(formatFilePath(file))}`);
2303
+ }
2304
+ return true;
2305
+ } catch (error) {
2306
+ logger.error(`Failed to reload file: ${file}`, error);
2307
+ return false;
2308
+ }
2309
+ }
2310
+ snapshotUnits(file) {
2311
+ return {
2312
+ handlers: [...this.store.fileToHandlers.get(file) ?? []],
2313
+ middlewares: [...this.store.fileToMiddlewares.get(file) ?? []]
2314
+ };
2315
+ }
2316
+ restoreUnits(file, snapshot) {
2317
+ for (const handler of snapshot.handlers) {
2318
+ this.options.registerHandler(handler, file);
2319
+ this.trackHandler(file, handler);
2320
+ }
2321
+ if (this.options.registerMiddleware) for (const middleware of snapshot.middlewares) {
2322
+ this.options.registerMiddleware(middleware, file);
2323
+ this.trackMiddleware(file, middleware);
2324
+ }
2325
+ }
2326
+ };
2327
+
2328
+ //#endregion
2329
+ //#region src/bot/utilities/miscellaneous/contextMenuLeaves.ts
2330
+ /**
2331
+ * Collects the names of every registered context-menu command across a set of command builders, split into a
2332
+ * user set and a message set. The same builder may appear more than once (a guild command is pushed once per
2333
+ * guild), and slash commands carry no context-menu name, so both collapse here. The split mirrors the
2334
+ * controller's two name-keyed maps, so the boot guard checks each name against its own kind.
2335
+ *
2336
+ * @internal
2337
+ */
2338
+ function contextMenuLeaves(commands) {
2339
+ const user = /* @__PURE__ */ new Set();
2340
+ const message = /* @__PURE__ */ new Set();
2341
+ for (const command of commands) {
2342
+ if (!(command instanceof ContextMenuCommandBuilder)) continue;
2343
+ if (command.type === ApplicationCommandType.User) user.add(command.name);
2344
+ else message.add(command.name);
2345
+ }
2346
+ return {
2347
+ user,
2348
+ message
2349
+ };
2350
+ }
2351
+
2352
+ //#endregion
2353
+ //#region src/bot/utilities/miscellaneous/slashRouteLeaves.ts
2354
+ /**
2355
+ * Collects the route keys of every executable slash leaf across a set of command builders, deduplicated. The
2356
+ * same builder may appear more than once (a guild command is pushed once per guild), and context-menu
2357
+ * commands carry no slash route, so both collapse here. Route keys come from the same {@link routeLeavesOf}
2358
+ * that `seedcord codegen` reads, so the boot-time check compares against the generated registry's keys.
2359
+ *
2360
+ * @internal
2361
+ */
2362
+ function slashRouteLeaves(commands) {
2363
+ const leaves = /* @__PURE__ */ new Set();
2364
+ for (const command of commands) {
2365
+ if (!(command instanceof SlashCommandBuilder)) continue;
2366
+ for (const leaf of routeLeavesOf(command.toJSON())) leaves.add(leaf.route);
2367
+ }
2368
+ return leaves;
2369
+ }
2370
+
2371
+ //#endregion
2372
+ //#region src/bot/controllers/CommandRegistry.ts
2373
+ /**
2374
+ * Manages Discord application command registration and deployment.
2375
+ *
2376
+ * Scans command directories, builds command structures, and registers both global and guild-scoped commands
2377
+ * to Discord's API. Accessed via `core.bot.commands`. Do not construct it directly.
2378
+ */
2379
+ var CommandRegistry = class {
2380
+ core;
2381
+ onDeployed;
2382
+ name = "Commands";
2383
+ logger = new Logger("Commands");
2384
+ isInitialised = false;
2385
+ globalCommands = [];
2386
+ guildCommands = new Collection();
2387
+ ctorToCommand = /* @__PURE__ */ new Map();
2388
+ hmrHandler;
2389
+ pendingEvents = /* @__PURE__ */ new Map();
2390
+ constructor(core, onDeployed) {
2391
+ this.core = core;
2392
+ this.onDeployed = onDeployed;
2393
+ const commandsDir = this.core.config.bot.commands.path;
2394
+ if (!commandsDir) throw new SeedcordError(SeedcordErrorCode.CoreControllerPathMissing, ["CommandRegistry", "commands"]);
2395
+ if (!Envapter.isDevelopment && !Envapter.isTest) return;
2396
+ this.hmrHandler = new HmrModuleHandler({
2397
+ handlersDir: commandsDir,
2398
+ isHandler: this.isCommandClass.bind(this),
2399
+ registerHandler: this.registerCommand.bind(this),
2400
+ unregisterHandler: this.unregisterCommand.bind(this),
2401
+ getArtifacts: this.getArtifacts.bind(this),
2402
+ logger: this.logger
2403
+ });
2404
+ }
2405
+ getArtifacts(ctor) {
2406
+ return this.ctorToCommand.get(ctor);
2407
+ }
2408
+ /** @internal */
2409
+ async init() {
2410
+ if (this.isInitialised) return;
2411
+ this.isInitialised = true;
2412
+ const commandsDir = this.core.config.bot.commands.path;
2413
+ if (!commandsDir) return;
2414
+ this.logger.info(chalk.bold(commandsDir));
2415
+ await this.loadCommands(commandsDir);
2416
+ this.logger.utils.summary("Loaded commands", {
2417
+ global: this.globalCommands.length,
2418
+ "guild groups": this.guildCommands.size
2419
+ });
2420
+ getDevChannel()?.on("seedcord:refresh-commands", (data) => {
2421
+ this.refresh(data.shouldRefresh);
2422
+ });
2423
+ }
2424
+ /** @internal */
2425
+ async refresh(shouldRefresh = true) {
2426
+ if (!shouldRefresh) {
2427
+ this.logger.info(chalk.italic("Command refresh cancelled."));
2428
+ this.pendingEvents.clear();
2429
+ return;
2430
+ }
2431
+ this.logger.info(chalk.italic("Refreshing commands..."));
2432
+ for (const event of this.pendingEvents.values()) await this.hmrHandler?.handle(event);
2433
+ this.pendingEvents.clear();
2434
+ await this.setCommands();
2435
+ }
2436
+ /** @internal */
2437
+ async onHmr(event) {
2438
+ const commandsDir = this.core.config.bot.commands.path;
2439
+ if (commandsDir && event.file.startsWith(resolve(process.cwd(), commandsDir))) {
2440
+ this.pendingEvents.delete(event.file);
2441
+ this.pendingEvents.set(event.file, event);
2442
+ getDevChannel()?.send("seedcord:commands-update-prompt", { files: [...this.pendingEvents.keys()].map((f) => formatFilePath(f)) });
2443
+ } else await this.hmrHandler?.handle(event);
2444
+ }
2445
+ async loadCommands(dir) {
2446
+ await traverseDirectory(dir, (fullPath, rel, mod) => {
2447
+ for (const exported of Object.values(mod)) if (this.isCommandClass(exported)) {
2448
+ this.registerCommand(exported, rel);
2449
+ this.hmrHandler?.trackHandler(fullPath, exported);
2450
+ }
2451
+ }, this.logger);
2452
+ }
2453
+ isCommandClass(obj) {
2454
+ if (typeof obj !== "function") return false;
2455
+ return obj.prototype instanceof BuilderComponent && Reflect.hasMetadata(CommandMetadataKey, obj);
2456
+ }
2457
+ registerCommand(ctor, rel) {
2458
+ const meta = Reflect.getMetadata(CommandMetadataKey, ctor);
2459
+ if (!meta) return;
2460
+ const comp = new ctor().component;
2461
+ const commandType = comp instanceof SlashCommandBuilder ? "slash command" : "context menu command";
2462
+ if (meta.scope === "global") {
2463
+ this.globalCommands.push(comp);
2464
+ this.logger.utils.registration(ctor.name, rel);
2465
+ this.logger.utils.item(`Global ${commandType}: ${chalk.bold.cyan(comp.name)}`);
2466
+ } else {
2467
+ for (const g of meta.guilds) {
2468
+ const arr = this.guildCommands.get(g) ?? [];
2469
+ arr.push(comp);
2470
+ this.guildCommands.set(g, arr);
2471
+ }
2472
+ this.logger.utils.registration(ctor.name, rel);
2473
+ this.logger.utils.item(`Guild ${commandType}: ${chalk.bold.cyan(comp.name)} for ${chalk.magenta.bold(meta.guilds.length)} guild(s)`);
2474
+ }
2475
+ this.ctorToCommand.set(ctor, {
2476
+ name: comp.name,
2477
+ scope: meta.scope,
2478
+ ...meta.scope === "guild" && { guilds: meta.guilds }
2479
+ });
2480
+ }
2481
+ unregisterCommand(ctor, artifacts) {
2482
+ const info = artifacts ?? this.ctorToCommand.get(ctor);
2483
+ if (!info) return;
2484
+ if (info.scope === "global") {
2485
+ const idx = this.globalCommands.findIndex((c) => c.name === info.name);
2486
+ if (idx !== -1) this.globalCommands.splice(idx, 1);
2487
+ } else for (const g of info.guilds ?? []) {
2488
+ const arr = this.guildCommands.get(g);
2489
+ if (arr) {
2490
+ const idx = arr.findIndex((c) => c.name === info.name);
2491
+ if (idx !== -1) arr.splice(idx, 1);
2492
+ }
2493
+ }
2494
+ this.ctorToCommand.delete(ctor);
2495
+ }
2496
+ /** @internal */
2497
+ async setCommands() {
2498
+ const result = {
2499
+ global: new Collection(),
2500
+ guilds: new Collection()
2501
+ };
2502
+ if (this.globalCommands.length > 0) {
2503
+ const deployed = await this.core.bot.client.application?.commands.set(this.globalCommands);
2504
+ if (deployed) result.global = deployed;
2505
+ const tag = this.globalCommands.length === 1 ? "command" : "commands";
2506
+ this.logger.utils.summary("Configured global", { [tag]: this.globalCommands.length });
2507
+ this.logger.utils.item(`${this.globalCommands.map((command) => chalk.bold.cyan(command.name)).join(", ")}`);
2508
+ }
2509
+ for (const [guildId, commands] of this.guildCommands.entries()) {
2510
+ const guild = this.core.bot.client.guilds.cache.get(guildId);
2511
+ if (!guild) {
2512
+ this.logger.warn(`Guild with ID ${guildId} not found, skipping command registration.`);
2513
+ continue;
2514
+ }
2515
+ const deployed = await guild.commands.set(commands);
2516
+ result.guilds.set(guildId, deployed);
2517
+ const tag = commands.length === 1 ? "command" : "commands";
2518
+ this.logger.utils.summary(`Configured commands for ${chalk.bold.yellow(guild.name)}`, { [tag]: commands.length });
2519
+ this.logger.utils.item(`${commands.map((command) => chalk.bold.cyan(command.name)).join(", ")}`);
2520
+ }
2521
+ this.onDeployed?.(result);
2522
+ return result;
2523
+ }
2524
+ /** The deduplicated slash route keys across every global and guild command. @internal */
2525
+ routeLeaves() {
2526
+ return slashRouteLeaves([...this.globalCommands, ...this.guildCommands.values()].flat());
2527
+ }
2528
+ /** The registered context-menu command names, split by kind, across every global and guild command. @internal */
2529
+ contextMenuLeaves() {
2530
+ return contextMenuLeaves([...this.globalCommands, ...this.guildCommands.values()].flat());
2531
+ }
2532
+ };
2533
+
2534
+ //#endregion
2535
+ //#region src/miscellaneous/deriveEventActor.ts
2536
+ function deriveEventActor(args) {
2537
+ const tuple = Array.isArray(args) ? args : [args];
2538
+ for (const arg of tuple) {
2539
+ if (arg instanceof Message) return {
2540
+ guild: arg.guild,
2541
+ member: arg.member,
2542
+ user: arg.author,
2543
+ channelId: arg.channelId
2544
+ };
2545
+ if (arg instanceof GuildMember) return {
2546
+ guild: arg.guild,
2547
+ member: arg,
2548
+ user: arg.user,
2549
+ channelId: null
2550
+ };
2551
+ if (arg instanceof User) return {
2552
+ guild: null,
2553
+ member: null,
2554
+ user: arg,
2555
+ channelId: null
2556
+ };
2557
+ }
2558
+ return {
2559
+ guild: null,
2560
+ member: null,
2561
+ user: null,
2562
+ channelId: null
2563
+ };
2564
+ }
2565
+
2566
+ //#endregion
2567
+ //#region src/bot/gates/runGates.ts
2568
+ function interactionGateContext(interaction, core) {
2569
+ const rawMember = interaction.member;
2570
+ const memberRoleIds = rawMember instanceof GuildMember ? [...rawMember.roles.cache.keys()].filter((id) => id !== interaction.guildId) : rawMember?.roles ?? [];
2571
+ return {
2572
+ kind: "interaction",
2573
+ interaction,
2574
+ core,
2575
+ user: interaction.user,
2576
+ guild: interaction.guild,
2577
+ member: rawMember instanceof GuildMember ? rawMember : null,
2578
+ userId: interaction.user.id,
2579
+ guildId: interaction.guildId,
2580
+ channelId: interaction.channelId,
2581
+ memberRoleIds,
2582
+ memberPermissions: interaction.memberPermissions?.bitfield ?? null,
2583
+ routeId: null
2584
+ };
2585
+ }
2586
+ function eventGateContext(eventName, args, core) {
2587
+ const actor = deriveEventActor(args);
2588
+ return {
2589
+ kind: "event",
2590
+ core,
2591
+ eventName,
2592
+ payload: args,
2593
+ user: actor.user,
2594
+ guild: actor.guild,
2595
+ member: actor.member,
2596
+ userId: actor.user?.id ?? null,
2597
+ guildId: actor.guild?.id ?? null,
2598
+ channelId: actor.channelId,
2599
+ memberRoleIds: actor.member ? [...actor.member.roles.cache.keys()].filter((id) => id !== actor.guild?.id) : [],
2600
+ memberPermissions: actor.member?.permissions.bitfield ?? null,
2601
+ routeId: null
2602
+ };
2603
+ }
2604
+
2605
+ //#endregion
2606
+ //#region src/miscellaneous/FaultThrottle.ts
2607
+ /**
2608
+ * Drops duplicate fault reports inside a fixed window so a recurring fault (a database outage on a
2609
+ * hot path) reports once per window instead of flooding the webhook. Keyed on a structural string, so
2610
+ * the map stays small, and a stale entry is evicted on the next read of its key.
2611
+ *
2612
+ * @internal
2613
+ */
2614
+ var FaultThrottle = class {
2615
+ windowMs;
2616
+ now;
2617
+ lastReportedAt = /* @__PURE__ */ new Map();
2618
+ constructor(windowMs = 6e4, now = () => Date.now()) {
2619
+ this.windowMs = windowMs;
2620
+ this.now = now;
2621
+ }
2622
+ /** Evicts the entry for this key if it has aged out, so the map never holds stale keys forever. */
2623
+ shouldReport(key) {
2624
+ const last = this.lastReportedAt.get(key);
2625
+ if (last === void 0) return true;
2626
+ if (this.now() - last < this.windowMs) return false;
2627
+ this.lastReportedAt.delete(key);
2628
+ return true;
2629
+ }
2630
+ markReported(key) {
2631
+ this.lastReportedAt.set(key, this.now());
2632
+ }
2633
+ clear() {
2634
+ this.lastReportedAt.clear();
2635
+ }
2636
+ };
2637
+
2638
+ //#endregion
2639
+ //#region src/miscellaneous/extractErrorResponse.ts
2640
+ const logger$2 = new Logger("ErrorsHandling");
2641
+ /**
2642
+ * The single throttle for every fault publish, so a recurring fault reports once per window across both
2643
+ * the interaction and event paths. Exported so tests reset it between cases.
2644
+ *
2645
+ * @internal
2646
+ */
2647
+ const faultThrottle = new FaultThrottle();
2648
+ /**
2649
+ * Processes an error into a user-facing reply and routes its report.
2650
+ *
2651
+ * A {@link Notice} always renders its own reply. A reporting denial (`report: true`) additionally
2652
+ * publishes `handledException` on the interaction path. A raw, non-denial throw publishes
2653
+ * `unknownException` and renders the configured `defaultError` (or a generic {@link Fault}). One uuid is
2654
+ * threaded into both the reply and the bus payload.
2655
+ *
2656
+ * @internal
2657
+ */
2658
+ function extractErrorResponse(error, core, origin) {
2659
+ const uuid = crypto.randomUUID();
2660
+ const developerUsername = core.config.notifications?.developerUsername;
2661
+ const ctx = developerUsername === void 0 ? { uuid } : {
2662
+ uuid,
2663
+ developerUsername
2664
+ };
2665
+ if (error instanceof Notice) {
2666
+ if (error.report) reportFault(error, core, origin, uuid);
2667
+ return {
2668
+ uuid,
2669
+ response: error.render(ctx)
2670
+ };
2671
+ }
2672
+ reportRawFault(error, core, origin, uuid);
2673
+ const override = core.config.errors?.defaultError;
2674
+ return {
2675
+ uuid,
2676
+ response: override ? new override(uuid).render(ctx) : new Fault().render(ctx)
2677
+ };
2678
+ }
2679
+ function withThrottle(origin, error, publish) {
2680
+ const key = faultKey(origin, error);
2681
+ if (!faultThrottle.shouldReport(key)) {
2682
+ logger$2.info(`throttled duplicate fault ${key}`);
2683
+ return;
2684
+ }
2685
+ publish();
2686
+ faultThrottle.markReported(key);
2687
+ }
2688
+ function reportFault(denial, core, origin, uuid) {
2689
+ withThrottle(origin, denial, () => {
2690
+ logger$2.error(`${denial.name}: ${uuid}`, denial);
2691
+ if (origin.interaction) core.bus.publish("handledException", {
2692
+ denial,
2693
+ uuid,
2694
+ source: buildInteractionSource(origin.interaction)
2695
+ });
2696
+ else if (origin.event) core.bus.publish("handledException", {
2697
+ denial,
2698
+ uuid,
2699
+ source: buildEventSource(origin.event, origin)
2700
+ });
2701
+ else core.bus.publish("unknownException", {
2702
+ uuid,
2703
+ error: denial,
2704
+ guild: origin.guild,
2705
+ user: origin.user,
2706
+ metadata: metadataFor(origin)
2707
+ });
2708
+ });
2709
+ }
2710
+ function reportRawFault(error, core, origin, uuid) {
2711
+ withThrottle(origin, error, () => {
2712
+ if (core.config.errors?.errorStack ?? false) logger$2.error(uuid, error);
2713
+ else logger$2.error(`${uuid} | ${error.message}`);
2714
+ core.bus.publish("unknownException", {
2715
+ uuid,
2716
+ error,
2717
+ guild: origin.guild,
2718
+ user: origin.user,
2719
+ metadata: metadataFor(origin)
2720
+ });
2721
+ });
2722
+ }
2723
+ function metadataFor(origin) {
2724
+ if (origin.event) return {
2725
+ eventName: origin.event.name,
2726
+ handler: origin.event.handler,
2727
+ args: origin.event.args
2728
+ };
2729
+ return origin.metadata;
2730
+ }
2731
+ function buildEventSource(event, origin) {
2732
+ return {
2733
+ kind: "event",
2734
+ eventName: event.name,
2735
+ handler: event.handler,
2736
+ userId: origin.user?.id ?? null,
2737
+ guildId: origin.guild?.id ?? null,
2738
+ channelId: event.channelId,
2739
+ raw: event.args
2740
+ };
2741
+ }
2742
+ function faultKey(origin, error) {
2743
+ const name = error instanceof Notice ? error.name : error instanceof DiscordAPIError ? String(error.code) : error.constructor.name;
2744
+ if (origin.event) return `${origin.event.name}:${origin.event.handler}:${name}`;
2745
+ if (origin.interaction) return `${interactionRoute(origin.interaction)}:${name}`;
2746
+ if (origin.route) return `autocomplete:${origin.route}:${name}`;
2747
+ return `autocomplete:${name}`;
2748
+ }
2749
+ function interactionRoute(interaction) {
2750
+ if (interaction.isChatInputCommand()) return slashRouteOf(interaction);
2751
+ if (interaction.isContextMenuCommand()) return interaction.commandName;
2752
+ if (interaction.isButton() || interaction.isAnySelectMenu() || interaction.isModalSubmit()) return prefixOf(interaction.customId) || interaction.customId;
2753
+ return "interaction";
2754
+ }
2755
+ function buildInteractionSource(interaction) {
2756
+ const command = interaction.isChatInputCommand() ? slashRouteOf(interaction) : interaction.isContextMenuCommand() ? interaction.commandName : null;
2757
+ const customId = interaction.isButton() || interaction.isAnySelectMenu() || interaction.isModalSubmit() ? interaction.customId : null;
2758
+ return {
2759
+ kind: "interaction",
2760
+ interactionKind: interactionKind(interaction),
2761
+ command,
2762
+ customId,
2763
+ userId: interaction.user.id,
2764
+ guildId: interaction.guildId,
2765
+ channelId: interaction.channelId,
2766
+ interactionId: interaction.id,
2767
+ raw: interaction
2768
+ };
2769
+ }
2770
+ function interactionKind(interaction) {
2771
+ if (interaction.isChatInputCommand()) return "slash";
2772
+ if (interaction.isContextMenuCommand()) return "context-menu";
2773
+ if (interaction.isButton()) return "button";
2774
+ if (interaction.isAnySelectMenu()) return "select";
2775
+ return "modal";
2776
+ }
2777
+
2778
+ //#endregion
2779
+ //#region src/bot/handleEventFault.ts
2780
+ const logger$1 = new Logger("EventBoundary");
2781
+ /**
2782
+ * The event controller boundary. Reports a throw from an event handler and never replies, since a
2783
+ * generic event has no reply target. A {@link Silence} or a non-reporting {@link Notice} stops quietly, a
2784
+ * reporting denial or a raw error publishes a fault with a best-effort actor derived from the args.
2785
+ *
2786
+ * @internal
2787
+ */
2788
+ function handleEventFault(caught, eventName, handlerName, args, core) {
2789
+ if (caught instanceof Silence) {
2790
+ if (caught.reason !== void 0) logger$1.debug(`Silence: ${caught.reason}`);
2791
+ return;
2792
+ }
2793
+ if (!Error.isError(caught)) throw caught;
2794
+ const ignore = new Set(core.config.errors?.ignoreEventApiCodes ?? []);
2795
+ if (caught instanceof DiscordAPIError && ignore.has(caught.code)) {
2796
+ logger$1.debug(`swallowed api code ${caught.code}`);
2797
+ return;
2798
+ }
2799
+ if (caught instanceof Notice && !caught.report) return;
2800
+ const actor = deriveEventActor(args);
2801
+ extractErrorResponse(caught, core, {
2802
+ event: {
2803
+ name: eventName,
2804
+ handler: handlerName,
2805
+ args,
2806
+ channelId: actor.channelId
2807
+ },
2808
+ guild: actor.guild,
2809
+ user: actor.user
2810
+ });
2811
+ }
2812
+
2813
+ //#endregion
2814
+ //#region src/bot/controllers/EventDispatcher.ts
2815
+ /**
2816
+ * Scans event handler directories, registers handlers with Discord client events,
2817
+ * and coordinates event execution through the handler system. Does not handle interactions.
2818
+ * Multiple handlers can point to one event.
2819
+ *
2820
+ * @internal
2821
+ */
2822
+ var EventDispatcher = class {
2823
+ core;
2824
+ logger = new Logger("Events");
2825
+ isInitialized = false;
2826
+ name = "Events";
2827
+ eventMap = /* @__PURE__ */ new Map();
2828
+ middlewares = [];
2829
+ executedOnceHandlers = /* @__PURE__ */ new Set();
2830
+ attachedEvents = /* @__PURE__ */ new Set();
2831
+ hmrHandler;
2832
+ constructor(core) {
2833
+ this.core = core;
2834
+ const eventsDir = this.core.config.bot.events.path;
2835
+ if (!eventsDir) throw new SeedcordError(SeedcordErrorCode.CoreControllerPathMissing, ["EventDispatcher", "events"]);
2836
+ if (!Envapter.isDevelopment && !Envapter.isTest) return;
2837
+ this.hmrHandler = new HmrModuleHandler({
2838
+ handlersDir: eventsDir,
2839
+ ...hasKeys(this.core.config.bot.events, ["middlewares"]) && { middlewaresDir: this.core.config.bot.events.middlewares },
2840
+ isHandler: this.isEventHandlerClass.bind(this),
2841
+ isMiddleware: this.isMiddlewareClass.bind(this),
2842
+ registerHandler: this.registerHandler.bind(this),
2843
+ registerMiddleware: this.registerMiddleware.bind(this),
2844
+ unregisterHandler: this.unregisterHandler.bind(this),
2845
+ unregisterMiddleware: this.unregisterMiddleware.bind(this),
2846
+ getArtifacts: this.getArtifacts.bind(this),
2847
+ logger: this.logger
2848
+ });
2849
+ }
2850
+ getArtifacts(ctor) {
2851
+ const events = [];
2852
+ for (const [event, handlers] of this.eventMap.entries()) if (handlers.some((h) => h.ctor === ctor)) events.push(event);
2853
+ return events;
2854
+ }
2855
+ async init() {
2856
+ if (this.isInitialized) return;
2857
+ this.isInitialized = true;
2858
+ const handlersDir = this.core.config.bot.events.path;
2859
+ if (!handlersDir) return;
2860
+ this.logger.info(chalk.bold(handlersDir));
2861
+ const middlewareDir = hasKeys(this.core.config.bot.events, ["middlewares"]) ? this.core.config.bot.events.middlewares : void 0;
2862
+ if (middlewareDir) {
2863
+ this.logger.info(`${chalk.bold(middlewareDir)} ${chalk.gray("(middlewares)")}`);
2864
+ await this.loadMiddlewares(middlewareDir);
2865
+ }
2866
+ await this.loadHandlers(handlersDir);
2867
+ this.attachToClient();
2868
+ this.logger.info(`${chalk.bold.green("Loaded event handlers:")}`);
2869
+ const eventList = [`${chalk.magenta.bold(this.middlewares.length)} middlewares`];
2870
+ this.eventMap.forEach((handlers, eventName) => {
2871
+ eventList.push(`${chalk.magenta.bold(handlers.length)} ${eventName}`);
2872
+ });
2873
+ this.logger.utils.list(eventList);
2874
+ }
2875
+ async loadHandlers(dir) {
2876
+ await traverseDirectory(dir, (fullPath, relativePath, imported) => {
2877
+ for (const val of Object.values(imported)) {
2878
+ if (!this.isEventHandlerClass(val)) continue;
2879
+ this.registerHandler(val, relativePath);
2880
+ this.hmrHandler?.trackHandler(fullPath, val);
2881
+ }
2882
+ }, this.logger);
2883
+ }
2884
+ async loadMiddlewares(dir) {
2885
+ await traverseDirectory(dir, (fullPath, relativePath, imported) => {
2886
+ for (const val of Object.values(imported)) {
2887
+ if (!this.isMiddlewareClass(val)) continue;
2888
+ this.registerMiddleware(val, relativePath);
2889
+ this.hmrHandler?.trackMiddleware(fullPath, val);
2890
+ }
2891
+ }, this.logger);
2892
+ }
2893
+ /** @internal For use in dev mode */
2894
+ async onHmr(event) {
2895
+ await this.hmrHandler?.handle(event);
2896
+ }
2897
+ unregisterHandler(handlerClass, artifacts) {
2898
+ const events = artifacts ?? [...this.eventMap.keys()];
2899
+ for (const event of events) {
2900
+ const handlers = this.eventMap.get(event);
2901
+ if (!handlers) continue;
2902
+ const index = handlers.findIndex((h) => h.ctor === handlerClass);
2903
+ if (index !== -1) {
2904
+ handlers.splice(index, 1);
2905
+ if (handlers.length === 0) this.eventMap.delete(event);
2906
+ }
2907
+ }
2908
+ }
2909
+ unregisterMiddleware(middlewareCtor) {
2910
+ const index = this.middlewares.findIndex((entry) => entry.ctor === middlewareCtor);
2911
+ if (index !== -1) this.middlewares.splice(index, 1);
2912
+ }
2913
+ registerMiddleware(middlewareCtor, relativePath) {
2914
+ const metadata = Reflect.getMetadata(MiddlewareMetadataKey, middlewareCtor);
2915
+ if (metadata?.type !== "event") return;
2916
+ if (this.middlewares.some((entry) => entry.ctor === middlewareCtor)) return;
2917
+ this.middlewares.push({
2918
+ ctor: middlewareCtor,
2919
+ priority: metadata.priority,
2920
+ ...metadata.events && { events: metadata.events }
2921
+ });
2922
+ this.middlewares.sort((a, b) => a.priority - b.priority);
2923
+ this.logger.utils.registration(`${middlewareCtor.name} ${chalk.gray(`(${metadata.priority})`)}`, relativePath, "event middleware");
2924
+ }
2925
+ async runMiddlewares(eventName, args) {
2926
+ for (const { ctor, events } of this.middlewares) {
2927
+ if (events && !events.includes(eventName)) continue;
2928
+ try {
2929
+ await new ctor(args, this.core, eventName).execute();
2930
+ } catch (caught) {
2931
+ handleEventFault(caught, String(eventName), ctor.name, args, this.core);
2932
+ return false;
2933
+ }
2934
+ }
2935
+ return true;
2936
+ }
2937
+ isEventHandlerClass(obj) {
2938
+ if (typeof obj !== "function") return false;
2939
+ return obj.prototype instanceof EventHandler && Reflect.hasMetadata(EventMetadataKey, obj);
2940
+ }
2941
+ isMiddlewareClass(obj) {
2942
+ if (typeof obj !== "function") return false;
2943
+ return obj.prototype instanceof EventMiddleware && Reflect.hasMetadata(MiddlewareMetadataKey, obj);
2944
+ }
2945
+ registerHandler(handlerClass, relativePath) {
2946
+ const raw = Reflect.getMetadata(EventMetadataKey, handlerClass);
2947
+ const register = (key, frequency) => {
2948
+ let handlers = this.eventMap.get(key);
2949
+ if (!handlers) {
2950
+ handlers = [];
2951
+ this.eventMap.set(key, handlers);
2952
+ }
2953
+ handlers.push({
2954
+ ctor: handlerClass,
2955
+ frequency
2956
+ });
2957
+ if (this.isInitialized && !this.attachedEvents.has(key)) this.attachListener(key);
2958
+ };
2959
+ if (Array.isArray(raw)) for (const entry of raw) register(entry.event, entry.frequency);
2960
+ else {
2961
+ const names = areRoutes(raw) ? raw : typeof raw === "string" ? [raw] : [];
2962
+ for (const name of names) register(name, "on");
2963
+ }
2964
+ this.logger.utils.registration(handlerClass.name, relativePath);
2965
+ }
2966
+ attachToClient() {
2967
+ for (const [eventName] of this.eventMap) this.attachListener(eventName);
2968
+ }
2969
+ attachListener(eventName) {
2970
+ if (this.attachedEvents.has(eventName)) return;
2971
+ this.attachedEvents.add(eventName);
2972
+ const handlerEntries = this.eventMap.get(eventName);
2973
+ this.logger.debug(`Attaching ${chalk.bold.green(eventName)} to the client with ${chalk.gray(handlerEntries?.length ?? 0)} handler(s)`);
2974
+ this.core.bot.client.on(eventName, (...args) => {
2975
+ this.core.bot.emitSafe("any:event", eventName, ...args);
2976
+ (async () => {
2977
+ await this.processEvent(eventName, args).catch((err) => {
2978
+ this.logger.error(`[${chalk.bold.red("UNHANDLED ERROR AT ROOT")}] ${err.name}`, err.stack);
2979
+ this.core.bot.emit("error:unhandled:event", err);
2980
+ });
2981
+ })();
2982
+ });
2983
+ }
2984
+ async processEvent(eventName, args) {
2985
+ const handlerEntries = this.eventMap.get(eventName);
2986
+ if (!handlerEntries || handlerEntries.length === 0) return;
2987
+ const handlersToExecute = handlerEntries.filter((entry) => entry.frequency !== "once" || !this.executedOnceHandlers.has(entry.ctor));
2988
+ if (handlersToExecute.length === 0) return;
2989
+ if (!await this.runMiddlewares(eventName, args)) return;
2990
+ for (const entry of handlersToExecute) {
2991
+ if (entry.frequency === "once") {
2992
+ if (this.executedOnceHandlers.has(entry.ctor)) continue;
2993
+ this.executedOnceHandlers.add(entry.ctor);
2994
+ }
2995
+ await this.processHandler(eventName, entry.ctor, args);
2996
+ }
2997
+ }
2998
+ async processHandler(eventName, ctor, args) {
2999
+ try {
3000
+ this.logger.debug(`Processing ${chalk.bold.green(eventName)} with ${chalk.gray(ctor.name)}`);
3001
+ const handler = new ctor(args, this.core, eventName);
3002
+ await runHandlerGates(ctor, eventGateContext(eventName, args, this.core));
3003
+ await handler.execute();
3004
+ } catch (caught) {
3005
+ handleEventFault(caught, String(eventName), ctor.name, args, this.core);
3006
+ }
3007
+ }
3008
+ };
3009
+
3010
+ //#endregion
3011
+ //#region src/bot/defaults/UnhandledEvent.ts
3012
+ /**
3013
+ * Default handler for unhandled interactions. A reply failure here rides the controller boundary as a
3014
+ * raw fault, so it needs no decorator of its own.
3015
+ *
3016
+ * @internal
3017
+ */
3018
+ var UnhandledEvent = class extends InteractionHandler {
3019
+ async execute() {
3020
+ await this.event.reply({
3021
+ content: `Feature not implemented yet.`,
3022
+ flags: MessageFlags.Ephemeral
3023
+ });
3024
+ }
3025
+ };
3026
+
3027
+ //#endregion
3028
+ //#region src/bot/handleInteractionFault.ts
3029
+ const logger = new Logger("InteractionBoundary");
3030
+ /**
3031
+ * The interaction controller boundary. Sorts a throw from any handler-lifecycle phase into the right
3032
+ * user reply plus the right bus event, building a {@link ReplySender} lazily so it reads the live
3033
+ * acknowledgement state at catch time.
3034
+ *
3035
+ * @internal
3036
+ */
3037
+ async function handleInteractionFault(caught, interaction, core) {
3038
+ if (caught instanceof Silence) {
3039
+ if (caught.reason !== void 0) logger.debug(`Silence: ${caught.reason}`);
3040
+ return;
3041
+ }
3042
+ if (!Error.isError(caught)) throw caught;
3043
+ const ignore = new Set(core.config.errors?.ignoreApiCodes ?? []);
3044
+ if (caught instanceof DiscordAPIError && ignore.has(caught.code)) {
3045
+ logger.debug(`swallowed api code ${caught.code}`);
3046
+ return;
3047
+ }
3048
+ if (interaction.isAutocomplete()) {
3049
+ extractErrorResponse(caught, core, {
3050
+ guild: interaction.guild,
3051
+ user: interaction.user,
3052
+ metadata: interaction,
3053
+ route: slashRouteOf(interaction)
3054
+ });
3055
+ return;
3056
+ }
3057
+ const { response } = extractErrorResponse(caught, core, {
3058
+ interaction,
3059
+ guild: interaction.guild,
3060
+ user: interaction.user,
3061
+ metadata: interaction
3062
+ });
3063
+ await new ReplySender(interaction).send(response, caught instanceof Notice ? caught.ephemeral : true);
3064
+ }
3065
+
3066
+ //#endregion
3067
+ //#region src/bot/controllers/InteractionDispatcher.ts
3068
+ /**
3069
+ * Scans handler directories, routes each interaction to its registered handler, and runs the handler.
3070
+ * One handler per interaction.
3071
+ *
3072
+ * @internal
3073
+ */
3074
+ var InteractionDispatcher = class {
3075
+ core;
3076
+ logger = new Logger("Interactions");
3077
+ isInitialized = false;
3078
+ name = "Interactions";
3079
+ slashMap = /* @__PURE__ */ new Map();
3080
+ buttonMap = /* @__PURE__ */ new Map();
3081
+ modalMap = /* @__PURE__ */ new Map();
3082
+ stringSelectMap = /* @__PURE__ */ new Map();
3083
+ userSelectMap = /* @__PURE__ */ new Map();
3084
+ roleSelectMap = /* @__PURE__ */ new Map();
3085
+ channelSelectMap = /* @__PURE__ */ new Map();
3086
+ mentionableSelectMap = /* @__PURE__ */ new Map();
3087
+ messageContextMenuMap = /* @__PURE__ */ new Map();
3088
+ userContextMenuMap = /* @__PURE__ */ new Map();
3089
+ autocompleteMap = /* @__PURE__ */ new Map();
3090
+ keysToIgnore = /* @__PURE__ */ new Set();
3091
+ middlewares = [];
3092
+ hmrHandler;
3093
+ routeTypes = [
3094
+ [InteractionRoutes.Slash, this.slashMap],
3095
+ [InteractionRoutes.Button, this.buttonMap],
3096
+ [InteractionRoutes.Modal, this.modalMap],
3097
+ [InteractionRoutes.StringMenu, this.stringSelectMap],
3098
+ [InteractionRoutes.UserMenu, this.userSelectMap],
3099
+ [InteractionRoutes.RoleMenu, this.roleSelectMap],
3100
+ [InteractionRoutes.ChannelMenu, this.channelSelectMap],
3101
+ [InteractionRoutes.MentionableMenu, this.mentionableSelectMap],
3102
+ [InteractionRoutes.MessageContextMenu, this.messageContextMenuMap],
3103
+ [InteractionRoutes.UserContextMenu, this.userContextMenuMap],
3104
+ [InteractionRoutes.Autocomplete, this.autocompleteMap]
3105
+ ];
3106
+ constructor(core) {
3107
+ this.core = core;
3108
+ const ignoredKeysFromConfig = hasKeys(this.core.config.bot.interactions, ["ignoreCustomIds"]) ? this.core.config.bot.interactions.ignoreCustomIds : void 0;
3109
+ if (ignoredKeysFromConfig) for (const ignoredKey of ignoredKeysFromConfig) this.keysToIgnore.add(ignoredKey);
3110
+ this.keysToIgnore.add(CONFIRM_DEF);
3111
+ const interactionsDir = this.core.config.bot.interactions.path;
3112
+ if (!interactionsDir) throw new SeedcordError(SeedcordErrorCode.CoreControllerPathMissing, ["InteractionDispatcher", "interactions"]);
3113
+ if (!Envapter.isDevelopment && !Envapter.isTest) return;
3114
+ this.hmrHandler = new HmrModuleHandler({
3115
+ handlersDir: interactionsDir,
3116
+ ...hasKeys(this.core.config.bot.interactions, ["middlewares"]) && this.core.config.bot.interactions.middlewares && { middlewaresDir: this.core.config.bot.interactions.middlewares },
3117
+ isHandler: this.isHandlerClass.bind(this),
3118
+ isMiddleware: this.isMiddlewareClass.bind(this),
3119
+ registerHandler: this.registerHandler.bind(this),
3120
+ registerMiddleware: this.registerMiddleware.bind(this),
3121
+ unregisterHandler: this.unregisterHandler.bind(this),
3122
+ unregisterMiddleware: this.unregisterMiddleware.bind(this),
3123
+ getArtifacts: this.getArtifacts.bind(this),
3124
+ logger: this.logger
3125
+ });
3126
+ }
3127
+ /**
3128
+ * Warns for each command route with no registered `@SlashRoute` handler, which would fall through to
3129
+ * UnhandledEvent at runtime. A bot may route commands outside the registry, so this does not throw.
3130
+ *
3131
+ * @internal
3132
+ */
3133
+ warnUnhandledRoutes(commandLeaves) {
3134
+ for (const route of commandLeaves) if (!this.slashMap.has(route)) this.logger.warn(`Slash route ${chalk.bold.cyan(route)} has no registered ${chalk.bold("@SlashRoute")} handler.`);
3135
+ }
3136
+ /**
3137
+ * Warns for each context-menu command with no matching handler, which would fall through to UnhandledEvent
3138
+ * at runtime. Checked per kind since a user and a message command can share a name.
3139
+ *
3140
+ * @internal
3141
+ */
3142
+ warnUnhandledContextMenuRoutes(leaves) {
3143
+ for (const name of leaves.user) if (!this.userContextMenuMap.has(name)) this.logger.warn(`User context menu ${chalk.bold.cyan(name)} has no registered ${chalk.bold("@ContextMenuRoute")} handler.`);
3144
+ for (const name of leaves.message) if (!this.messageContextMenuMap.has(name)) this.logger.warn(`Message context menu ${chalk.bold.cyan(name)} has no registered ${chalk.bold("@ContextMenuRoute")} handler.`);
3145
+ }
3146
+ getArtifacts(handlerClass) {
3147
+ const artifacts = [];
3148
+ for (const [routeType] of this.routeTypes) {
3149
+ const meta = Reflect.getMetadata(InteractionRouteKeys[routeType], handlerClass);
3150
+ if (areRoutes(meta)) artifacts.push({
3151
+ routeType,
3152
+ routes: meta
3153
+ });
3154
+ }
3155
+ return artifacts;
3156
+ }
3157
+ async init() {
3158
+ if (this.isInitialized) return;
3159
+ this.isInitialized = true;
3160
+ const handlersDir = this.core.config.bot.interactions.path;
3161
+ if (!handlersDir) return;
3162
+ this.logger.info(chalk.bold(handlersDir));
3163
+ const middlewareDir = hasKeys(this.core.config.bot.interactions, ["middlewares"]) ? this.core.config.bot.interactions.middlewares : void 0;
3164
+ if (middlewareDir) {
3165
+ this.logger.info(`${chalk.bold(middlewareDir)} ${chalk.gray("(middlewares)")}`);
3166
+ await this.loadMiddlewares(middlewareDir);
3167
+ }
3168
+ await this.loadHandlers(handlersDir);
3169
+ this.attachToClient();
3170
+ this.logger.info(`${chalk.bold.green("Loaded interaction handlers:")}`);
3171
+ this.logger.utils.list([
3172
+ `${chalk.magenta.bold(this.middlewares.length)} middlewares`,
3173
+ `${chalk.magenta.bold(this.slashMap.size)} slash commands`,
3174
+ `${chalk.magenta.bold(this.buttonMap.size)} buttons`,
3175
+ `${chalk.magenta.bold(this.modalMap.size)} modals`,
3176
+ `${chalk.magenta.bold(this.stringSelectMap.size)} string selects`,
3177
+ `${chalk.magenta.bold(this.userSelectMap.size)} user selects`,
3178
+ `${chalk.magenta.bold(this.roleSelectMap.size)} role selects`,
3179
+ `${chalk.magenta.bold(this.channelSelectMap.size)} channel selects`,
3180
+ `${chalk.magenta.bold(this.mentionableSelectMap.size)} mentionable selects`,
3181
+ `${chalk.magenta.bold(this.messageContextMenuMap.size)} message context menus`,
3182
+ `${chalk.magenta.bold(this.userContextMenuMap.size)} user context menus`,
3183
+ `${chalk.magenta.bold(this.autocompleteMap.size)} autocomplete`
3184
+ ]);
3185
+ }
3186
+ async loadHandlers(dir) {
3187
+ await traverseDirectory(dir, (fullPath, relativePath, imported) => {
3188
+ for (const val of Object.values(imported)) {
3189
+ if (!this.isHandlerClass(val)) continue;
3190
+ this.registerHandler(val, relativePath);
3191
+ this.hmrHandler?.trackHandler(fullPath, val);
3192
+ }
3193
+ }, this.logger);
3194
+ }
3195
+ async loadMiddlewares(dir) {
3196
+ await traverseDirectory(dir, (fullPath, relativePath, imported) => {
3197
+ for (const val of Object.values(imported)) {
3198
+ if (!this.isMiddlewareClass(val)) continue;
3199
+ this.registerMiddleware(val, relativePath);
3200
+ this.hmrHandler?.trackMiddleware(fullPath, val);
3201
+ }
3202
+ }, this.logger);
3203
+ }
3204
+ registerMiddleware(middlewareCtor, relativePath) {
3205
+ const metadata = Reflect.getMetadata(MiddlewareMetadataKey, middlewareCtor);
3206
+ if (metadata?.type !== "interaction") return;
3207
+ if (this.middlewares.some((entry) => entry.ctor === middlewareCtor)) return;
3208
+ if (this.middlewares.some((entry) => entry.ctor.name === middlewareCtor.name)) throw new SeedcordError(SeedcordErrorCode.InteractionDuplicateMiddleware, [middlewareCtor.name]);
3209
+ this.middlewares.push({
3210
+ ctor: middlewareCtor,
3211
+ priority: metadata.priority
3212
+ });
3213
+ this.middlewares.sort((a, b) => a.priority - b.priority);
3214
+ this.logger.utils.registration(`${middlewareCtor.name} ${chalk.gray(`(${metadata.priority})`)}`, relativePath, "middleware");
3215
+ }
3216
+ isHandlerClass(obj) {
3217
+ if (typeof obj !== "function") return false;
3218
+ return obj.prototype instanceof InteractionHandler && Reflect.hasMetadata(InteractionMetadataKey, obj) || obj.prototype instanceof AutocompleteHandler && Reflect.hasMetadata(InteractionMetadataKey, obj);
3219
+ }
3220
+ isMiddlewareClass(obj) {
3221
+ if (typeof obj !== "function") return false;
3222
+ return obj.prototype instanceof InteractionMiddleware && Reflect.hasMetadata(MiddlewareMetadataKey, obj);
3223
+ }
3224
+ registerHandler(handlerClass, relativePath) {
3225
+ const writes = [];
3226
+ for (const [routeType, map] of this.routeTypes) {
3227
+ const meta = Reflect.getMetadata(InteractionRouteKeys[routeType], handlerClass);
3228
+ if (!areRoutes(meta)) continue;
3229
+ for (const route of meta) {
3230
+ const existing = map.get(route);
3231
+ if (existing && existing !== handlerClass) throw new SeedcordError(SeedcordErrorCode.InteractionDuplicateRoute, [
3232
+ route,
3233
+ existing.name,
3234
+ handlerClass.name
3235
+ ]);
3236
+ writes.push([map, route]);
3237
+ }
3238
+ this.logger.utils.registration(handlerClass.name, formatFilePath(relativePath));
3239
+ }
3240
+ for (const [map, route] of writes) map.set(route, handlerClass);
3241
+ }
3242
+ /** @internal For use in dev mode */
3243
+ async onHmr(event) {
3244
+ await this.hmrHandler?.handle(event);
3245
+ }
3246
+ unregisterHandler(handlerClass, artifacts) {
3247
+ if (artifacts) {
3248
+ for (const { routeType, routes } of artifacts) {
3249
+ const map = this.routeTypes.find(([type]) => type === routeType)?.[1];
3250
+ if (map) routes.forEach((route) => map.delete(route));
3251
+ }
3252
+ return;
3253
+ }
3254
+ for (const [routeType, map] of this.routeTypes) {
3255
+ const meta = Reflect.getMetadata(InteractionRouteKeys[routeType], handlerClass);
3256
+ if (!areRoutes(meta)) continue;
3257
+ meta.forEach((route) => map.delete(route));
3258
+ }
3259
+ }
3260
+ unregisterMiddleware(middlewareCtor) {
3261
+ const index = this.middlewares.findIndex((entry) => entry.ctor === middlewareCtor);
3262
+ if (index !== -1) this.middlewares.splice(index, 1);
3263
+ }
3264
+ attachToClient() {
3265
+ this.core.bot.client.on(Events.InteractionCreate, (interaction) => {
3266
+ this.core.bot.emitSafe("any:interaction", interaction);
3267
+ this.handleInteraction(interaction).catch((err) => {
3268
+ this.logger.error(`[${chalk.bold.red("UNHANDLED ERROR AT ROOT")}] ${err.name}`, err.stack);
3269
+ this.core.bot.emit("error:unhandled:interaction", err);
3270
+ });
3271
+ });
3272
+ }
3273
+ async handleCustomIdInteraction(interaction, getMap, interactionType) {
3274
+ if ([...this.keysToIgnore].some((matcher) => matcher.owns(interaction.customId))) return;
3275
+ const prefix = prefixOf(interaction.customId);
3276
+ if (!prefix) return this.logger.warn(`${interactionType} has invalid customId: ${interaction.customId}`);
3277
+ await this.processInteraction(interaction, () => prefix, (key) => getMap().get(key));
3278
+ }
3279
+ async processInteraction(interaction, extractKey, getHandler) {
3280
+ const key = extractKey(interaction);
3281
+ try {
3282
+ if (!interaction.isAutocomplete()) for (const { ctor } of this.middlewares) await new ctor(interaction, this.core).execute();
3283
+ let HandlerCtor = getHandler(key);
3284
+ if (!HandlerCtor) {
3285
+ this.logger.warn(`No handler found for key ${chalk.bold.cyan(key)}. Falling back to UnhandledEvent.`);
3286
+ HandlerCtor = UnhandledEvent;
3287
+ }
3288
+ this.logger.debug(`Processing ${chalk.bold.green(key)} with ${chalk.gray(HandlerCtor.name)}`);
3289
+ const dispatch = new DispatchContext(routeIdOf(HandlerCtor));
3290
+ const handler = new HandlerCtor(interaction, this.core, dispatch);
3291
+ if (!interaction.isAutocomplete()) await runHandlerGates(HandlerCtor, interactionGateContext(interaction, this.core));
3292
+ await handler.execute();
3293
+ } catch (caught) {
3294
+ await handleInteractionFault(caught, interaction, this.core);
3295
+ }
3296
+ }
3297
+ async handleInteraction(interaction) {
3298
+ switch (true) {
3299
+ case interaction.isChatInputCommand():
3300
+ await this.handleSlashCommand(interaction);
3301
+ break;
3302
+ case interaction.isButton():
3303
+ await this.handleButton(interaction);
3304
+ break;
3305
+ case interaction.isModalSubmit():
3306
+ await this.handleModal(interaction);
3307
+ break;
3308
+ case interaction.isStringSelectMenu():
3309
+ await this.handleStringSelectMenu(interaction);
3310
+ break;
3311
+ case interaction.isUserSelectMenu():
3312
+ await this.handleUserSelectMenu(interaction);
3313
+ break;
3314
+ case interaction.isRoleSelectMenu():
3315
+ await this.handleRoleSelectMenu(interaction);
3316
+ break;
3317
+ case interaction.isChannelSelectMenu():
3318
+ await this.handleChannelSelectMenu(interaction);
3319
+ break;
3320
+ case interaction.isMentionableSelectMenu():
3321
+ await this.handleMentionableSelectMenu(interaction);
3322
+ break;
3323
+ case interaction.isMessageContextMenuCommand():
3324
+ await this.handleMessageContextMenu(interaction);
3325
+ break;
3326
+ case interaction.isUserContextMenuCommand():
3327
+ await this.handleUserContextMenu(interaction);
3328
+ break;
3329
+ case interaction.isAutocomplete():
3330
+ await this.handleAutocomplete(interaction);
3331
+ break;
3332
+ default:
3333
+ this.logger.warn(`Unhandled interaction type: ${interaction.type}`);
3334
+ break;
3335
+ }
3336
+ }
3337
+ async handleSlashCommand(interaction) {
3338
+ const route = slashRouteOf(interaction);
3339
+ await this.processInteraction(interaction, () => route, (key) => this.slashMap.get(key));
3340
+ }
3341
+ async handleButton(interaction) {
3342
+ await this.handleCustomIdInteraction(interaction, () => this.buttonMap, "Button");
3343
+ }
3344
+ async handleModal(interaction) {
3345
+ await this.handleCustomIdInteraction(interaction, () => this.modalMap, "Modal");
3346
+ }
3347
+ async handleStringSelectMenu(interaction) {
3348
+ await this.handleCustomIdInteraction(interaction, () => this.stringSelectMap, "String select menu");
3349
+ }
3350
+ async handleUserSelectMenu(interaction) {
3351
+ await this.handleCustomIdInteraction(interaction, () => this.userSelectMap, "User select menu");
3352
+ }
3353
+ async handleRoleSelectMenu(interaction) {
3354
+ await this.handleCustomIdInteraction(interaction, () => this.roleSelectMap, "Role select menu");
3355
+ }
3356
+ async handleChannelSelectMenu(interaction) {
3357
+ await this.handleCustomIdInteraction(interaction, () => this.channelSelectMap, "Channel select menu");
3358
+ }
3359
+ async handleMentionableSelectMenu(interaction) {
3360
+ await this.handleCustomIdInteraction(interaction, () => this.mentionableSelectMap, "Mentionable select menu");
3361
+ }
3362
+ async handleMessageContextMenu(interaction) {
3363
+ await this.processInteraction(interaction, () => interaction.commandName, (key) => this.messageContextMenuMap.get(key));
3364
+ }
3365
+ async handleUserContextMenu(interaction) {
3366
+ await this.processInteraction(interaction, () => interaction.commandName, (key) => this.userContextMenuMap.get(key));
3367
+ }
3368
+ async handleAutocomplete(interaction) {
3369
+ const route = slashRouteOf(interaction);
3370
+ if (!this.autocompleteMap.has(route)) {
3371
+ this.logger.warn(`No autocomplete handler for ${chalk.bold.cyan(route)}.`);
3372
+ await interaction.respond([]);
3373
+ return;
3374
+ }
3375
+ await this.processInteraction(interaction, () => route, (key) => this.autocompleteMap.get(key));
3376
+ }
3377
+ };
3378
+
3379
+ //#endregion
3380
+ //#region \0@oxc-project+runtime@0.135.0/helpers/esm/decorateMetadata.js
3381
+ function __decorateMetadata(k, v) {
3382
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
3383
+ }
3384
+
3385
+ //#endregion
3386
+ //#region \0@oxc-project+runtime@0.135.0/helpers/esm/decorate.js
3387
+ function __decorate(decorators, target, key, desc) {
3388
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3389
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
3390
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
3391
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
3392
+ }
3393
+
3394
+ //#endregion
3395
+ //#region src/bot/Bot.ts
3396
+ /**
3397
+ * Discord bot implementation that manages client and controllers
3398
+ *
3399
+ * Don't instantiate this class directly. Use `core.bot` instead.
3400
+ */
3401
+ var Bot = class extends Plugin {
3402
+ /** @internal */
3403
+ logger = new Logger("Bot");
3404
+ isInitialized = false;
3405
+ _client;
3406
+ interactions;
3407
+ events;
3408
+ commands;
3409
+ emojiInjector;
3410
+ emojis = Emojis;
3411
+ mentions = CommandMentions;
3412
+ /** @internal For use in dev mode */
3413
+ async onHmr(event) {
3414
+ if (this.interactions) await this.interactions.onHmr(event);
3415
+ if (this.events) await this.events.onHmr(event);
3416
+ if (this.commands) await this.commands.onHmr(event);
3417
+ }
3418
+ /** @internal */
3419
+ constructor(core) {
3420
+ super(core);
3421
+ this._client = new Client(core.config.bot.clientOptions);
3422
+ if (core.config.bot.interactions.path) this.interactions = new InteractionDispatcher(core);
3423
+ if (core.config.bot.events.path) this.events = new EventDispatcher(core);
3424
+ if (core.config.bot.commands.path) {
3425
+ const mentionInjector = new CommandMentionInjector(core);
3426
+ this.commands = new CommandRegistry(core, (result) => {
3427
+ mentionInjector.inject(result);
3428
+ });
3429
+ }
3430
+ this.emojiInjector = new EmojiInjector(core);
3431
+ core.shutdown.addTask(ShutdownPhase.DiscordCleanup, "stop-bot", async () => await this.stop(), 2e3);
3432
+ }
3433
+ /**
3434
+ * Initializes Discord client and all controllers
3435
+ * @internal
3436
+ */
3437
+ async init() {
3438
+ if (this.isInitialized) return;
3439
+ this.isInitialized = true;
3440
+ const token = this.botToken;
3441
+ if (this.interactions) await this.interactions.init();
3442
+ if (this.events) await this.events.init();
3443
+ await this.login(token);
3444
+ await this.emojiInjector.init();
3445
+ if (this.commands) {
3446
+ await this.commands.init();
3447
+ await this.commands.setCommands();
3448
+ this.interactions?.warnUnhandledRoutes(this.commands.routeLeaves());
3449
+ this.interactions?.warnUnhandledContextMenuRoutes(this.commands.contextMenuLeaves());
3450
+ }
3451
+ }
3452
+ /**
3453
+ * Stops the bot and cleans up connections
3454
+ * @internal
3455
+ */
3456
+ async stop() {
3457
+ this._client.removeAllListeners();
3458
+ await this.logout();
3459
+ }
3460
+ /**
3461
+ * Logs the bot into Discord using the configured token
3462
+ */
3463
+ async login(token) {
3464
+ await this._client.login(token);
3465
+ this.logger.info(`Logged in as ${chalk.bold.magenta(this._client.user?.username)}!`);
3466
+ return this;
3467
+ }
3468
+ /**
3469
+ * Logs out and destroys the Discord client connection
3470
+ */
3471
+ async logout() {
3472
+ await this._client.destroy();
3473
+ this.logger.info(chalk.bold.red("Logged out of Discord!"));
3474
+ }
3475
+ get client() {
3476
+ return this._client;
3477
+ }
3478
+ emit(event, ...args) {
3479
+ return super.emit(event, ...args);
3480
+ }
3481
+ emitSafe(event, ...args) {
3482
+ return super.emitSafe(event, ...args);
3483
+ }
3484
+ onListenerError(error, event) {
3485
+ this.logger.error(`listener for ${String(event)} threw`, error);
3486
+ }
3487
+ };
3488
+ __decorate([Envapt("DISCORD_BOT_TOKEN", { converter: (raw) => validateDiscordToken(raw) }), __decorateMetadata("design:type", String)], Bot.prototype, "botToken", void 0);
3489
+
3490
+ //#endregion
3491
+ //#region src/hmr/HmrManager.ts
3492
+ var HmrManager = class {
3493
+ logger = new Logger("HMR", { channel: "hmr" });
3494
+ listeners = /* @__PURE__ */ new Set();
3495
+ constructor() {}
3496
+ /** @internal */
3497
+ init() {
3498
+ if (!import.meta.hot) return;
3499
+ setDevChannel(wrapHot(import.meta.hot));
3500
+ if (Envapter.isDevelopment || Envapter.isTest) {
3501
+ this.logger.info("Enabled");
3502
+ getDevChannel()?.on("seedcord:hmr", (payload) => {
3503
+ const affected = payload.affectedModules?.length ?? 0;
3504
+ this.logger.info(`${chalk.bold("1")} module changed, ${chalk.bold(affected)} affected modules`);
3505
+ if (payload.affectedModules) this.logger.utils.list(payload.affectedModules.map((mod) => formatFilePath(mod)), "Affected modules: ");
3506
+ this.handleUpdate(payload);
3507
+ });
3508
+ }
3509
+ }
3510
+ /** @internal */
3511
+ register(listener) {
3512
+ this.listeners.add(listener);
3513
+ }
3514
+ /** @internal */
3515
+ unregister(listener) {
3516
+ this.listeners.delete(listener);
3517
+ }
3518
+ async handleUpdate(event) {
3519
+ const promises = [...this.listeners].map(async (listener) => {
3520
+ try {
3521
+ await listener.onHmr(event);
3522
+ } catch (error) {
3523
+ this.logger.error(`Error handling HMR update in ${chalk.bold(listener.name)}: `, error);
3524
+ }
3525
+ });
3526
+ await Promise.all(promises);
3527
+ }
3528
+ };
3529
+
3530
+ //#endregion
3531
+ //#region src/subscribers/bases/webhookHelpers.ts
3532
+ const DISCORD_WEBHOOK_REGEX = new RegExp(String.raw`^https?:\/\/(?:canary\.|ptb\.)?discord(?:app)?\.com\/api\/webhooks\/\d+\/[\w$-]+$`);
3533
+ /**
3534
+ * Whether a string is a well-formed Discord webhook URL.
3535
+ *
3536
+ * @internal
3537
+ */
3538
+ function isDiscordWebhookUrl(value) {
3539
+ return URL.canParse(value) && DISCORD_WEBHOOK_REGEX.test(value);
3540
+ }
3541
+ /**
3542
+ * Serializes a value to a JSON attachment, made circular-safe first.
3543
+ *
3544
+ * @internal
3545
+ */
3546
+ function jsonAttachment(name, description, data) {
3547
+ const content = filterCirculars(data);
3548
+ return new AttachmentBuilder(Buffer.from(JSON.stringify(content, void 0, 2), "utf8"), {
3549
+ name,
3550
+ description
3551
+ });
3552
+ }
3553
+ /**
3554
+ * The small divider the default webhook reporters place between sections.
3555
+ *
3556
+ * @internal
3557
+ */
3558
+ var WebhookSeparator = class extends BuilderComponent {
3559
+ constructor() {
3560
+ super("separator");
3561
+ this.instance.setSpacing(SeparatorSpacingSize.Small).setDivider(true);
3562
+ }
3563
+ };
3564
+
3565
+ //#endregion
3566
+ //#region src/subscribers/default/HandledException.ts
3567
+ var _HandledException;
3568
+ function webhookUrlValidator$1(raw) {
3569
+ if (raw !== null && typeof raw !== "string") throw new SeedcordError(SeedcordErrorCode.ConfigHandledExceptionWebhookInvalid);
3570
+ const value = raw?.trim() ?? "";
3571
+ if (value === "") throw new SeedcordError(SeedcordErrorCode.ConfigHandledExceptionWebhookMissing);
3572
+ if (!isDiscordWebhookUrl(value)) throw new SeedcordError(SeedcordErrorCode.ConfigHandledExceptionWebhookInvalid);
3573
+ return value;
3574
+ }
3575
+ let HandledException = class HandledException extends WebhookLog {
3576
+ static {
3577
+ _HandledException = this;
3578
+ }
3579
+ webhook = new WebhookClient({ url: _HandledException.handledExceptionWebhookUrl });
3580
+ async execute() {
3581
+ const { source } = this.data;
3582
+ try {
3583
+ await this.webhook.send({
3584
+ flags: flagsFor(false),
3585
+ withComponents: true,
3586
+ username: "Handled Exception",
3587
+ components: [new HandledExceptionContainer(this.data).component],
3588
+ files: [jsonAttachment("source.json", "The raw source the fault came from", source.raw)]
3589
+ });
3590
+ } catch (error) {
3591
+ this.logger.error("Failed to send handled exception webhook", error);
3592
+ }
3593
+ }
3594
+ };
3595
+ __decorate([Envapt("HANDLED_EXCEPTION_WEBHOOK_URL", { converter: (raw) => webhookUrlValidator$1(raw) }), __decorateMetadata("design:type", String)], HandledException, "handledExceptionWebhookUrl", void 0);
3596
+ HandledException = _HandledException = __decorate([Subscribe("handledException")], HandledException);
3597
+ var HandledExceptionContainer = class extends BuilderComponent {
3598
+ constructor(data) {
3599
+ super("container");
3600
+ const { denial, uuid, source } = data;
3601
+ this.instance.addTextDisplayComponents((text) => text.setContent(faultSummary(denial, source))).addSeparatorComponents(new WebhookSeparator().component).addTextDisplayComponents((text) => text.setContent(`### UUID \`${uuid}\`\n\`\`\`${causeStack(denial)}\`\`\``)).addSeparatorComponents(new WebhookSeparator().component).addTextDisplayComponents((text) => text.setContent("### Source")).addFileComponents((file) => file.setURL("attachment://source.json"));
3602
+ }
3603
+ };
3604
+ /**
3605
+ * The summary block of a fault report, narrowed per source kind so an interaction fault shows its
3606
+ * command and customId while an event fault shows its event name and handler.
3607
+ *
3608
+ * @internal
3609
+ */
3610
+ function faultSummary(denial, source) {
3611
+ const head = `### A handled fault was reported: \`${denial.name}\`\n**Message:** ${denial.message}\n`;
3612
+ if (source.kind === "event") return `${head}**Event:** ${source.eventName}\n**Handler:** ${source.handler}\n**User ID:** \`${source.userId ?? "n/a"}\`\n**Guild ID:** \`${source.guildId ?? "n/a"}\`\n**Channel ID:** \`${source.channelId ?? "n/a"}\``;
3613
+ return `${head}**Kind:** ${source.interactionKind}\n**Command:** ${source.command ?? "n/a"}\n**CustomId:** ${source.customId ?? "n/a"}\n**User ID:** \`${source.userId}\`\n**Guild ID:** \`${source.guildId ?? "n/a"}\`\n**Channel ID:** \`${source.channelId ?? "n/a"}\`\n**Interaction ID:** \`${source.interactionId}\``;
3614
+ }
3615
+ /**
3616
+ * The text shown for a denial's cause in the report. Tolerates a non-serializable cause (a bigint or a
3617
+ * circular object) so building the report never throws.
3618
+ *
3619
+ * @internal
3620
+ */
3621
+ function causeStack(denial) {
3622
+ const { cause } = denial;
3623
+ if (Error.isError(cause)) return cause.stack ?? cause.message;
3624
+ if (typeof cause === "string") return cause;
3625
+ if (typeof cause === "bigint" || typeof cause === "symbol" || typeof cause === "function") return cause.toString();
3626
+ if (cause !== void 0) try {
3627
+ return JSON.stringify(cause);
3628
+ } catch {
3629
+ return "[unserializable cause]";
3630
+ }
3631
+ return denial.stack ?? "No cause recorded.";
3632
+ }
3633
+
3634
+ //#endregion
3635
+ //#region src/subscribers/default/UnknownException.ts
3636
+ var _UnknownException;
3637
+ function webhookUrlValidator(raw) {
3638
+ if (raw !== null && typeof raw !== "string") throw new SeedcordError(SeedcordErrorCode.ConfigUnknownExceptionWebhookInvalid);
3639
+ const value = raw?.trim() ?? "";
3640
+ if (value === "") throw new SeedcordError(SeedcordErrorCode.ConfigUnknownExceptionWebhookMissing);
3641
+ if (!isDiscordWebhookUrl(value)) throw new SeedcordError(SeedcordErrorCode.ConfigUnknownExceptionWebhookInvalid);
3642
+ return value;
3643
+ }
3644
+ let UnknownException = class UnknownException extends WebhookLog {
3645
+ static {
3646
+ _UnknownException = this;
3647
+ }
3648
+ webhook = new WebhookClient({ url: _UnknownException.unknownExceptionWebhookUrl });
3649
+ async execute() {
3650
+ const { metadata } = this.data;
3651
+ const metadataFile = metadata ? jsonAttachment("metadata.json", "Metadata associated with the error", metadata) : null;
3652
+ try {
3653
+ await this.webhook.send({
3654
+ flags: flagsFor(false),
3655
+ withComponents: true,
3656
+ username: "Unknown Exception",
3657
+ components: [new UnhandledErrorContainer(this.data).component],
3658
+ files: metadataFile ? [metadataFile] : []
3659
+ });
3660
+ } catch (error) {
3661
+ this.logger.error("Failed to send unknown exception webhook", error);
3662
+ }
3663
+ }
3664
+ };
3665
+ __decorate([Envapt("UNKNOWN_EXCEPTION_WEBHOOK_URL", { converter: (raw) => webhookUrlValidator(raw) }), __decorateMetadata("design:type", String)], UnknownException, "unknownExceptionWebhookUrl", void 0);
3666
+ UnknownException = _UnknownException = __decorate([Subscribe("unknownException")], UnknownException);
3667
+ var UnhandledErrorContainer = class extends BuilderComponent {
3668
+ constructor(data) {
3669
+ super("container");
3670
+ const { uuid, error, guild, user, metadata } = data;
3671
+ this.instance.addTextDisplayComponents((text) => text.setContent(`### An unknown exception was thrown\n**Guild ID:** \`${guild?.id ?? "Not used in a guild"}\`\n**Guild Name:** ${guild?.name ?? "Not used in a guild"}\n**User ID:** \`${user?.id ?? "Missing user info"}\`\n**Username:** ${user?.username ?? "Missing user info"}\n`)).addSeparatorComponents(new WebhookSeparator().component).addTextDisplayComponents((text) => text.setContent(`### UUID \`${uuid}\`\n\`\`\`${error.stack}\`\`\``));
3672
+ this.addTimestampsIfAvailable(error);
3673
+ this.addMetadataIfAvailable(metadata);
3674
+ }
3675
+ addTimestampsIfAvailable(error) {
3676
+ if (!(error instanceof DiscordAPIError)) return;
3677
+ const now = Date.now();
3678
+ const snowflake = error.url.match(/\/interactions\/(\d+)\//)?.[1];
3679
+ if (!snowflake) return void 0;
3680
+ const interactionTs = Number(SnowflakeUtil.deconstruct(snowflake).timestamp);
3681
+ const diff = now - interactionTs;
3682
+ const seconds = Math.floor(diff / 1e3);
3683
+ const millis = diff % 1e3;
3684
+ this.instance.addSeparatorComponents(new WebhookSeparator().component).addTextDisplayComponents((text) => text.setContent(`### Timestamps\n- **\`Interaction sent\` :** ${new Date(interactionTs).toISOString()} (${interactionTs})\n- **\`Error logged \` :** ${new Date(now).toISOString()} (${now})\n- **\`Offset \` :** ${seconds}s ${millis}ms`));
3685
+ }
3686
+ addMetadataIfAvailable(metadata) {
3687
+ if (!metadata) return;
3688
+ this.instance.addSeparatorComponents(new WebhookSeparator().component).addTextDisplayComponents((text) => text.setContent("### Metadata")).addFileComponents((file) => file.setURL("attachment://metadata.json"));
3689
+ }
3690
+ };
3691
+
3692
+ //#endregion
3693
+ //#region src/subscribers/Bus.ts
3694
+ /**
3695
+ * Manages application subscribers and event handling
3696
+ *
3697
+ * Provides a centralized system for registering and executing custom subscribers
3698
+ * throughout the application lifecycle. Bus subscribers are loaded from configured directories
3699
+ * and can be triggered programmatically or by framework events. Accessed via `core.bus`. Do not
3700
+ * construct it directly.
3701
+ */
3702
+ var Bus = class extends Plugin {
3703
+ core;
3704
+ logger = new Logger("Subscribers");
3705
+ /** @internal */
3706
+ name = "Subscribers";
3707
+ isInitialized = false;
3708
+ subscribersMap = /* @__PURE__ */ new Map();
3709
+ executedOnceHandlers = /* @__PURE__ */ new Set();
3710
+ hmrHandler;
3711
+ constructor(core) {
3712
+ super(core);
3713
+ this.core = core;
3714
+ if (this.core.config.subscribers.path) {
3715
+ if (!Envapter.isDevelopment && !Envapter.isTest) return;
3716
+ this.hmrHandler = new HmrModuleHandler({
3717
+ handlersDir: this.core.config.subscribers.path,
3718
+ isHandler: this.isSubscriber.bind(this),
3719
+ registerHandler: this.registerSubscriber.bind(this),
3720
+ unregisterHandler: this.unregisterSubscriber.bind(this),
3721
+ getArtifacts: this.getArtifacts.bind(this),
3722
+ logger: this.logger
3723
+ });
3724
+ }
3725
+ }
3726
+ getArtifacts(ctor) {
3727
+ return [Reflect.getMetadata(SubscribeMetadataKey, ctor).subscriber];
3728
+ }
3729
+ /** @internal */
3730
+ async init() {
3731
+ if (this.isInitialized) return;
3732
+ this.isInitialized = true;
3733
+ this.registerSubscriber(UnknownException);
3734
+ this.registerSubscriber(HandledException);
3735
+ Envapter.require("UNKNOWN_EXCEPTION_WEBHOOK_URL", "HANDLED_EXCEPTION_WEBHOOK_URL");
3736
+ const subscribersDir = this.core.config.subscribers.path;
3737
+ if (subscribersDir) {
3738
+ this.logger.info(chalk.bold(subscribersDir));
3739
+ await this.loadSubscribers(subscribersDir);
3740
+ const totalSubscribers = [...this.subscribersMap.values()].reduce((acc, handlers) => acc + handlers.length, 0);
3741
+ this.logger.utils.list([`${chalk.bold.magenta(totalSubscribers)} subscribers`], chalk.bold.green("Loaded"));
3742
+ }
3743
+ }
3744
+ /** @internal For use in dev mode */
3745
+ async onHmr(event) {
3746
+ if (this.hmrHandler) await this.hmrHandler.handle(event);
3747
+ }
3748
+ async loadSubscribers(dir) {
3749
+ await traverseDirectory(dir, (fullPath, relativePath, imported) => {
3750
+ for (const exportName of Object.keys(imported)) {
3751
+ const val = imported[exportName];
3752
+ if (this.isSubscriber(val)) {
3753
+ this.registerSubscriber(val);
3754
+ this.hmrHandler?.trackHandler(fullPath, val);
3755
+ this.logger.utils.registration(val.name, relativePath);
3756
+ }
3757
+ }
3758
+ }, this.logger);
3759
+ }
3760
+ registerSubscriber(handler) {
3761
+ const options = Reflect.getMetadata(SubscribeMetadataKey, handler);
3762
+ let handlers = this.subscribersMap.get(options.subscriber);
3763
+ if (!handlers) {
3764
+ handlers = [];
3765
+ this.subscribersMap.set(options.subscriber, handlers);
3766
+ }
3767
+ handlers.push({
3768
+ ctor: handler,
3769
+ frequency: options.frequency ?? "on"
3770
+ });
3771
+ }
3772
+ unregisterSubscriber(handler, artifacts) {
3773
+ const subscribers = artifacts ?? [...this.subscribersMap.keys()];
3774
+ for (const subscriber of subscribers) {
3775
+ const handlers = this.subscribersMap.get(subscriber);
3776
+ if (!handlers) continue;
3777
+ const index = handlers.findIndex((entry) => entry.ctor === handler);
3778
+ if (index !== -1) handlers.splice(index, 1);
3779
+ }
3780
+ }
3781
+ isSubscriber(obj) {
3782
+ if (typeof obj !== "function") return false;
3783
+ return obj.prototype instanceof Subscriber && Reflect.hasMetadata(SubscribeMetadataKey, obj);
3784
+ }
3785
+ /**
3786
+ * Publishes an event to its subscribers and native listeners.
3787
+ *
3788
+ * Fire-and-forget, so subscriber handlers run asynchronously and this returns before they
3789
+ * complete, and callers must not assume side effects have landed. Errors thrown by a subscriber
3790
+ * are caught and logged, never surfaced here. A `'once'` subscriber is marked as executed when
3791
+ * it starts (even if it throws), so it never runs twice.
3792
+ *
3793
+ * @param event - The subscription key to publish
3794
+ * @param data - Payload passed to each subscriber
3795
+ * @returns Whether the underlying emitter had native listeners for the event
3796
+ */
3797
+ publish(event, data) {
3798
+ this.processSubscriber(event, data);
3799
+ return super.emit(event, ...[data]);
3800
+ }
3801
+ async processSubscriber(subscriberName, data) {
3802
+ const handlers = this.subscribersMap.get(subscriberName);
3803
+ if (!handlers) return;
3804
+ for (const entry of handlers) {
3805
+ if (entry.frequency === "once" && this.executedOnceHandlers.has(entry.ctor)) continue;
3806
+ try {
3807
+ if (entry.frequency === "once") this.executedOnceHandlers.add(entry.ctor);
3808
+ const Ctor = entry.ctor;
3809
+ await new Ctor(data, this.core).execute();
3810
+ } catch (err) {
3811
+ this.logger.error(`Error in subscriber ${String(subscriberName)} handler ${entry.ctor.name}:`, err);
3812
+ }
3813
+ }
3814
+ }
3815
+ };
3816
+
3817
+ //#endregion
3818
+ //#region src/version.ts
2
3819
  /** Package version */
3
- const version = "0.0.1";
3820
+ const version = "0.1.0-next.1";
3821
+
3822
+ //#endregion
3823
+ //#region src/Seedcord.ts
3824
+ /**
3825
+ * Main Seedcord bot framework class
3826
+ *
3827
+ * Primary entry point for creating Discord bots with Seedcord.
3828
+ * Manages component lifecycle and provides plugin support.
3829
+ */
3830
+ var Seedcord = class Seedcord extends Pluggable {
3831
+ config;
3832
+ /** @internal */
3833
+ [SeedcordBrand] = true;
3834
+ /** @internal */
3835
+ augmentTarget = "@seedcord/gateway";
3836
+ /** @internal */
3837
+ version = version;
3838
+ static isInstantiated = false;
3839
+ /** @see {@link CoordinatedShutdown} */
3840
+ shutdown;
3841
+ /** @see {@link CoordinatedStartup} */
3842
+ startup;
3843
+ /** @see {@link Bus} */
3844
+ bus;
3845
+ /** @see {@link Bot} */
3846
+ bot;
3847
+ /** @see {@link IRateLimiter} */
3848
+ rateLimiter;
3849
+ /** @see {@link HealthCheck} */
3850
+ healthCheck;
3851
+ /** @see {@link HmrManager} */
3852
+ hmrManager;
3853
+ /**
3854
+ * Creates a new Seedcord instance
3855
+ *
3856
+ * @param config - Bot configuration including paths and Discord client options
3857
+ * @throws A **SeedcordError** When attempting to create multiple instances (singleton)
3858
+ */
3859
+ constructor(config) {
3860
+ if (Seedcord.isInstantiated) throw new SeedcordError(SeedcordErrorCode.CoreSingletonViolation);
3861
+ Seedcord.isInstantiated = true;
3862
+ const shutdown = new CoordinatedShutdown(config.shutdownEnabled);
3863
+ const startup = new CoordinatedStartup();
3864
+ super(shutdown, startup);
3865
+ this.config = config;
3866
+ setBotColor(config.botColor);
3867
+ this.shutdown = shutdown;
3868
+ this.startup = startup;
3869
+ this.hmrManager = new HmrManager();
3870
+ this.hmrManager.init();
3871
+ this.bus = new Bus(this);
3872
+ this.bot = new Bot(this);
3873
+ this.rateLimiter = config.store ?? new MemoryRateLimiter();
3874
+ this.healthCheck = new HealthCheck(this.shutdown, config.healthCheck);
3875
+ this.registerStartupTasks();
3876
+ }
3877
+ /** @internal */
3878
+ static reset() {
3879
+ Seedcord.isInstantiated = false;
3880
+ }
3881
+ /**
3882
+ * Registers default startup tasks
3883
+ * @internal
3884
+ */
3885
+ registerStartupTasks() {
3886
+ if (Envapter.isDevelopment || Envapter.isTest) this.registerHmrAwareModules();
3887
+ this.startup.addTask(StartupPhase.Configuration, "Bus Initialization", async () => {
3888
+ this.bus.logger.utils.initialization("Subscribers", "start");
3889
+ await this.bus.init();
3890
+ this.bus.logger.utils.initialization("Subscribers", "end");
3891
+ });
3892
+ this.startup.addTask(StartupPhase.Instantiation, "Bot Initialization", async () => {
3893
+ this.bot.logger.utils.initialization("Bot", "start");
3894
+ await this.bot.init();
3895
+ this.bot.logger.utils.initialization("Bot", "end");
3896
+ });
3897
+ this.startup.addTask(StartupPhase.Ready, "Health Check", async () => {
3898
+ this.healthCheck.logger.utils.initialization("HealthCheck", "start");
3899
+ await this.healthCheck.init();
3900
+ this.healthCheck.logger.utils.initialization("HealthCheck", "end");
3901
+ });
3902
+ }
3903
+ /**
3904
+ * Starts the bot and runs all initialization tasks
3905
+ *
3906
+ * @returns This Seedcord instance when fully initialized
3907
+ */
3908
+ async start() {
3909
+ await super.init();
3910
+ return this;
3911
+ }
3912
+ registerHmrAwareModules() {
3913
+ this.startup.addTask(StartupPhase.Configuration, "HMR Registration", async () => {
3914
+ this.hmrManager.register(this.bot);
3915
+ this.hmrManager.register(this.bus);
3916
+ for (const plugin of this.plugins) this.hmrManager.register(plugin);
3917
+ await Promise.resolve();
3918
+ });
3919
+ }
3920
+ };
4
3921
 
5
3922
  //#endregion
6
- export { version };
3923
+ export { ArraySource, AutocompleteHandler, AutocompleteRoute, ButtonHandler, ButtonRoute, CommandMentions, ContextMenuHandler, ContextMenuRoute, CursorSource, Emojis, EventHandler, EventMiddleware, Gated, HmrModuleHandler, IgnoreBots, InteractionHandler, InteractionMiddleware, Middleware, MiddlewareType, ModalHandler, ModalRoute, Nsfw, Paginator, Pluggable, Plugin, RegisterCommand, RegisterEvent, ReplySender, RequireBotPermissions, RequirePermissions, RequireRole, Seedcord, SelectMenuHandler, SelectMenuKind, SelectMenuRoute, SlashHandler, SlashRoute, Subscribe, Subscriber, WebhookLog, checkBotPermissions, checkPermissions, fetchGuildMember, fetchManyGuildMembers, fetchManyUsers, fetchRole, fetchText, fetchUser, getBotRole, getConfirmation, hasPermsToAssign, updateMemberRoles, version };
7
3924
  //# sourceMappingURL=index.mjs.map