@seedcord/core 0.4.0 → 0.4.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.
Files changed (30) hide show
  1. package/dist/{Bus-BVwmKc-A.mjs → Bus-yJGE6Fs2.mjs} +78 -78
  2. package/dist/{Bus-BVwmKc-A.mjs.map → Bus-yJGE6Fs2.mjs.map} +1 -1
  3. package/dist/{Pluggable-Cf5-WWmW.mjs → Pluggable-BI_LQuPm.mjs} +3 -3
  4. package/dist/{Pluggable-Cf5-WWmW.mjs.map → Pluggable-BI_LQuPm.mjs.map} +1 -1
  5. package/dist/{Pluggable-DFNUIlJM.d.mts → Pluggable-bFCmT4oB.d.mts} +3 -3
  6. package/dist/{Plugin-C6oMqWf8.mjs → Plugin-B0SRHzMX.mjs} +2 -2
  7. package/dist/{Plugin-C6oMqWf8.mjs.map → Plugin-B0SRHzMX.mjs.map} +1 -1
  8. package/dist/{Plugin-CG9pWbPF.d.mts → Plugin-BW2JH2_h.d.mts} +2 -2
  9. package/dist/{cursor-BcRfmTSo.d.mts → cursor-CO_MTgdZ.d.mts} +5 -203
  10. package/dist/{cursor-GBUYz3jk.mjs → cursor-CaT051ii.mjs} +6 -472
  11. package/dist/cursor-CaT051ii.mjs.map +1 -0
  12. package/dist/{index-ZzdQafFv.d.mts → index-CvneCObW.d.mts} +2 -2
  13. package/dist/index.d.mts +6 -5
  14. package/dist/index.mjs +42 -7
  15. package/dist/index.mjs.map +1 -1
  16. package/dist/internal.index.d.mts +6 -5
  17. package/dist/internal.index.mjs +4 -4
  18. package/dist/node-internal.index.d.mts +4 -4
  19. package/dist/node-internal.index.mjs +6 -6
  20. package/dist/node.index.d.mts +1 -1
  21. package/dist/node.index.mjs +2 -2
  22. package/dist/{phases-F8yvPd60.d.mts → phases-C5Steaa2.d.mts} +56 -56
  23. package/dist/plugin.index.d.mts +1 -1
  24. package/dist/plugin.index.mjs +1 -1
  25. package/dist/{slashRouteLeaves-CbYRwqMY.mjs → slashRouteLeaves-BQmbFm-S.mjs} +2 -2
  26. package/dist/{slashRouteLeaves-CbYRwqMY.mjs.map → slashRouteLeaves-BQmbFm-S.mjs.map} +1 -1
  27. package/dist/{subscribers-CGGQkUfM.mjs → subscribers-DVa-Pr45.mjs} +3 -3
  28. package/dist/{subscribers-CGGQkUfM.mjs.map → subscribers-DVa-Pr45.mjs.map} +1 -1
  29. package/package.json +8 -7
  30. package/dist/cursor-GBUYz3jk.mjs.map +0 -1
@@ -1,11 +1,12 @@
1
- import { C as InteractionMetadataKey, T as InteractionRoutes, g as BuilderComponent, w as InteractionRouteKeys } from "./Bus-BVwmKc-A.mjs";
1
+ import { b as InteractionRouteKeys, k as BuilderComponent, x as InteractionRoutes, y as InteractionMetadataKey } from "./Bus-yJGE6Fs2.mjs";
2
2
  import { n as asError, t as PublishDefault } from "./publishDefault-D826XXDQ.mjs";
3
3
  import "reflect-metadata";
4
+ import { CustomId, decodeFor } from "@seedcord/custom-id";
4
5
  import { TextDisplayBuilder } from "@discordjs/builders";
6
+ import { ApplicationCommandType, PermissionFlagsBits } from "discord-api-types/v10";
5
7
  import { SeedcordErrorCode, paint } from "@seedcord/errors";
8
+ import { SeedcordError } from "@seedcord/errors/internal";
6
9
  import { Logger } from "@seedcord/logger";
7
- import { ApplicationCommandType, PermissionFlagsBits } from "discord-api-types/v10";
8
- import { SeedcordError, SeedcordRangeError, SeedcordTypeError } from "@seedcord/errors/internal";
9
10
  import { prettify, toEpochSeconds } from "@seedcord/utils";
10
11
 
11
12
  //#region src/stops/Notice.ts
@@ -83,473 +84,6 @@ var NoticeCard = class extends BuilderComponent {
83
84
  }
84
85
  };
85
86
 
