@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.
package/index.cjs.js DELETED
@@ -1,817 +0,0 @@
1
- 'use strict';
2
-
3
- var util = require('@dereekb/util');
4
- var fetch = require('@dereekb/util/fetch');
5
- var makeError = require('make-error');
6
-
7
- function _define_property$1(obj, key, value) {
8
- if (key in obj) {
9
- Object.defineProperty(obj, key, {
10
- value: value,
11
- enumerable: true,
12
- configurable: true,
13
- writable: true
14
- });
15
- } else {
16
- obj[key] = value;
17
- }
18
- return obj;
19
- }
20
- function _object_spread(target) {
21
- for(var i = 1; i < arguments.length; i++){
22
- var source = arguments[i] != null ? arguments[i] : {};
23
- var ownKeys = Object.keys(source);
24
- if (typeof Object.getOwnPropertySymbols === "function") {
25
- ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
26
- return Object.getOwnPropertyDescriptor(source, sym).enumerable;
27
- }));
28
- }
29
- ownKeys.forEach(function(key) {
30
- _define_property$1(target, key, source[key]);
31
- });
32
- }
33
- return target;
34
- }
35
- function ownKeys(object, enumerableOnly) {
36
- var keys = Object.keys(object);
37
- if (Object.getOwnPropertySymbols) {
38
- var symbols = Object.getOwnPropertySymbols(object);
39
- keys.push.apply(keys, symbols);
40
- }
41
- return keys;
42
- }
43
- function _object_spread_props(target, source) {
44
- source = source != null ? source : {};
45
- if (Object.getOwnPropertyDescriptors) {
46
- Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
47
- } else {
48
- ownKeys(Object(source)).forEach(function(key) {
49
- Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
50
- });
51
- }
52
- return target;
53
- }
54
- /**
55
- * Default number of messages per page when fetching Discord channel messages.
56
- */ var DEFAULT_DISCORD_MESSAGES_PER_PAGE = 100;
57
- /**
58
- * Creates a page factory that wraps a Discord message fetch function with automatic cursor-based pagination.
59
- *
60
- * Discord paginates via `before`/`after` snowflake IDs. This factory automatically reads the last
61
- * message's ID from each response and sets it as the `before` cursor for the next request.
62
- * When the number of returned messages is less than the requested limit, pagination stops.
63
- *
64
- * @param input - The factory input configuration.
65
- * @returns A page factory that produces iterable page fetchers.
66
- *
67
- * @example
68
- * ```typescript
69
- * const pageFactory = discordFetchMessagePageFactory({ fetch: fetchChannelMessages });
70
- *
71
- * const fetchPage = pageFactory({ limit: 50 });
72
- * const firstPage = await fetchPage.fetchNext();
73
- *
74
- * if (firstPage.hasNext) {
75
- * const secondPage = await firstPage.fetchNext();
76
- * }
77
- * ```
78
- */ function discordFetchMessagePageFactory(input) {
79
- var _ref;
80
- var fetch$1 = input.fetch, config = input.config, defaults = input.defaults;
81
- var readMessageId = (_ref = config === null || config === void 0 ? void 0 : config.readMessageId) !== null && _ref !== void 0 ? _ref : function(message) {
82
- return message.id;
83
- };
84
- return fetch.fetchPageFactory(_object_spread_props(_object_spread({}, defaults), {
85
- fetch: fetch$1,
86
- readFetchPageResultInfo: function readFetchPageResultInfo(result) {
87
- var count = result.data.length;
88
- var nextCursor = count > 0 ? readMessageId(util.lastValue(result.data)) : undefined;
89
- return {
90
- hasNext: count > 0,
91
- nextPageCursor: nextCursor
92
- };
93
- },
94
- buildInputForNextPage: function buildInputForNextPage(pageResult, input, options) {
95
- var _ref, _options_maxItemsPerPage, _ref1;
96
- var _pageResult_result;
97
- var nextCursor = pageResult.nextPageCursor;
98
- var effectiveLimit = (_ref = (_options_maxItemsPerPage = options.maxItemsPerPage) !== null && _options_maxItemsPerPage !== void 0 ? _options_maxItemsPerPage : input.limit) !== null && _ref !== void 0 ? _ref : DEFAULT_DISCORD_MESSAGES_PER_PAGE;
99
- var resultCount = (_ref1 = (_pageResult_result = pageResult.result) === null || _pageResult_result === void 0 ? void 0 : _pageResult_result.data.length) !== null && _ref1 !== void 0 ? _ref1 : 0;
100
- var nextInput;
101
- // Discord signals no more results when fewer items than the limit are returned
102
- if (!nextCursor || resultCount < effectiveLimit) {
103
- nextInput = undefined;
104
- } else {
105
- nextInput = _object_spread_props(_object_spread({}, input), {
106
- before: nextCursor,
107
- after: undefined,
108
- around: undefined,
109
- limit: effectiveLimit
110
- });
111
- }
112
- return nextInput;
113
- }
114
- }));
115
- }
116
-
117
- /**
118
- * The Discord REST API base, pinned to a version.
119
- *
120
- * Endpoint paths are appended to this base, so it intentionally carries no endpoint segment of its
121
- * own. Discord requires an explicit version in the path; an unversioned base resolves to the oldest
122
- * still-supported version.
123
- */ var DISCORD_API_URL = 'https://discord.com/api/v10';
124
-
125
- /**
126
- * Maps a {@link DiscordOAuthTokenResponse} to a {@link DiscordAccessToken}.
127
- *
128
- * @param response - The token response returned by the Discord token endpoint.
129
- * @returns The equivalent DiscordAccessToken, with `expiresAt` resolved against the current time.
130
- *
131
- * @__NO_SIDE_EFFECTS__
132
- */ function discordAccessTokenFromTokenResponse(response) {
133
- var createdAt = Date.now();
134
- var access_token = response.access_token, refresh_token = response.refresh_token, scope = response.scope, expires_in = response.expires_in;
135
- var accessToken = {
136
- accessToken: access_token,
137
- refreshToken: refresh_token,
138
- expiresIn: expires_in,
139
- expiresAt: new Date(createdAt + expires_in * util.MS_IN_SECOND),
140
- scope: scope !== null && scope !== void 0 ? scope : ''
141
- };
142
- return accessToken;
143
- }
144
-
145
- /**
146
- * The Discord OAuth2 authorize URL the user's browser is redirected to.
147
- *
148
- * Note this is NOT under `/api`: Discord serves the consent screen from the site root, while the
149
- * token endpoint lives under {@link DISCORD_API_URL}. It is therefore a full URL rather than a path
150
- * relative to the API base.
151
- */ var DISCORD_OAUTH_AUTHORIZE_URL = 'https://discord.com/oauth2/authorize';
152
- /**
153
- * The Discord OAuth2 token endpoint path, relative to {@link DISCORD_API_URL}.
154
- */ var DISCORD_OAUTH_TOKEN_PATH = '/oauth2/token';
155
- /**
156
- * The Discord OAuth2 token revocation endpoint path, relative to {@link DISCORD_API_URL}.
157
- */ var DISCORD_OAUTH_REVOKE_PATH = '/oauth2/token/revoke';
158
- /**
159
- * Path of the endpoint returning the user an access token belongs to.
160
- *
161
- * Requires the `identify` scope.
162
- */ var DISCORD_OAUTH_CURRENT_USER_PATH = '/users/@me';
163
-
164
- /**
165
- * The `Content-Type` Discord's token endpoint requires.
166
- *
167
- * Discord rejects a JSON body outright, unlike Cal.com, which requires one.
168
- *
169
- * `@dereekb/util/oidc`'s `postTokenEndpoint` is the in-workspace precedent for this form-encoded
170
- * shape and is deliberately NOT reused: its `exchangeAuthorizationCode` requires a PKCE
171
- * `code_verifier`, it authenticates with `client_secret_post` rather than Basic, and it is
172
- * discovery-driven. Discord is not an OIDC provider — there is no discovery document and no
173
- * `id_token`.
174
- */ var DISCORD_OAUTH_TOKEN_CONTENT_TYPE = 'application/x-www-form-urlencoded';
175
- /**
176
- * Builds the HTTP Basic `Authorization` header value that authenticates the OAuth client.
177
- *
178
- * Discord accepts the client credentials as Basic auth rather than in the request body, which is why
179
- * `client_id` / `client_secret` are absent from the exchange body below.
180
- *
181
- * Uses `btoa()` rather than `Buffer`, so this package stays usable outside Node — the same choice
182
- * `@dereekb/util`'s PKCE helpers make.
183
- *
184
- * @param config - The client credentials to encode.
185
- * @returns The `Authorization` header value, including the `Basic ` prefix.
186
- *
187
- * @__NO_SIDE_EFFECTS__
188
- */ function discordOAuthBasicAuthorizationHeader(config) {
189
- var credentials = "".concat(config.clientId, ":").concat(config.clientSecret);
190
- return "Basic ".concat(btoa(credentials));
191
- }
192
- /**
193
- * Exchanges an OAuth authorization code for access and refresh tokens.
194
- *
195
- * Discord requires `application/x-www-form-urlencoded` — a JSON body is rejected — and authenticates
196
- * the client with HTTP Basic rather than credentials in the body. Both differ from Cal.com, which
197
- * posts JSON with the credentials inline. The Basic header rides on the context's configured fetch.
198
- *
199
- * @param context - The Discord OAuth context providing the authenticated fetch.
200
- * @returns Exchanges an authorization code for access and refresh tokens.
201
- *
202
- * @see https://docs.discord.com/developers/topics/oauth2
203
- *
204
- * @example
205
- * ```ts
206
- * const response = await exchangeAuthorizationCode(context)({
207
- * code: 'auth-code-from-redirect',
208
- * redirectUri: 'http://localhost:9901/oauth/discord/callback'
209
- * });
210
- * ```
211
- */ function exchangeAuthorizationCode(context) {
212
- return function(input) {
213
- var body = new URLSearchParams({
214
- grant_type: 'authorization_code',
215
- code: input.code,
216
- redirect_uri: input.redirectUri
217
- });
218
- var fetchJsonInput = {
219
- method: 'POST',
220
- body: body.toString()
221
- };
222
- return context.fetchJson(DISCORD_OAUTH_TOKEN_PATH, fetchJsonInput);
223
- };
224
- }
225
- /**
226
- * Refreshes an access token.
227
- *
228
- * Discord's refresh response carries a `refresh_token` of its own, so persist whatever comes back
229
- * rather than assuming the sent one stays valid. That is correct for rotating and non-rotating
230
- * providers alike.
231
- *
232
- * Reached through `DiscordUserExternalConnectionOAuthService.refreshCredentials`, which the external
233
- * connection reader dispatches to when a user's stored Discord credentials are near expiration.
234
- *
235
- * @param context - The Discord OAuth context providing the authenticated fetch.
236
- * @returns Refreshes an access token using the given refresh token.
237
- *
238
- * @see https://docs.discord.com/developers/topics/oauth2
239
- */ function refreshAccessToken(context) {
240
- return function(input) {
241
- var body = new URLSearchParams({
242
- grant_type: 'refresh_token',
243
- refresh_token: input.refreshToken
244
- });
245
- var fetchJsonInput = {
246
- method: 'POST',
247
- body: body.toString()
248
- };
249
- return context.fetchJson(DISCORD_OAUTH_TOKEN_PATH, fetchJsonInput);
250
- };
251
- }
252
- /**
253
- * Reads the user an access token belongs to. Requires the `identify` scope.
254
- *
255
- * Bearer-authenticated with the USER's token, not Basic-authenticated with the client credentials, so
256
- * the `Authorization` header is passed per-request to override the one on the context's fetch. A
257
- * per-request header wins over the base header of the same name, which is what makes one configured
258
- * fetch enough for both shapes.
259
- *
260
- * @param context - The Discord OAuth context providing the authenticated fetch.
261
- * @returns Reads the Discord user the given access token belongs to.
262
- *
263
- * @see https://docs.discord.com/developers/resources/user
264
- */ function readCurrentUser(context) {
265
- return function(input) {
266
- var fetchJsonInput = {
267
- method: 'GET',
268
- headers: {
269
- Authorization: "Bearer ".concat(input.accessToken)
270
- }
271
- };
272
- return context.fetchJson(DISCORD_OAUTH_CURRENT_USER_PATH, fetchJsonInput);
273
- };
274
- }
275
-
276
- /**
277
- * The Discord OAuth scopes this package models.
278
- *
279
- * A runtime list rather than a bare type union, so a configured scope can be validated instead of
280
- * being passed through to the consent screen and refused there.
281
- *
282
- * Deliberately NOT Discord's full ~40-scope surface: only what a per-user account connect can
283
- * legitimately ask for. Add a scope here when code actually uses it.
284
- *
285
- * @see https://docs.discord.com/developers/topics/oauth2
286
- */ var ALL_DISCORD_OAUTH_SCOPES = [
287
- 'identify',
288
- 'email',
289
- 'guilds',
290
- 'connections'
291
- ];
292
- /**
293
- * Returns whether the input is a known {@link DiscordOAuthScope}.
294
- *
295
- * @param value - The value to check.
296
- * @returns True when the value is a Discord OAuth scope this package models.
297
- */ function isDiscordOAuthScope(value) {
298
- return ALL_DISCORD_OAUTH_SCOPES.includes(value);
299
- }
300
- /**
301
- * The delimiter used to join scopes in the `scope` query parameter.
302
- *
303
- * OAuth2 specifies a space-delimited list and Discord follows it. `URL.searchParams.set` handles the
304
- * percent-encoding, so this stays a literal space.
305
- */ var DISCORD_OAUTH_SCOPE_DELIMITER = ' ';
306
- /**
307
- * The `response_type` used by the authorization-code flow.
308
- */ var DISCORD_OAUTH_AUTHORIZE_RESPONSE_TYPE = 'code';
309
- /**
310
- * Creates a {@link DiscordOAuthAuthorizeUrlFactory} that composes the Discord authorize URL a user's
311
- * browser is redirected to in order to begin the authorization-code flow.
312
- *
313
- * The client id, redirect URI, and scopes are fixed by the config, since a consumer holds those
314
- * constant and varies only the per-request `state`.
315
- *
316
- * @param config - The client id, redirect URI, and scopes to request.
317
- * @returns A factory that builds an authorize URL for the given params.
318
- *
319
- * @see https://docs.discord.com/developers/topics/oauth2
320
- *
321
- * @example
322
- * ```ts
323
- * const authorizeUrlFactory = discordOAuthAuthorizeUrlFactory({
324
- * clientId: 'client-id',
325
- * redirectUri: 'http://localhost:9901/oauth/discord/callback',
326
- * scopes: ['identify']
327
- * });
328
- *
329
- * const url = authorizeUrlFactory({ state: 'signed-state' });
330
- * ```
331
- *
332
- * @__NO_SIDE_EFFECTS__
333
- */ function discordOAuthAuthorizeUrlFactory(config) {
334
- var clientId = config.clientId, redirectUri = config.redirectUri, scopes = config.scopes, inputAuthorizeUrl = config.authorizeUrl;
335
- var authorizeUrl = inputAuthorizeUrl !== null && inputAuthorizeUrl !== void 0 ? inputAuthorizeUrl : DISCORD_OAUTH_AUTHORIZE_URL;
336
- var scope = scopes.join(DISCORD_OAUTH_SCOPE_DELIMITER);
337
- return function(params) {
338
- var url = new URL(authorizeUrl);
339
- var state = params === null || params === void 0 ? void 0 : params.state;
340
- url.searchParams.set('client_id', clientId);
341
- url.searchParams.set('redirect_uri', redirectUri);
342
- url.searchParams.set('response_type', DISCORD_OAUTH_AUTHORIZE_RESPONSE_TYPE);
343
- url.searchParams.set('scope', scope);
344
- if (state != null) {
345
- url.searchParams.set('state', state);
346
- }
347
- return url.toString();
348
- };
349
- }
350
-
351
- function _assert_this_initialized(self) {
352
- if (self === void 0) {
353
- throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
354
- }
355
- return self;
356
- }
357
- function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
358
- try {
359
- var info = gen[key](arg);
360
- var value = info.value;
361
- } catch (error) {
362
- reject(error);
363
- return;
364
- }
365
- if (info.done) {
366
- resolve(value);
367
- } else {
368
- Promise.resolve(value).then(_next, _throw);
369
- }
370
- }
371
- function _async_to_generator(fn) {
372
- return function() {
373
- var self = this, args = arguments;
374
- return new Promise(function(resolve, reject) {
375
- var gen = fn.apply(self, args);
376
- function _next(value) {
377
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
378
- }
379
- function _throw(err) {
380
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
381
- }
382
- _next(undefined);
383
- });
384
- };
385
- }
386
- function _call_super(_this, derived, args) {
387
- derived = _get_prototype_of(derived);
388
- return _possible_constructor_return(_this, _is_native_reflect_construct() ? Reflect.construct(derived, args || [], _get_prototype_of(_this).constructor) : derived.apply(_this, args));
389
- }
390
- function _class_call_check(instance, Constructor) {
391
- if (!(instance instanceof Constructor)) {
392
- throw new TypeError("Cannot call a class as a function");
393
- }
394
- }
395
- function _defineProperties(target, props) {
396
- for(var i = 0; i < props.length; i++){
397
- var descriptor = props[i];
398
- descriptor.enumerable = descriptor.enumerable || false;
399
- descriptor.configurable = true;
400
- if ("value" in descriptor) descriptor.writable = true;
401
- Object.defineProperty(target, descriptor.key, descriptor);
402
- }
403
- }
404
- function _create_class(Constructor, protoProps, staticProps) {
405
- if (protoProps) _defineProperties(Constructor.prototype, protoProps);
406
- return Constructor;
407
- }
408
- function _define_property(obj, key, value) {
409
- if (key in obj) {
410
- Object.defineProperty(obj, key, {
411
- value: value,
412
- enumerable: true,
413
- configurable: true,
414
- writable: true
415
- });
416
- } else {
417
- obj[key] = value;
418
- }
419
- return obj;
420
- }
421
- function _get_prototype_of(o) {
422
- _get_prototype_of = Object.setPrototypeOf ? Object.getPrototypeOf : function getPrototypeOf(o) {
423
- return o.__proto__ || Object.getPrototypeOf(o);
424
- };
425
- return _get_prototype_of(o);
426
- }
427
- function _inherits(subClass, superClass) {
428
- if (typeof superClass !== "function" && superClass !== null) {
429
- throw new TypeError("Super expression must either be null or a function");
430
- }
431
- subClass.prototype = Object.create(superClass && superClass.prototype, {
432
- constructor: {
433
- value: subClass,
434
- writable: true,
435
- configurable: true
436
- }
437
- });
438
- if (superClass) _set_prototype_of(subClass, superClass);
439
- }
440
- function _instanceof(left, right) {
441
- "@swc/helpers - instanceof";
442
- if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
443
- return !!right[Symbol.hasInstance](left);
444
- } else {
445
- return left instanceof right;
446
- }
447
- }
448
- function _possible_constructor_return(self, call) {
449
- if (call && (_type_of(call) === "object" || typeof call === "function")) {
450
- return call;
451
- }
452
- return _assert_this_initialized(self);
453
- }
454
- function _set_prototype_of(o, p) {
455
- _set_prototype_of = Object.setPrototypeOf || function setPrototypeOf(o, p) {
456
- o.__proto__ = p;
457
- return o;
458
- };
459
- return _set_prototype_of(o, p);
460
- }
461
- function _type_of(obj) {
462
- "@swc/helpers - typeof";
463
- return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
464
- }
465
- function _is_native_reflect_construct() {
466
- try {
467
- var result = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
468
- } catch (_) {}
469
- return (_is_native_reflect_construct = function() {
470
- return !!result;
471
- })();
472
- }
473
- function _ts_generator(thisArg, body) {
474
- var f, y, t, _ = {
475
- label: 0,
476
- sent: function() {
477
- if (t[0] & 1) throw t[1];
478
- return t[1];
479
- },
480
- trys: [],
481
- ops: []
482
- }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
483
- return d(g, "next", {
484
- value: verb(0)
485
- }), d(g, "throw", {
486
- value: verb(1)
487
- }), d(g, "return", {
488
- value: verb(2)
489
- }), typeof Symbol === "function" && d(g, Symbol.iterator, {
490
- value: function() {
491
- return this;
492
- }
493
- }), g;
494
- function verb(n) {
495
- return function(v) {
496
- return step([
497
- n,
498
- v
499
- ]);
500
- };
501
- }
502
- function step(op) {
503
- if (f) throw new TypeError("Generator is already executing.");
504
- while(g && (g = 0, op[0] && (_ = 0)), _)try {
505
- 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;
506
- if (y = 0, t) op = [
507
- op[0] & 2,
508
- t.value
509
- ];
510
- switch(op[0]){
511
- case 0:
512
- case 1:
513
- t = op;
514
- break;
515
- case 4:
516
- _.label++;
517
- return {
518
- value: op[1],
519
- done: false
520
- };
521
- case 5:
522
- _.label++;
523
- y = op[1];
524
- op = [
525
- 0
526
- ];
527
- continue;
528
- case 7:
529
- op = _.ops.pop();
530
- _.trys.pop();
531
- continue;
532
- default:
533
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
534
- _ = 0;
535
- continue;
536
- }
537
- if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
538
- _.label = op[1];
539
- break;
540
- }
541
- if (op[0] === 6 && _.label < t[1]) {
542
- _.label = t[1];
543
- t = op;
544
- break;
545
- }
546
- if (t && _.label < t[2]) {
547
- _.label = t[2];
548
- _.ops.push(op);
549
- break;
550
- }
551
- if (t[2]) _.ops.pop();
552
- _.trys.pop();
553
- continue;
554
- }
555
- op = body.call(thisArg, _);
556
- } catch (e) {
557
- op = [
558
- 6,
559
- e
560
- ];
561
- y = 0;
562
- } finally{
563
- f = t = 0;
564
- }
565
- if (op[0] & 5) throw op[1];
566
- return {
567
- value: op[0] ? op[1] : void 0,
568
- done: true
569
- };
570
- }
571
- }
572
- /**
573
- * Error code returned when a code or refresh token is invalid, expired, or was already spent.
574
- */ var DISCORD_OAUTH_INVALID_GRANT_ERROR_CODE = 'invalid_grant';
575
- /**
576
- * Error code returned when the requested scope set is not one the application may ask for.
577
- */ var DISCORD_OAUTH_INVALID_SCOPE_ERROR_CODE = 'invalid_scope';
578
- /**
579
- * An error reported by a Discord OAuth endpoint.
580
- */ var DiscordOAuthError = /*#__PURE__*/ function(BaseError) {
581
- _inherits(DiscordOAuthError, BaseError);
582
- function DiscordOAuthError(error) {
583
- _class_call_check(this, DiscordOAuthError);
584
- var _this;
585
- _this = _call_super(this, DiscordOAuthError, [
586
- error.error_description ? "".concat(error.error, ": ").concat(error.error_description) : error.error
587
- ]), _define_property(_this, "error", void 0);
588
- _this.error = error;
589
- return _this;
590
- }
591
- _create_class(DiscordOAuthError, [
592
- {
593
- key: "code",
594
- get: function get() {
595
- return this.error.error;
596
- }
597
- }
598
- ]);
599
- return DiscordOAuthError;
600
- }(makeError.BaseError);
601
- /**
602
- * A {@link DiscordOAuthError} that retains the HTTP response it was parsed from.
603
- */ var DiscordOAuthFetchResponseError = /*#__PURE__*/ function(DiscordOAuthError) {
604
- _inherits(DiscordOAuthFetchResponseError, DiscordOAuthError);
605
- function DiscordOAuthFetchResponseError(data, responseError) {
606
- _class_call_check(this, DiscordOAuthFetchResponseError);
607
- var _this;
608
- _this = _call_super(this, DiscordOAuthFetchResponseError, [
609
- data
610
- ]), _define_property(_this, "data", void 0), _define_property(_this, "responseError", void 0);
611
- _this.data = data;
612
- _this.responseError = responseError;
613
- return _this;
614
- }
615
- return DiscordOAuthFetchResponseError;
616
- }(DiscordOAuthError);
617
- /**
618
- * Creates a {@link LogDiscordOAuthErrorFunction} that logs the error to the console.
619
- *
620
- * @param discordApiNamePrefix - Prefix to use when logging, e.g. `DiscordOAuth`.
621
- * @returns A log function that prefixes each logged error.
622
- *
623
- * @__NO_SIDE_EFFECTS__
624
- */ function logDiscordOAuthErrorFunction(discordApiNamePrefix) {
625
- return function(error) {
626
- if (_instanceof(error, DiscordOAuthFetchResponseError)) {
627
- console.log("".concat(discordApiNamePrefix, "Error(").concat(error.responseError.response.status, "): "), {
628
- error: error,
629
- errorData: error.data
630
- });
631
- } else if (_instanceof(error, DiscordOAuthError)) {
632
- console.log("".concat(discordApiNamePrefix, "Error(code:").concat(error.code, "): "), {
633
- error: error
634
- });
635
- } else {
636
- console.log("".concat(discordApiNamePrefix, "Error(name:").concat(error.name, "): "), {
637
- error: error
638
- });
639
- }
640
- };
641
- }
642
- var logDiscordOAuthErrorToConsole = logDiscordOAuthErrorFunction('DiscordOAuth');
643
- /**
644
- * Parses a {@link FetchResponseError} from a Discord OAuth call into a typed error.
645
- *
646
- * @param responseError - The fetch response error to parse.
647
- * @returns The parsed error, or undefined when the body carried no OAuth error to parse.
648
- */ function parseDiscordOAuthError(responseError) {
649
- return _async_to_generator(function() {
650
- var data, result;
651
- return _ts_generator(this, function(_state) {
652
- switch(_state.label){
653
- case 0:
654
- return [
655
- 4,
656
- responseError.response.clone().json().catch(function() {
657
- return undefined;
658
- })
659
- ];
660
- case 1:
661
- data = _state.sent();
662
- if (data === null || data === void 0 ? void 0 : data.error) {
663
- result = new DiscordOAuthFetchResponseError(data, responseError);
664
- }
665
- return [
666
- 2,
667
- result
668
- ];
669
- }
670
- });
671
- })();
672
- }
673
- /**
674
- * Wraps a {@link ConfiguredFetch} so that Discord OAuth error responses surface as typed errors.
675
- *
676
- * @param fetch - The fetch to wrap.
677
- * @param logError - Optional override of the error logging function.
678
- * @returns The wrapped fetch.
679
- *
680
- * @__NO_SIDE_EFFECTS__
681
- */ function handleDiscordOAuthErrorFetch(fetch$1) {
682
- var logError = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : logDiscordOAuthErrorToConsole;
683
- return function(x, y) {
684
- return _async_to_generator(function() {
685
- var e, error;
686
- return _ts_generator(this, function(_state) {
687
- switch(_state.label){
688
- case 0:
689
- _state.trys.push([
690
- 0,
691
- 2,
692
- ,
693
- 5
694
- ]);
695
- return [
696
- 4,
697
- fetch$1(x, y)
698
- ];
699
- case 1:
700
- return [
701
- 2,
702
- _state.sent()
703
- ]; // await to catch thrown errors
704
- case 2:
705
- e = _state.sent();
706
- if (!_instanceof(e, fetch.FetchResponseError)) return [
707
- 3,
708
- 4
709
- ];
710
- return [
711
- 4,
712
- parseDiscordOAuthError(e)
713
- ];
714
- case 3:
715
- error = _state.sent();
716
- if (error) {
717
- logError(error); // log before throwing
718
- throw error;
719
- }
720
- _state.label = 4;
721
- case 4:
722
- throw e;
723
- case 5:
724
- return [
725
- 2
726
- ];
727
- }
728
- });
729
- })();
730
- };
731
- }
732
-
733
- /**
734
- * Creates a {@link DiscordOAuthFactory} that produces configured Discord OAuth instances.
735
- *
736
- * There is no access-token cache or per-user token factory here, unlike `calcomOAuthFactory`: the
737
- * external-connection framework stores each user's credentials itself, so the client only ever needs
738
- * to make the calls it is asked to make.
739
- *
740
- * @param factoryConfig - Configuration including an optional fetch factory, fetch handler, and error logging.
741
- * @returns A factory accepting a DiscordOAuthConfig and producing a DiscordOAuth instance.
742
- *
743
- * @__NO_SIDE_EFFECTS__
744
- */ function discordOAuthFactory(factoryConfig) {
745
- var fetchHandler = factoryConfig.fetchHandler, logDiscordOAuthErrorFunction = factoryConfig.logDiscordOAuthErrorFunction;
746
- var _factoryConfig_fetchFactory = factoryConfig.fetchFactory, fetchFactory = _factoryConfig_fetchFactory === void 0 ? function(input) {
747
- return fetch.fetchApiFetchService.makeFetch({
748
- baseUrl: DISCORD_API_URL,
749
- baseRequest: {
750
- headers: {
751
- // the token endpoint's shape, since it is the only endpoint that posts a body. A
752
- // per-request header of the same name wins, which is how readCurrentUser swaps the
753
- // client's Basic credentials for the user's Bearer token.
754
- 'Content-Type': DISCORD_OAUTH_TOKEN_CONTENT_TYPE,
755
- Authorization: discordOAuthBasicAuthorizationHeader(input.config)
756
- }
757
- },
758
- fetchHandler: fetchHandler !== null && fetchHandler !== void 0 ? fetchHandler : undefined,
759
- timeout: 20 * 1000,
760
- requireOkResponse: true,
761
- useTimeout: true // use timeout
762
- });
763
- } : _factoryConfig_fetchFactory;
764
- return function(config) {
765
- // a missing credential otherwise composes `client_id=undefined` on the authorize URL and fails at
766
- // the consent screen rather than at startup
767
- if (!config.clientId) {
768
- throw new Error('DiscordOAuthConfig missing clientId.');
769
- } else if (!config.clientSecret) {
770
- throw new Error('DiscordOAuthConfig missing clientSecret.');
771
- }
772
- var baseFetch = fetchFactory({
773
- config: config
774
- });
775
- var fetch$1 = handleDiscordOAuthErrorFetch(baseFetch, logDiscordOAuthErrorFunction);
776
- var fetchJson = fetch.fetchJsonFunction(fetch$1, {
777
- handleFetchJsonParseErrorFunction: fetch.returnNullHandleFetchJsonParseErrorFunction
778
- });
779
- var oauthContext = {
780
- fetch: fetch$1,
781
- fetchJson: fetchJson,
782
- config: config
783
- };
784
- var discordOAuth = {
785
- oauthContext: oauthContext
786
- };
787
- return discordOAuth;
788
- };
789
- }
790
-
791
- exports.ALL_DISCORD_OAUTH_SCOPES = ALL_DISCORD_OAUTH_SCOPES;
792
- exports.DEFAULT_DISCORD_MESSAGES_PER_PAGE = DEFAULT_DISCORD_MESSAGES_PER_PAGE;
793
- exports.DISCORD_API_URL = DISCORD_API_URL;
794
- exports.DISCORD_OAUTH_AUTHORIZE_RESPONSE_TYPE = DISCORD_OAUTH_AUTHORIZE_RESPONSE_TYPE;
795
- exports.DISCORD_OAUTH_AUTHORIZE_URL = DISCORD_OAUTH_AUTHORIZE_URL;
796
- exports.DISCORD_OAUTH_CURRENT_USER_PATH = DISCORD_OAUTH_CURRENT_USER_PATH;
797
- exports.DISCORD_OAUTH_INVALID_GRANT_ERROR_CODE = DISCORD_OAUTH_INVALID_GRANT_ERROR_CODE;
798
- exports.DISCORD_OAUTH_INVALID_SCOPE_ERROR_CODE = DISCORD_OAUTH_INVALID_SCOPE_ERROR_CODE;
799
- exports.DISCORD_OAUTH_REVOKE_PATH = DISCORD_OAUTH_REVOKE_PATH;
800
- exports.DISCORD_OAUTH_SCOPE_DELIMITER = DISCORD_OAUTH_SCOPE_DELIMITER;
801
- exports.DISCORD_OAUTH_TOKEN_CONTENT_TYPE = DISCORD_OAUTH_TOKEN_CONTENT_TYPE;
802
- exports.DISCORD_OAUTH_TOKEN_PATH = DISCORD_OAUTH_TOKEN_PATH;
803
- exports.DiscordOAuthError = DiscordOAuthError;
804
- exports.DiscordOAuthFetchResponseError = DiscordOAuthFetchResponseError;
805
- exports.discordAccessTokenFromTokenResponse = discordAccessTokenFromTokenResponse;
806
- exports.discordFetchMessagePageFactory = discordFetchMessagePageFactory;
807
- exports.discordOAuthAuthorizeUrlFactory = discordOAuthAuthorizeUrlFactory;
808
- exports.discordOAuthBasicAuthorizationHeader = discordOAuthBasicAuthorizationHeader;
809
- exports.discordOAuthFactory = discordOAuthFactory;
810
- exports.exchangeAuthorizationCode = exchangeAuthorizationCode;
811
- exports.handleDiscordOAuthErrorFetch = handleDiscordOAuthErrorFetch;
812
- exports.isDiscordOAuthScope = isDiscordOAuthScope;
813
- exports.logDiscordOAuthErrorFunction = logDiscordOAuthErrorFunction;
814
- exports.logDiscordOAuthErrorToConsole = logDiscordOAuthErrorToConsole;
815
- exports.parseDiscordOAuthError = parseDiscordOAuthError;
816
- exports.readCurrentUser = readCurrentUser;
817
- exports.refreshAccessToken = refreshAccessToken;