@logto/connector-github 1.3.0 → 1.4.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/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,565 @@ 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
- }
612
-
613
- return encode(key, options) + '=' + encode(value, options);
614
- }).filter(x => x.length > 0).join('&');
29
+ // eslint-lint-disable-next-line @typescript-eslint/naming-convention
30
+ class HTTPError extends Error {
31
+ constructor(response, request, options) {
32
+ const code = (response.status || response.status === 0) ? response.status : '';
33
+ const title = response.statusText || '';
34
+ const status = `${code} ${title}`.trim();
35
+ const reason = status ? `status code ${status}` : 'an unknown error';
36
+ super(`Request failed with ${reason}`);
37
+ Object.defineProperty(this, "response", {
38
+ enumerable: true,
39
+ configurable: true,
40
+ writable: true,
41
+ value: void 0
42
+ });
43
+ Object.defineProperty(this, "request", {
44
+ enumerable: true,
45
+ configurable: true,
46
+ writable: true,
47
+ value: void 0
48
+ });
49
+ Object.defineProperty(this, "options", {
50
+ enumerable: true,
51
+ configurable: true,
52
+ writable: true,
53
+ value: void 0
54
+ });
55
+ this.name = 'HTTPError';
56
+ this.response = response;
57
+ this.request = request;
58
+ this.options = options;
59
+ }
615
60
  }
616
61
 
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
- };
62
+ class TimeoutError extends Error {
63
+ constructor(request) {
64
+ super('Request timed out');
65
+ Object.defineProperty(this, "request", {
66
+ enumerable: true,
67
+ configurable: true,
68
+ writable: true,
69
+ value: void 0
70
+ });
71
+ this.name = 'TimeoutError';
72
+ this.request = request;
73
+ }
634
74
  }
635
75
 
