@logto/connector-github 1.3.0 → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -1,5 +1,4 @@
1
- import { got, HTTPError } from 'got';
2
- import { ConnectorPlatform, ConnectorConfigFormItemType, ConnectorError, ConnectorErrorCodes, ConnectorType, validateConfig, parseJson } from '@logto/connector-kit';
1
+ import { ConnectorPlatform, ConnectorConfigFormItemType, ConnectorError, ConnectorErrorCodes, ConnectorType, validateConfig, jsonGuard } from '@logto/connector-kit';
3
2
  import { z } from 'zod';
4
3
 
5
4
  // https://github.com/facebook/jest/issues/7547
@@ -27,678 +26,587 @@ const notFalsy = (value) => Boolean(value);
27
26
  */
28
27
  const conditional = (exp) => (notFalsy(exp) ? exp : undefined);
29
28
 
30
- const token = '%[a-f0-9]{2}';
31
- const singleMatcher = new RegExp('(' + token + ')|([^%]+?)', 'gi');
32
- const multiMatcher = new RegExp('(' + token + ')+', 'gi');
33
-
34
- function decodeComponents(components, split) {
35
- try {
36
- // Try to decode the entire string first
37
- return [decodeURIComponent(components.join(''))];
38
- } catch {
39
- // Do nothing
40
- }
41
-
42
- if (components.length === 1) {
43
- return components;
44
- }
45
-
46
- split = split || 1;
47
-
48
- // Split the array in 2 parts
49
- const left = components.slice(0, split);
50
- const right = components.slice(split);
51
-
52
- return Array.prototype.concat.call([], decodeComponents(left), decodeComponents(right));
53
- }
54
-
55
- function decode$1(input) {
56
- try {
57
- return decodeURIComponent(input);
58
- } catch {
59
- let tokens = input.match(singleMatcher) || [];
60
-
61
- for (let i = 1; i < tokens.length; i++) {
62
- input = decodeComponents(tokens, i).join('');
63
-
64
- tokens = input.match(singleMatcher) || [];
65
- }
66
-
67
- return input;
68
- }
69
- }
70
-
71
- function customDecodeURIComponent(input) {
72
- // Keep track of all the replacements and prefill the map with the `BOM`
73
- const replaceMap = {
74
- '%FE%FF': '\uFFFD\uFFFD',
75
- '%FF%FE': '\uFFFD\uFFFD',
76
- };
77
-
78
- let match = multiMatcher.exec(input);
79
- while (match) {
80
- try {
81
- // Decode as big chunks as possible
82
- replaceMap[match[0]] = decodeURIComponent(match[0]);
83
- } catch {
84
- const result = decode$1(match[0]);
85
-
86
- if (result !== match[0]) {
87
- replaceMap[match[0]] = result;
88
- }
89
- }
90
-
91
- match = multiMatcher.exec(input);
92
- }
93
-
94
- // Add `%C2` at the end of the map to make sure it does not replace the combinator before everything else
95
- replaceMap['%C2'] = '\uFFFD';
96
-
97
- const entries = Object.keys(replaceMap);
98
-
99
- for (const key of entries) {
100
- // Replace all decoded components
101
- input = input.replace(new RegExp(key, 'g'), replaceMap[key]);
102
- }
103
-
104
- return input;
105
- }
106
-
107
- function decodeUriComponent(encodedURI) {
108
- if (typeof encodedURI !== 'string') {
109
- throw new TypeError('Expected `encodedURI` to be of type `string`, got `' + typeof encodedURI + '`');
110
- }
111
-
112
- try {
113
- // Try the built in decoder first
114
- return decodeURIComponent(encodedURI);
115
- } catch {
116
- // Fallback to a more advanced decoder
117
- return customDecodeURIComponent(encodedURI);
118
- }
119
- }
120
-
121
- function splitOnFirst(string, separator) {
122
- if (!(typeof string === 'string' && typeof separator === 'string')) {
123
- throw new TypeError('Expected the arguments to be of type `string`');
124
- }
125
-
126
- if (string === '' || separator === '') {
127
- return [];
128
- }
129
-
130
- const separatorIndex = string.indexOf(separator);
131
-
132
- if (separatorIndex === -1) {
133
- return [];
134
- }
135
-
136
- return [
137
- string.slice(0, separatorIndex),
138
- string.slice(separatorIndex + separator.length)
139
- ];
140
- }
141
-
142
- function includeKeys(object, predicate) {
143
- const result = {};
144
-
145
- if (Array.isArray(predicate)) {
146
- for (const key of predicate) {
147
- const descriptor = Object.getOwnPropertyDescriptor(object, key);
148
- if (descriptor?.enumerable) {
149
- Object.defineProperty(result, key, descriptor);
150
- }
151
- }
152
- } else {
153
- // `Reflect.ownKeys()` is required to retrieve symbol properties
154
- for (const key of Reflect.ownKeys(object)) {
155
- const descriptor = Object.getOwnPropertyDescriptor(object, key);
156
- if (descriptor.enumerable) {
157
- const value = object[key];
158
- if (predicate(key, value, object)) {
159
- Object.defineProperty(result, key, descriptor);
160
- }
161
- }
162
- }
163
- }
164
-
165
- return result;
166
- }
167
-
168
- const isNullOrUndefined = value => value === null || value === undefined;
169
-
170
- // eslint-disable-next-line unicorn/prefer-code-point
171
- const strictUriEncode = string => encodeURIComponent(string).replaceAll(/[!'()*]/g, x => `%${x.charCodeAt(0).toString(16).toUpperCase()}`);
172
-
173
- const encodeFragmentIdentifier = Symbol('encodeFragmentIdentifier');
174
-
175
- function encoderForArrayFormat(options) {
176
- switch (options.arrayFormat) {
177
- case 'index': {
178
- return key => (result, value) => {
179
- const index = result.length;
180
-
181
- if (
182
- value === undefined
183
- || (options.skipNull && value === null)
184
- || (options.skipEmptyString && value === '')
185
- ) {
186
- return result;
187
- }
188
-
189
- if (value === null) {
190
- return [
191
- ...result, [encode(key, options), '[', index, ']'].join(''),
192
- ];
193
- }
194
-
195
- return [
196
- ...result,
197
- [encode(key, options), '[', encode(index, options), ']=', encode(value, options)].join(''),
198
- ];
199
- };
200
- }
201
-
202
- case 'bracket': {
203
- return key => (result, value) => {
204
- if (
205
- value === undefined
206
- || (options.skipNull && value === null)
207
- || (options.skipEmptyString && value === '')
208
- ) {
209
- return result;
210
- }
211
-
212
- if (value === null) {
213
- return [
214
- ...result,
215
- [encode(key, options), '[]'].join(''),
216
- ];
217
- }
218
-
219
- return [
220
- ...result,
221
- [encode(key, options), '[]=', encode(value, options)].join(''),
222
- ];
223
- };
224
- }
225
-
226
- case 'colon-list-separator': {
227
- return key => (result, value) => {
228
- if (
229
- value === undefined
230
- || (options.skipNull && value === null)
231
- || (options.skipEmptyString && value === '')
232
- ) {
233
- return result;
234
- }
235
-
236
- if (value === null) {
237
- return [
238
- ...result,
239
- [encode(key, options), ':list='].join(''),
240
- ];
241
- }
242
-
243
- return [
244
- ...result,
245
- [encode(key, options), ':list=', encode(value, options)].join(''),
246
- ];
247
- };
248
- }
249
-
250
- case 'comma':
251
- case 'separator':
252
- case 'bracket-separator': {
253
- const keyValueSeparator = options.arrayFormat === 'bracket-separator'
254
- ? '[]='
255
- : '=';
256
-
257
- return key => (result, value) => {
258
- if (
259
- value === undefined
260
- || (options.skipNull && value === null)
261
- || (options.skipEmptyString && value === '')
262
- ) {
263
- return result;
264
- }
265
-
266
- // Translate null to an empty string so that it doesn't serialize as 'null'
267
- value = value === null ? '' : value;
268
-
269
- if (result.length === 0) {
270
- return [[encode(key, options), keyValueSeparator, encode(value, options)].join('')];
271
- }
272
-
273
- return [[result, encode(value, options)].join(options.arrayFormatSeparator)];
274
- };
275
- }
276
-
277
- default: {
278
- return key => (result, value) => {
279
- if (
280
- value === undefined
281
- || (options.skipNull && value === null)
282
- || (options.skipEmptyString && value === '')
283
- ) {
284
- return result;
285
- }
286
-
287
- if (value === null) {
288
- return [
289
- ...result,
290
- encode(key, options),
291
- ];
292
- }
293
-
294
- return [
295
- ...result,
296
- [encode(key, options), '=', encode(value, options)].join(''),
297
- ];
298
- };
299
- }
300
- }
301
- }
302
-
303
- function parserForArrayFormat(options) {
304
- let result;
305
-
306
- switch (options.arrayFormat) {
307
- case 'index': {
308
- return (key, value, accumulator) => {
309
- result = /\[(\d*)]$/.exec(key);
310
-
311
- key = key.replace(/\[\d*]$/, '');
312
-
313
- if (!result) {
314
- accumulator[key] = value;
315
- return;
316
- }
317
-
318
- if (accumulator[key] === undefined) {
319
- accumulator[key] = {};
320
- }
321
-
322
- accumulator[key][result[1]] = value;
323
- };
324
- }
325
-
326
- case 'bracket': {
327
- return (key, value, accumulator) => {
328
- result = /(\[])$/.exec(key);
329
- key = key.replace(/\[]$/, '');
330
-
331
- if (!result) {
332
- accumulator[key] = value;
333
- return;
334
- }
335
-
336
- if (accumulator[key] === undefined) {
337
- accumulator[key] = [value];
338
- return;
339
- }
340
-
341
- accumulator[key] = [...accumulator[key], value];
342
- };
343
- }
344
-
345
- case 'colon-list-separator': {
346
- return (key, value, accumulator) => {
347
- result = /(:list)$/.exec(key);
348
- key = key.replace(/:list$/, '');
349
-
350
- if (!result) {
351
- accumulator[key] = value;
352
- return;
353
- }
354
-
355
- if (accumulator[key] === undefined) {
356
- accumulator[key] = [value];
357
- return;
358
- }
359
-
360
- accumulator[key] = [...accumulator[key], value];
361
- };
362
- }
363
-
364
- case 'comma':
365
- case 'separator': {
366
- return (key, value, accumulator) => {
367
- const isArray = typeof value === 'string' && value.includes(options.arrayFormatSeparator);
368
- const isEncodedArray = (typeof value === 'string' && !isArray && decode(value, options).includes(options.arrayFormatSeparator));
369
- value = isEncodedArray ? decode(value, options) : value;
370
- const newValue = isArray || isEncodedArray ? value.split(options.arrayFormatSeparator).map(item => decode(item, options)) : (value === null ? value : decode(value, options));
371
- accumulator[key] = newValue;
372
- };
373
- }
374
-
375
- case 'bracket-separator': {
376
- return (key, value, accumulator) => {
377
- const isArray = /(\[])$/.test(key);
378
- key = key.replace(/\[]$/, '');
379
-
380
- if (!isArray) {
381
- accumulator[key] = value ? decode(value, options) : value;
382
- return;
383
- }
384
-
385
- const arrayValue = value === null
386
- ? []
387
- : value.split(options.arrayFormatSeparator).map(item => decode(item, options));
388
-
389
- if (accumulator[key] === undefined) {
390
- accumulator[key] = arrayValue;
391
- return;
392
- }
393
-
394
- accumulator[key] = [...accumulator[key], ...arrayValue];
395
- };
396
- }
397
-
398
- default: {
399
- return (key, value, accumulator) => {
400
- if (accumulator[key] === undefined) {
401
- accumulator[key] = value;
402
- return;
403
- }
404
-
405
- accumulator[key] = [...[accumulator[key]].flat(), value];
406
- };
407
- }
408
- }
409
- }
410
-
411
- function validateArrayFormatSeparator(value) {
412
- if (typeof value !== 'string' || value.length !== 1) {
413
- throw new TypeError('arrayFormatSeparator must be single character string');
414
- }
415
- }
416
-
417
- function encode(value, options) {
418
- if (options.encode) {
419
- return options.strict ? strictUriEncode(value) : encodeURIComponent(value);
420
- }
421
-
422
- return value;
423
- }
424
-
425
- function decode(value, options) {
426
- if (options.decode) {
427
- return decodeUriComponent(value);
428
- }
429
-
430
- return value;
431
- }
432
-
433
- function keysSorter(input) {
434
- if (Array.isArray(input)) {
435
- return input.sort();
436
- }
437
-
438
- if (typeof input === 'object') {
439
- return keysSorter(Object.keys(input))
440
- .sort((a, b) => Number(a) - Number(b))
441
- .map(key => input[key]);
442
- }
443
-
444
- return input;
445
- }
446
-
447
- function removeHash(input) {
448
- const hashStart = input.indexOf('#');
449
- if (hashStart !== -1) {
450
- input = input.slice(0, hashStart);
451
- }
452
-
453
- return input;
454
- }
455
-
456
- function getHash(url) {
457
- let hash = '';
458
- const hashStart = url.indexOf('#');
459
- if (hashStart !== -1) {
460
- hash = url.slice(hashStart);
461
- }
462
-
463
- return hash;
464
- }
465
-
466
- function parseValue(value, options) {
467
- if (options.parseNumbers && !Number.isNaN(Number(value)) && (typeof value === 'string' && value.trim() !== '')) {
468
- value = Number(value);
469
- } else if (options.parseBooleans && value !== null && (value.toLowerCase() === 'true' || value.toLowerCase() === 'false')) {
470
- value = value.toLowerCase() === 'true';
471
- }
472
-
473
- return value;
474
- }
475
-
476
- function extract(input) {
477
- input = removeHash(input);
478
- const queryStart = input.indexOf('?');
479
- if (queryStart === -1) {
480
- return '';
481
- }
482
-
483
- return input.slice(queryStart + 1);
484
- }
485
-
486
- function parse(query, options) {
487
- options = {
488
- decode: true,
489
- sort: true,
490
- arrayFormat: 'none',
491
- arrayFormatSeparator: ',',
492
- parseNumbers: false,
493
- parseBooleans: false,
494
- ...options,
495
- };
496
-
497
- validateArrayFormatSeparator(options.arrayFormatSeparator);
498
-
499
- const formatter = parserForArrayFormat(options);
500
-
501
- // Create an object with no prototype
502
- const returnValue = Object.create(null);
503
-
504
- if (typeof query !== 'string') {
505
- return returnValue;
506
- }
507
-
508
- query = query.trim().replace(/^[?#&]/, '');
509
-
510
- if (!query) {
511
- return returnValue;
512
- }
513
-
514
- for (const parameter of query.split('&')) {
515
- if (parameter === '') {
516
- continue;
517
- }
518
-
519
- const parameter_ = options.decode ? parameter.replaceAll('+', ' ') : parameter;
520
-
521
- let [key, value] = splitOnFirst(parameter_, '=');
522
-
523
- if (key === undefined) {
524
- key = parameter_;
525
- }
526
-
527
- // Missing `=` should be `null`:
528
- // http://w3.org/TR/2012/WD-url-20120524/#collect-url-parameters
529
- value = value === undefined ? null : (['comma', 'separator', 'bracket-separator'].includes(options.arrayFormat) ? value : decode(value, options));
530
- formatter(decode(key, options), value, returnValue);
531
- }
532
-
533
- for (const [key, value] of Object.entries(returnValue)) {
534
- if (typeof value === 'object' && value !== null) {
535
- for (const [key2, value2] of Object.entries(value)) {
536
- value[key2] = parseValue(value2, options);
537
- }
538
- } else {
539
- returnValue[key] = parseValue(value, options);
540
- }
541
- }
542
-
543
- if (options.sort === false) {
544
- return returnValue;
545
- }
546
-
547
- // TODO: Remove the use of `reduce`.
548
- // eslint-disable-next-line unicorn/no-array-reduce
549
- return (options.sort === true ? Object.keys(returnValue).sort() : Object.keys(returnValue).sort(options.sort)).reduce((result, key) => {
550
- const value = returnValue[key];
551
- result[key] = Boolean(value) && typeof value === 'object' && !Array.isArray(value) ? keysSorter(value) : value;
552
- return result;
553
- }, Object.create(null));
554
- }
555
-
556
- function stringify(object, options) {
557
- if (!object) {
558
- return '';
559
- }
560
-
561
- options = {
562
- encode: true,
563
- strict: true,
564
- arrayFormat: 'none',
565
- arrayFormatSeparator: ',',
566
- ...options,
567
- };
568
-
569
- validateArrayFormatSeparator(options.arrayFormatSeparator);
570
-
571
- const shouldFilter = key => (
572
- (options.skipNull && isNullOrUndefined(object[key]))
573
- || (options.skipEmptyString && object[key] === '')
574
- );
575
-
576
- const formatter = encoderForArrayFormat(options);
577
-
578
- const objectCopy = {};
579
-
580
- for (const [key, value] of Object.entries(object)) {
581
- if (!shouldFilter(key)) {
582
- objectCopy[key] = value;
583
- }
584
- }
585
-
586
- const keys = Object.keys(objectCopy);
587
-
588
- if (options.sort !== false) {
589
- keys.sort(options.sort);
590
- }
591
-
592
- return keys.map(key => {
593
- const value = object[key];
594
-
595
- if (value === undefined) {
596
- return '';
597
- }
598
-
599
- if (value === null) {
600
- return encode(key, options);
601
- }
602
-
603
- if (Array.isArray(value)) {
604
- if (value.length === 0 && options.arrayFormat === 'bracket-separator') {
605
- return encode(key, options) + '[]';
606
- }
607
-
608
- return value
609
- .reduce(formatter(key), [])
610
- .join('&');
611
- }
29
+ // Intended
30
+ // eslint-disable-next-line @typescript-eslint/no-empty-function
31
+ const isPromise = (value) => value !== null &&
32
+ (typeof value === 'object' || typeof value === 'function') &&
33
+ 'then' in value &&
34
+ typeof value.then === 'function';
35
+ // eslint-disable-next-line @typescript-eslint/promise-function-async
36
+ const trySafe = (exec, onError) => {
37
+ try {
38
+ const unwrapped = typeof exec === 'function' ? exec() : exec;
39
+ return isPromise(unwrapped)
40
+ ? // eslint-disable-next-line promise/prefer-await-to-then
41
+ unwrapped.catch((error) => {
42
+ onError?.(error);
43
+ })
44
+ : unwrapped;
45
+ }
46
+ catch (error) {
47
+ onError?.(error);
48
+ }
49
+ };
612
50
 
613
- return encode(key, options) + '=' + encode(value, options);
614
- }).filter(x => x.length > 0).join('&');
51
+ // eslint-lint-disable-next-line @typescript-eslint/naming-convention
52
+ class HTTPError extends Error {
53
+ constructor(response, request, options) {
54
+ const code = (response.status || response.status === 0) ? response.status : '';
55
+ const title = response.statusText || '';
56
+ const status = `${code} ${title}`.trim();
57
+ const reason = status ? `status code ${status}` : 'an unknown error';
58
+ super(`Request failed with ${reason}`);
59
+ Object.defineProperty(this, "response", {
60
+ enumerable: true,
61
+ configurable: true,
62
+ writable: true,
63
+ value: void 0
64
+ });
65
+ Object.defineProperty(this, "request", {
66
+ enumerable: true,
67
+ configurable: true,
68
+ writable: true,
69
+ value: void 0
70
+ });
71
+ Object.defineProperty(this, "options", {
72
+ enumerable: true,
73
+ configurable: true,
74
+ writable: true,
75
+ value: void 0
76
+ });
77
+ this.name = 'HTTPError';
78
+ this.response = response;
79
+ this.request = request;
80
+ this.options = options;
81
+ }
615
82
  }
616
83
 
617
- function parseUrl(url, options) {
618
- options = {
619
- decode: true,
620
- ...options,
621
- };
622
-
623
- let [url_, hash] = splitOnFirst(url, '#');
624
-
625
- if (url_ === undefined) {
626
- url_ = url;
627
- }
628
-
629
- return {
630
- url: url_?.split('?')?.[0] ?? '',
631
- query: parse(extract(url), options),
632
- ...(options && options.parseFragmentIdentifier && hash ? {fragmentIdentifier: decode(hash, options)} : {}),
633
- };
84
+ class TimeoutError extends Error {
85
+ constructor(request) {
86
+ super('Request timed out');
87
+ Object.defineProperty(this, "request", {
88
+ enumerable: true,
89
+ configurable: true,
90
+ writable: true,
91
+ value: void 0
92
+ });
93
+ this.name = 'TimeoutError';
94
+ this.request = request;
95
+ }
634
96
  }
635
97
 
636
- function stringifyUrl(object, options) {
637
- options = {
638
- encode: true,
639
- strict: true,
640
- [encodeFragmentIdentifier]: true,
641
- ...options,
642
- };
98
+ // eslint-disable-next-line @typescript-eslint/ban-types
99
+ const isObject = (value) => value !== null && typeof value === 'object';
643
100
 
644
- const url = removeHash(object.url).split('?')[0] || '';
645
- const queryFromUrl = extract(object.url);
646
-
647
- const query = {
648
- ...parse(queryFromUrl, {sort: false}),
649
- ...object.query,
650
- };
101
+ const validateAndMerge = (...sources) => {
102
+ for (const source of sources) {
103
+ if ((!isObject(source) || Array.isArray(source)) && source !== undefined) {
104
+ throw new TypeError('The `options` argument must be an object');
105
+ }
106
+ }
107
+ return deepMerge({}, ...sources);
108
+ };
109
+ const mergeHeaders = (source1 = {}, source2 = {}) => {
110
+ const result = new globalThis.Headers(source1);
111
+ const isHeadersInstance = source2 instanceof globalThis.Headers;
112
+ const source = new globalThis.Headers(source2);
113
+ for (const [key, value] of source.entries()) {
114
+ if ((isHeadersInstance && value === 'undefined') || value === undefined) {
115
+ result.delete(key);
116
+ }
117
+ else {
118
+ result.set(key, value);
119
+ }
120
+ }
121
+ return result;
122
+ };
123
+ // TODO: Make this strongly-typed (no `any`).
124
+ const deepMerge = (...sources) => {
125
+ let returnValue = {};
126
+ let headers = {};
127
+ for (const source of sources) {
128
+ if (Array.isArray(source)) {
129
+ if (!Array.isArray(returnValue)) {
130
+ returnValue = [];
131
+ }
132
+ returnValue = [...returnValue, ...source];
133
+ }
134
+ else if (isObject(source)) {
135
+ for (let [key, value] of Object.entries(source)) {
136
+ if (isObject(value) && key in returnValue) {
137
+ value = deepMerge(returnValue[key], value);
138
+ }
139
+ returnValue = { ...returnValue, [key]: value };
140
+ }
141
+ if (isObject(source.headers)) {
142
+ headers = mergeHeaders(headers, source.headers);
143
+ returnValue.headers = headers;
144
+ }
145
+ }
146
+ }
147
+ return returnValue;
148
+ };
651
149
 
652
- let queryString = stringify(query, options);
653
- queryString &&= `?${queryString}`;
150
+ const supportsRequestStreams = (() => {
151
+ let duplexAccessed = false;
152
+ let hasContentType = false;
153
+ const supportsReadableStream = typeof globalThis.ReadableStream === 'function';
154
+ const supportsRequest = typeof globalThis.Request === 'function';
155
+ if (supportsReadableStream && supportsRequest) {
156
+ hasContentType = new globalThis.Request('https://empty.invalid', {
157
+ body: new globalThis.ReadableStream(),
158
+ method: 'POST',
159
+ // @ts-expect-error - Types are outdated.
160
+ get duplex() {
161
+ duplexAccessed = true;
162
+ return 'half';
163
+ },
164
+ }).headers.has('Content-Type');
165
+ }
166
+ return duplexAccessed && !hasContentType;
167
+ })();
168
+ const supportsAbortController = typeof globalThis.AbortController === 'function';
169
+ const supportsResponseStreams = typeof globalThis.ReadableStream === 'function';
170
+ const supportsFormData = typeof globalThis.FormData === 'function';
171
+ const requestMethods = ['get', 'post', 'put', 'patch', 'head', 'delete'];
172
+ const responseTypes = {
173
+ json: 'application/json',
174
+ text: 'text/*',
175
+ formData: 'multipart/form-data',
176
+ arrayBuffer: '*/*',
177
+ blob: '*/*',
178
+ };
179
+ // The maximum value of a 32bit int (see issue #117)
180
+ const maxSafeTimeout = 2_147_483_647;
181
+ const stop = Symbol('stop');
182
+ const kyOptionKeys = {
183
+ json: true,
184
+ parseJson: true,
185
+ searchParams: true,
186
+ prefixUrl: true,
187
+ retry: true,
188
+ timeout: true,
189
+ hooks: true,
190
+ throwHttpErrors: true,
191
+ onDownloadProgress: true,
192
+ fetch: true,
193
+ };
194
+ const requestOptionsRegistry = {
195
+ method: true,
196
+ headers: true,
197
+ body: true,
198
+ mode: true,
199
+ credentials: true,
200
+ cache: true,
201
+ redirect: true,
202
+ referrer: true,
203
+ referrerPolicy: true,
204
+ integrity: true,
205
+ keepalive: true,
206
+ signal: true,
207
+ window: true,
208
+ dispatcher: true,
209
+ duplex: true,
210
+ priority: true,
211
+ };
654
212
 
655
- let hash = getHash(object.url);
656
- if (typeof object.fragmentIdentifier === 'string') {
657
- const urlObjectForFragmentEncode = new URL(url);
658
- urlObjectForFragmentEncode.hash = object.fragmentIdentifier;
659
- hash = options[encodeFragmentIdentifier] ? urlObjectForFragmentEncode.hash : `#${object.fragmentIdentifier}`;
660
- }
213
+ const normalizeRequestMethod = (input) => requestMethods.includes(input) ? input.toUpperCase() : input;
214
+ const retryMethods = ['get', 'put', 'head', 'delete', 'options', 'trace'];
215
+ const retryStatusCodes = [408, 413, 429, 500, 502, 503, 504];
216
+ const retryAfterStatusCodes = [413, 429, 503];
217
+ const defaultRetryOptions = {
218
+ limit: 2,
219
+ methods: retryMethods,
220
+ statusCodes: retryStatusCodes,
221
+ afterStatusCodes: retryAfterStatusCodes,
222
+ maxRetryAfter: Number.POSITIVE_INFINITY,
223
+ backoffLimit: Number.POSITIVE_INFINITY,
224
+ delay: attemptCount => 0.3 * (2 ** (attemptCount - 1)) * 1000,
225
+ };
226
+ const normalizeRetryOptions = (retry = {}) => {
227
+ if (typeof retry === 'number') {
228
+ return {
229
+ ...defaultRetryOptions,
230
+ limit: retry,
231
+ };
232
+ }
233
+ if (retry.methods && !Array.isArray(retry.methods)) {
234
+ throw new Error('retry.methods must be an array');
235
+ }
236
+ if (retry.statusCodes && !Array.isArray(retry.statusCodes)) {
237
+ throw new Error('retry.statusCodes must be an array');
238
+ }
239
+ return {
240
+ ...defaultRetryOptions,
241
+ ...retry,
242
+ afterStatusCodes: retryAfterStatusCodes,
243
+ };
244
+ };
661
245
 
662
- return `${url}${queryString}${hash}`;
246
+ // `Promise.race()` workaround (#91)
247
+ async function timeout(request, init, abortController, options) {
248
+ return new Promise((resolve, reject) => {
249
+ const timeoutId = setTimeout(() => {
250
+ if (abortController) {
251
+ abortController.abort();
252
+ }
253
+ reject(new TimeoutError(request));
254
+ }, options.timeout);
255
+ void options
256
+ .fetch(request, init)
257
+ .then(resolve)
258
+ .catch(reject)
259
+ .then(() => {
260
+ clearTimeout(timeoutId);
261
+ });
262
+ });
663
263
  }
664
264
 
665
- function pick(input, filter, options) {
666
- options = {
667
- parseFragmentIdentifier: true,
668
- [encodeFragmentIdentifier]: false,
669
- ...options,
670
- };
671
-
672
- const {url, query, fragmentIdentifier} = parseUrl(input, options);
673
-
674
- return stringifyUrl({
675
- url,
676
- query: includeKeys(query, filter),
677
- fragmentIdentifier,
678
- }, options);
265
+ // https://github.com/sindresorhus/delay/tree/ab98ae8dfcb38e1593286c94d934e70d14a4e111
266
+ async function delay(ms, { signal }) {
267
+ return new Promise((resolve, reject) => {
268
+ if (signal) {
269
+ signal.throwIfAborted();
270
+ signal.addEventListener('abort', abortHandler, { once: true });
271
+ }
272
+ function abortHandler() {
273
+ clearTimeout(timeoutId);
274
+ reject(signal.reason);
275
+ }
276
+ const timeoutId = setTimeout(() => {
277
+ signal?.removeEventListener('abort', abortHandler);
278
+ resolve();
279
+ }, ms);
280
+ });
679
281
  }
680
282
 
681
- function exclude(input, filter, options) {
682
- const exclusionFilter = Array.isArray(filter) ? key => !filter.includes(key) : (key, value) => !filter(key, value);
283
+ const findUnknownOptions = (request, options) => {
284
+ const unknownOptions = {};
285
+ for (const key in options) {
286
+ if (!(key in requestOptionsRegistry) && !(key in kyOptionKeys) && !(key in request)) {
287
+ unknownOptions[key] = options[key];
288
+ }
289
+ }
290
+ return unknownOptions;
291
+ };
683
292
 
684
- return pick(input, exclusionFilter, options);
293
+ class Ky {
294
+ static create(input, options) {
295
+ const ky = new Ky(input, options);
296
+ const function_ = async () => {
297
+ if (typeof ky._options.timeout === 'number' && ky._options.timeout > maxSafeTimeout) {
298
+ throw new RangeError(`The \`timeout\` option cannot be greater than ${maxSafeTimeout}`);
299
+ }
300
+ // Delay the fetch so that body method shortcuts can set the Accept header
301
+ await Promise.resolve();
302
+ let response = await ky._fetch();
303
+ for (const hook of ky._options.hooks.afterResponse) {
304
+ // eslint-disable-next-line no-await-in-loop
305
+ const modifiedResponse = await hook(ky.request, ky._options, ky._decorateResponse(response.clone()));
306
+ if (modifiedResponse instanceof globalThis.Response) {
307
+ response = modifiedResponse;
308
+ }
309
+ }
310
+ ky._decorateResponse(response);
311
+ if (!response.ok && ky._options.throwHttpErrors) {
312
+ let error = new HTTPError(response, ky.request, ky._options);
313
+ for (const hook of ky._options.hooks.beforeError) {
314
+ // eslint-disable-next-line no-await-in-loop
315
+ error = await hook(error);
316
+ }
317
+ throw error;
318
+ }
319
+ // If `onDownloadProgress` is passed, it uses the stream API internally
320
+ /* istanbul ignore next */
321
+ if (ky._options.onDownloadProgress) {
322
+ if (typeof ky._options.onDownloadProgress !== 'function') {
323
+ throw new TypeError('The `onDownloadProgress` option must be a function');
324
+ }
325
+ if (!supportsResponseStreams) {
326
+ throw new Error('Streams are not supported in your environment. `ReadableStream` is missing.');
327
+ }
328
+ return ky._stream(response.clone(), ky._options.onDownloadProgress);
329
+ }
330
+ return response;
331
+ };
332
+ const isRetriableMethod = ky._options.retry.methods.includes(ky.request.method.toLowerCase());
333
+ const result = (isRetriableMethod ? ky._retry(function_) : function_());
334
+ for (const [type, mimeType] of Object.entries(responseTypes)) {
335
+ result[type] = async () => {
336
+ // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
337
+ ky.request.headers.set('accept', ky.request.headers.get('accept') || mimeType);
338
+ const awaitedResult = await result;
339
+ const response = awaitedResult.clone();
340
+ if (type === 'json') {
341
+ if (response.status === 204) {
342
+ return '';
343
+ }
344
+ const arrayBuffer = await response.clone().arrayBuffer();
345
+ const responseSize = arrayBuffer.byteLength;
346
+ if (responseSize === 0) {
347
+ return '';
348
+ }
349
+ if (options.parseJson) {
350
+ return options.parseJson(await response.text());
351
+ }
352
+ }
353
+ return response[type]();
354
+ };
355
+ }
356
+ return result;
357
+ }
358
+ // eslint-disable-next-line complexity
359
+ constructor(input, options = {}) {
360
+ Object.defineProperty(this, "request", {
361
+ enumerable: true,
362
+ configurable: true,
363
+ writable: true,
364
+ value: void 0
365
+ });
366
+ Object.defineProperty(this, "abortController", {
367
+ enumerable: true,
368
+ configurable: true,
369
+ writable: true,
370
+ value: void 0
371
+ });
372
+ Object.defineProperty(this, "_retryCount", {
373
+ enumerable: true,
374
+ configurable: true,
375
+ writable: true,
376
+ value: 0
377
+ });
378
+ Object.defineProperty(this, "_input", {
379
+ enumerable: true,
380
+ configurable: true,
381
+ writable: true,
382
+ value: void 0
383
+ });
384
+ Object.defineProperty(this, "_options", {
385
+ enumerable: true,
386
+ configurable: true,
387
+ writable: true,
388
+ value: void 0
389
+ });
390
+ this._input = input;
391
+ const credentials = this._input instanceof Request && 'credentials' in Request.prototype
392
+ ? this._input.credentials
393
+ : undefined;
394
+ this._options = {
395
+ ...(credentials && { credentials }), // For exactOptionalPropertyTypes
396
+ ...options,
397
+ headers: mergeHeaders(this._input.headers, options.headers),
398
+ hooks: deepMerge({
399
+ beforeRequest: [],
400
+ beforeRetry: [],
401
+ beforeError: [],
402
+ afterResponse: [],
403
+ }, options.hooks),
404
+ method: normalizeRequestMethod(options.method ?? this._input.method),
405
+ // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
406
+ prefixUrl: String(options.prefixUrl || ''),
407
+ retry: normalizeRetryOptions(options.retry),
408
+ throwHttpErrors: options.throwHttpErrors !== false,
409
+ timeout: options.timeout ?? 10_000,
410
+ fetch: options.fetch ?? globalThis.fetch.bind(globalThis),
411
+ };
412
+ if (typeof this._input !== 'string' && !(this._input instanceof URL || this._input instanceof globalThis.Request)) {
413
+ throw new TypeError('`input` must be a string, URL, or Request');
414
+ }
415
+ if (this._options.prefixUrl && typeof this._input === 'string') {
416
+ if (this._input.startsWith('/')) {
417
+ throw new Error('`input` must not begin with a slash when using `prefixUrl`');
418
+ }
419
+ if (!this._options.prefixUrl.endsWith('/')) {
420
+ this._options.prefixUrl += '/';
421
+ }
422
+ this._input = this._options.prefixUrl + this._input;
423
+ }
424
+ if (supportsAbortController) {
425
+ this.abortController = new globalThis.AbortController();
426
+ if (this._options.signal) {
427
+ const originalSignal = this._options.signal;
428
+ this._options.signal.addEventListener('abort', () => {
429
+ this.abortController.abort(originalSignal.reason);
430
+ });
431
+ }
432
+ this._options.signal = this.abortController.signal;
433
+ }
434
+ if (supportsRequestStreams) {
435
+ // @ts-expect-error - Types are outdated.
436
+ this._options.duplex = 'half';
437
+ }
438
+ this.request = new globalThis.Request(this._input, this._options);
439
+ if (this._options.searchParams) {
440
+ // eslint-disable-next-line unicorn/prevent-abbreviations
441
+ const textSearchParams = typeof this._options.searchParams === 'string'
442
+ ? this._options.searchParams.replace(/^\?/, '')
443
+ : new URLSearchParams(this._options.searchParams).toString();
444
+ // eslint-disable-next-line unicorn/prevent-abbreviations
445
+ const searchParams = '?' + textSearchParams;
446
+ const url = this.request.url.replace(/(?:\?.*?)?(?=#|$)/, searchParams);
447
+ // To provide correct form boundary, Content-Type header should be deleted each time when new Request instantiated from another one
448
+ if (((supportsFormData && this._options.body instanceof globalThis.FormData)
449
+ || this._options.body instanceof URLSearchParams) && !(this._options.headers && this._options.headers['content-type'])) {
450
+ this.request.headers.delete('content-type');
451
+ }
452
+ // The spread of `this.request` is required as otherwise it misses the `duplex` option for some reason and throws.
453
+ this.request = new globalThis.Request(new globalThis.Request(url, { ...this.request }), this._options);
454
+ }
455
+ if (this._options.json !== undefined) {
456
+ this._options.body = JSON.stringify(this._options.json);
457
+ this.request.headers.set('content-type', this._options.headers.get('content-type') ?? 'application/json');
458
+ this.request = new globalThis.Request(this.request, { body: this._options.body });
459
+ }
460
+ }
461
+ _calculateRetryDelay(error) {
462
+ this._retryCount++;
463
+ if (this._retryCount <= this._options.retry.limit && !(error instanceof TimeoutError)) {
464
+ if (error instanceof HTTPError) {
465
+ if (!this._options.retry.statusCodes.includes(error.response.status)) {
466
+ return 0;
467
+ }
468
+ const retryAfter = error.response.headers.get('Retry-After');
469
+ if (retryAfter && this._options.retry.afterStatusCodes.includes(error.response.status)) {
470
+ let after = Number(retryAfter);
471
+ if (Number.isNaN(after)) {
472
+ after = Date.parse(retryAfter) - Date.now();
473
+ }
474
+ else {
475
+ after *= 1000;
476
+ }
477
+ if (this._options.retry.maxRetryAfter !== undefined && after > this._options.retry.maxRetryAfter) {
478
+ return 0;
479
+ }
480
+ return after;
481
+ }
482
+ if (error.response.status === 413) {
483
+ return 0;
484
+ }
485
+ }
486
+ const retryDelay = this._options.retry.delay(this._retryCount);
487
+ return Math.min(this._options.retry.backoffLimit, retryDelay);
488
+ }
489
+ return 0;
490
+ }
491
+ _decorateResponse(response) {
492
+ if (this._options.parseJson) {
493
+ response.json = async () => this._options.parseJson(await response.text());
494
+ }
495
+ return response;
496
+ }
497
+ async _retry(function_) {
498
+ try {
499
+ return await function_();
500
+ }
501
+ catch (error) {
502
+ const ms = Math.min(this._calculateRetryDelay(error), maxSafeTimeout);
503
+ if (ms !== 0 && this._retryCount > 0) {
504
+ await delay(ms, { signal: this._options.signal });
505
+ for (const hook of this._options.hooks.beforeRetry) {
506
+ // eslint-disable-next-line no-await-in-loop
507
+ const hookResult = await hook({
508
+ request: this.request,
509
+ options: this._options,
510
+ error: error,
511
+ retryCount: this._retryCount,
512
+ });
513
+ // If `stop` is returned from the hook, the retry process is stopped
514
+ if (hookResult === stop) {
515
+ return;
516
+ }
517
+ }
518
+ return this._retry(function_);
519
+ }
520
+ throw error;
521
+ }
522
+ }
523
+ async _fetch() {
524
+ for (const hook of this._options.hooks.beforeRequest) {
525
+ // eslint-disable-next-line no-await-in-loop
526
+ const result = await hook(this.request, this._options);
527
+ if (result instanceof Request) {
528
+ this.request = result;
529
+ break;
530
+ }
531
+ if (result instanceof Response) {
532
+ return result;
533
+ }
534
+ }
535
+ const nonRequestOptions = findUnknownOptions(this.request, this._options);
536
+ if (this._options.timeout === false) {
537
+ return this._options.fetch(this.request.clone(), nonRequestOptions);
538
+ }
539
+ return timeout(this.request.clone(), nonRequestOptions, this.abortController, this._options);
540
+ }
541
+ /* istanbul ignore next */
542
+ _stream(response, onDownloadProgress) {
543
+ const totalBytes = Number(response.headers.get('content-length')) || 0;
544
+ let transferredBytes = 0;
545
+ if (response.status === 204) {
546
+ if (onDownloadProgress) {
547
+ onDownloadProgress({ percent: 1, totalBytes, transferredBytes }, new Uint8Array());
548
+ }
549
+ return new globalThis.Response(null, {
550
+ status: response.status,
551
+ statusText: response.statusText,
552
+ headers: response.headers,
553
+ });
554
+ }
555
+ return new globalThis.Response(new globalThis.ReadableStream({
556
+ async start(controller) {
557
+ const reader = response.body.getReader();
558
+ if (onDownloadProgress) {
559
+ onDownloadProgress({ percent: 0, transferredBytes: 0, totalBytes }, new Uint8Array());
560
+ }
561
+ async function read() {
562
+ const { done, value } = await reader.read();
563
+ if (done) {
564
+ controller.close();
565
+ return;
566
+ }
567
+ if (onDownloadProgress) {
568
+ transferredBytes += value.byteLength;
569
+ const percent = totalBytes === 0 ? 0 : transferredBytes / totalBytes;
570
+ onDownloadProgress({ percent, transferredBytes, totalBytes }, value);
571
+ }
572
+ controller.enqueue(value);
573
+ await read();
574
+ }
575
+ await read();
576
+ },
577
+ }), {
578
+ status: response.status,
579
+ statusText: response.statusText,
580
+ headers: response.headers,
581
+ });
582
+ }
685
583
  }
686
584
 
687
- var queryString = /*#__PURE__*/Object.freeze({
688
- __proto__: null,
689
- exclude: exclude,
690
- extract: extract,
691
- parse: parse,
692
- parseUrl: parseUrl,
693
- pick: pick,
694
- stringify: stringify,
695
- stringifyUrl: stringifyUrl
696
- });
585
+ /*! MIT License © Sindre Sorhus */
586
+ const createInstance = (defaults) => {
587
+ // eslint-disable-next-line @typescript-eslint/promise-function-async
588
+ const ky = (input, options) => Ky.create(input, validateAndMerge(defaults, options));
589
+ for (const method of requestMethods) {
590
+ // eslint-disable-next-line @typescript-eslint/promise-function-async
591
+ ky[method] = (input, options) => Ky.create(input, validateAndMerge(defaults, options, { method }));
592
+ }
593
+ ky.create = (newDefaults) => createInstance(validateAndMerge(newDefaults));
594
+ ky.extend = (newDefaults) => createInstance(validateAndMerge(defaults, newDefaults));
595
+ ky.stop = stop;
596
+ return ky;
597
+ };
598
+ const ky = createInstance();
697
599
 
698
600
  const authorizationEndpoint = 'https://github.com/login/oauth/authorize';
699
- const scope = 'read:user';
601
+ /**
602
+ * `read:user` read user profile data; `user:email` read user email addresses (including private email addresses).
603
+ * Ref: https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/scopes-for-oauth-apps
604
+ */
605
+ const scope = 'read:user user:email';
700
606
  const accessTokenEndpoint = 'https://github.com/login/oauth/access_token';
701
607
  const userInfoEndpoint = 'https://api.github.com/user';
608
+ // Ref: https://docs.github.com/en/rest/users/emails?apiVersion=2022-11-28#list-email-addresses-for-the-authenticated-user
609
+ const userEmailsEndpoint = 'https://api.github.com/user/emails';
702
610
  const defaultMetadata = {
703
611
  id: 'github-universal',
704
612
  target: 'github',
@@ -750,6 +658,16 @@ const githubConfigGuard = z.object({
750
658
  clientSecret: z.string(),
751
659
  scope: z.string().optional(),
752
660
  });
661
+ /**
662
+ * This guard is used to validate the response from the GitHub API when requesting the user's email addresses.
663
+ * Ref: https://docs.github.com/en/rest/users/emails?apiVersion=2022-11-28#list-email-addresses-for-the-authenticated-user
664
+ */
665
+ const emailAddressGuard = z.object({
666
+ email: z.string(),
667
+ primary: z.boolean(),
668
+ verified: z.boolean(),
669
+ visibility: z.string().nullable(),
670
+ });
753
671
  const accessTokenResponseGuard = z.object({
754
672
  access_token: z.string(),
755
673
  scope: z.string(),
@@ -801,16 +719,17 @@ const authorizationCallbackHandler = async (parameterObject) => {
801
719
  const getAccessToken = async (config, codeObject) => {
802
720
  const { code } = codeObject;
803
721
  const { clientId: client_id, clientSecret: client_secret } = config;
804
- const httpResponse = await got.post({
805
- url: accessTokenEndpoint,
806
- json: {
722
+ const httpResponse = await ky
723
+ .post(accessTokenEndpoint, {
724
+ body: new URLSearchParams({
807
725
  client_id,
808
726
  client_secret,
809
727
  code,
810
- },
811
- timeout: { request: defaultTimeout },
812
- });
813
- const result = accessTokenResponseGuard.safeParse(queryString.parse(httpResponse.body));
728
+ }),
729
+ timeout: defaultTimeout,
730
+ })
731
+ .json();
732
+ const result = accessTokenResponseGuard.safeParse(httpResponse);
814
733
  if (!result.success) {
815
734
  throw new ConnectorError(ConnectorErrorCodes.InvalidResponse, result.error);
816
735
  }
@@ -823,31 +742,53 @@ const getUserInfo = (getConfig) => async (data) => {
823
742
  const config = await getConfig(defaultMetadata.id);
824
743
  validateConfig(config, githubConfigGuard);
825
744
  const { accessToken } = await getAccessToken(config, { code });
745
+ const authedApi = ky.create({
746
+ timeout: defaultTimeout,
747
+ hooks: {
748
+ beforeRequest: [
749
+ (request) => {
750
+ request.headers.set('Authorization', `Bearer ${accessToken}`);
751
+ },
752
+ ],
753
+ },
754
+ });
826
755
  try {
827
- const httpResponse = await got.get(userInfoEndpoint, {
828
- headers: {
829
- authorization: `token ${accessToken}`,
830
- },
831
- timeout: { request: defaultTimeout },
832
- });
833
- const rawData = parseJson(httpResponse.body);
834
- const result = userInfoResponseGuard.safeParse(rawData);
835
- if (!result.success) {
836
- throw new ConnectorError(ConnectorErrorCodes.InvalidResponse, result.error);
756
+ /**
757
+ * If user(s) is using GitHub Apps (instead of OAuth Apps), they can customize
758
+ * "Account permissions" and restrict the "email addresses" visibility, and GitHub
759
+ * hence throws error instead of returning an empty array.
760
+ *
761
+ * We try catch the error and return an empty array instead.
762
+ */
763
+ const [userInfo, userEmails = []] = await Promise.all([
764
+ authedApi.get(userInfoEndpoint).json(),
765
+ trySafe(authedApi.get(userEmailsEndpoint).json()),
766
+ ]);
767
+ const userInfoResult = userInfoResponseGuard.safeParse(userInfo);
768
+ const userEmailsResult = emailAddressGuard.array().safeParse(userEmails);
769
+ if (!userInfoResult.success) {
770
+ throw new ConnectorError(ConnectorErrorCodes.InvalidResponse, userInfoResult.error);
771
+ }
772
+ if (!userEmailsResult.success) {
773
+ throw new ConnectorError(ConnectorErrorCodes.InvalidResponse, userEmailsResult.error);
837
774
  }
838
- const { id, avatar_url: avatar, email, name } = result.data;
775
+ const { id, avatar_url: avatar, email: publicEmail, name } = userInfoResult.data;
839
776
  return {
840
777
  id: String(id),
841
778
  avatar: conditional(avatar),
842
- email: conditional(email),
779
+ email: conditional(publicEmail ??
780
+ userEmailsResult.data.find(({ verified, primary }) => verified && primary)?.email),
843
781
  name: conditional(name),
844
- rawData,
782
+ rawData: jsonGuard.parse({
783
+ userInfo,
784
+ userEmails,
785
+ }),
845
786
  };
846
787
  }
847
788
  catch (error) {
848
789
  if (error instanceof HTTPError) {
849
- const { statusCode, body: rawBody } = error.response;
850
- if (statusCode === 401) {
790
+ const { status, body: rawBody } = error.response;
791
+ if (status === 401) {
851
792
  throw new ConnectorError(ConnectorErrorCodes.SocialAccessTokenInvalid);
852
793
  }
853
794
  throw new ConnectorError(ConnectorErrorCodes.General, JSON.stringify(rawBody));