86
- //#endregion
87
- //#region src/customId/Errors.ts
88
- /**
89
- * Thrown when a customId was minted by an older version of its shape.
90
- *
91
- * This is normal after the shape changes.
92
- */
93
- var StaleCustomId = class extends Notice {
94
- constructor(prefix) {
95
- super(`Stale customId for "${prefix}".`);
96
- }
97
- render() {
98
- return { components: [new NoticeCard("This button or menu is from an older version. Please run the command again.", "Outdated").component] };
99
- }
100
- };
101
- /**
102
- * Thrown when a customId wire is corrupt or tampered with and cannot be trusted.
103
- *
104
- * It reports because this is an odd case that should not happen.
105
- */
106
- var InvalidCustomId = class extends Notice {
107
- constructor(detail) {
108
- super(`Invalid customId. ${detail}`);
109
- this.report = true;
110
- }
111
- render() {
112
- return { components: [new NoticeCard("Something went wrong. Please try again.").component] };
113
- }
114
- };
115
-
116
- //#endregion
117
- //#region src/customId/codec.ts
118
- const ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
119
- const BASE = 64n;
120
- const CHAR_TO_VALUE = new Map([...ALPHABET].map((char, index) => [char, index]));
121
- const DELIMITER = "";
122
- const ESCAPE = "\x1B";
123
- /** @internal */
124
- const HASH_LENGTH = 3;
125
- const SAFE_MAX = BigInt(Number.MAX_SAFE_INTEGER);
126
- const SAFE_MIN = BigInt(Number.MIN_SAFE_INTEGER);
127
- function bigintToBase64(value) {
128
- if (value === 0n) return ALPHABET.charAt(0);
129
- let text = "";
130
- for (let remaining = value; remaining > 0n; remaining /= BASE) text = ALPHABET.charAt(Number(remaining % BASE)) + text;
131
- return text;
132
- }
133
- function base64ToBigint(text) {
134
- let value = 0n;
135
- for (const char of text) {
136
- const digit = CHAR_TO_VALUE.get(char);
137
- if (digit === void 0) throw new InvalidCustomId(`bad character ${JSON.stringify(char)}`);
138
- value = value * BASE + BigInt(digit);
139
- }
140
- return value;
141
- }
142
- function zigzagEncode(value) {
143
- const big = BigInt(value);
144
- return big >= 0n ? big << 1n : (-big << 1n) - 1n;
145
- }
146
- function zigzagDecode(encoded) {
147
- return (encoded & 1n) === 1n ? -(encoded + 1n >> 1n) : encoded >> 1n;
148
- }
149
- function escapeToken(text) {
150
- return text.replaceAll(/[\x1B\x1F]/g, (char) => ESCAPE + char);
151
- }
152
- function unescapeToken(text) {
153
- let out = "";
154
- for (let i = 0; i < text.length; i++) {
155
- if (text.charAt(i) !== ESCAPE) {
156
- out += text.charAt(i);
157
- continue;
158
- }
159
- const next = text.charAt(i + 1);
160
- if (next === "") throw new InvalidCustomId("dangling escape at end of token");
161
- out += next;
162
- i++;
163
- }
164
- return out;
165
- }
166
- function splitTokens(body) {
167
- const pieces = [];
168
- let current = "";
169
- for (let i = 0; i < body.length; i++) {
170
- const char = body.charAt(i);
171
- if (char === ESCAPE) {
172
- current += char + body.charAt(i + 1);
173
- i++;
174
- } else if (char === DELIMITER) {
175
- pieces.push(current);
176
- current = "";
177
- } else current += char;
178
- }
179
- pieces.push(current);
180
- return pieces;
181
- }
182
- function isBounded(field) {
183
- if (field.kind === "int") return field.min !== void 0 && field.max !== void 0;
184
- return field.kind === "snowflake" || field.kind === "uuid" || field.kind === "bool" || field.kind === "oneOf";
185
- }
186
- function radixOf(field) {
187
- return kindRadix(field) + (field.nullable === true ? 1n : 0n);
188
- }
189
- function kindRadix(field) {
190
- switch (field.kind) {
191
- case "snowflake": return 1n << 64n;
192
- case "uuid": return 1n << 128n;
193
- case "bool": return 2n;
194
- case "oneOf":
195
- if (!field.choices?.length) throw new InvalidCustomId("oneOf field has no choices");
196
- return BigInt(field.choices.length);
197
- case "int":
198
- if (field.min === void 0 || field.max === void 0) throw new InvalidCustomId("bounded int field is missing a bound");
199
- return BigInt(field.max) - BigInt(field.min) + 1n;
200
- default: throw new InvalidCustomId(`field kind ${field.kind} has no radix`);
201
- }
202
- }
203
- function boundedToBigint(field, name, value) {
204
- if (field.nullable === true) {
205
- if (value === null) return 0n;
206
- return boundedToBigint({
207
- ...field,
208
- nullable: false
209
- }, name, value) + 1n;
210
- }
211
- const slot = boundedSlot(field, name, value);
212
- if (slot < 0n || slot >= radixOf(field)) outOfRange(name, value);
213
- return slot;
214
- }
215
- function boundedSlot(field, name, value) {
216
- switch (field.kind) {
217
- case "snowflake":
218
- if (typeof value !== "string" || !/^\d+$/.test(value)) return outOfRange(name, value);
219
- return BigInt(value);
220
- case "uuid": {
221
- if (typeof value !== "string") return outOfRange(name, value);
222
- const hex = value.replaceAll("-", "");
223
- if (!/^[0-9a-fA-F]{32}$/.test(hex)) return outOfRange(name, value);
224
- return BigInt(`0x${hex}`);
225
- }
226
- case "bool": return value ? 1n : 0n;
227
- case "oneOf": {
228
- const index = (field.choices ?? []).indexOf(value);
229
- return index === -1 ? outOfRange(name, value) : BigInt(index);
230
- }
231
- case "int":
232
- if (!Number.isInteger(value)) return outOfRange(name, value);
233
- return BigInt(value - (field.min ?? 0));
234
- default: return outOfRange(name, value);
235
- }
236
- }
237
- function outOfRange(name, value) {
238
- throw new SeedcordRangeError(SeedcordErrorCode.CustomIdValueOutOfRange, [name, String(value)]);
239
- }
240
- function bigintToBoundedValue(field, slot) {
241
- if (field.nullable === true) return slot === 0n ? null : bigintToBoundedValue({
242
- ...field,
243
- nullable: false
244
- }, slot - 1n);
245
- return kindValue(field, slot);
246
- }
247
- function kindValue(field, slot) {
248
- switch (field.kind) {
249
- case "snowflake": return slot.toString();
250
- case "uuid": return bigintToUuid(slot);
251
- case "bool": return slot === 1n;
252
- case "oneOf": return (field.choices ?? [])[Number(slot)];
253
- case "int": return Number(slot) + (field.min ?? 0);
254
- default: throw new InvalidCustomId(`field kind ${field.kind} is not bounded`);
255
- }
256
- }
257
- function bigintToUuid(value) {
258
- const hex = value.toString(16).padStart(32, "0");
259
- return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
260
- }
261
- const ABSENT = "0";
262
- const PRESENT = "1";
263
- function encodeUnboundedToken(field, name, value) {
264
- if (field.nullable === true) {
265
- if (value === null) return ABSENT;
266
- return PRESENT + encodeUnboundedToken({
267
- ...field,
268
- nullable: false
269
- }, name, value);
270
- }
271
- if (field.kind === "int") {
272
- if (!Number.isSafeInteger(value)) outOfRange(name, value);
273
- return bigintToBase64(zigzagEncode(value));
274
- }
275
- return escapeToken(value);
276
- }
277
- function decodeUnboundedToken(field, piece) {
278
- if (field.nullable === true) {
279
- const marker = piece.charAt(0);
280
- if (marker === ABSENT && piece.length === 1) return null;
281
- if (marker !== PRESENT) throw new InvalidCustomId(`bad presence marker ${JSON.stringify(marker)}`);
282
- return decodeUnboundedToken({
283
- ...field,
284
- nullable: false
285
- }, piece.slice(1));
286
- }
287
- if (field.kind !== "int") return unescapeToken(piece);
288
- if (piece === "") throw new InvalidCustomId("empty integer token");
289
- const decoded = zigzagDecode(base64ToBigint(piece));
290
- if (decoded > SAFE_MAX || decoded < SAFE_MIN) throw new InvalidCustomId("integer out of safe range");
291
- return Number(decoded);
292
- }
293
- /** @internal */
294
- function computeLayoutHash(shape) {
295
- const signature = JSON.stringify(Object.entries(shape).map(([name, field]) => [
296
- name,
297
- field.kind,
298
- isBounded(field),
299
- field.nullable === true,
300
- field.kind === "oneOf" ? field.choices ?? [] : null,
301
- field.kind === "int" ? [field.min ?? null, field.max ?? null] : null
302
- ]));
303
- const modulus = BASE ** BigInt(3);
304
- let hash = 0n;
305
- for (const char of signature) hash = (hash * 131n + BigInt(char.charCodeAt(0))) % modulus;
306
- let text = "";
307
- for (let i = 0; i < 3; i++) {
308
- text = ALPHABET.charAt(Number(hash % BASE)) + text;
309
- hash /= BASE;
310
- }
311
- return text;
312
- }
313
- /** @internal */
314
- function encodeBody(shape, values) {
315
- const fields = Object.entries(shape);
316
- const pieces = [];
317
- const bounded = fields.filter(([, field]) => isBounded(field));
318
- if (bounded.length > 0) {
319
- let packed = 0n;
320
- for (const [name, field] of bounded) packed = packed * radixOf(field) + boundedToBigint(field, name, values[name]);
321
- pieces.push(bigintToBase64(packed));
322
- }
323
- for (const [name, field] of fields) if (!isBounded(field)) pieces.push(encodeUnboundedToken(field, name, values[name]));
324
- return pieces.join(DELIMITER);
325
- }
326
- function unpackBounded(bounded, blob, result) {
327
- if (blob === void 0 || blob === "") throw new InvalidCustomId("empty packed block");
328
- let packed = base64ToBigint(blob);
329
- for (const [name, field] of [...bounded].reverse()) {
330
- const radix = radixOf(field);
331
- result[name] = bigintToBoundedValue(field, packed % radix);
332
- packed /= radix;
333
- }
334
- if (packed !== 0n) throw new InvalidCustomId("leftover bits after unpacking");
335
- }
336
- /** @internal */
337
- function decodeBody(shape, body) {
338
- const fields = Object.entries(shape);
339
- const bounded = fields.filter(([, field]) => isBounded(field));
340
- const unbounded = fields.filter(([, field]) => !isBounded(field));
341
- const expected = (bounded.length > 0 ? 1 : 0) + unbounded.length;
342
- if (expected === 0) {
343
- if (body !== "") throw new InvalidCustomId(`expected an empty body, got ${JSON.stringify(body)}`);
344
- return {};
345
- }
346
- const pieces = splitTokens(body);
347
- if (pieces.length !== expected) throw new InvalidCustomId(`expected ${expected} piece(s), got ${pieces.length}`);
348
- const result = {};
349
- let cursor = 0;
350
- if (bounded.length > 0) {
351
- unpackBounded(bounded, pieces[cursor], result);
352
- cursor++;
353
- }
354
- for (const [name, field] of unbounded) {
355
- const piece = pieces[cursor];
356
- cursor++;
357
- if (piece === void 0) throw new InvalidCustomId("missing trailing piece");
358
- result[name] = decodeUnboundedToken(field, piece);
359
- }
360
- return result;
361
- }
362
-
363
- //#endregion
364
- //#region src/customId/CustomId.ts
365
- const MAX_WIRE_LENGTH = 100;
366
- function routeKeyOf(wire) {
367
- const colon = wire.indexOf(":");
368
- return colon === -1 ? "" : wire.slice(0, colon);
369
- }
370
- /** Strip the layout hash off the routeKey to recover the stable prefix the controller routes by. @internal */
371
- function prefixOf(wire) {
372
- const key = routeKeyOf(wire);
373
- return key.length <= 3 ? "" : key.slice(0, key.length - 3);
374
- }
375
- /**
376
- * A typed customId. The single source of truth shared by the component that mints it and the handler
377
- * that reads it. This gives you typed reads on the `.customId` field in components. Values are packed
378
- * into a compact wire string, which fits more of them inside Discord's 100-char limit.
379
- *
380
- * @typeParam Prefix - The stable route prefix, e.g. 'approve'.
381
- * @typeParam Shape - The accumulated fields, filled in by the chain.
382
- *
383
- * @example
384
- * ```ts
385
- * const ApproveId = new CustomId('approve')
386
- * .snowflake('userId')
387
- * .oneOf('action', ['approve', 'deny']);
388
- *
389
- * // Set the custom id on a button when creating it.
390
- * new ButtonBuilder().setCustomId(ApproveId.encode({ userId: '123', action: 'approve' }));
391
- *
392
- * // in the handler, userId comes back a string
393
- * const { userId, action } = this.params; // userId: string, action: 'approve' | 'deny'
394
- * await this.event.guild?.members.fetch(userId);
395
- * ```
396
- */
397
- var CustomId = class CustomId {
398
- /** The stable route prefix, e.g. 'approve'. */
399
- prefix;
400
- /** The field definitions accumulated by the chain, keyed by name. */
401
- shape;
402
- /** The prefix plus a short hash of the shape, the part of the wire before the colon. */
403
- routeKey;
404
- constructor(prefix, shape = {}) {
405
- if (!prefix || /[:\x1B\x1F]/.test(prefix)) throw new SeedcordTypeError(SeedcordErrorCode.CustomIdInvalidPrefix, [prefix]);
406
- this.prefix = prefix;
407
- this.shape = shape;
408
- this.routeKey = prefix + computeLayoutHash(shape);
409
- }
410
- add(name, field) {
411
- if (/^(?:0|[1-9]\d*)$/.test(name)) throw new SeedcordTypeError(SeedcordErrorCode.CustomIdReservedFieldName, [name]);
412
- if (name in this.shape) throw new SeedcordTypeError(SeedcordErrorCode.CustomIdDuplicateFieldName, [name]);
413
- const shape = {
414
- ...this.shape,
415
- [name]: field
416
- };
417
- return new CustomId(this.prefix, shape);
418
- }
419
- /**
420
- * Add a Discord ID field, decoded as a string (the `Snowflake` type from discord-api-types).
421
- *
422
- * @example
423
- * ```ts
424
- * new CustomId('ban').snowflake('userId');
425
- * ```
426
- */
427
- snowflake(name, opts) {
428
- return this.add(name, {
429
- ...opts,
430
- kind: "snowflake"
431
- });
432
- }
433
- /**
434
- * Add a UUID field, decoded as a lowercase uuid string.
435
- *
436
- * @example
437
- * ```ts
438
- * new CustomId('ticket').uuid('ticketId');
439
- * ```
440
- */
441
- uuid(name, opts) {
442
- return this.add(name, {
443
- ...opts,
444
- kind: "uuid"
445
- });
446
- }
447
- int(name, minOrOpts, max, opts) {
448
- const min = typeof minOrOpts === "number" ? minOrOpts : void 0;
449
- if (min !== void 0 && max !== void 0 && min > max) throw new SeedcordRangeError(SeedcordErrorCode.CustomIdInvalidBounds, [
450
- name,
451
- min,
452
- max
453
- ]);
454
- const options = typeof minOrOpts === "number" ? opts : minOrOpts;
455
- const bounds = min === void 0 || max === void 0 ? {} : {
456
- min,
457
- max
458
- };
459
- return this.add(name, {
460
- ...options,
461
- kind: "int",
462
- ...bounds
463
- });
464
- }
465
- /**
466
- * Add a boolean flag.
467
- *
468
- * @example
469
- * ```ts
470
- * new CustomId('settings').bool('silent');
471
- * ```
472
- */
473
- bool(name, opts) {
474
- return this.add(name, {
475
- ...opts,
476
- kind: "bool"
477
- });
478
- }
479
- /**
480
- * Add a field that is one value from a fixed list, decoded as the literal union. No `as const` needed.
481
- *
482
- * @example
483
- * ```ts
484
- * new CustomId('poll').oneOf('choice', ['yes', 'no', 'abstain']);
485
- * ```
486
- */
487
- oneOf(name, choices, opts) {
488
- if (choices.length === 0) throw new SeedcordRangeError(SeedcordErrorCode.CustomIdEmptyChoices, [name]);
489
- return this.add(name, {
490
- ...opts,
491
- kind: "oneOf",
492
- choices
493
- });
494
- }
495
- /**
496
- * Add a free short text field. Avoid it where possible. It cannot be packed, which makes it the most
497
- * expensive field on the wire.
498
- *
499
- * @example
500
- * ```ts
501
- * new CustomId('note').str('message');
502
- * ```
503
- */
504
- str(name, opts) {
505
- return this.add(name, {
506
- ...opts,
507
- kind: "string"
508
- });
509
- }
510
- /**
511
- * Mint a wire string from values. Throws if a value is out of its field's range or the wire is over 100 chars.
512
- *
513
- * @param values - One value per field, typed by the chain.
514
- * @returns The wire string to put on the component's customId.
515
- */
516
- encode(values) {
517
- const wire = `${this.routeKey}:${encodeBody(this.shape, values)}`;
518
- if (wire.length > MAX_WIRE_LENGTH) throw new SeedcordRangeError(SeedcordErrorCode.CustomIdWireTooLong, [wire.length]);
519
- return wire;
520
- }
521
- /**
522
- * Read a wire string back into values.
523
- *
524
- * - This will refuse with a default Notice when the shape changed since the wire was minted.
525
- * - Or refuse with a different default Notice on a corrupt or foreign wire.
526
- *
527
- * @param wire - The customId string from the interaction.
528
- * @returns The decoded values, typed by the chain.
529
- */
530
- decode(wire) {
531
- const key = routeKeyOf(wire);
532
- if (key !== this.routeKey) {
533
- if (prefixOf(wire) === this.prefix) throw new StaleCustomId(this.prefix);
534
- throw new InvalidCustomId(`routeKey ${JSON.stringify(key)} is not ${JSON.stringify(this.routeKey)}`);
535
- }
536
- return decodeBody(this.shape, wire.slice(key.length + 1));
537
- }
538
- /** True if this wire was minted from this customId's prefix, ignoring the shape hash. */
539
- owns(wire) {
540
- return prefixOf(wire) === this.prefix;
541
- }
542
- };
543
- /** @internal */
544
- function decodeFor(defs, wire) {
545
- const match = defs.find((def) => def.owns(wire));
546
- if (!match) throw new InvalidCustomId(`no customId owns ${JSON.stringify(routeKeyOf(wire))}`);
547
- return {
548
- prefix: match.prefix,
549
- params: match.decode(wire)
550
- };
551
- }
552
-
553
87
  //#endregion