636
- function stringifyUrl(object, options) {
637
- options = {
638
- encode: true,
639
- strict: true,
640
- [encodeFragmentIdentifier]: true,
641
- ...options,
642
- };
643
-
644
- const url = removeHash(object.url).split('?')[0] || '';
645
- const queryFromUrl = extract(object.url);
76
+ // eslint-disable-next-line @typescript-eslint/ban-types
77
+ const isObject = (value) => value !== null && typeof value === 'object';
646
78
 
647
- const query = {
648
- ...parse(queryFromUrl, {sort: false}),
649
- ...object.query,
650
- };
79
+ const validateAndMerge = (...sources) => {
80
+ for (const source of sources) {
81
+ if ((!isObject(source) || Array.isArray(source)) && source !== undefined) {
82
+ throw new TypeError('The `options` argument must be an object');
83
+ }
84
+ }
85
+ return deepMerge({}, ...sources);
86
+ };
87
+ const mergeHeaders = (source1 = {}, source2 = {}) => {
88
+ const result = new globalThis.Headers(source1);
89
+ const isHeadersInstance = source2 instanceof globalThis.Headers;
90
+ const source = new globalThis.Headers(source2);
91
+ for (const [key, value] of source.entries()) {
92
+ if ((isHeadersInstance && value === 'undefined') || value === undefined) {
93
+ result.delete(key);
94
+ }
95
+ else {
96
+ result.set(key, value);
97
+ }
98
+ }
99
+ return result;
100
+ };
101
+ // TODO: Make this strongly-typed (no `any`).
102
+ const deepMerge = (...sources) => {
103
+ let returnValue = {};
104
+ let headers = {};
105
+ for (const source of sources) {
106
+ if (Array.isArray(source)) {
107
+ if (!Array.isArray(returnValue)) {
108
+ returnValue = [];
109
+ }
110
+ returnValue = [...returnValue, ...source];
111
+ }
112
+ else if (isObject(source)) {
113
+ for (let [key, value] of Object.entries(source)) {
114
+ if (isObject(value) && key in returnValue) {
115
+ value = deepMerge(returnValue[key], value);
116
+ }
117
+ returnValue = { ...returnValue, [key]: value };
118
+ }
119
+ if (isObject(source.headers)) {
120
+ headers = mergeHeaders(headers, source.headers);
121
+ returnValue.headers = headers;
122
+ }
123
+ }
124
+ }
125
+ return returnValue;
126
+ };
651
127
 
652
- let queryString = stringify(query, options);
653
- queryString &&= `?${queryString}`;
128
+ const supportsRequestStreams = (() => {
129
+ let duplexAccessed = false;
130
+ let hasContentType = false;
131
+ const supportsReadableStream = typeof globalThis.ReadableStream === 'function';
132
+ const supportsRequest = typeof globalThis.Request === 'function';
133
+ if (supportsReadableStream && supportsRequest) {
134
+ hasContentType = new globalThis.Request('https://empty.invalid', {
135
+ body: new globalThis.ReadableStream(),
136
+ method: 'POST',
137
+ // @ts-expect-error - Types are outdated.
138
+ get duplex() {
139
+ duplexAccessed = true;
140
+ return 'half';
141
+ },
142
+ }).headers.has('Content-Type');
143
+ }
144
+ return duplexAccessed && !hasContentType;
145
+ })();
146
+ const supportsAbortController = typeof globalThis.AbortController === 'function';
147
+ const supportsResponseStreams = typeof globalThis.ReadableStream === 'function';
148
+ const supportsFormData = typeof globalThis.FormData === 'function';
149
+ const requestMethods = ['get', 'post', 'put', 'patch', 'head', 'delete'];
150
+ const responseTypes = {
151
+ json: 'application/json',
152
+ text: 'text/*',
153
+ formData: 'multipart/form-data',
154
+ arrayBuffer: '*/*',
155
+ blob: '*/*',
156
+ };
157
+ // The maximum value of a 32bit int (see issue #117)
158
+ const maxSafeTimeout = 2_147_483_647;
159
+ const stop = Symbol('stop');
160
+ const kyOptionKeys = {
161
+ json: true,
162
+ parseJson: true,
163
+ searchParams: true,
164
+ prefixUrl: true,
165
+ retry: true,
166
+ timeout: true,
167
+ hooks: true,
168
+ throwHttpErrors: true,
169
+ onDownloadProgress: true,
170
+ fetch: true,
171
+ };
172
+ const requestOptionsRegistry = {
173
+ method: true,
174
+ headers: true,
175
+ body: true,
176
+ mode: true,
177
+ credentials: true,
178
+ cache: true,
179
+ redirect: true,
180
+ referrer: true,
181
+ referrerPolicy: true,
182
+ integrity: true,
183
+ keepalive: true,
184
+ signal: true,
185
+ window: true,
186
+ dispatcher: true,
187
+ duplex: true,
188
+ priority: true,
189
+ };
654
190
 
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
- }
191
+ const normalizeRequestMethod = (input) => requestMethods.includes(input) ? input.toUpperCase() : input;
192
+ const retryMethods = ['get', 'put', 'head', 'delete', 'options', 'trace'];
193
+ const retryStatusCodes = [408, 413, 429, 500, 502, 503, 504];
194
+ const retryAfterStatusCodes = [413, 429, 503];
195
+ const defaultRetryOptions = {
196
+ limit: 2,
197
+ methods: retryMethods,
198
+ statusCodes: retryStatusCodes,
199
+ afterStatusCodes: retryAfterStatusCodes,
200
+ maxRetryAfter: Number.POSITIVE_INFINITY,
201
+ backoffLimit: Number.POSITIVE_INFINITY,
202
+ delay: attemptCount => 0.3 * (2 ** (attemptCount - 1)) * 1000,
203
+ };
204
+ const normalizeRetryOptions = (retry = {}) => {
205
+ if (typeof retry === 'number') {
206
+ return {
207
+ ...defaultRetryOptions,
208
+ limit: retry,
209
+ };
210
+ }
211
+ if (retry.methods && !Array.isArray(retry.methods)) {
212
+ throw new Error('retry.methods must be an array');
213
+ }
214
+ if (retry.statusCodes && !Array.isArray(retry.statusCodes)) {
215
+ throw new Error('retry.statusCodes must be an array');
216
+ }
217
+ return {
218
+ ...defaultRetryOptions,
219
+ ...retry,
220
+ afterStatusCodes: retryAfterStatusCodes,
221
+ };
222
+ };
661
223
 
