@dereekb/discord 13.38.0 → 13.40.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1928 +0,0 @@
1
- 'use strict';
2
-
3
- var discord_js = require('discord.js');
4
- var common = require('@nestjs/common');
5
- var nestjs = require('@dereekb/nestjs');
6
- var config = require('@nestjs/config');
7
- var discord = require('@dereekb/discord');
8
- var util = require('@dereekb/util');
9
- var node_crypto = require('node:crypto');
10
-
11
- function _type_of(obj) {
12
- "@swc/helpers - typeof";
13
- return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
14
- }
15
- function __decorate(decorators, target, key, desc) {
16
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
17
- if ((typeof Reflect === "undefined" ? "undefined" : _type_of(Reflect)) === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
18
- 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;
19
- return c > 3 && r && Object.defineProperty(target, key, r), r;
20
- }
21
- function __param(paramIndex, decorator) {
22
- return function(target, key) {
23
- decorator(target, key, paramIndex);
24
- };
25
- }
26
- typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
27
- var e = new Error(message);
28
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
29
- };
30
-
31
- function _class_call_check$8(instance, Constructor) {
32
- if (!(instance instanceof Constructor)) {
33
- throw new TypeError("Cannot call a class as a function");
34
- }
35
- }
36
- function _defineProperties$6(target, props) {
37
- for(var i = 0; i < props.length; i++){
38
- var descriptor = props[i];
39
- descriptor.enumerable = descriptor.enumerable || false;
40
- descriptor.configurable = true;
41
- if ("value" in descriptor) descriptor.writable = true;
42
- Object.defineProperty(target, descriptor.key, descriptor);
43
- }
44
- }
45
- function _create_class$6(Constructor, protoProps, staticProps) {
46
- if (staticProps) _defineProperties$6(Constructor, staticProps);
47
- return Constructor;
48
- }
49
- function _define_property$7(obj, key, value) {
50
- if (key in obj) {
51
- Object.defineProperty(obj, key, {
52
- value: value,
53
- enumerable: true,
54
- configurable: true,
55
- writable: true
56
- });
57
- } else {
58
- obj[key] = value;
59
- }
60
- return obj;
61
- }
62
- /**
63
- * Default environment variable for the Discord bot token.
64
- */ var DISCORD_BOT_TOKEN_ENV_VAR = 'DISCORD_BOT_TOKEN';
65
- /**
66
- * Placeholder bot token value used in development and CI environments where a real Discord
67
- * login should not be attempted. Mirrors the value used in the workspace's .env file.
68
- */ var DISCORD_BOT_TOKEN_PLACEHOLDER = 'placeholder';
69
- /**
70
- * Returns true if the input is a real, usable Discord bot token.
71
- *
72
- * A token is usable when it is non-empty and is not the shared placeholder value, allowing
73
- * non-production environments to skip a real gateway login that would always fail.
74
- *
75
- * @param botToken - The bot token read from configuration, if any.
76
- * @returns True when the token should be used to log in.
77
- *
78
- * @example
79
- * ```ts
80
- * isUsableDiscordBotToken('placeholder'); // false
81
- * isUsableDiscordBotToken('real-token'); // true
82
- * ```
83
- */ function isUsableDiscordBotToken(botToken) {
84
- return Boolean(botToken) && botToken !== DISCORD_BOT_TOKEN_PLACEHOLDER;
85
- }
86
- /**
87
- * Default gateway intents for a bot that reads guild messages.
88
- *
89
- * Includes Guilds, GuildMessages, and MessageContent.
90
- * Note: MessageContent is a privileged intent and must be enabled in the Discord Developer Portal.
91
- */ var DEFAULT_DISCORD_INTENTS = [
92
- discord_js.GatewayIntentBits.Guilds,
93
- discord_js.GatewayIntentBits.GuildMessages,
94
- discord_js.GatewayIntentBits.MessageContent
95
- ];
96
- /**
97
- * Configuration for the DiscordApi service.
98
- */ var DiscordServiceConfig = /*#__PURE__*/ function() {
99
- function DiscordServiceConfig() {
100
- _class_call_check$8(this, DiscordServiceConfig);
101
- _define_property$7(this, "discord", void 0);
102
- }
103
- _create_class$6(DiscordServiceConfig, null, [
104
- {
105
- key: "assertValidConfig",
106
- value: function assertValidConfig(config) {
107
- if (!config.discord.botToken) {
108
- throw new Error('No Discord bot token specified.');
109
- }
110
- }
111
- }
112
- ]);
113
- return DiscordServiceConfig;
114
- }
115
- ();
116
-
117
- function asyncGeneratorStep$4(gen, resolve, reject, _next, _throw, key, arg) {
118
- try {
119
- var info = gen[key](arg);
120
- var value = info.value;
121
- } catch (error) {
122
- reject(error);
123
- return;
124
- }
125
- if (info.done) {
126
- resolve(value);
127
- } else {
128
- Promise.resolve(value).then(_next, _throw);
129
- }
130
- }
131
- function _async_to_generator$4(fn) {
132
- return function() {
133
- var self = this, args = arguments;
134
- return new Promise(function(resolve, reject) {
135
- var gen = fn.apply(self, args);
136
- function _next(value) {
137
- asyncGeneratorStep$4(gen, resolve, reject, _next, _throw, "next", value);
138
- }
139
- function _throw(err) {
140
- asyncGeneratorStep$4(gen, resolve, reject, _next, _throw, "throw", err);
141
- }
142
- _next(undefined);
143
- });
144
- };
145
- }
146
- function _class_call_check$7(instance, Constructor) {
147
- if (!(instance instanceof Constructor)) {
148
- throw new TypeError("Cannot call a class as a function");
149
- }
150
- }
151
- function _defineProperties$5(target, props) {
152
- for(var i = 0; i < props.length; i++){
153
- var descriptor = props[i];
154
- descriptor.enumerable = descriptor.enumerable || false;
155
- descriptor.configurable = true;
156
- if ("value" in descriptor) descriptor.writable = true;
157
- Object.defineProperty(target, descriptor.key, descriptor);
158
- }
159
- }
160
- function _create_class$5(Constructor, protoProps, staticProps) {
161
- if (protoProps) _defineProperties$5(Constructor.prototype, protoProps);
162
- return Constructor;
163
- }
164
- function _define_property$6(obj, key, value) {
165
- if (key in obj) {
166
- Object.defineProperty(obj, key, {
167
- value: value,
168
- enumerable: true,
169
- configurable: true,
170
- writable: true
171
- });
172
- } else {
173
- obj[key] = value;
174
- }
175
- return obj;
176
- }
177
- function _instanceof(left, right) {
178
- "@swc/helpers - instanceof";
179
- if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
180
- return !!right[Symbol.hasInstance](left);
181
- } else {
182
- return left instanceof right;
183
- }
184
- }
185
- function _object_spread$2(target) {
186
- for(var i = 1; i < arguments.length; i++){
187
- var source = arguments[i] != null ? arguments[i] : {};
188
- var ownKeys = Object.keys(source);
189
- if (typeof Object.getOwnPropertySymbols === "function") {
190
- ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
191
- return Object.getOwnPropertyDescriptor(source, sym).enumerable;
192
- }));
193
- }
194
- ownKeys.forEach(function(key) {
195
- _define_property$6(target, key, source[key]);
196
- });
197
- }
198
- return target;
199
- }
200
- function _ts_generator$4(thisArg, body) {
201
- var f, y, t, _ = {
202
- label: 0,
203
- sent: function() {
204
- if (t[0] & 1) throw t[1];
205
- return t[1];
206
- },
207
- trys: [],
208
- ops: []
209
- }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
210
- return d(g, "next", {
211
- value: verb(0)
212
- }), d(g, "throw", {
213
- value: verb(1)
214
- }), d(g, "return", {
215
- value: verb(2)
216
- }), typeof Symbol === "function" && d(g, Symbol.iterator, {
217
- value: function() {
218
- return this;
219
- }
220
- }), g;
221
- function verb(n) {
222
- return function(v) {
223
- return step([
224
- n,
225
- v
226
- ]);
227
- };
228
- }
229
- function step(op) {
230
- if (f) throw new TypeError("Generator is already executing.");
231
- while(g && (g = 0, op[0] && (_ = 0)), _)try {
232
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
233
- if (y = 0, t) op = [
234
- op[0] & 2,
235
- t.value
236
- ];
237
- switch(op[0]){
238
- case 0:
239
- case 1:
240
- t = op;
241
- break;
242
- case 4:
243
- _.label++;
244
- return {
245
- value: op[1],
246
- done: false
247
- };
248
- case 5:
249
- _.label++;
250
- y = op[1];
251
- op = [
252
- 0
253
- ];
254
- continue;
255
- case 7:
256
- op = _.ops.pop();
257
- _.trys.pop();
258
- continue;
259
- default:
260
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
261
- _ = 0;
262
- continue;
263
- }
264
- if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
265
- _.label = op[1];
266
- break;
267
- }
268
- if (op[0] === 6 && _.label < t[1]) {
269
- _.label = t[1];
270
- t = op;
271
- break;
272
- }
273
- if (t && _.label < t[2]) {
274
- _.label = t[2];
275
- _.ops.push(op);
276
- break;
277
- }
278
- if (t[2]) _.ops.pop();
279
- _.trys.pop();
280
- continue;
281
- }
282
- op = body.call(thisArg, _);
283
- } catch (e) {
284
- op = [
285
- 6,
286
- e
287
- ];
288
- y = 0;
289
- } finally{
290
- f = t = 0;
291
- }
292
- if (op[0] & 5) throw op[1];
293
- return {
294
- value: op[0] ? op[1] : void 0,
295
- done: true
296
- };
297
- }
298
- }
299
- /**
300
- * Injectable service that wraps the discord.js Client for bot operations.
301
- *
302
- * Automatically logs in on module init and destroys the client on module destroy
303
- * when autoLogin is enabled (default).
304
- */ exports.DiscordApi = /*#__PURE__*/ function() {
305
- function DiscordApi(config) {
306
- _class_call_check$7(this, DiscordApi);
307
- _define_property$6(this, "config", void 0);
308
- _define_property$6(this, "logger", new common.Logger('DiscordApi'));
309
- /**
310
- * The underlying discord.js Client instance.
311
- */ _define_property$6(this, "client", void 0);
312
- this.config = config;
313
- var clientOptions = config.discord.clientOptions;
314
- this.client = new discord_js.Client(_object_spread$2({
315
- intents: DEFAULT_DISCORD_INTENTS
316
- }, clientOptions));
317
- }
318
- _create_class$5(DiscordApi, [
319
- {
320
- key: "onModuleInit",
321
- value: function onModuleInit() {
322
- return _async_to_generator$4(function() {
323
- var _this, _this_config_discord, _this_config_discord_autoLogin, autoLogin, botToken, result;
324
- return _ts_generator$4(this, function(_state) {
325
- _this = this;
326
- _this_config_discord = this.config.discord, _this_config_discord_autoLogin = _this_config_discord.autoLogin, autoLogin = _this_config_discord_autoLogin === void 0 ? true : _this_config_discord_autoLogin, botToken = _this_config_discord.botToken;
327
- if (autoLogin) {
328
- result = this.client.login(botToken).then(function() {
329
- return undefined;
330
- }).catch(function(e) {
331
- _this.logger.error('Failed to log in to Discord', e);
332
- });
333
- } else {
334
- result = Promise.resolve();
335
- }
336
- return [
337
- 2,
338
- result
339
- ];
340
- });
341
- }).call(this);
342
- }
343
- },
344
- {
345
- key: "onModuleDestroy",
346
- value: function onModuleDestroy() {
347
- return _async_to_generator$4(function() {
348
- return _ts_generator$4(this, function(_state) {
349
- return [
350
- 2,
351
- this.client.destroy()
352
- ];
353
- });
354
- }).call(this);
355
- }
356
- },
357
- {
358
- key: "sendMessage",
359
- value: /**
360
- * Sends a text message to a Discord channel.
361
- *
362
- * @param channelId - target channel's snowflake ID
363
- * @param content - message text to send
364
- *
365
- * @throws {Error} When the channel is not found or is not a text channel.
366
- *
367
- * @example
368
- * ```ts
369
- * const message = await discordApi.sendMessage('123456789', 'Hello from the bot!');
370
- * ```
371
- */ /**
372
- * Sends a text message to the specified Discord channel.
373
- *
374
- * @param channelId - Target channel's snowflake ID.
375
- * @param content - Message text to send.
376
- * @returns The sent Discord Message.
377
- * @throws {Error} When the channel is not found or is not a text channel.
378
- */ function sendMessage(channelId, content) {
379
- return _async_to_generator$4(function() {
380
- var channel;
381
- return _ts_generator$4(this, function(_state) {
382
- switch(_state.label){
383
- case 0:
384
- return [
385
- 4,
386
- this.client.channels.fetch(channelId)
387
- ];
388
- case 1:
389
- channel = _state.sent();
390
- if (!channel || !_instanceof(channel, discord_js.TextChannel)) {
391
- throw new Error("Channel ".concat(channelId, " not found or is not a text channel."));
392
- }
393
- return [
394
- 2,
395
- channel.send(content)
396
- ];
397
- }
398
- });
399
- }).call(this);
400
- }
401
- },
402
- {
403
- /**
404
- * Registers a handler for the MessageCreate event (incoming messages).
405
- *
406
- * Returns an unsubscribe function to remove the handler.
407
- *
408
- * @param handler - callback invoked for each incoming message
409
- *
410
- * @example
411
- * ```ts
412
- * const unsubscribe = discordApi.onMessage((message) => {
413
- * if (!message.author.bot) {
414
- * console.log(`${message.author.tag}: ${message.content}`);
415
- * }
416
- * });
417
- *
418
- * // Later, to stop listening:
419
- * unsubscribe();
420
- * ```
421
- */ /**
422
- * Registers a handler for incoming Discord messages (MessageCreate event).
423
- *
424
- * @param handler - Callback invoked for each incoming Message.
425
- * @returns An unsubscribe function that removes the registered handler.
426
- */ key: "onMessage",
427
- value: function onMessage(handler) {
428
- var _this = this;
429
- this.client.on(discord_js.Events.MessageCreate, handler);
430
- return function() {
431
- return _this.client.off(discord_js.Events.MessageCreate, handler);
432
- };
433
- }
434
- }
435
- ]);
436
- return DiscordApi;
437
- }();
438
- exports.DiscordApi = __decorate([
439
- common.Injectable(),
440
- __param(0, common.Inject(DiscordServiceConfig))
441
- ], exports.DiscordApi);
442
-
443
- function _class_call_check$6(instance, Constructor) {
444
- if (!(instance instanceof Constructor)) {
445
- throw new TypeError("Cannot call a class as a function");
446
- }
447
- }
448
- /**
449
- * Factory that creates a DiscordServiceConfig from environment variables.
450
- *
451
- * autoLogin is enabled only when a real bot token is configured and the process is not running
452
- * under a test environment, so development and CI runs (which use a placeholder token) never
453
- * attempt a real gateway login that would fail.
454
- *
455
- * @param configService - The NestJS config service used to read Discord environment variables.
456
- * @returns A validated DiscordServiceConfig populated from environment variables.
457
- */ function discordServiceConfigFactory(configService) {
458
- var botToken = configService.get(DISCORD_BOT_TOKEN_ENV_VAR);
459
- var config = {
460
- discord: {
461
- botToken: botToken,
462
- autoLogin: isUsableDiscordBotToken(botToken) && !nestjs.isTestNodeEnv()
463
- }
464
- };
465
- DiscordServiceConfig.assertValidConfig(config);
466
- return config;
467
- }
468
- /**
469
- * NestJS module that provides the DiscordApi service.
470
- *
471
- * Reads the bot token from the DISCORD_BOT_TOKEN environment variable.
472
- */ exports.DiscordModule = function DiscordModule() {
473
- _class_call_check$6(this, DiscordModule);
474
- };
475
- exports.DiscordModule = __decorate([
476
- common.Module({
477
- imports: [
478
- config.ConfigModule
479
- ],
480
- providers: [
481
- {
482
- provide: DiscordServiceConfig,
483
- inject: [
484
- config.ConfigService
485
- ],
486
- useFactory: discordServiceConfigFactory
487
- },
488
- exports.DiscordApi
489
- ],
490
- exports: [
491
- exports.DiscordApi
492
- ]
493
- })
494
- ], exports.DiscordModule);
495
-
496
- function _array_like_to_array$1(arr, len) {
497
- if (len == null || len > arr.length) len = arr.length;
498
- for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
499
- return arr2;
500
- }
501
- function _array_without_holes$1(arr) {
502
- if (Array.isArray(arr)) return _array_like_to_array$1(arr);
503
- }
504
- function _iterable_to_array$1(iter) {
505
- if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
506
- }
507
- function _non_iterable_spread$1() {
508
- throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
509
- }
510
- function _to_consumable_array$1(arr) {
511
- return _array_without_holes$1(arr) || _iterable_to_array$1(arr) || _unsupported_iterable_to_array$1(arr) || _non_iterable_spread$1();
512
- }
513
- function _unsupported_iterable_to_array$1(o, minLen) {
514
- if (!o) return;
515
- if (typeof o === "string") return _array_like_to_array$1(o, minLen);
516
- var n = Object.prototype.toString.call(o).slice(8, -1);
517
- if (n === "Object" && o.constructor) n = o.constructor.name;
518
- if (n === "Map" || n === "Set") return Array.from(n);
519
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array$1(o, minLen);
520
- }
521
- /**
522
- * Returns default ClientOptions for a bot that reads guild messages.
523
- *
524
- * Includes Guilds, GuildMessages, and MessageContent intents.
525
- *
526
- * @returns Partial ClientOptions with the default bot intents set.
527
- *
528
- * @example
529
- * ```ts
530
- * const options = discordDefaultClientOptions();
531
- * // options.intents === [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent]
532
- * ```
533
- */ function discordDefaultClientOptions() {
534
- return {
535
- intents: DEFAULT_DISCORD_INTENTS
536
- };
537
- }
538
- /**
539
- * Returns ClientOptions with additional intents merged with the defaults.
540
- *
541
- * @param additionalIntents - Extra intents to include beyond the defaults.
542
- * @returns Partial ClientOptions with the merged intent list.
543
- *
544
- * @example
545
- * ```ts
546
- * const options = discordClientOptionsWithIntents([GatewayIntentBits.DirectMessages]);
547
- * // options.intents includes Guilds, GuildMessages, MessageContent, and DirectMessages
548
- * ```
549
- */ function discordClientOptionsWithIntents(additionalIntents) {
550
- return {
551
- intents: _to_consumable_array$1(DEFAULT_DISCORD_INTENTS).concat(_to_consumable_array$1(additionalIntents))
552
- };
553
- }
554
-
555
- function _class_call_check$5(instance, Constructor) {
556
- if (!(instance instanceof Constructor)) {
557
- throw new TypeError("Cannot call a class as a function");
558
- }
559
- }
560
- function _defineProperties$4(target, props) {
561
- for(var i = 0; i < props.length; i++){
562
- var descriptor = props[i];
563
- descriptor.enumerable = descriptor.enumerable || false;
564
- descriptor.configurable = true;
565
- if ("value" in descriptor) descriptor.writable = true;
566
- Object.defineProperty(target, descriptor.key, descriptor);
567
- }
568
- }
569
- function _create_class$4(Constructor, protoProps, staticProps) {
570
- if (staticProps) _defineProperties$4(Constructor, staticProps);
571
- return Constructor;
572
- }
573
- function _define_property$5(obj, key, value) {
574
- if (key in obj) {
575
- Object.defineProperty(obj, key, {
576
- value: value,
577
- enumerable: true,
578
- configurable: true,
579
- writable: true
580
- });
581
- } else {
582
- obj[key] = value;
583
- }
584
- return obj;
585
- }
586
- var DISCORD_SERVICE_NAME = 'discord';
587
- var DISCORD_CLIENT_ID_CONFIG_KEY = 'DISCORD_CLIENT_ID';
588
- var DISCORD_CLIENT_SECRET_CONFIG_KEY = 'DISCORD_CLIENT_SECRET';
589
- /**
590
- * Configuration for the {@link DiscordOAuthApi}.
591
- *
592
- * Carries no server-level token or access-token cache, unlike `CalcomOAuthServiceConfig`: Discord has
593
- * no api-key alternative to the client-credentials pair, and the app acting as *itself* against
594
- * Discord authenticates with a bot token through `DiscordServiceConfig` and discord.js instead. This
595
- * config only ever describes the OAuth client that performs the per-user authorization-code handoff.
596
- */ var DiscordOAuthServiceConfig = /*#__PURE__*/ function() {
597
- function DiscordOAuthServiceConfig() {
598
- _class_call_check$5(this, DiscordOAuthServiceConfig);
599
- _define_property$5(this, "discordOAuth", void 0);
600
- /**
601
- * Optional configuration for the Discord OAuth client the api builds — a custom fetch handler or
602
- * error logger.
603
- */ _define_property$5(this, "factoryConfig", void 0);
604
- }
605
- _create_class$4(DiscordOAuthServiceConfig, null, [
606
- {
607
- key: "assertValidConfig",
608
- value: function assertValidConfig(config) {
609
- var discordOAuth = config.discordOAuth;
610
- if (!discordOAuth) {
611
- throw new Error('DiscordOAuthServiceConfig.discordOAuth is required');
612
- } else if (!discordOAuth.clientId) {
613
- throw new Error("DiscordOAuthServiceConfig requires a Discord OAuth client id (".concat(DISCORD_CLIENT_ID_CONFIG_KEY, ")."));
614
- } else if (!discordOAuth.clientSecret) {
615
- throw new Error("DiscordOAuthServiceConfig requires a Discord OAuth client secret (".concat(DISCORD_CLIENT_SECRET_CONFIG_KEY, ")."));
616
- }
617
- }
618
- },
619
- {
620
- key: "assertedDiscordOAuthConfig",
621
- value: /**
622
- * Narrows the environment-facing config to the fully-populated {@link DiscordOAuthConfig} the core
623
- * factory requires, asserting both credentials are present.
624
- *
625
- * @param config - The service configuration to read.
626
- * @returns The validated OAuth client configuration.
627
- * @throws {Error} When either client credential is missing.
628
- */ function assertedDiscordOAuthConfig(config) {
629
- DiscordOAuthServiceConfig.assertValidConfig(config);
630
- var _config_discordOAuth = config.discordOAuth, clientId = _config_discordOAuth.clientId, clientSecret = _config_discordOAuth.clientSecret;
631
- return {
632
- clientId: clientId,
633
- clientSecret: clientSecret
634
- };
635
- }
636
- }
637
- ]);
638
- return DiscordOAuthServiceConfig;
639
- }();
640
- /**
641
- * Factory function that creates a {@link DiscordOAuthServiceConfig} from NestJS ConfigService
642
- * environment variables.
643
- *
644
- * Fails at startup rather than at the consent screen: a missing client id otherwise composes an
645
- * authorize URL carrying `client_id=undefined`, and a missing secret fails the exchange only after the
646
- * user has already consented.
647
- *
648
- * @param configService - The NestJS ConfigService instance.
649
- * @returns A validated DiscordOAuthServiceConfig.
650
- * @throws {Error} When either client credential is missing.
651
- */ function discordOAuthServiceConfigFactory(configService) {
652
- var clientId = configService.get(DISCORD_CLIENT_ID_CONFIG_KEY);
653
- var clientSecret = configService.get(DISCORD_CLIENT_SECRET_CONFIG_KEY);
654
- var config = {
655
- discordOAuth: {
656
- clientId: clientId || undefined,
657
- clientSecret: clientSecret || undefined
658
- }
659
- };
660
- DiscordOAuthServiceConfig.assertValidConfig(config);
661
- return config;
662
- }
663
-
664
- function asyncGeneratorStep$3(gen, resolve, reject, _next, _throw, key, arg) {
665
- try {
666
- var info = gen[key](arg);
667
- var value = info.value;
668
- } catch (error) {
669
- reject(error);
670
- return;
671
- }
672
- if (info.done) {
673
- resolve(value);
674
- } else {
675
- Promise.resolve(value).then(_next, _throw);
676
- }
677
- }
678
- function _async_to_generator$3(fn) {
679
- return function() {
680
- var self = this, args = arguments;
681
- return new Promise(function(resolve, reject) {
682
- var gen = fn.apply(self, args);
683
- function _next(value) {
684
- asyncGeneratorStep$3(gen, resolve, reject, _next, _throw, "next", value);
685
- }
686
- function _throw(err) {
687
- asyncGeneratorStep$3(gen, resolve, reject, _next, _throw, "throw", err);
688
- }
689
- _next(undefined);
690
- });
691
- };
692
- }
693
- function _class_call_check$4(instance, Constructor) {
694
- if (!(instance instanceof Constructor)) {
695
- throw new TypeError("Cannot call a class as a function");
696
- }
697
- }
698
- function _defineProperties$3(target, props) {
699
- for(var i = 0; i < props.length; i++){
700
- var descriptor = props[i];
701
- descriptor.enumerable = descriptor.enumerable || false;
702
- descriptor.configurable = true;
703
- if ("value" in descriptor) descriptor.writable = true;
704
- Object.defineProperty(target, descriptor.key, descriptor);
705
- }
706
- }
707
- function _create_class$3(Constructor, protoProps, staticProps) {
708
- if (protoProps) _defineProperties$3(Constructor.prototype, protoProps);
709
- return Constructor;
710
- }
711
- function _define_property$4(obj, key, value) {
712
- if (key in obj) {
713
- Object.defineProperty(obj, key, {
714
- value: value,
715
- enumerable: true,
716
- configurable: true,
717
- writable: true
718
- });
719
- } else {
720
- obj[key] = value;
721
- }
722
- return obj;
723
- }
724
- function _object_spread$1(target) {
725
- for(var i = 1; i < arguments.length; i++){
726
- var source = arguments[i] != null ? arguments[i] : {};
727
- var ownKeys = Object.keys(source);
728
- if (typeof Object.getOwnPropertySymbols === "function") {
729
- ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
730
- return Object.getOwnPropertyDescriptor(source, sym).enumerable;
731
- }));
732
- }
733
- ownKeys.forEach(function(key) {
734
- _define_property$4(target, key, source[key]);
735
- });
736
- }
737
- return target;
738
- }
739
- function ownKeys$1(object, enumerableOnly) {
740
- var keys = Object.keys(object);
741
- if (Object.getOwnPropertySymbols) {
742
- var symbols = Object.getOwnPropertySymbols(object);
743
- keys.push.apply(keys, symbols);
744
- }
745
- return keys;
746
- }
747
- function _object_spread_props$1(target, source) {
748
- source = source != null ? source : {};
749
- if (Object.getOwnPropertyDescriptors) {
750
- Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
751
- } else {
752
- ownKeys$1(Object(source)).forEach(function(key) {
753
- Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
754
- });
755
- }
756
- return target;
757
- }
758
- function _ts_generator$3(thisArg, body) {
759
- var f, y, t, _ = {
760
- label: 0,
761
- sent: function() {
762
- if (t[0] & 1) throw t[1];
763
- return t[1];
764
- },
765
- trys: [],
766
- ops: []
767
- }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
768
- return d(g, "next", {
769
- value: verb(0)
770
- }), d(g, "throw", {
771
- value: verb(1)
772
- }), d(g, "return", {
773
- value: verb(2)
774
- }), typeof Symbol === "function" && d(g, Symbol.iterator, {
775
- value: function() {
776
- return this;
777
- }
778
- }), g;
779
- function verb(n) {
780
- return function(v) {
781
- return step([
782
- n,
783
- v
784
- ]);
785
- };
786
- }
787
- function step(op) {
788
- if (f) throw new TypeError("Generator is already executing.");
789
- while(g && (g = 0, op[0] && (_ = 0)), _)try {
790
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
791
- if (y = 0, t) op = [
792
- op[0] & 2,
793
- t.value
794
- ];
795
- switch(op[0]){
796
- case 0:
797
- case 1:
798
- t = op;
799
- break;
800
- case 4:
801
- _.label++;
802
- return {
803
- value: op[1],
804
- done: false
805
- };
806
- case 5:
807
- _.label++;
808
- y = op[1];
809
- op = [
810
- 0
811
- ];
812
- continue;
813
- case 7:
814
- op = _.ops.pop();
815
- _.trys.pop();
816
- continue;
817
- default:
818
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
819
- _ = 0;
820
- continue;
821
- }
822
- if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
823
- _.label = op[1];
824
- break;
825
- }
826
- if (op[0] === 6 && _.label < t[1]) {
827
- _.label = t[1];
828
- t = op;
829
- break;
830
- }
831
- if (t && _.label < t[2]) {
832
- _.label = t[2];
833
- _.ops.push(op);
834
- break;
835
- }
836
- if (t[2]) _.ops.pop();
837
- _.trys.pop();
838
- continue;
839
- }
840
- op = body.call(thisArg, _);
841
- } catch (e) {
842
- op = [
843
- 6,
844
- e
845
- ];
846
- y = 0;
847
- } finally{
848
- f = t = 0;
849
- }
850
- if (op[0] & 5) throw op[1];
851
- return {
852
- value: op[0] ? op[1] : void 0,
853
- done: true
854
- };
855
- }
856
- }
857
- /**
858
- * Provides the app's configured Discord OAuth client.
859
- *
860
- * Deliberately thinner than `CalcomOAuthApi`, which owns an access-token cache service and memoizes a
861
- * token factory per user. Discord needs neither: the external-connection framework persists each
862
- * user's credentials itself, so this api holds one client authenticated with the *application's*
863
- * credentials and hands out the three calls that run through it.
864
- *
865
- * Note this is not the bot. The app acting as itself against Discord goes through `DiscordApi` and
866
- * discord.js with a bot token; that token never reaches this client.
867
- */ exports.DiscordOAuthApi = /*#__PURE__*/ function() {
868
- function DiscordOAuthApi(config) {
869
- _class_call_check$4(this, DiscordOAuthApi);
870
- var _config_factoryConfig;
871
- _define_property$4(this, "config", void 0);
872
- _define_property$4(this, "discordOAuth", void 0);
873
- this.config = config;
874
- // asserted here rather than trusted: the config's credentials are optional to mirror the DISCORD_*
875
- // variables they are read from, while the core factory requires both
876
- var discordOAuthConfig = DiscordOAuthServiceConfig.assertedDiscordOAuthConfig(config);
877
- this.discordOAuth = discord.discordOAuthFactory((_config_factoryConfig = config.factoryConfig) !== null && _config_factoryConfig !== void 0 ? _config_factoryConfig : {})(discordOAuthConfig);
878
- }
879
- _create_class$3(DiscordOAuthApi, [
880
- {
881
- key: "oauthContext",
882
- get: function get() {
883
- return this.discordOAuth.oauthContext;
884
- }
885
- },
886
- {
887
- key: "clientId",
888
- get: /**
889
- * The OAuth client id the api authorizes as. Read from the context so there is a single source.
890
- *
891
- * @returns The configured Discord OAuth client id.
892
- */ function get() {
893
- return this.oauthContext.config.clientId;
894
- }
895
- },
896
- {
897
- key: "exchangeAuthorizationCode",
898
- get: // MARK: Accessors
899
- /**
900
- * Configured pass-through for {@link exchangeAuthorizationCode}.
901
- *
902
- * @returns Function to exchange an OAuth authorization code for tokens.
903
- */ function get() {
904
- return discord.exchangeAuthorizationCode(this.oauthContext);
905
- }
906
- },
907
- {
908
- key: "refreshAccessToken",
909
- get: /**
910
- * Configured pass-through for {@link refreshAccessToken}.
911
- *
912
- * @returns Function to refresh an access token using a stored refresh token.
913
- */ function get() {
914
- return discord.refreshAccessToken(this.oauthContext);
915
- }
916
- },
917
- {
918
- key: "readCurrentUser",
919
- get: /**
920
- * Configured pass-through for {@link readCurrentUser}.
921
- *
922
- * Bearer-authenticated with the user's own access token, unlike the two token-endpoint calls above,
923
- * which authenticate with the application's Basic credentials.
924
- *
925
- * @returns Function to read the Discord user an access token belongs to.
926
- */ function get() {
927
- return discord.readCurrentUser(this.oauthContext);
928
- }
929
- },
930
- {
931
- /**
932
- * Builds a {@link DiscordOAuthAuthorizeUrlFactory} for the app's client id.
933
- *
934
- * The redirect URI and scopes stay the caller's, since they are properties of the flow being
935
- * mounted rather than of the client, but the client id comes from this api so a caller never has to
936
- * read it out of the config itself.
937
- *
938
- * @param config - The redirect URI, requested scopes, and optional authorize URL override.
939
- * @returns A factory composing the authorize URL to redirect a user's browser to.
940
- */ key: "authorizeUrlFactory",
941
- value: function authorizeUrlFactory(config) {
942
- return discord.discordOAuthAuthorizeUrlFactory(_object_spread_props$1(_object_spread$1({}, config), {
943
- clientId: this.clientId
944
- }));
945
- }
946
- },
947
- {
948
- key: "exchangeAuthorizationCodeToAccessToken",
949
- value: /**
950
- * Exchanges an OAuth authorization code and maps the response to a {@link DiscordAccessToken}.
951
- *
952
- * @param input - The authorization code and the exact redirect URI it was issued for.
953
- * @returns The exchanged access token.
954
- */ function exchangeAuthorizationCodeToAccessToken(input) {
955
- return _async_to_generator$3(function() {
956
- var response;
957
- return _ts_generator$3(this, function(_state) {
958
- switch(_state.label){
959
- case 0:
960
- return [
961
- 4,
962
- this.exchangeAuthorizationCode(input)
963
- ];
964
- case 1:
965
- response = _state.sent();
966
- return [
967
- 2,
968
- discord.discordAccessTokenFromTokenResponse(response)
969
- ];
970
- }
971
- });
972
- }).call(this);
973
- }
974
- },
975
- {
976
- key: "refreshToAccessToken",
977
- value: /**
978
- * Refreshes an access token and maps the response to a {@link DiscordAccessToken}.
979
- *
980
- * The returned `refreshToken` is the one to persist: Discord's refresh responses carry a refresh
981
- * token of their own, so storing whatever came back is correct whether or not it rotated.
982
- *
983
- * @param input - The stored refresh token.
984
- * @returns The refreshed access token.
985
- */ function refreshToAccessToken(input) {
986
- return _async_to_generator$3(function() {
987
- var response;
988
- return _ts_generator$3(this, function(_state) {
989
- switch(_state.label){
990
- case 0:
991
- return [
992
- 4,
993
- this.refreshAccessToken(input)
994
- ];
995
- case 1:
996
- response = _state.sent();
997
- return [
998
- 2,
999
- discord.discordAccessTokenFromTokenResponse(response)
1000
- ];
1001
- }
1002
- });
1003
- }).call(this);
1004
- }
1005
- }
1006
- ]);
1007
- return DiscordOAuthApi;
1008
- }();
1009
- exports.DiscordOAuthApi = __decorate([
1010
- common.Injectable(),
1011
- __param(0, common.Inject(DiscordOAuthServiceConfig))
1012
- ], exports.DiscordOAuthApi);
1013
-
1014
- function _array_like_to_array(arr, len) {
1015
- if (len == null || len > arr.length) len = arr.length;
1016
- for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
1017
- return arr2;
1018
- }
1019
- function _array_without_holes(arr) {
1020
- if (Array.isArray(arr)) return _array_like_to_array(arr);
1021
- }
1022
- function _iterable_to_array(iter) {
1023
- if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
1024
- }
1025
- function _non_iterable_spread() {
1026
- throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
1027
- }
1028
- function _to_consumable_array(arr) {
1029
- return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread();
1030
- }
1031
- function _unsupported_iterable_to_array(o, minLen) {
1032
- if (!o) return;
1033
- if (typeof o === "string") return _array_like_to_array(o, minLen);
1034
- var n = Object.prototype.toString.call(o).slice(8, -1);
1035
- if (n === "Object" && o.constructor) n = o.constructor.name;
1036
- if (n === "Map" || n === "Set") return Array.from(n);
1037
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
1038
- }
1039
- /**
1040
- * Convenience function used to generate ModuleMetadata for an app's DiscordOAuthModule.
1041
- *
1042
- * Takes no `dependencyModule`, unlike the Cal.com equivalent: {@link DiscordOAuthApi} depends only on
1043
- * its own config, since Discord's connect flow needs no access-token cache service.
1044
- *
1045
- * @param config - The module metadata configuration including an optional config factory.
1046
- * @returns NestJS ModuleMetadata for registering the DiscordOAuthModule.
1047
- */ function appDiscordOAuthModuleMetadata(config$1) {
1048
- var _config_discordOAuthServiceConfigFactory;
1049
- var imports = config$1.imports, exports$1 = config$1.exports, providers = config$1.providers;
1050
- return {
1051
- imports: [
1052
- config.ConfigModule
1053
- ].concat(_to_consumable_array(imports !== null && imports !== void 0 ? imports : [])),
1054
- exports: [
1055
- exports.DiscordOAuthApi
1056
- ].concat(_to_consumable_array(exports$1 !== null && exports$1 !== void 0 ? exports$1 : [])),
1057
- providers: [
1058
- {
1059
- provide: DiscordOAuthServiceConfig,
1060
- inject: [
1061
- config.ConfigService
1062
- ],
1063
- useFactory: (_config_discordOAuthServiceConfigFactory = config$1.discordOAuthServiceConfigFactory) !== null && _config_discordOAuthServiceConfigFactory !== void 0 ? _config_discordOAuthServiceConfigFactory : discordOAuthServiceConfigFactory
1064
- },
1065
- exports.DiscordOAuthApi
1066
- ].concat(_to_consumable_array(providers !== null && providers !== void 0 ? providers : []))
1067
- };
1068
- }
1069
-
1070
- function _define_property$3(obj, key, value) {
1071
- if (key in obj) {
1072
- Object.defineProperty(obj, key, {
1073
- value: value,
1074
- enumerable: true,
1075
- configurable: true,
1076
- writable: true
1077
- });
1078
- } else {
1079
- obj[key] = value;
1080
- }
1081
- return obj;
1082
- }
1083
- function _object_spread(target) {
1084
- for(var i = 1; i < arguments.length; i++){
1085
- var source = arguments[i] != null ? arguments[i] : {};
1086
- var ownKeys = Object.keys(source);
1087
- if (typeof Object.getOwnPropertySymbols === "function") {
1088
- ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
1089
- return Object.getOwnPropertyDescriptor(source, sym).enumerable;
1090
- }));
1091
- }
1092
- ownKeys.forEach(function(key) {
1093
- _define_property$3(target, key, source[key]);
1094
- });
1095
- }
1096
- return target;
1097
- }
1098
- function ownKeys(object, enumerableOnly) {
1099
- var keys = Object.keys(object);
1100
- if (Object.getOwnPropertySymbols) {
1101
- var symbols = Object.getOwnPropertySymbols(object);
1102
- keys.push.apply(keys, symbols);
1103
- }
1104
- return keys;
1105
- }
1106
- function _object_spread_props(target, source) {
1107
- source = source != null ? source : {};
1108
- if (Object.getOwnPropertyDescriptors) {
1109
- Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
1110
- } else {
1111
- ownKeys(Object(source)).forEach(function(key) {
1112
- Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
1113
- });
1114
- }
1115
- return target;
1116
- }
1117
- /**
1118
- * Casts an untyped Discord interaction to a typed one.
1119
- *
1120
- * @param interaction - The raw interaction to cast.
1121
- * @returns The interaction cast to the specified typed DiscordWebhookInteraction.
1122
- */ function discordWebhookInteraction(interaction) {
1123
- return interaction;
1124
- }
1125
- var discordInteractionHandlerFactory = util.handlerFactory(function(x) {
1126
- return x.type;
1127
- });
1128
- var discordInteractionHandlerConfigurerFactory = util.handlerConfigurerFactory({
1129
- configurerForAccessor: function configurerForAccessor(accessor) {
1130
- var fnWithKey = util.handlerMappedSetFunctionFactory(accessor, discordWebhookInteraction);
1131
- var configurer = _object_spread_props(_object_spread({}, accessor), {
1132
- handleApplicationCommand: fnWithKey(discord_js.InteractionType.ApplicationCommand),
1133
- handleMessageComponent: fnWithKey(discord_js.InteractionType.MessageComponent),
1134
- handleModalSubmit: fnWithKey(discord_js.InteractionType.ModalSubmit),
1135
- handleAutocomplete: fnWithKey(discord_js.InteractionType.ApplicationCommandAutocomplete)
1136
- });
1137
- return configurer;
1138
- }
1139
- });
1140
-
1141
- function _class_call_check$3(instance, Constructor) {
1142
- if (!(instance instanceof Constructor)) {
1143
- throw new TypeError("Cannot call a class as a function");
1144
- }
1145
- }
1146
- function _defineProperties$2(target, props) {
1147
- for(var i = 0; i < props.length; i++){
1148
- var descriptor = props[i];
1149
- descriptor.enumerable = descriptor.enumerable || false;
1150
- descriptor.configurable = true;
1151
- if ("value" in descriptor) descriptor.writable = true;
1152
- Object.defineProperty(target, descriptor.key, descriptor);
1153
- }
1154
- }
1155
- function _create_class$2(Constructor, protoProps, staticProps) {
1156
- if (staticProps) _defineProperties$2(Constructor, staticProps);
1157
- return Constructor;
1158
- }
1159
- function _define_property$2(obj, key, value) {
1160
- if (key in obj) {
1161
- Object.defineProperty(obj, key, {
1162
- value: value,
1163
- enumerable: true,
1164
- configurable: true,
1165
- writable: true
1166
- });
1167
- } else {
1168
- obj[key] = value;
1169
- }
1170
- return obj;
1171
- }
1172
- /**
1173
- * Default environment variable for the Discord application public key.
1174
- */ var DISCORD_PUBLIC_KEY_ENV_VAR = 'DISCORD_PUBLIC_KEY';
1175
- /**
1176
- * The byte length of a Discord Ed25519 public key (32 bytes = 64 hex characters).
1177
- */ var DISCORD_ED25519_PUBLIC_KEY_BYTE_LENGTH = 32;
1178
- /**
1179
- * Configuration for the DiscordWebhookService.
1180
- */ var DiscordWebhookServiceConfig = /*#__PURE__*/ function() {
1181
- function DiscordWebhookServiceConfig() {
1182
- _class_call_check$3(this, DiscordWebhookServiceConfig);
1183
- _define_property$2(this, "discordWebhook", void 0);
1184
- }
1185
- _create_class$2(DiscordWebhookServiceConfig, null, [
1186
- {
1187
- key: "assertValidConfig",
1188
- value: function assertValidConfig(config) {
1189
- var publicKey = config.discordWebhook.publicKey;
1190
- if (!publicKey) {
1191
- throw new Error('No Discord public key specified.');
1192
- }
1193
- if (!util.isHexWithByteLength(publicKey, {
1194
- byteLength: DISCORD_ED25519_PUBLIC_KEY_BYTE_LENGTH
1195
- })) {
1196
- throw new Error('Discord public key is not available or is invalid. Expected a 64-character hex string (32-byte Ed25519 key).');
1197
- }
1198
- }
1199
- }
1200
- ]);
1201
- return DiscordWebhookServiceConfig;
1202
- }
1203
- ();
1204
-
1205
- function asyncGeneratorStep$2(gen, resolve, reject, _next, _throw, key, arg) {
1206
- try {
1207
- var info = gen[key](arg);
1208
- var value = info.value;
1209
- } catch (error) {
1210
- reject(error);
1211
- return;
1212
- }
1213
- if (info.done) {
1214
- resolve(value);
1215
- } else {
1216
- Promise.resolve(value).then(_next, _throw);
1217
- }
1218
- }
1219
- function _async_to_generator$2(fn) {
1220
- return function() {
1221
- var self = this, args = arguments;
1222
- return new Promise(function(resolve, reject) {
1223
- var gen = fn.apply(self, args);
1224
- function _next(value) {
1225
- asyncGeneratorStep$2(gen, resolve, reject, _next, _throw, "next", value);
1226
- }
1227
- function _throw(err) {
1228
- asyncGeneratorStep$2(gen, resolve, reject, _next, _throw, "throw", err);
1229
- }
1230
- _next(undefined);
1231
- });
1232
- };
1233
- }
1234
- function _ts_generator$2(thisArg, body) {
1235
- var f, y, t, _ = {
1236
- label: 0,
1237
- sent: function() {
1238
- if (t[0] & 1) throw t[1];
1239
- return t[1];
1240
- },
1241
- trys: [],
1242
- ops: []
1243
- }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
1244
- return d(g, "next", {
1245
- value: verb(0)
1246
- }), d(g, "throw", {
1247
- value: verb(1)
1248
- }), d(g, "return", {
1249
- value: verb(2)
1250
- }), typeof Symbol === "function" && d(g, Symbol.iterator, {
1251
- value: function() {
1252
- return this;
1253
- }
1254
- }), g;
1255
- function verb(n) {
1256
- return function(v) {
1257
- return step([
1258
- n,
1259
- v
1260
- ]);
1261
- };
1262
- }
1263
- function step(op) {
1264
- if (f) throw new TypeError("Generator is already executing.");
1265
- while(g && (g = 0, op[0] && (_ = 0)), _)try {
1266
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
1267
- if (y = 0, t) op = [
1268
- op[0] & 2,
1269
- t.value
1270
- ];
1271
- switch(op[0]){
1272
- case 0:
1273
- case 1:
1274
- t = op;
1275
- break;
1276
- case 4:
1277
- _.label++;
1278
- return {
1279
- value: op[1],
1280
- done: false
1281
- };
1282
- case 5:
1283
- _.label++;
1284
- y = op[1];
1285
- op = [
1286
- 0
1287
- ];
1288
- continue;
1289
- case 7:
1290
- op = _.ops.pop();
1291
- _.trys.pop();
1292
- continue;
1293
- default:
1294
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
1295
- _ = 0;
1296
- continue;
1297
- }
1298
- if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
1299
- _.label = op[1];
1300
- break;
1301
- }
1302
- if (op[0] === 6 && _.label < t[1]) {
1303
- _.label = t[1];
1304
- t = op;
1305
- break;
1306
- }
1307
- if (t && _.label < t[2]) {
1308
- _.label = t[2];
1309
- _.ops.push(op);
1310
- break;
1311
- }
1312
- if (t[2]) _.ops.pop();
1313
- _.trys.pop();
1314
- continue;
1315
- }
1316
- op = body.call(thisArg, _);
1317
- } catch (e) {
1318
- op = [
1319
- 6,
1320
- e
1321
- ];
1322
- y = 0;
1323
- } finally{
1324
- f = t = 0;
1325
- }
1326
- if (op[0] & 5) throw op[1];
1327
- return {
1328
- value: op[0] ? op[1] : void 0,
1329
- done: true
1330
- };
1331
- }
1332
- }
1333
- /**
1334
- * Creates a verifier for Discord interaction webhook requests.
1335
- *
1336
- * Discord signs interaction webhook requests with Ed25519. The signed message is
1337
- * the concatenation of the x-signature-timestamp header and the raw request body.
1338
- * The signature is provided in the x-signature-ed25519 header as a hex string.
1339
- *
1340
- * Uses Node.js built-in crypto with JWK key import — no external dependencies required.
1341
- *
1342
- * @param config - Verification config containing the application's public key.
1343
- * @returns A DiscordWebhookEventVerifier function that validates Ed25519-signed requests.
1344
- *
1345
- * @example
1346
- * ```ts
1347
- * const verifier = discordWebhookEventVerifier({ publicKey: 'your-hex-public-key' });
1348
- * const result = await verifier(req, rawBody);
1349
- *
1350
- * if (result.valid) {
1351
- * // result.body contains the parsed interaction
1352
- * }
1353
- * ```
1354
- */ function discordWebhookEventVerifier(config) {
1355
- var publicKeyHex = config.publicKey;
1356
- // Import the raw 32-byte Ed25519 public key via JWK format.
1357
- var publicKey = node_crypto.createPublicKey({
1358
- key: {
1359
- kty: 'OKP',
1360
- crv: 'Ed25519',
1361
- x: Buffer.from(publicKeyHex, 'hex').toString('base64url')
1362
- },
1363
- format: 'jwk'
1364
- });
1365
- return function(request, rawBody) {
1366
- return _async_to_generator$2(function() {
1367
- var signature, timestamp, result, message, signatureBuffer, valid, body;
1368
- return _ts_generator$2(this, function(_state) {
1369
- signature = request.headers['x-signature-ed25519'];
1370
- timestamp = request.headers['x-signature-timestamp'];
1371
- if (!signature || !timestamp) {
1372
- result = {
1373
- valid: false
1374
- };
1375
- } else {
1376
- message = Buffer.concat([
1377
- Buffer.from(timestamp),
1378
- rawBody
1379
- ]);
1380
- signatureBuffer = Buffer.from(signature, 'hex');
1381
- valid = false;
1382
- try {
1383
- valid = node_crypto.verify(null, message, publicKey, signatureBuffer);
1384
- } catch (unused) {
1385
- valid = false;
1386
- }
1387
- if (valid) {
1388
- body = JSON.parse(rawBody.toString('utf-8'));
1389
- result = {
1390
- valid: true,
1391
- body: body
1392
- };
1393
- } else {
1394
- result = {
1395
- valid: false
1396
- };
1397
- }
1398
- }
1399
- return [
1400
- 2,
1401
- result
1402
- ];
1403
- });
1404
- })();
1405
- };
1406
- }
1407
-
1408
- function asyncGeneratorStep$1(gen, resolve, reject, _next, _throw, key, arg) {
1409
- try {
1410
- var info = gen[key](arg);
1411
- var value = info.value;
1412
- } catch (error) {
1413
- reject(error);
1414
- return;
1415
- }
1416
- if (info.done) {
1417
- resolve(value);
1418
- } else {
1419
- Promise.resolve(value).then(_next, _throw);
1420
- }
1421
- }
1422
- function _async_to_generator$1(fn) {
1423
- return function() {
1424
- var self = this, args = arguments;
1425
- return new Promise(function(resolve, reject) {
1426
- var gen = fn.apply(self, args);
1427
- function _next(value) {
1428
- asyncGeneratorStep$1(gen, resolve, reject, _next, _throw, "next", value);
1429
- }
1430
- function _throw(err) {
1431
- asyncGeneratorStep$1(gen, resolve, reject, _next, _throw, "throw", err);
1432
- }
1433
- _next(undefined);
1434
- });
1435
- };
1436
- }
1437
- function _class_call_check$2(instance, Constructor) {
1438
- if (!(instance instanceof Constructor)) {
1439
- throw new TypeError("Cannot call a class as a function");
1440
- }
1441
- }
1442
- function _defineProperties$1(target, props) {
1443
- for(var i = 0; i < props.length; i++){
1444
- var descriptor = props[i];
1445
- descriptor.enumerable = descriptor.enumerable || false;
1446
- descriptor.configurable = true;
1447
- if ("value" in descriptor) descriptor.writable = true;
1448
- Object.defineProperty(target, descriptor.key, descriptor);
1449
- }
1450
- }
1451
- function _create_class$1(Constructor, protoProps, staticProps) {
1452
- if (protoProps) _defineProperties$1(Constructor.prototype, protoProps);
1453
- return Constructor;
1454
- }
1455
- function _define_property$1(obj, key, value) {
1456
- if (key in obj) {
1457
- Object.defineProperty(obj, key, {
1458
- value: value,
1459
- enumerable: true,
1460
- configurable: true,
1461
- writable: true
1462
- });
1463
- } else {
1464
- obj[key] = value;
1465
- }
1466
- return obj;
1467
- }
1468
- function _ts_generator$1(thisArg, body) {
1469
- var f, y, t, _ = {
1470
- label: 0,
1471
- sent: function() {
1472
- if (t[0] & 1) throw t[1];
1473
- return t[1];
1474
- },
1475
- trys: [],
1476
- ops: []
1477
- }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
1478
- return d(g, "next", {
1479
- value: verb(0)
1480
- }), d(g, "throw", {
1481
- value: verb(1)
1482
- }), d(g, "return", {
1483
- value: verb(2)
1484
- }), typeof Symbol === "function" && d(g, Symbol.iterator, {
1485
- value: function() {
1486
- return this;
1487
- }
1488
- }), g;
1489
- function verb(n) {
1490
- return function(v) {
1491
- return step([
1492
- n,
1493
- v
1494
- ]);
1495
- };
1496
- }
1497
- function step(op) {
1498
- if (f) throw new TypeError("Generator is already executing.");
1499
- while(g && (g = 0, op[0] && (_ = 0)), _)try {
1500
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
1501
- if (y = 0, t) op = [
1502
- op[0] & 2,
1503
- t.value
1504
- ];
1505
- switch(op[0]){
1506
- case 0:
1507
- case 1:
1508
- t = op;
1509
- break;
1510
- case 4:
1511
- _.label++;
1512
- return {
1513
- value: op[1],
1514
- done: false
1515
- };
1516
- case 5:
1517
- _.label++;
1518
- y = op[1];
1519
- op = [
1520
- 0
1521
- ];
1522
- continue;
1523
- case 7:
1524
- op = _.ops.pop();
1525
- _.trys.pop();
1526
- continue;
1527
- default:
1528
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
1529
- _ = 0;
1530
- continue;
1531
- }
1532
- if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
1533
- _.label = op[1];
1534
- break;
1535
- }
1536
- if (op[0] === 6 && _.label < t[1]) {
1537
- _.label = t[1];
1538
- t = op;
1539
- break;
1540
- }
1541
- if (t && _.label < t[2]) {
1542
- _.label = t[2];
1543
- _.ops.push(op);
1544
- break;
1545
- }
1546
- if (t[2]) _.ops.pop();
1547
- _.trys.pop();
1548
- continue;
1549
- }
1550
- op = body.call(thisArg, _);
1551
- } catch (e) {
1552
- op = [
1553
- 6,
1554
- e
1555
- ];
1556
- y = 0;
1557
- } finally{
1558
- f = t = 0;
1559
- }
1560
- if (op[0] & 5) throw op[1];
1561
- return {
1562
- value: op[0] ? op[1] : void 0,
1563
- done: true
1564
- };
1565
- }
1566
- }
1567
- /**
1568
- * Service that handles Discord interaction webhook events.
1569
- *
1570
- * Verifies incoming webhook signatures and dispatches interactions to registered handlers.
1571
- */ exports.DiscordWebhookService = /*#__PURE__*/ function() {
1572
- function DiscordWebhookService(discordWebhookServiceConfig) {
1573
- _class_call_check$2(this, DiscordWebhookService);
1574
- _define_property$1(this, "logger", new common.Logger('DiscordWebhookService'));
1575
- _define_property$1(this, "_verifier", void 0);
1576
- _define_property$1(this, "handler", discordInteractionHandlerFactory());
1577
- _define_property$1(this, "configure", discordInteractionHandlerConfigurerFactory(this.handler));
1578
- this._verifier = discordWebhookEventVerifier({
1579
- publicKey: discordWebhookServiceConfig.discordWebhook.publicKey
1580
- });
1581
- }
1582
- _create_class$1(DiscordWebhookService, [
1583
- {
1584
- key: "updateForWebhook",
1585
- value: function updateForWebhook(req, rawBody) {
1586
- return _async_to_generator$1(function() {
1587
- var result;
1588
- return _ts_generator$1(this, function(_state) {
1589
- switch(_state.label){
1590
- case 0:
1591
- return [
1592
- 4,
1593
- this._verifier(req, rawBody)
1594
- ];
1595
- case 1:
1596
- result = _state.sent();
1597
- if (!result.valid) return [
1598
- 3,
1599
- 3
1600
- ];
1601
- return [
1602
- 4,
1603
- this.updateForDiscordInteraction(result.body)
1604
- ];
1605
- case 2:
1606
- _state.sent();
1607
- return [
1608
- 3,
1609
- 4
1610
- ];
1611
- case 3:
1612
- this.logger.warn('Received invalid Discord interaction event.', req);
1613
- _state.label = 4;
1614
- case 4:
1615
- return [
1616
- 2
1617
- ];
1618
- }
1619
- });
1620
- }).call(this);
1621
- }
1622
- },
1623
- {
1624
- key: "updateForDiscordInteraction",
1625
- value: function updateForDiscordInteraction(interaction) {
1626
- return _async_to_generator$1(function() {
1627
- var result;
1628
- return _ts_generator$1(this, function(_state) {
1629
- switch(_state.label){
1630
- case 0:
1631
- return [
1632
- 4,
1633
- this.handler(interaction)
1634
- ];
1635
- case 1:
1636
- result = _state.sent();
1637
- if (!result) {
1638
- this.logger.warn('Received unexpected/unhandled Discord interaction.', interaction);
1639
- }
1640
- return [
1641
- 2
1642
- ];
1643
- }
1644
- });
1645
- }).call(this);
1646
- }
1647
- }
1648
- ]);
1649
- return DiscordWebhookService;
1650
- }();
1651
- exports.DiscordWebhookService = __decorate([
1652
- common.Injectable(),
1653
- __param(0, common.Inject(DiscordWebhookServiceConfig))
1654
- ], exports.DiscordWebhookService);
1655
-
1656
- function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
1657
- try {
1658
- var info = gen[key](arg);
1659
- var value = info.value;
1660
- } catch (error) {
1661
- reject(error);
1662
- return;
1663
- }
1664
- if (info.done) {
1665
- resolve(value);
1666
- } else {
1667
- Promise.resolve(value).then(_next, _throw);
1668
- }
1669
- }
1670
- function _async_to_generator(fn) {
1671
- return function() {
1672
- var self = this, args = arguments;
1673
- return new Promise(function(resolve, reject) {
1674
- var gen = fn.apply(self, args);
1675
- function _next(value) {
1676
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
1677
- }
1678
- function _throw(err) {
1679
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
1680
- }
1681
- _next(undefined);
1682
- });
1683
- };
1684
- }
1685
- function _class_call_check$1(instance, Constructor) {
1686
- if (!(instance instanceof Constructor)) {
1687
- throw new TypeError("Cannot call a class as a function");
1688
- }
1689
- }
1690
- function _defineProperties(target, props) {
1691
- for(var i = 0; i < props.length; i++){
1692
- var descriptor = props[i];
1693
- descriptor.enumerable = descriptor.enumerable || false;
1694
- descriptor.configurable = true;
1695
- if ("value" in descriptor) descriptor.writable = true;
1696
- Object.defineProperty(target, descriptor.key, descriptor);
1697
- }
1698
- }
1699
- function _create_class(Constructor, protoProps, staticProps) {
1700
- if (protoProps) _defineProperties(Constructor.prototype, protoProps);
1701
- return Constructor;
1702
- }
1703
- function _define_property(obj, key, value) {
1704
- if (key in obj) {
1705
- Object.defineProperty(obj, key, {
1706
- value: value,
1707
- enumerable: true,
1708
- configurable: true,
1709
- writable: true
1710
- });
1711
- } else {
1712
- obj[key] = value;
1713
- }
1714
- return obj;
1715
- }
1716
- function _ts_generator(thisArg, body) {
1717
- var f, y, t, _ = {
1718
- label: 0,
1719
- sent: function() {
1720
- if (t[0] & 1) throw t[1];
1721
- return t[1];
1722
- },
1723
- trys: [],
1724
- ops: []
1725
- }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
1726
- return d(g, "next", {
1727
- value: verb(0)
1728
- }), d(g, "throw", {
1729
- value: verb(1)
1730
- }), d(g, "return", {
1731
- value: verb(2)
1732
- }), typeof Symbol === "function" && d(g, Symbol.iterator, {
1733
- value: function() {
1734
- return this;
1735
- }
1736
- }), g;
1737
- function verb(n) {
1738
- return function(v) {
1739
- return step([
1740
- n,
1741
- v
1742
- ]);
1743
- };
1744
- }
1745
- function step(op) {
1746
- if (f) throw new TypeError("Generator is already executing.");
1747
- while(g && (g = 0, op[0] && (_ = 0)), _)try {
1748
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
1749
- if (y = 0, t) op = [
1750
- op[0] & 2,
1751
- t.value
1752
- ];
1753
- switch(op[0]){
1754
- case 0:
1755
- case 1:
1756
- t = op;
1757
- break;
1758
- case 4:
1759
- _.label++;
1760
- return {
1761
- value: op[1],
1762
- done: false
1763
- };
1764
- case 5:
1765
- _.label++;
1766
- y = op[1];
1767
- op = [
1768
- 0
1769
- ];
1770
- continue;
1771
- case 7:
1772
- op = _.ops.pop();
1773
- _.trys.pop();
1774
- continue;
1775
- default:
1776
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
1777
- _ = 0;
1778
- continue;
1779
- }
1780
- if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
1781
- _.label = op[1];
1782
- break;
1783
- }
1784
- if (op[0] === 6 && _.label < t[1]) {
1785
- _.label = t[1];
1786
- t = op;
1787
- break;
1788
- }
1789
- if (t && _.label < t[2]) {
1790
- _.label = t[2];
1791
- _.ops.push(op);
1792
- break;
1793
- }
1794
- if (t[2]) _.ops.pop();
1795
- _.trys.pop();
1796
- continue;
1797
- }
1798
- op = body.call(thisArg, _);
1799
- } catch (e) {
1800
- op = [
1801
- 6,
1802
- e
1803
- ];
1804
- y = 0;
1805
- } finally{
1806
- f = t = 0;
1807
- }
1808
- if (op[0] & 5) throw op[1];
1809
- return {
1810
- value: op[0] ? op[1] : void 0,
1811
- done: true
1812
- };
1813
- }
1814
- }
1815
- exports.DiscordWebhookController = /*#__PURE__*/ function() {
1816
- function DiscordWebhookController(discordWebhookService) {
1817
- _class_call_check$1(this, DiscordWebhookController);
1818
- _define_property(this, "_discordWebhookService", void 0);
1819
- this._discordWebhookService = discordWebhookService;
1820
- }
1821
- _create_class(DiscordWebhookController, [
1822
- {
1823
- key: "handleDiscordWebhook",
1824
- value: function handleDiscordWebhook(req, rawBody) {
1825
- return _async_to_generator(function() {
1826
- return _ts_generator(this, function(_state) {
1827
- switch(_state.label){
1828
- case 0:
1829
- return [
1830
- 4,
1831
- this._discordWebhookService.updateForWebhook(req, rawBody)
1832
- ];
1833
- case 1:
1834
- _state.sent();
1835
- return [
1836
- 2
1837
- ];
1838
- }
1839
- });
1840
- }).call(this);
1841
- }
1842
- }
1843
- ]);
1844
- return DiscordWebhookController;
1845
- }();
1846
- __decorate([
1847
- common.Post(),
1848
- __param(0, common.Req()),
1849
- __param(1, nestjs.RawBody())
1850
- ], exports.DiscordWebhookController.prototype, "handleDiscordWebhook", null);
1851
- exports.DiscordWebhookController = __decorate([
1852
- common.Controller('/webhook/discord'),
1853
- __param(0, common.Inject(exports.DiscordWebhookService))
1854
- ], exports.DiscordWebhookController);
1855
-
1856
- function _class_call_check(instance, Constructor) {
1857
- if (!(instance instanceof Constructor)) {
1858
- throw new TypeError("Cannot call a class as a function");
1859
- }
1860
- }
1861
- /**
1862
- * Factory that creates a DiscordWebhookServiceConfig from environment variables.
1863
- *
1864
- * @param configService - The NestJS config service used to read the Discord public key environment variable.
1865
- * @returns A validated DiscordWebhookServiceConfig populated from environment variables.
1866
- */ function discordWebhookServiceConfigFactory(configService) {
1867
- var config = {
1868
- discordWebhook: {
1869
- publicKey: configService.get(DISCORD_PUBLIC_KEY_ENV_VAR)
1870
- }
1871
- };
1872
- DiscordWebhookServiceConfig.assertValidConfig(config);
1873
- return config;
1874
- }
1875
- /**
1876
- * NestJS module that provides Discord interaction webhook handling.
1877
- *
1878
- * Standalone — does not depend on DiscordModule (no bot token needed).
1879
- * Reads the application public key from the DISCORD_PUBLIC_KEY environment variable.
1880
- */ exports.DiscordWebhookModule = function DiscordWebhookModule() {
1881
- _class_call_check(this, DiscordWebhookModule);
1882
- };
1883
- exports.DiscordWebhookModule = __decorate([
1884
- common.Module({
1885
- imports: [
1886
- config.ConfigModule
1887
- ],
1888
- controllers: [
1889
- exports.DiscordWebhookController
1890
- ],
1891
- providers: [
1892
- {
1893
- provide: DiscordWebhookServiceConfig,
1894
- inject: [
1895
- config.ConfigService
1896
- ],
1897
- useFactory: discordWebhookServiceConfigFactory
1898
- },
1899
- exports.DiscordWebhookService
1900
- ],
1901
- exports: [
1902
- exports.DiscordWebhookService
1903
- ]
1904
- })
1905
- ], exports.DiscordWebhookModule);
1906
-
1907
- exports.DEFAULT_DISCORD_INTENTS = DEFAULT_DISCORD_INTENTS;
1908
- exports.DISCORD_BOT_TOKEN_ENV_VAR = DISCORD_BOT_TOKEN_ENV_VAR;
1909
- exports.DISCORD_BOT_TOKEN_PLACEHOLDER = DISCORD_BOT_TOKEN_PLACEHOLDER;
1910
- exports.DISCORD_CLIENT_ID_CONFIG_KEY = DISCORD_CLIENT_ID_CONFIG_KEY;
1911
- exports.DISCORD_CLIENT_SECRET_CONFIG_KEY = DISCORD_CLIENT_SECRET_CONFIG_KEY;
1912
- exports.DISCORD_ED25519_PUBLIC_KEY_BYTE_LENGTH = DISCORD_ED25519_PUBLIC_KEY_BYTE_LENGTH;
1913
- exports.DISCORD_PUBLIC_KEY_ENV_VAR = DISCORD_PUBLIC_KEY_ENV_VAR;
1914
- exports.DISCORD_SERVICE_NAME = DISCORD_SERVICE_NAME;
1915
- exports.DiscordOAuthServiceConfig = DiscordOAuthServiceConfig;
1916
- exports.DiscordServiceConfig = DiscordServiceConfig;
1917
- exports.DiscordWebhookServiceConfig = DiscordWebhookServiceConfig;
1918
- exports.appDiscordOAuthModuleMetadata = appDiscordOAuthModuleMetadata;
1919
- exports.discordClientOptionsWithIntents = discordClientOptionsWithIntents;
1920
- exports.discordDefaultClientOptions = discordDefaultClientOptions;
1921
- exports.discordInteractionHandlerConfigurerFactory = discordInteractionHandlerConfigurerFactory;
1922
- exports.discordInteractionHandlerFactory = discordInteractionHandlerFactory;
1923
- exports.discordOAuthServiceConfigFactory = discordOAuthServiceConfigFactory;
1924
- exports.discordServiceConfigFactory = discordServiceConfigFactory;
1925
- exports.discordWebhookEventVerifier = discordWebhookEventVerifier;
1926
- exports.discordWebhookInteraction = discordWebhookInteraction;
1927
- exports.discordWebhookServiceConfigFactory = discordWebhookServiceConfigFactory;
1928
- exports.isUsableDiscordBotToken = isUsableDiscordBotToken;