554
88
  //#region src/customId/routing.ts
555
89
  /**
@@ -1249,5 +783,5 @@ function pageCursor(prefix) {
1249
783
  }
1250
784
 
1251
785
  //#endregion
1252
- export { translateSerializationError as A, interactionRoutesOf as B, NotInDm as C, defineEffectGate as D, OnCooldown as E, checkAckLegality as F, decodeComponentRoute as G, storeComponentRoute as H, sendTarget as I, prefixOf as J, CustomId as K, SelectMenuKind as L, publishResponse as M, reportedWrite as N, defineGate as O, AckTrace as P, areRoutes as R, NotAllowed as S, NotOwner as T, storeInteractionRoute as U, selectMenuRouteOf as V, ComponentDefsKey as W, Notice as X, NoticeCard as Y, GateNotice as _, RequirePermissions as a, MissingRole as b, hasAll as c, pickNotice as d, discardCommits as f, runCommits as g, runCheck as h, RequireBotPermissions as i, attemptWrite as j, serializeReply as k, missingNames as l, rollbackCommits as m, pageCursor as n, RequireRole as o, markCommits as p, decodeFor as q, Silence as r, PermissionNames as s, PAGE_MAX as t, presentNames as u, HasDangerousPermissions as v, NotInGuild as w, NeedsAny as x, MissingPermissions as y, contextMenuRouteOf as z };
1253
- //# sourceMappingURL=cursor-GBUYz3jk.mjs.map
786
+ export { translateSerializationError as A, interactionRoutesOf as B, NotInDm as C, defineEffectGate as D, OnCooldown as E, checkAckLegality as F, decodeComponentRoute as G, storeComponentRoute as H, sendTarget as I, NoticeCard as K, SelectMenuKind as L, publishResponse as M, reportedWrite as N, defineGate as O, AckTrace as P, areRoutes as R, NotAllowed as S, NotOwner as T, storeInteractionRoute as U, selectMenuRouteOf as V, ComponentDefsKey as W, GateNotice as _, RequirePermissions as a, MissingRole as b, hasAll as c, pickNotice as d, discardCommits as f, runCommits as g, runCheck as h, RequireBotPermissions as i, attemptWrite as j, serializeReply as k, missingNames as l, rollbackCommits as m, pageCursor as n, RequireRole as o, markCommits as p, Notice as q, Silence as r, PermissionNames as s, PAGE_MAX as t, presentNames as u, HasDangerousPermissions as v, NotInGuild as w, NeedsAny as x, MissingPermissions as y, contextMenuRouteOf as z };
787
+ //# sourceMappingURL=cursor-CaT051ii.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cursor-CaT051ii.mjs","names":[],"sources":["../src/stops/Notice.ts","../src/stops/NoticeCard.ts","../src/customId/routing.ts","../src/decorators/interactionRoutes.ts","../src/reply/ackLegality.ts","../src/reply/AckTrace.ts","../src/reply/responseReport.ts","../src/reply/translateSerialization.ts","../src/reply/serializeReply.ts","../src/gates/Gate.ts","../src/notices/index.ts","../src/gates/effects.ts","../src/gates/catalog/options.ts","../src/permissions/bits.ts","../src/gates/catalog/permissions.ts","../src/stops/Silence.ts","../src/pagination/cursor.ts"],"sourcesContent":["import type { RenderContext, ReplyResponse } from '@seedcord/types';\n\n/**\n * Base class for a user-facing refusal or a reported fault.\n *\n * Throw a `Notice` to stop a handler and reply to the user. The framework catches it at the controller\n * boundary and renders {@link Notice.render}, which always decides what the user sees. With `report`\n * false that render is all that happens. With `report` true the framework also logs the fault and\n * publishes it to the `handledException` bus. A raw, non-Notice throw shows the generic message.\n *\n * @example\n * ```ts\n * import { Notice, BuilderComponent, type RenderContext, type ReplyResponse } from '@seedcord/gateway';\n * import { TextDisplayBuilder } from '@discordjs/builders';\n *\n * // reading `.component` applies the configured bot color to the container accent\n * class TooPoorCard extends BuilderComponent<'container'> {\n * constructor(balance: number) {\n * super('container');\n * this.instance.addTextDisplayComponents(\n * new TextDisplayBuilder().setContent(`### Insufficient balance\\nYou need more than ${balance} coins.`)\n * );\n * }\n * }\n *\n * class TooPoor extends Notice {\n * constructor(private readonly balance: number) {\n * super(`balance ${balance} is below the cost`);\n * }\n *\n * render(_ctx: RenderContext): ReplyResponse {\n * return { components: [new TooPoorCard(this.balance).component] };\n * }\n * }\n *\n * // in a handler, throwing stops the handler and replies with render(ctx)\n * if (wallet.balance < cost) throw new TooPoor(wallet.balance);\n * ```\n */\nexport abstract class Notice extends Error {\n /**\n * Whether this denial is a reported fault. True also logs it and publishes it to the `handledException`\n * bus. The user always sees {@link Notice.render} either way.\n *\n * @defaultValue `false`\n */\n public report = false;\n\n /**\n * Whether the reply is ephemeral, seen only by the invoking user. Set it false for a refusal the\n * whole channel should see.\n *\n * @defaultValue `true`\n */\n public ephemeral = true;\n\n /**\n * A short one-line reason. When every arm of an {@link or} gate refuses and each one sets this, `or`\n * throws a refusal listing them under `You need to meet at least one of these:`. Write a verb phrase that\n * finishes that line, for example, \"be the bot owner\".\n */\n public summary?: string;\n\n protected constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n\n // Error sets name to 'Error', so stamp the concrete subclass name for logs and the fault report\n this.name = new.target.name;\n Error.captureStackTrace(this, this.constructor);\n }\n\n /**\n * Builds what the user sees. Called fresh each time the denial is shown, so the builders are new\n * and the bot color resolves at render time.\n */\n public abstract render(ctx: RenderContext): ReplyResponse;\n}\n","import { TextDisplayBuilder } from '@discordjs/builders';\n\nimport { BuilderComponent } from '#components/Component';\n\n// built fresh inside a Notice's render to back its ComponentsV2 reply\n// discord renders the ### line as an h3 with the description below\nexport class NoticeCard extends BuilderComponent<'container'> {\n public constructor(description: string, title = 'Cannot Proceed') {\n super('container');\n this.instance.addTextDisplayComponents(new TextDisplayBuilder().setContent(`### ${title}\\n${description}`));\n }\n}\n","import 'reflect-metadata';\n\nimport { decodeFor } from '@seedcord/custom-id';\nimport { SeedcordErrorCode } from '@seedcord/errors';\nimport { SeedcordError } from '@seedcord/errors/internal';\n\nimport type { ComponentDefsBrand } from '#src/decorators/brands';\nimport type { AnyCustomId, DecodedParams } from '@seedcord/custom-id';\nimport type { Promisable } from 'type-fest';\n\n/**\n * route decorators store a handler's customId defs here, so the component base can decode\n * against them at runtime.\n *\n * @internal\n */\nexport const ComponentDefsKey = Symbol('seedcord:customId:componentDefs');\n\n/**\n * the phantom a component handler base carries. a route decorator constrains its argument to this, so\n * passing different defs to the decorator and the handler's generic is a compile error. never set at runtime.\n *\n * @internal\n */\nexport interface HasComponentDefs<Defs extends readonly AnyCustomId[]> {\n /** @internal */\n readonly [ComponentDefsBrand]?: Defs;\n}\n\n/** @internal */\nexport interface DecodedComponentRoute {\n prefix: string;\n params: Record<string, unknown>;\n}\n\n/**\n * throws `CustomIdHandlerRouteMissing` when the class has no stored defs. a drifted or corrupt wire\n * throws `StaleCustomId` or `InvalidCustomId`.\n *\n * @internal\n */\nexport function decodeComponentRoute(handlerClass: { name: string }, wire: string): DecodedComponentRoute {\n const defs = Reflect.getMetadata(ComponentDefsKey, handlerClass) as readonly AnyCustomId[] | undefined;\n if (!defs) throw new SeedcordError(SeedcordErrorCode.CustomIdHandlerRouteMissing, [handlerClass.name]);\n return decodeFor(defs, wire);\n}\n\n/** @internal */\nexport type SingleParams<Defs extends readonly AnyCustomId[]> = Defs extends readonly [infer One extends AnyCustomId]\n ? DecodedParams<One['shape']>\n : never;\n\n/** @internal */\nexport type MatchArms<Defs extends readonly AnyCustomId[], Ret> = {\n [Def in Defs[number] as Def['prefix']]: (params: DecodedParams<Def['shape']>) => Promisable<Ret>;\n};\n","import 'reflect-metadata';\n\nimport { ApplicationCommandType } from 'discord-api-types/v10';\n\nimport { ComponentDefsKey } from '#customId/routing';\nimport { InteractionMetadataKey, InteractionRouteKeys, InteractionRoutes } from '#src/metadataKeys';\n\nimport type { ContextMenuKind } from '#registries/ContextMenuRegistry';\nimport type { AnyCustomId } from '@seedcord/custom-id';\n\n/** The select menu kinds the select route decorators take. */\nexport enum SelectMenuKind {\n String = 'string',\n User = 'user',\n Role = 'role',\n Channel = 'channel',\n Mentionable = 'mentionable'\n}\n\n// loose on purpose, each transport's typed decorators pass their asserted ctors straight in\nexport type RoutableConstructor = new (...args: never[]) => unknown;\n\nexport function areRoutes(routes: unknown): routes is string[] {\n return Array.isArray(routes) && routes.every((route) => typeof route === 'string');\n}\n\n/**\n * every stored route kind and its route strings on a decorated constructor. the build's manifest\n * emitter reads the same pairs.\n */\nexport function interactionRoutesOf(constructor: RoutableConstructor): [InteractionRoutes, string[]][] {\n const pairs: [InteractionRoutes, string[]][] = [];\n for (const route of Object.values(InteractionRoutes)) {\n const meta: unknown = Reflect.getMetadata(InteractionRouteKeys[route], constructor);\n if (areRoutes(meta)) pairs.push([route, meta]);\n }\n return pairs;\n}\n\nexport function storeInteractionRoute(\n route: InteractionRoutes,\n routes: string | readonly string[],\n constructor: RoutableConstructor\n): void {\n const key = InteractionRouteKeys[route];\n const saved: unknown = Reflect.getMetadata(key, constructor);\n const existing = areRoutes(saved) ? saved : [];\n const toStore = typeof routes === 'string' ? [routes] : routes;\n Reflect.defineMetadata(key, [...existing, ...toStore], constructor);\n Reflect.defineMetadata(InteractionMetadataKey, true, constructor);\n}\n\n// each definition's stable prefix is the routing key\n// the full defs stay on the ctor for decoding\nexport function storeComponentRoute(\n route: InteractionRoutes,\n defs: readonly AnyCustomId[],\n constructor: RoutableConstructor\n): void {\n storeInteractionRoute(\n route,\n defs.map((def) => def.prefix),\n constructor\n );\n Reflect.defineMetadata(ComponentDefsKey, defs, constructor);\n}\n\nconst SELECT_ROUTES: Record<SelectMenuKind, InteractionRoutes> = {\n [SelectMenuKind.String]: InteractionRoutes.StringMenu,\n [SelectMenuKind.User]: InteractionRoutes.UserMenu,\n [SelectMenuKind.Role]: InteractionRoutes.RoleMenu,\n [SelectMenuKind.Channel]: InteractionRoutes.ChannelMenu,\n [SelectMenuKind.Mentionable]: InteractionRoutes.MentionableMenu\n};\n\nexport function selectMenuRouteOf(kind: SelectMenuKind): InteractionRoutes {\n return SELECT_ROUTES[kind];\n}\n\nexport function contextMenuRouteOf(kind: ContextMenuKind): InteractionRoutes {\n return kind === ApplicationCommandType.User\n ? InteractionRoutes.UserContextMenu\n : InteractionRoutes.MessageContextMenu;\n}\n","import { SeedcordErrorCode } from '@seedcord/errors';\nimport { SeedcordError } from '@seedcord/errors/internal';\n\nimport type { AckTrace } from './AckTrace';\n\nexport type AckState = 'unacked' | 'deferred-reply' | 'deferred-update' | 'replied';\n\nexport type ReplyMethod =\n 'reply' | 'defer' | 'deferUpdate' | 'update' | 'followUp' | 'edit' | 'delete' | 'send' | 'showModal';\n\ninterface Illegal {\n // spliced into the message after \"was called when\"\n readonly reason: string;\n readonly alternative: string;\n}\n\nconst showModalReason: Illegal = {\n reason: 'this interaction was already acknowledged',\n alternative: 'showModal() must be the initial response.'\n};\n\nfunction deferReason(what: string): Illegal {\n return {\n reason: `this interaction was already acknowledged with ${what}`,\n alternative: 'A deferral can only be the initial response.'\n };\n}\n\n// a missing entry means legal in that state\nconst ILLEGAL: Record<Exclude<ReplyMethod, 'send'>, Partial<Record<AckState, Illegal>>> = {\n reply: {\n 'deferred-reply': {\n reason: 'this interaction was already deferred',\n alternative: 'Use edit() to fill the deferred reply or followUp() for a new message.'\n },\n 'deferred-update': {\n reason: 'this interaction was already acknowledged with a deferred update',\n alternative: 'Use followUp() for a new message.'\n },\n replied: {\n reason: 'this interaction was already replied to',\n alternative: 'Use followUp() for a new message or edit() to rewrite the reply.'\n }\n },\n defer: {\n 'deferred-reply': deferReason('a deferred reply'),\n 'deferred-update': deferReason('a deferred update'),\n replied: deferReason('a reply')\n },\n deferUpdate: {\n 'deferred-reply': deferReason('a deferred reply'),\n 'deferred-update': deferReason('a deferred update'),\n replied: deferReason('a reply')\n },\n update: {\n 'deferred-reply': {\n reason: 'this interaction was deferred as a reply',\n alternative: 'The placeholder is yours via edit(). update() rewrites a source message.'\n },\n replied: {\n reason: 'this interaction was already replied to',\n alternative: 'update() rewrites a source message. Use edit() or followUp() instead.'\n }\n },\n followUp: {\n unacked: {\n reason: 'this interaction has not been acknowledged yet',\n alternative: 'Ack first with reply() or defer().'\n }\n },\n edit: {\n unacked: {\n reason: 'nothing has been sent yet',\n alternative: 'Send with reply() or defer() first, then edit() rewrites it.'\n }\n },\n delete: {\n unacked: {\n reason: 'nothing has been sent yet',\n alternative: 'Acknowledge first with reply() or defer(), then delete() removes it.'\n }\n },\n showModal: {\n 'deferred-reply': showModalReason,\n 'deferred-update': showModalReason,\n replied: showModalReason\n }\n};\n\nconst SEND_TARGET: Record<AckState, 'reply' | 'edit' | 'followUp'> = {\n unacked: 'reply',\n 'deferred-reply': 'edit',\n 'deferred-update': 'followUp',\n replied: 'followUp'\n};\n\n// throws before any API call, and ackedBy becomes the throw cause with its stack pointing at the first ack\nexport function checkAckLegality(method: ReplyMethod, state: AckState, routeId: string, ackedBy?: AckTrace): void {\n if (method === 'send') return;\n const illegal = ILLEGAL[method][state];\n if (!illegal) return;\n throw new SeedcordError(\n SeedcordErrorCode.ReplyIllegalAckState,\n [method, illegal.reason, illegal.alternative, routeId],\n { cause: ackedBy }\n );\n}\n\nexport function sendTarget(state: AckState): 'reply' | 'edit' | 'followUp' {\n return SEND_TARGET[state];\n}\n","import type { ReplyMethod } from './ackLegality';\n\n// the first ack's stack, passed as the throw cause so a double-ack points to both lines\nexport class AckTrace extends Error {\n public constructor(method: ReplyMethod) {\n super(`${method}() acknowledged this interaction`);\n this.name = 'AckTrace';\n }\n}\n","import { paint } from '@seedcord/errors';\nimport { Logger } from '@seedcord/logger';\n\nimport { asError } from '#stops/asError';\nimport { PublishDefault } from '#subscribers/publishDefault';\n\nimport type { Bus } from '#subscribers/Bus';\nimport type { ReplyMethod } from './ackLegality';\n\nlet replyLogger: Logger | undefined;\nfunction logger(): Logger {\n replyLogger ??= new Logger('Reply', { channel: 'interactions' });\n return replyLogger;\n}\n\nexport interface ReplyTelemetry {\n readonly bus: Bus;\n readonly interactionId: string;\n}\n\n// the reply verbs plus the autocomplete choices callback, which runs outside the ack state machine\nexport type WriteMethod = ReplyMethod | 'respond';\n\ninterface WriteStart {\n readonly routeId: string;\n readonly method: WriteMethod;\n // performance.now() captured before the write began\n readonly startedAt: number;\n}\n\ninterface SentReport extends WriteStart {\n readonly outcome: 'sent';\n readonly messageId: string | null;\n}\n\ninterface FailedReport extends WriteStart {\n readonly outcome: 'failed';\n readonly error: Error;\n}\n\nexport type ResponseReport = SentReport | FailedReport;\n\n/** @internal */\nexport function publishResponse(telemetry: ReplyTelemetry, report: ResponseReport): void {\n const durationMs = performance.now() - report.startedAt;\n const write = {\n routeId: report.routeId,\n interactionId: telemetry.interactionId,\n method: report.method,\n durationMs\n };\n telemetry.bus[PublishDefault](\n 'responseAttempted',\n report.outcome === 'failed'\n ? { ...write, outcome: 'failed', messageId: null, error: report.error }\n : { ...write, outcome: 'sent', messageId: report.messageId }\n );\n\n // after publish so a throwing sink doesn't reach the publish above\n logger().trace(\n `${paint.sky.bold(report.routeId)} ${report.method} ${report.outcome} ${paint.mute('in')} ${Math.round(durationMs)}ms`\n );\n}\n\nexport async function reportedWrite<Result>(\n telemetry: ReplyTelemetry,\n routeId: string,\n method: WriteMethod,\n write: () => Promise<Result>\n): Promise<Result> {\n const startedAt = performance.now();\n const result = await attemptWrite(telemetry, routeId, method, startedAt, write);\n publishResponse(telemetry, { routeId, method, startedAt, outcome: 'sent', messageId: null });\n return result;\n}\n\n// publishes the failed arm when write() throws, since the caller's success report sits after the write and a throw skips it\nexport async function attemptWrite<Result>(\n telemetry: ReplyTelemetry,\n routeId: string,\n method: WriteMethod,\n startedAt: number,\n write: () => Promise<Result>\n): Promise<Result> {\n try {\n return await write();\n } catch (caught) {\n const error = asError(caught);\n publishResponse(telemetry, { routeId, method, startedAt, outcome: 'failed', error });\n // rethrown raw\n throw caught;\n }\n}\n","import { SeedcordErrorCode } from '@seedcord/errors';\nimport { SeedcordError } from '@seedcord/errors/internal';\n\n// shapeshift aggregate errors nest, so the cap bounds the recursion\nconst MAX_DEPTH = 8;\n\ninterface ShapeshiftLike {\n readonly message?: unknown;\n readonly errors?: unknown;\n readonly constraint?: unknown;\n readonly validator?: unknown;\n readonly expected?: unknown;\n readonly given?: unknown;\n}\n\nconst OPERATOR_WORD: Record<string, string> = {\n '<=': 'at most',\n '>=': 'at least',\n '<': 'fewer than',\n '>': 'more than'\n};\n\nconst KIND_WORD: Record<string, string> = {\n string: 'a string',\n number: 'a number',\n boolean: 'a boolean',\n bigint: 'a bigint',\n array: 'a list',\n tuple: 'a list',\n date: 'a date',\n object: 'an object'\n};\n\nfunction asRecord(value: unknown): ShapeshiftLike | null {\n return typeof value === 'object' && value !== null ? value : null;\n}\n\nfunction firstLine(message: unknown): string {\n if (typeof message !== 'string') return 'unknown validation failure';\n return message.split('\\n')[0] ?? message;\n}\n\n// strings over this limit render as a character count\nconst GIVEN_PREVIEW_LIMIT = 40;\n\nfunction gotPhrase(given: unknown): string {\n if (given === undefined) return 'nothing';\n if (given === null) return 'null';\n if (typeof given === 'string') {\n if (given.length === 0) return 'an empty string';\n if (given.length > GIVEN_PREVIEW_LIMIT) return `${given.length} characters`;\n return JSON.stringify(given);\n }\n if (Array.isArray(given)) return given.length === 0 ? 'an empty list' : `${given.length} items`;\n if (typeof given === 'number' || typeof given === 'bigint' || typeof given === 'boolean') return String(given);\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- a null-prototype value has no constructor at runtime\n if (typeof given === 'object') return given.constructor?.name ?? 'an object';\n return typeof given;\n}\n\n// shapeshift constraint strings take the form 'expected.length >= 1' or 'expected <= 16777215'\nfunction needPhrase(expected: string, given: unknown): string | null {\n const bounds = [...expected.matchAll(/expected(\\.length)?\\s*(<=|>=|<|>)\\s*(\\d+)/g)];\n if (bounds.length === 0) return null;\n const phrases = bounds.map(([, lengthPart, operator, limit]) => {\n const word = OPERATOR_WORD[operator ?? ''] ?? operator ?? '';\n if (!lengthPart) return `${word} ${limit}`;\n const unit = typeof given === 'string' ? 'character' : 'item';\n return `${word} ${limit} ${Number(limit) === 1 ? unit : `${unit}s`}`;\n });\n return phrases.join(' and ');\n}\n\nfunction instanceName(expected: unknown): string {\n if (typeof expected === 'function' && expected.name) return expected.name;\n return 'specific class instance';\n}\n\nfunction describeLeaf(record: ShapeshiftLike): string {\n if (typeof record.constraint === 'string') {\n const need = typeof record.expected === 'string' ? needPhrase(record.expected, record.given) : null;\n if (need) return `need ${need}, got ${gotPhrase(record.given)}`;\n return `${firstLine(record.message)}${'given' in record ? ` (got ${gotPhrase(record.given)})` : ''}`;\n }\n if (typeof record.expected === 'function') {\n return `need a ${instanceName(record.expected)}, got ${gotPhrase(record.given)}`;\n }\n if (typeof record.validator === 'string') {\n const kind = KIND_WORD[record.validator.replace(/^s\\./, '').replace(/\\(.*$/, '')];\n if (kind) return `need ${kind}, got ${gotPhrase(record.given)}`;\n return `${firstLine(record.message)}, got ${gotPhrase(record.given)}`;\n }\n return firstLine(record.message);\n}\n\nfunction describeUnion(branches: unknown[], depth: number): string {\n const records: ShapeshiftLike[] = [];\n for (const branch of branches) {\n const record = asRecord(branch);\n if (record) records.push(record);\n }\n const bounded = records.find((record) => typeof record.constraint === 'string');\n if (bounded) return describeLeaf(bounded);\n\n const names: string[] = [];\n let allInstances = records.length > 0;\n for (const record of records) {\n if (typeof record.expected === 'function') names.push(instanceName(record.expected));\n else allInstances = false;\n }\n if (allInstances) {\n return `need a ${[...new Set(names)].join(' or ')}, got ${gotPhrase(records[0]?.given)}`;\n }\n return detailOf(branches[0], depth + 1);\n}\n\n// shapeshift nests errors as [key, inner] tuples\nfunction detailOf(value: unknown, depth: number): string {\n const record = asRecord(value);\n if (!record || depth >= MAX_DEPTH) return firstLine(record?.message);\n\n if (Array.isArray(record.errors) && record.errors.length > 0) {\n const errors = record.errors as unknown[];\n const [first] = errors;\n if (Array.isArray(first)) {\n const [key, inner] = first as [unknown, unknown];\n return `${String(key)}: ${detailOf(inner, depth + 1)}`;\n }\n return describeUnion(errors, depth);\n }\n\n return describeLeaf(record);\n}\n\n// a shapeshift throw becomes an actionable message with the cause kept, while anything else contributes its own message as the detail\nexport function translateSerializationError(\n error: unknown,\n componentClass: string,\n index: number,\n routeId: string\n): SeedcordError<SeedcordErrorCode.ReplyComponentSerialization> {\n const detail = detailOf(error, 0);\n return new SeedcordError(SeedcordErrorCode.ReplyComponentSerialization, [componentClass, index, detail, routeId], {\n cause: error\n });\n}\n","import { TextDisplayBuilder } from '@discordjs/builders';\n\nimport { translateSerializationError } from './translateSerialization';\n\nimport type { ReplyResponse } from '@seedcord/types';\nimport type { APIMessageTopLevelComponent } from 'discord-api-types/v10';\n\nexport interface SerializedReply<TNative = never> {\n readonly components: APIMessageTopLevelComponent[];\n readonly allowedMentions?: ReplyResponse['allowedMentions'];\n readonly files?: ReplyResponse<TNative>['files'];\n}\n\nexport function serializeReply<TNative>(\n response: ReplyResponse<TNative> | string,\n routeId: string\n): SerializedReply<TNative> {\n if (typeof response === 'string') {\n try {\n return { components: [new TextDisplayBuilder().setContent(response).toJSON()] };\n } catch (error) {\n throw translateSerializationError(error, 'TextDisplayBuilder', 0, routeId);\n }\n }\n\n const components = response.components.map((component, index) => {\n try {\n return component.toJSON();\n } catch (error) {\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- a null-prototype value has no constructor at runtime\n const name = component.constructor?.name;\n throw translateSerializationError(error, !name || name === 'Object' ? 'component' : name, index, routeId);\n }\n });\n\n return {\n components,\n ...(response.allowedMentions && { allowedMentions: response.allowedMentions }),\n ...(response.files && { files: response.files })\n };\n}\n","import type { CoreBase } from '#interfaces/CoreBase';\n\n/**\n * The transport-agnostic gate context, the scalar identity of the acting user resolvable from any\n * transport's payload. Every field except `core` is nullable, since an event or DM may carry no\n * guild or member. Each transport extends it with its own arm. For example, the gateway adds the djs\n * `user`/`guild`/`member` objects and the live interaction or event payload.\n *\n * @example\n * ```ts\n * // a gate reading only the base fields fits any handler on any transport\n * const NeedsGuild = defineGate('NeedsGuild', (ctx: GateContextBase) => {\n * if (!ctx.guildId) throw new NotInGuild();\n * });\n * ```\n */\nexport interface GateContextBase {\n /** Gates read the config and the rate limiter through it. */\n readonly core: CoreBase;\n /** The acting user's id, or null on an event that carries none. */\n readonly userId: string | null;\n /** The guild id, or null outside a guild. */\n readonly guildId: string | null;\n /** The channel id, or null when the source carries none. */\n readonly channelId: string | null;\n /**\n * The member's role ids without the everyone role, the shape a raw interaction payload\n * contains. Empty outside a guild or when the source contains none.\n */\n readonly memberRoleIds: readonly string[];\n /**\n * The member's permission bits, or null outside a guild. On an interaction these are the\n * channel-scoped permissions the payload contains, and on a gateway event they're the member's guild-level ones.\n */\n readonly memberPermissions: bigint | null;\n /**\n * The bot's permissions in the invoked channel, the wire `app_permissions` value. Null on gateway events.\n */\n readonly appPermissions: bigint | null;\n /**\n * The dispatched handler as `kind:route` (`slash:daily`, `button:confirm`), or null off a route (a\n * plain event handler, or a gate run outside a handler). `runHandlerGates` sets it from the handler's\n * metadata. `Cooldown` uses it so its window is stable across restarts and isolates.\n */\n readonly routeId: string | null;\n}\n\n/**\n * The context the guild-scoped permission gates require. It adds the base permission sets computed from\n * roles alone, which only the gateway transport can provide from its cache. The http transport's context\n * does not define these fields.\n *\n * @example\n * ```ts\n * // in:'guild' returns a Gate<GuildPermissionsContext>, which fits only a gateway handler\n * \\@Gated(RequirePermissions([PermissionFlagsBits.BanMembers], { in: 'guild' }))\n * ```\n */\nexport interface GuildPermissionsContext extends GateContextBase {\n /**\n * The member's base permission set, roles only, matching djs `GuildMember.permissions`. Null when the\n * member is unavailable.\n */\n readonly memberGuildPermissions: bigint | null;\n /**\n * The bot's base permission set from the transport's cache. Null when the cached member is unavailable.\n */\n readonly appGuildPermissions: bigint | null;\n}\n\n// phantom brand rejects a bare check function or plain object where a Gate is expected\ndeclare const GateBrand: unique symbol;\n\n/**\n * A precondition attached to a handler. It refuses by throwing a `Notice` (a reply) or a `Silence`\n * (a drop with no reply), and passes by returning. `Ctx` is the context it requires, so a gate that reads\n * a field absent on a handler's context is rejected at compile time. `Name` is captured as a literal so\n * a mismatch error can name the gate. Build one with {@link defineGate} or {@link defineEffectGate}.\n *\n * @typeParam Ctx - The context the gate requires. A field missing from it is a compile error.\n * @typeParam Name - The gate's literal name, named in a mismatch error.\n *\n * @example\n * ```ts\n * // a factory returning a typed, agnostic gate\n * function MyGate(): Gate<GateContextBase, 'MyGate'> {\n * return defineGate('MyGate', (ctx) => {\n * if (shouldRefuse(ctx)) throw new MyNotice();\n * });\n * }\n * ```\n *\n * @see {@link defineGate}\n */\nexport interface Gate<Ctx extends GateContextBase = GateContextBase, Name extends string = string> {\n /** The gate's name, surfaced in a mismatch error and joined by the combinators. */\n readonly name: Name;\n /** Reads the context and refuses by throwing a Notice or a Silence, or passes by resolving. */\n check(ctx: Ctx): Promise<void>;\n\n /** @internal */\n readonly [GateBrand]: true;\n}\n\n/**\n * A gate that carries a side effect, split so the effect fires only once the gate is the one that\n * let the request through. `check` peeks and refuses, while `commit` applies the effect after the whole\n * gate set passes. {@link Cooldown} is the catalog gate that returns one. Build one with\n * {@link defineEffectGate}.\n *\n * @typeParam Ctx - The context both `check` and `commit` require. A field missing from it fails to compile.\n * @typeParam Name - The gate's literal name, shown when a mismatch error names the gate.\n *\n * @example\n * ```ts\n * // a factory returning a typed effect gate\n * function MyEffectGate(): EffectGate<GateContextBase, 'MyEffectGate'> {\n * return defineEffectGate(\n * 'MyEffectGate',\n * (ctx) => {\n * if (shouldRefuse(ctx)) throw new MyNotice();\n * },\n * (ctx) => {\n * applyMyEffect(ctx);\n * }\n * );\n * }\n * ```\n *\n * @see {@link defineEffectGate}\n */\nexport interface EffectGate<Ctx extends GateContextBase = GateContextBase, Name extends string = string> extends Gate<\n Ctx,\n Name\n> {\n /** Applies the side effect, run only after the whole gate set passes. */\n commit(ctx: Ctx): Promise<void>;\n}\n\n/**\n * Builds a {@link Gate} from a check. The check refuses by throwing a Notice or a Silence and passes\n * by returning. The required context is inferred from `ctx`, so annotate it as narrowly as the fields\n * the check reads. No annotation defaults to {@link GateContextBase}, an agnostic gate that fits every\n * handler.\n *\n * @typeParam Name - The gate's name, captured as a literal for mismatch errors.\n * @typeParam Ctx - The context the check reads, inferred from the `ctx` annotation.\n *\n * @param name - The gate's name, used in mismatch errors.\n * @param fn - The check, which refuses by throwing a Notice or a Silence and passes by returning.\n *\n * @see {@link defineEffectGate}\n * @see the `@Gated` decorator from your transport package\n *\n * @example\n * ```ts\n * // a gate factory that takes its own option and closes over it\n * function MinRoles(min: number): Gate<GateContextBase, 'MinRoles'> {\n * return defineGate('MinRoles', (ctx) => {\n * if (ctx.memberRoleIds.length < min) throw new NotEnoughRoles(min);\n * });\n * }\n * ```\n *\n * @example\n * ```ts\n * // agnostic gate (no ctx annotation): fits any handler\n * const Owner = defineGate('owner', (ctx) => {\n * if (!ctx.userId) throw new NotOwner();\n * });\n * ```\n */\nexport function defineGate<const Name extends string, Ctx extends GateContextBase = GateContextBase>(\n name: Name,\n fn: (ctx: Ctx) => void | Promise<void>\n): Gate<Ctx, Name> {\n return { name, check: async (ctx) => fn(ctx) } as Gate<Ctx, Name>;\n}\n\n/**\n * Builds an {@link EffectGate} from a `check` and a `commit`. `check` peeks and refuses by throwing, and\n * `commit` applies the side effect, running only once the whole gate set passes so a later refusal never\n * commits. In an `or`, a refusing arm's queued commit is rolled back. This is how {@link Cooldown} peeks\n * in `check` and charges the slot in `commit`.\n *\n * @typeParam Name - The gate's literal name, used to name a mismatch error.\n * @typeParam Ctx - The context both `check` and `commit` read, inferred from the `ctx` annotation.\n *\n * @param name - The gate's name, used in mismatch errors.\n * @param check - Peeks and refuses by throwing, without applying the side effect.\n * @param commit - Applies the side effect, running only after the whole gate set passes.\n *\n * @see {@link defineGate}\n * @see the `@Gated` decorator from your transport package\n * @see {@link Cooldown}\n *\n * @example\n * ```ts\n * // an effect-gate factory that takes its own limit and closes over it\n * function UsesPerDay(max: number): EffectGate<GateContextBase, 'UsesPerDay'> {\n * return defineEffectGate(\n * 'UsesPerDay',\n * (ctx) => {\n * // peek and refuse by throwing. do not mutate yet\n * if (usedToday(ctx.userId) >= max) throw new OutOfUsesNotice(max);\n * },\n * (ctx) => {\n * // runs only after the whole gate set passes\n * recordUse(ctx.userId);\n * }\n * );\n * }\n * ```\n */\nexport function defineEffectGate<const Name extends string, Ctx extends GateContextBase = GateContextBase>(\n name: Name,\n check: (ctx: Ctx) => void | Promise<void>,\n commit: (ctx: Ctx) => void | Promise<void>\n): EffectGate<Ctx, Name> {\n return {\n name,\n check: async (ctx) => check(ctx),\n commit: async (ctx) => commit(ctx)\n } as EffectGate<Ctx, Name>;\n}\n\n/**\n * The context a {@link Gate} requires.\n *\n * @typeParam TGate - The gate type to read the required context from.\n *\n * @example\n * ```ts\n * type OwnerCtx = RequiredOf<ReturnType<typeof OwnerOnly>>; // GateContextBase\n * ```\n */\nexport type RequiredOf<TGate> = TGate extends Gate<infer Ctx> ? Ctx : never;\n","import { toEpochSeconds } from '@seedcord/utils';\n\nimport { Notice } from '#stops/Notice';\nimport { NoticeCard } from '#stops/NoticeCard';\n\nimport type { EpochMs, ReplyResponse } from '@seedcord/types';\n\nexport abstract class GateNotice extends Notice {\n public render(): ReplyResponse {\n return { components: [new NoticeCard(this.message).component] };\n }\n}\n\nexport class NotOwner extends GateNotice {\n public constructor(message = 'Only the bot owner can use this.') {\n super(message);\n this.summary = 'be the bot owner';\n }\n}\n\nexport class NotInGuild extends GateNotice {\n public constructor(message = 'This can only be used in a server.') {\n super(message);\n this.summary = 'be in a server';\n }\n}\n\nexport class NotInDm extends GateNotice {\n public constructor(message = 'This can only be used in a direct message.') {\n super(message);\n this.summary = 'be in a direct message';\n }\n}\n\nfunction retryAt(resetAt: EpochMs): string {\n return `<t:${toEpochSeconds(resetAt)}:R>`;\n}\n\nexport class OnCooldown extends GateNotice {\n public constructor(\n public readonly resetAt: EpochMs,\n message?: string\n ) {\n super(message ?? `You are doing that too fast. Try again ${retryAt(resetAt)}.`);\n this.summary = `try again ${retryAt(resetAt)}`;\n }\n}\n\nexport class NotAllowed extends Notice {\n public constructor() {\n super('not allowed');\n }\n\n public render(): ReplyResponse {\n return { components: [new NoticeCard('You are not allowed to use this command.').component] };\n }\n}\n\nexport class NeedsAny extends Notice {\n private readonly summaries: readonly string[];\n\n public constructor(summaries: readonly string[]) {\n super('not allowed');\n // two arms can refuse with the same summary\n this.summaries = [...new Set(summaries)];\n }\n\n public render(): ReplyResponse {\n const bullets = this.summaries.map((summary) => `• ${summary}`).join('\\n');\n return { components: [new NoticeCard(`You need to meet at least one of these:\\n${bullets}`).component] };\n }\n}\n\nexport class MissingRole extends GateNotice {\n public constructor(message: string | undefined, roleId: string | null) {\n super(\n message ?? (roleId ? `You need the <@&${roleId}> role to use this.` : 'You do not have the required role.')\n );\n this.summary = roleId ? `hold the <@&${roleId}> role` : 'hold the required role';\n }\n}\n\nexport class MissingPermissions extends Notice {\n private readonly customLead: string | undefined;\n\n public constructor(\n message: string | undefined,\n private readonly subject: string | null,\n private readonly missingPerms: readonly string[]\n ) {\n super(message ?? 'A required permission is missing.');\n this.customLead = message;\n const names = missingPerms.join(', ');\n this.summary = subject === null ? `hold ${names}` : `${subject} needs ${names}`;\n }\n\n public render(): ReplyResponse {\n const bullets = this.missingPerms.map((perm) => `• ${perm}`).join('\\n');\n const lead =\n this.customLead ??\n `${this.subject === null ? 'You are' : `${this.subject} is`} missing the following permission entries:`;\n return {\n components: [new NoticeCard(`${lead}\\n\\n${bullets}`).component]\n };\n }\n}\n\nexport class HasDangerousPermissions extends Notice {\n private readonly customLead: string | undefined;\n\n public constructor(\n message: string | undefined,\n private readonly subject: string,\n private readonly dangerousPerms: readonly string[]\n ) {\n super(message ?? 'A dangerous permission is enabled.');\n this.customLead = message;\n this.summary = `${subject} must not hold ${dangerousPerms.join(', ')}`;\n }\n\n public render(): ReplyResponse {\n const bullets = this.dangerousPerms.map((perm) => `• ${perm}`).join('\\n');\n const lead =\n this.customLead ?? `${this.subject} has the following permission entries that must not be enabled:`;\n return { components: [new NoticeCard(`${lead}\\n\\n${bullets}`).component] };\n }\n}\n","import type { EffectGate, Gate, GateContextBase } from './Gate';\n\ntype CommitFn = () => Promise<void>;\n\n// commits wait here until the whole gate set passes, one queue per request. the key is the context\n// itself and the map is weak, so an entry goes when its request does\nconst commitQueues = new WeakMap<GateContextBase, CommitFn[]>();\n\nfunction isEffectGate(gate: Gate<GateContextBase>): gate is EffectGate<GateContextBase> {\n return typeof (gate as Partial<EffectGate<GateContextBase>>).commit === 'function';\n}\n\n// a refused effect gate never commits. combinators call this too\nexport async function runCheck(gate: Gate<GateContextBase>, ctx: GateContextBase): Promise<void> {\n await gate.check(ctx);\n if (!isEffectGate(gate)) return;\n\n let queue = commitQueues.get(ctx);\n if (!queue) {\n queue = [];\n commitQueues.set(ctx, queue);\n }\n queue.push(() => gate.commit(ctx));\n}\n\nexport async function runCommits(ctx: GateContextBase): Promise<void> {\n const queue = commitQueues.get(ctx);\n if (!queue) return;\n for (const commit of queue) await commit();\n}\n\n// the runner calls this from a finally, refused run or not\nexport function discardCommits(ctx: GateContextBase): void {\n commitQueues.delete(ctx);\n}\n\n// an `or` arm takes this mark before it runs\nexport function markCommits(ctx: GateContextBase): number {\n return commitQueues.get(ctx)?.length ?? 0;\n}\n\n// and rolls back to it when the arm refuses, leaving no commit behind\nexport function rollbackCommits(ctx: GateContextBase, mark: number): void {\n const queue = commitQueues.get(ctx);\n if (queue && queue.length > mark) queue.length = mark;\n}\n","import type { Notice } from '#stops/Notice';\n\n/**\n * The override a catalog gate accepts. A one-line `message` reword or a full `notice` replacement. Accepted by\n * the agnostic catalog gates and, nested per refusal, by {@link RequireRole}. {@link RequirePermissions} and\n * {@link RequireBotPermissions} take `RequirePermissionsOptions` instead.\n *\n * @example\n * ```ts\n * // reword the default refusal\n * OwnerOnly({ message: 'Bot owners only.' });\n * ```\n *\n * @example\n * ```ts\n * // replace the refusal entirely, for example a translated Notice\n * GuildOnly({ notice: new MyTranslatedNotice() });\n * ```\n */\nexport interface GateNoticeOptions {\n /** Reword the default refusal, keeping its embed styling. */\n message?: string;\n /** Replace the default refusal Notice entirely, for full control or a translated copy. */\n notice?: Notice;\n}\n\nexport function pickNotice(options: GateNoticeOptions | undefined, makeDefault: (message?: string) => Notice): Notice {\n return options?.notice ?? makeDefault(options?.message);\n}\n","import { prettify } from '@seedcord/utils';\nimport { PermissionFlagsBits } from 'discord-api-types/v10';\n\n/**\n * The permission flag bits a caller or the bot must hold. Pass the `PermissionFlagsBits` values from\n * `discord-api-types/v10` (or `discord.js`).\n */\nexport type PermissionScope = readonly bigint[];\n\n// permission bit to its prettified human-readable name\nexport const PermissionNames = new Map<bigint, string>(\n Object.entries(PermissionFlagsBits).map(([key, bit]) => [bit, prettify(key)])\n);\n\nconst ADMINISTRATOR = PermissionFlagsBits.Administrator;\n\nfunction nameOf(bit: bigint): string {\n return PermissionNames.get(bit) ?? String(bit);\n}\n\n// discord treats the administrator bit as granting every permission\nfunction holds(held: bigint, bit: bigint): boolean {\n return (held & ADMINISTRATOR) === ADMINISTRATOR || (held & bit) === bit;\n}\n\n/** @internal */\nexport function hasAll(held: bigint, scope: PermissionScope): boolean {\n return scope.every((bit) => holds(held, bit));\n}\n\n/** @internal only reached once hasAll failed, so the administrator bit is absent */\nexport function missingNames(held: bigint, scope: PermissionScope): string[] {\n return scope.reduce<string[]>((names, bit) => {\n if ((held & bit) !== bit) names.push(nameOf(bit));\n return names;\n }, []);\n}\n\n/** @internal */\nexport function presentNames(held: bigint, scope: PermissionScope): string[] {\n return scope.reduce<string[]>((names, bit) => {\n if (holds(held, bit)) names.push(nameOf(bit));\n return names;\n }, []);\n}\n","import { defineGate } from '#gates/Gate';\nimport { MissingPermissions, MissingRole, NotInGuild } from '#notices/index';\nimport { hasAll, missingNames } from '#src/permissions/bits';\n\nimport { pickNotice } from './options';\n\nimport type { Gate, GateContextBase, GuildPermissionsContext } from '#gates/Gate';\nimport type { PermissionScope } from '#src/permissions/bits';\nimport type { GateNoticeOptions } from './options';\n\nexport type { PermissionScope } from '#src/permissions/bits';\nexport { PermissionNames } from '#src/permissions/bits';\n\ninterface PermCheckKind {\n unresolved: string;\n subject: string | null;\n}\n\nconst MEMBER_CHECK: PermCheckKind = {\n unresolved: 'Your server member data could not be resolved. Try again.',\n subject: null\n};\nconst BOT_CHECK: PermCheckKind = {\n unresolved: \"The bot's permissions could not be resolved. Try again.\",\n subject: 'The bot'\n};\n\nfunction refusePermissions(\n held: bigint | null,\n scope: PermissionScope,\n options: RequirePermissionsOptions | undefined,\n guildId: string | null,\n kind: PermCheckKind\n): void {\n if (held === null) {\n throw pickNotice(\n options?.notInGuild,\n (message) => new NotInGuild(message ?? (guildId ? kind.unresolved : undefined))\n );\n }\n if (hasAll(held, scope)) return;\n throw pickNotice(\n options?.missing,\n (message) => new MissingPermissions(message, kind.subject, missingNames(held, scope))\n );\n}\n\n/**\n * Options for {@link RequirePermissions} and {@link RequireBotPermissions}.\n */\nexport interface RequirePermissionsOptions {\n /**\n * The set the check reads. `'channel'` reads the effective channel set the payload carries, what\n * Discord enforces in the invoked channel. `'guild'` reads the base set from roles, available on the\n * gateway transport only.\n *\n * @defaultValue `'channel'`\n */\n in?: 'channel' | 'guild';\n /** Reword or replace the refusal shown when the set is unavailable (outside a guild, or unresolved inside one). */\n notInGuild?: GateNoticeOptions;\n /** Reword or replace the refusal shown when a permission is missing. */\n missing?: GateNoticeOptions;\n}\n\n/**\n * Options for {@link RequireRole}.\n */\nexport interface RequireRoleOptions {\n /** Reword or replace the refusal shown outside a guild. */\n notInGuild?: GateNoticeOptions;\n /** Reword or replace the refusal shown when the caller lacks the role. */\n missingRole?: GateNoticeOptions;\n}\n\n/**\n * Requires the caller to hold every permission in `scope`. Refuses outside a guild first, then when a\n * permission is missing. The Administrator bit passes any scope.\n *\n * The default `'channel'` scope reads the effective channel set the payload carries, what Discord enforces\n * in the invoked channel. The `'guild'` scope reads the base set from roles and requires a\n * {@link GuildPermissionsContext}, so it fits a gateway handler only.\n *\n * @param scope - The permission flag bits the caller must all hold.\n * @param options - Pick the scope with `in`, and override each refusal with `notInGuild` or `missing`.\n *\n * @see the `@Gated` decorator from your transport package\n *\n * @example\n * ```ts\n * import { PermissionFlagsBits } from 'discord-api-types/v10';\n *\n * \\@Gated(RequirePermissions([PermissionFlagsBits.BanMembers]))\n * \\@SlashRoute('ban')\n * class BanHandler extends SlashHandler<'ban'> {\n * async execute() {\n * // ...\n * }\n * }\n * ```\n *\n * @example\n * ```ts\n * // the base set from roles, on a gateway handler\n * RequirePermissions([PermissionFlagsBits.BanMembers], { in: 'guild' });\n * ```\n */\nexport function RequirePermissions(\n scope: PermissionScope,\n options: RequirePermissionsOptions & { in: 'guild' }\n): Gate<GuildPermissionsContext, 'RequirePermissions'>;\nexport function RequirePermissions(\n scope: PermissionScope,\n options?: RequirePermissionsOptions & { in?: 'channel' }\n): Gate<GateContextBase, 'RequirePermissions'>;\nexport function RequirePermissions(\n scope: PermissionScope,\n options?: RequirePermissionsOptions\n): Gate<GuildPermissionsContext, 'RequirePermissions'> | Gate<GateContextBase, 'RequirePermissions'> {\n if (options?.in === 'guild') {\n return defineGate('RequirePermissions', (ctx: GuildPermissionsContext) => {\n refusePermissions(ctx.memberGuildPermissions, scope, options, ctx.guildId, MEMBER_CHECK);\n });\n }\n return defineGate('RequirePermissions', (ctx: GateContextBase) => {\n refusePermissions(ctx.memberPermissions, scope, options, ctx.guildId, MEMBER_CHECK);\n });\n}\n\n/**\n * Requires the bot to hold every permission in `scope`. Refuses outside a guild first, then when a\n * permission is missing. The Administrator bit passes any scope.\n *\n * The default `'channel'` scope reads the bot's effective channel set (wire `app_permissions`), what\n * Discord enforces in the invoked channel. The `'guild'` scope reads the bot's base set from roles and\n * requires a {@link GuildPermissionsContext}, fitting a gateway handler only. `app_permissions` is\n * absent on gateway events, the channel scope refuses there as unresolved, use `in: 'guild'` on an\n * event handler.\n *\n * @param scope - The permission flag bits the bot must all hold.\n * @param options - Pick the scope with `in`, and override each refusal with `notInGuild` or `missing`.\n *\n * @see the `@Gated` decorator from your transport package\n *\n * @example\n * ```ts\n * import { PermissionFlagsBits } from 'discord-api-types/v10';\n *\n * \\@Gated(RequireBotPermissions([PermissionFlagsBits.ManageMessages]))\n * \\@SlashRoute('purge')\n * class PurgeHandler extends SlashHandler<'purge'> {\n * async execute() {\n * // ...\n * }\n * }\n * ```\n */\nexport function RequireBotPermissions(\n scope: PermissionScope,\n options: RequirePermissionsOptions & { in: 'guild' }\n): Gate<GuildPermissionsContext, 'RequireBotPermissions'>;\nexport function RequireBotPermissions(\n scope: PermissionScope,\n options?: RequirePermissionsOptions & { in?: 'channel' }\n): Gate<GateContextBase, 'RequireBotPermissions'>;\nexport function RequireBotPermissions(\n scope: PermissionScope,\n options?: RequirePermissionsOptions\n): Gate<GuildPermissionsContext, 'RequireBotPermissions'> | Gate<GateContextBase, 'RequireBotPermissions'> {\n if (options?.in === 'guild') {\n return defineGate('RequireBotPermissions', (ctx: GuildPermissionsContext) => {\n refusePermissions(ctx.appGuildPermissions, scope, options, ctx.guildId, BOT_CHECK);\n });\n }\n return defineGate('RequireBotPermissions', (ctx: GateContextBase) => {\n refusePermissions(ctx.appPermissions, scope, options, ctx.guildId, BOT_CHECK);\n });\n}\n\n/**\n * Requires the caller to hold `roleId`, read from the member's role ids. Refuses outside a guild first,\n * then when the role is missing. Roles are guild-global, so there is no scope dimension.\n *\n * @param roleId - The role snowflake the caller must hold.\n * @param options - Override each refusal, the outside-guild one with `notInGuild` and the missing-role one with `missingRole`.\n *\n * @see the `@Gated` decorator from your transport package\n *\n * @example\n * ```ts\n * \\@Gated(RequireRole('123456789012345678'))\n * \\@SlashRoute('vip')\n * class VipHandler extends SlashHandler<'vip'> {\n * async execute() {\n * // ...\n * }\n * }\n * ```\n */\nexport function RequireRole(roleId: string, options?: RequireRoleOptions): Gate<GateContextBase, 'RequireRole'> {\n return defineGate('RequireRole', (ctx) => {\n if (!ctx.guildId) throw pickNotice(options?.notInGuild, (message) => new NotInGuild(message));\n if (ctx.memberRoleIds.includes(roleId)) return;\n throw pickNotice(options?.missingRole, (message) => new MissingRole(message, roleId));\n });\n}\n","/**\n * Throw to stop a handler with no reply and no report.\n *\n * The framework boundary catches `Silence` before {@link Notice}, makes zero Discord calls, and stops.\n * Ideally you'd only throw this in `EventHandlers` (or `Gates` for those), because it doesn't make sense to\n * leave the user with no reply for an interaction.\n *\n * @example\n * ```ts\n * import { Silence } from '@seedcord/gateway';\n *\n * // a helper under a guildMemberAdd handler, stopping when this guild configured nothing to send\n * const template = await settings.welcome(member.guild.id);\n * if (!template) throw new Silence('no welcome message set');\n * ```\n */\nexport class Silence extends Error {\n /**\n * @param reason - Optional note written only to a debug log, never shown to the user or reported.\n */\n public constructor(public readonly reason?: string) {\n super(reason ?? 'Silence');\n\n Error.captureStackTrace(this, this.constructor);\n }\n}\n","import { CustomId } from '@seedcord/custom-id';\n\nimport type { CustomIdField } from '@seedcord/custom-id';\n\n// Included in the layout hash so it is fixed per prefix. Reducing it marks every active button as StaleCustomId.\n// @internal\nexport const PAGE_MAX = 1_000_000;\n\n// Discord rejects a message with duplicate custom_ids, and two controls can target the same page (first and\n// prev both hit 0).\n// @internal\nconst SLOT_MAX = 4;\n\n/** Page cursor for a paginator. */\nexport type PageCursor<Prefix extends string> = CustomId<\n Prefix,\n { page: CustomIdField<number>; slot: CustomIdField<number> }\n>;\n\n/** Build the page cursor for a paginator. */\nexport function pageCursor<Prefix extends string>(prefix: Prefix): PageCursor<Prefix> {\n return new CustomId(prefix).int('page', 0, PAGE_MAX).int('slot', 0, SLOT_MAX);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;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