662
- return `${url}${queryString}${hash}`;
224
+ // `Promise.race()` workaround (#91)
225
+ async function timeout(request, init, abortController, options) {
226
+ return new Promise((resolve, reject) => {
227
+ const timeoutId = setTimeout(() => {
228
+ if (abortController) {
229
+ abortController.abort();
230
+ }
231
+ reject(new TimeoutError(request));
232
+ }, options.timeout);
233
+ void options
234
+ .fetch(request, init)
235
+ .then(resolve)
236
+ .catch(reject)
237
+ .then(() => {
238
+ clearTimeout(timeoutId);
239
+ });
240
+ });
663
241
  }
664
242
 
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);
243
+ // https://github.com/sindresorhus/delay/tree/ab98ae8dfcb38e1593286c94d934e70d14a4e111
244
+ async function delay(ms, { signal }) {
245
+ return new Promise((resolve, reject) => {
246
+ if (signal) {
247
+ signal.throwIfAborted();
248
+ signal.addEventListener('abort', abortHandler, { once: true });
249
+ }
250
+ function abortHandler() {
251
+ clearTimeout(timeoutId);
252
+ reject(signal.reason);
253
+ }
254
+ const timeoutId = setTimeout(() => {
255
+ signal?.removeEventListener('abort', abortHandler);
256
+ resolve();
257
+ }, ms);
258
+ });
679
259
  }
680
260
 
681
- function exclude(input, filter, options) {
682
- const exclusionFilter = Array.isArray(filter) ? key => !filter.includes(key) : (key, value) => !filter(key, value);
261
+ const findUnknownOptions = (request, options) => {
262
+ const unknownOptions = {};
263
+ for (const key in options) {
264
+ if (!(key in requestOptionsRegistry) && !(key in kyOptionKeys) && !(key in request)) {
265
+ unknownOptions[key] = options[key];
266
+ }
267
+ }
268
+ return unknownOptions;
269
+ };
683
270
 
684
- return pick(input, exclusionFilter, options);
271
+ class Ky {
272
+ static create(input, options) {
273
+ const ky = new Ky(input, options);
274
+ const function_ = async () => {
275
+ if (typeof ky._options.timeout === 'number' && ky._options.timeout > maxSafeTimeout) {
276
+ throw new RangeError(`The \`timeout\` option cannot be greater than ${maxSafeTimeout}`);
277
+ }
278
+ // Delay the fetch so that body method shortcuts can set the Accept header
279
+ await Promise.resolve();
280
+ let response = await ky._fetch();
281
+ for (const hook of ky._options.hooks.afterResponse) {
282
+ // eslint-disable-next-line no-await-in-loop
283
+ const modifiedResponse = await hook(ky.request, ky._options, ky._decorateResponse(response.clone()));
284
+ if (modifiedResponse instanceof globalThis.Response) {
285
+ response = modifiedResponse;
286
+ }
287
+ }
288
+ ky._decorateResponse(response);
289
+ if (!response.ok && ky._options.throwHttpErrors) {
290
+ let error = new HTTPError(response, ky.request, ky._options);
291
+ for (const hook of ky._options.hooks.beforeError) {
292
+ // eslint-disable-next-line no-await-in-loop
293
+ error = await hook(error);
294
+ }
295
+ throw error;
296
+ }
297
+ // If `onDownloadProgress` is passed, it uses the stream API internally
298
+ /* istanbul ignore next */
299
+ if (ky._options.onDownloadProgress) {
300
+ if (typeof ky._options.onDownloadProgress !== 'function') {
301
+ throw new TypeError('The `onDownloadProgress` option must be a function');
302
+ }
303
+ if (!supportsResponseStreams) {
304
+ throw new Error('Streams are not supported in your environment. `ReadableStream` is missing.');
305
+ }
306
+ return ky._stream(response.clone(), ky._options.onDownloadProgress);
307
+ }
308
+ return response;
309
+ };
310
+ const isRetriableMethod = ky._options.retry.methods.includes(ky.request.method.toLowerCase());
311
+ const result = (isRetriableMethod ? ky._retry(function_) : function_());
312
+ for (const [type, mimeType] of Object.entries(responseTypes)) {
313
+ result[type] = async () => {
314
+ // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
315
+ ky.request.headers.set('accept', ky.request.headers.get('accept') || mimeType);
316
+ const awaitedResult = await result;
317
+ const response = awaitedResult.clone();
318
+ if (type === 'json') {
319
+ if (response.status === 204) {
320
+ return '';
321
+ }
322
+ const arrayBuffer = await response.clone().arrayBuffer();
323
+ const responseSize = arrayBuffer.byteLength;
324
+ if (responseSize === 0) {
325
+ return '';
326
+ }
327
+ if (options.parseJson) {
328
+ return options.parseJson(await response.text());
329
+ }
330
+ }
331
+ return response[type]();
332
+ };
333
+ }
334
+ return result;
335
+ }
336
+ // eslint-disable-next-line complexity
337
+ constructor(input, options = {}) {
338
+ Object.defineProperty(this, "request", {
339
+ enumerable: true,
340
+ configurable: true,
341
+ writable: true,
342
+ value: void 0
343
+ });
344
+ Object.defineProperty(this, "abortController", {
345
+ enumerable: true,
346
+ configurable: true,
347
+ writable: true,
348
+ value: void 0
349
+ });
350
+ Object.defineProperty(this, "_retryCount", {
351
+ enumerable: true,
352
+ configurable: true,
353
+ writable: true,
354
+ value: 0
355
+ });
356
+ Object.defineProperty(this, "_input", {
357
+ enumerable: true,
358
+ configurable: true,
359
+ writable: true,
360
+ value: void 0
361
+ });
362
+ Object.defineProperty(this, "_options", {
363
+ enumerable: true,
364
+ configurable: true,
365
+ writable: true,
366
+ value: void 0
367
+ });
368
+ this._input = input;
369
+ const credentials = this._input instanceof Request && 'credentials' in Request.prototype
370
+ ? this._input.credentials
371
+ : undefined;
372
+ this._options = {
373
+ ...(credentials && { credentials }), // For exactOptionalPropertyTypes
374
+ ...options,
375
+ headers: mergeHeaders(this._input.headers, options.headers),
376
+ hooks: deepMerge({
377
+ beforeRequest: [],
378
+ beforeRetry: [],
379
+ beforeError: [],
380
+ afterResponse: [],
381
+ }, options.hooks),
382
+ method: normalizeRequestMethod(options.method ?? this._input.method),
383
+ // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
384
+ prefixUrl: String(options.prefixUrl || ''),
385
+ retry: normalizeRetryOptions(options.retry),
386
+ throwHttpErrors: options.throwHttpErrors !== false,
387
+ timeout: options.timeout ?? 10_000,
388
+ fetch: options.fetch ?? globalThis.fetch.bind(globalThis),
389
+ };
390
+ if (typeof this._input !== 'string' && !(this._input instanceof URL || this._input instanceof globalThis.Request)) {
391
+ throw new TypeError('`input` must be a string, URL, or Request');
392
+ }
393
+ if (this._options.prefixUrl && typeof this._input === 'string') {
394
+ if (this._input.startsWith('/')) {
395
+ throw new Error('`input` must not begin with a slash when using `prefixUrl`');
396
+ }
397
+ if (!this._options.prefixUrl.endsWith('/')) {
398
+ this._options.prefixUrl += '/';
399
+ }
400
+ this._input = this._options.prefixUrl + this._input;
401
+ }
402
+ if (supportsAbortController) {
403
+ this.abortController = new globalThis.AbortController();
404
+ if (this._options.signal) {
405
+ const originalSignal = this._options.signal;
406
+ this._options.signal.addEventListener('abort', () => {
407
+ this.abortController.abort(originalSignal.reason);
408
+ });
409
+ }
410
+ this._options.signal = this.abortController.signal;
411
+ }
412
+ if (supportsRequestStreams) {
413
+ // @ts-expect-error - Types are outdated.
414
+ this._options.duplex = 'half';
415
+ }
416
+ this.request = new globalThis.Request(this._input, this._options);
417
+ if (this._options.searchParams) {
418
+ // eslint-disable-next-line unicorn/prevent-abbreviations
419
+ const textSearchParams = typeof this._options.searchParams === 'string'
420
+ ? this._options.searchParams.replace(/^\?/, '')
421
+ : new URLSearchParams(this._options.searchParams).toString();
422
+ // eslint-disable-next-line unicorn/prevent-abbreviations
423
+ const searchParams = '?' + textSearchParams;
424
+ const url = this.request.url.replace(/(?:\?.*?)?(?=#|$)/, searchParams);
425
+ // To provide correct form boundary, Content-Type header should be deleted each time when new Request instantiated from another one
426
+ if (((supportsFormData && this._options.body instanceof globalThis.FormData)
427
+ || this._options.body instanceof URLSearchParams) && !(this._options.headers && this._options.headers['content-type'])) {
428
+ this.request.headers.delete('content-type');
429
+ }
430
+ // The spread of `this.request` is required as otherwise it misses the `duplex` option for some reason and throws.
431
+ this.request = new globalThis.Request(new globalThis.Request(url, { ...this.request }), this._options);
432
+ }
433
+ if (this._options.json !== undefined) {
434
+ this._options.body = JSON.stringify(this._options.json);
435
+ this.request.headers.set('content-type', this._options.headers.get('content-type') ?? 'application/json');
436
+ this.request = new globalThis.Request(this.request, { body: this._options.body });
437
+ }
438
+ }
439
+ _calculateRetryDelay(error) {
440
+ this._retryCount++;
441
+ if (this._retryCount <= this._options.retry.limit && !(error instanceof TimeoutError)) {
442
+ if (error instanceof HTTPError) {
443
+ if (!this._options.retry.statusCodes.includes(error.response.status)) {
444
+ return 0;
445
+ }
446
+ const retryAfter = error.response.headers.get('Retry-After');
447
+ if (retryAfter && this._options.retry.afterStatusCodes.includes(error.response.status)) {
448
+ let after = Number(retryAfter);
449
+ if (Number.isNaN(after)) {
450
+ after = Date.parse(retryAfter) - Date.now();
451
+ }
452
+ else {
453
+ after *= 1000;
454
+ }
455
+ if (this._options.retry.maxRetryAfter !== undefined && after > this._options.retry.maxRetryAfter) {
456
+ return 0;
457
+ }
458
+ return after;
459
+ }
460
+ if (error.response.status === 413) {
461
+ return 0;
462
+ }
463
+ }
464
+ const retryDelay = this._options.retry.delay(this._retryCount);
465
+ return Math.min(this._options.retry.backoffLimit, retryDelay);
466
+ }
467
+ return 0;
468
+ }
469
+ _decorateResponse(response) {
470
+ if (this._options.parseJson) {
471
+ response.json = async () => this._options.parseJson(await response.text());
472
+ }
473
+ return response;
474
+ }
475
+ async _retry(function_) {
476
+ try {
477
+ return await function_();
478
+ }
479
+ catch (error) {
480
+ const ms = Math.min(this._calculateRetryDelay(error), maxSafeTimeout);
481
+ if (ms !== 0 && this._retryCount > 0) {
482
+ await delay(ms, { signal: this._options.signal });
483
+ for (const hook of this._options.hooks.beforeRetry) {
484
+ // eslint-disable-next-line no-await-in-loop
485
+ const hookResult = await hook({
486
+ request: this.request,
487
+ options: this._options,
488
+ error: error,
489
+ retryCount: this._retryCount,
490
+ });
491
+ // If `stop` is returned from the hook, the retry process is stopped
492
+ if (hookResult === stop) {
493
+ return;
494
+ }
495
+ }
496
+ return this._retry(function_);
497
+ }
498
+ throw error;
499
+ }
500
+ }
501
+ async _fetch() {
502
+ for (const hook of this._options.hooks.beforeRequest) {
503
+ // eslint-disable-next-line no-await-in-loop
504
+ const result = await hook(this.request, this._options);
505
+ if (result instanceof Request) {
506
+ this.request = result;
507
+ break;
508
+ }
509
+ if (result instanceof Response) {
510
+ return result;
511
+ }
512
+ }
513
+ const nonRequestOptions = findUnknownOptions(this.request, this._options);
514
+ if (this._options.timeout === false) {
515
+ return this._options.fetch(this.request.clone(), nonRequestOptions);
516
+ }
517
+ return timeout(this.request.clone(), nonRequestOptions, this.abortController, this._options);
518
+ }
519
+ /* istanbul ignore next */
520
+ _stream(response, onDownloadProgress) {
521
+ const totalBytes = Number(response.headers.get('content-length')) || 0;
522
+ let transferredBytes = 0;
523
+ if (response.status === 204) {
524
+ if (onDownloadProgress) {
525
+ onDownloadProgress({ percent: 1, totalBytes, transferredBytes }, new Uint8Array());
526
+ }
527
+ return new globalThis.Response(null, {
528
+ status: response.status,
529
+ statusText: response.statusText,
530
+ headers: response.headers,
531
+ });
532
+ }
533
+ return new globalThis.Response(new globalThis.ReadableStream({
534
+ async start(controller) {
535
+ const reader = response.body.getReader();
536
+ if (onDownloadProgress) {
537
+ onDownloadProgress({ percent: 0, transferredBytes: 0, totalBytes }, new Uint8Array());
538
+ }
539
+ async function read() {
540
+ const { done, value } = await reader.read();
541
+ if (done) {
542
+ controller.close();
543
+ return;
544
+ }
545
+ if (onDownloadProgress) {
546
+ transferredBytes += value.byteLength;
547
+ const percent = totalBytes === 0 ? 0 : transferredBytes / totalBytes;
548
+ onDownloadProgress({ percent, transferredBytes, totalBytes }, value);
549
+ }
550
+ controller.enqueue(value);
551
+ await read();
552
+ }
553
+ await read();
554
+ },
555
+ }), {
556
+ status: response.status,
557
+ statusText: response.statusText,
558
+ headers: response.headers,
559
+ });
560
+ }
685
561
  }
686
562
 
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
- });
563
+ /*! MIT License © Sindre Sorhus */
564
+ const createInstance = (defaults) => {
565
+ // eslint-disable-next-line @typescript-eslint/promise-function-async
566
+ const ky = (input, options) => Ky.create(input, validateAndMerge(defaults, options));
567
+ for (const method of requestMethods) {
568
+ // eslint-disable-next-line @typescript-eslint/promise-function-async
569
+ ky[method] = (input, options) => Ky.create(input, validateAndMerge(defaults, options, { method }));
570
+ }
571
+ ky.create = (newDefaults) => createInstance(validateAndMerge(newDefaults));
572
+ ky.extend = (newDefaults) => createInstance(validateAndMerge(defaults, newDefaults));
573
+ ky.stop = stop;
574
+ return ky;
575
+ };
576
+ const ky = createInstance();
697
577
 
698
578
  const authorizationEndpoint = 'https://github.com/login/oauth/authorize';
699
- const scope = 'read:user';
579
+ /**
580
+ * `read:user` read user profile data; `user:email` read user email addresses (including private email addresses).
581
+ * Ref: https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/scopes-for-oauth-apps
582
+ */
583
+ const scope = 'read:user user:email';
700
584
  const accessTokenEndpoint = 'https://github.com/login/oauth/access_token';
701
585
  const userInfoEndpoint = 'https://api.github.com/user';
586
+ // Ref: https://docs.github.com/en/rest/users/emails?apiVersion=2022-11-28#list-email-addresses-for-the-authenticated-user
587
+ const userEmailsEndpoint = 'https://api.github.com/user/emails';
702
588
  const defaultMetadata = {
703
589
  id: 'github-universal',
704
590
  target: 'github',
@@ -750,6 +636,16 @@ const githubConfigGuard = z.object({
750
636
  clientSecret: z.string(),
751
637
  scope: z.string().optional(),
752
638
  });
639
+ /**
640
+ * This guard is used to validate the response from the GitHub API when requesting the user's email addresses.
641
+ * Ref: https://docs.github.com/en/rest/users/emails?apiVersion=2022-11-28#list-email-addresses-for-the-authenticated-user
642
+ */
643
+ const emailAddressGuard = z.object({
644
+ email: z.string(),
645
+ primary: z.boolean(),
646
+ verified: z.boolean(),
647
+ visibility: z.string().nullable(),
648
+ });
753
649
  const accessTokenResponseGuard = z.object({
754
650
  access_token: z.string(),
755
651
  scope: z.string(),
@@ -801,16 +697,17 @@ const authorizationCallbackHandler = async (parameterObject) => {
801
697
  const getAccessToken = async (config, codeObject) => {
802
698
  const { code } = codeObject;
803
699
  const { clientId: client_id, clientSecret: client_secret } = config;
804
- const httpResponse = await got.post({
805
- url: accessTokenEndpoint,
806
- json: {
700
+ const httpResponse = await ky
701
+ .post(accessTokenEndpoint, {
702
+ body: new URLSearchParams({
807
703
  client_id,
808
704
  client_secret,
809
705
  code,
810
- },
811
- timeout: { request: defaultTimeout },
812
- });
813
- const result = accessTokenResponseGuard.safeParse(queryString.parse(httpResponse.body));
706
+ }),
707
+ timeout: defaultTimeout,
708
+ })
709
+ .json();
710
+ const result = accessTokenResponseGuard.safeParse(httpResponse);
814
711
  if (!result.success) {
815
712
  throw new ConnectorError(ConnectorErrorCodes.InvalidResponse, result.error);
816
713
  }
@@ -823,31 +720,46 @@ const getUserInfo = (getConfig) => async (data) => {
823
720
  const config = await getConfig(defaultMetadata.id);
824
721
  validateConfig(config, githubConfigGuard);
825
722
  const { accessToken } = await getAccessToken(config, { code });
723
+ const authedApi = ky.create({
724
+ timeout: defaultTimeout,
725
+ hooks: {
726
+ beforeRequest: [
727
+ (request) => {
728
+ request.headers.set('Authorization', `Bearer ${accessToken}`);
729
+ },
730
+ ],
731
+ },
732
+ });
826
733
  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);
734
+ const [userInfo, userEmails] = await Promise.all([
735
+ authedApi.get(userInfoEndpoint).json(),
736
+ authedApi.get(userEmailsEndpoint).json(),
737
+ ]);
738
+ const userInfoResult = userInfoResponseGuard.safeParse(userInfo);
739
+ const userEmailsResult = emailAddressGuard.array().safeParse(userEmails);
740
+ if (!userInfoResult.success) {
741
+ throw new ConnectorError(ConnectorErrorCodes.InvalidResponse, userInfoResult.error);
742
+ }
743
+ if (!userEmailsResult.success) {
744
+ throw new ConnectorError(ConnectorErrorCodes.InvalidResponse, userEmailsResult.error);
837
745
  }
838
- const { id, avatar_url: avatar, email, name } = result.data;
746
+ const { id, avatar_url: avatar, email: publicEmail, name } = userInfoResult.data;
839
747
  return {
840
748
  id: String(id),
841
749
  avatar: conditional(avatar),
842
- email: conditional(email),
750
+ email: conditional(publicEmail ??
751
+ userEmailsResult.data.find(({ verified, primary }) => verified && primary)?.email),
843
752
  name: conditional(name),
844
- rawData,
753
+ rawData: jsonGuard.parse({
754
+ userInfo,
755
+ userEmails,
756
+ }),
845
757
  };
846
758
  }
847
759
  catch (error) {
848
760
  if (error instanceof HTTPError) {
849
- const { statusCode, body: rawBody } = error.response;
850
- if (statusCode === 401) {
761
+ const { status, body: rawBody } = error.response;
762
+ if (status === 401) {
851
763
  throw new ConnectorError(ConnectorErrorCodes.SocialAccessTokenInvalid);
852
764
  }
853
765
  throw new ConnectorError(ConnectorErrorCodes.General, JSON.stringify(rawBody));