@data-loom/node-fetch 0.0.2-alpha.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.
@@ -0,0 +1,1792 @@
1
+ process.emitWarning("The .es.js file is deprecated. Use .mjs instead.");
2
+
3
+ import Stream from 'stream';
4
+ import http from 'http';
5
+ import Url from 'url';
6
+ import whatwgUrl from 'whatwg-url';
7
+ import https from 'https';
8
+ import zlib from 'zlib';
9
+
10
+ // Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js
11
+
12
+ // fix for "Readable" isn't a named export issue
13
+ const Readable = Stream.Readable;
14
+
15
+ const BUFFER = Symbol('buffer');
16
+ const TYPE = Symbol('type');
17
+
18
+ class Blob {
19
+ constructor() {
20
+ this[TYPE] = '';
21
+
22
+ const blobParts = arguments[0];
23
+ const options = arguments[1];
24
+
25
+ const buffers = [];
26
+ let size = 0;
27
+
28
+ if (blobParts) {
29
+ const a = blobParts;
30
+ const length = Number(a.length);
31
+ for (let i = 0; i < length; i++) {
32
+ const element = a[i];
33
+ let buffer;
34
+ if (element instanceof Buffer) {
35
+ buffer = element;
36
+ } else if (ArrayBuffer.isView(element)) {
37
+ buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength);
38
+ } else if (element instanceof ArrayBuffer) {
39
+ buffer = Buffer.from(element);
40
+ } else if (element instanceof Blob) {
41
+ buffer = element[BUFFER];
42
+ } else {
43
+ buffer = Buffer.from(typeof element === 'string' ? element : String(element));
44
+ }
45
+ size += buffer.length;
46
+ buffers.push(buffer);
47
+ }
48
+ }
49
+
50
+ this[BUFFER] = Buffer.concat(buffers);
51
+
52
+ let type = options && options.type !== undefined && String(options.type).toLowerCase();
53
+ if (type && !/[^\u0020-\u007E]/.test(type)) {
54
+ this[TYPE] = type;
55
+ }
56
+ }
57
+ get size() {
58
+ return this[BUFFER].length;
59
+ }
60
+ get type() {
61
+ return this[TYPE];
62
+ }
63
+ text() {
64
+ return Promise.resolve(this[BUFFER].toString());
65
+ }
66
+ arrayBuffer() {
67
+ const buf = this[BUFFER];
68
+ const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
69
+ return Promise.resolve(ab);
70
+ }
71
+ stream() {
72
+ const readable = new Readable();
73
+ readable._read = function () {};
74
+ readable.push(this[BUFFER]);
75
+ readable.push(null);
76
+ return readable;
77
+ }
78
+ toString() {
79
+ return '[object Blob]';
80
+ }
81
+ slice() {
82
+ const size = this.size;
83
+
84
+ const start = arguments[0];
85
+ const end = arguments[1];
86
+ let relativeStart, relativeEnd;
87
+ if (start === undefined) {
88
+ relativeStart = 0;
89
+ } else if (start < 0) {
90
+ relativeStart = Math.max(size + start, 0);
91
+ } else {
92
+ relativeStart = Math.min(start, size);
93
+ }
94
+ if (end === undefined) {
95
+ relativeEnd = size;
96
+ } else if (end < 0) {
97
+ relativeEnd = Math.max(size + end, 0);
98
+ } else {
99
+ relativeEnd = Math.min(end, size);
100
+ }
101
+ const span = Math.max(relativeEnd - relativeStart, 0);
102
+
103
+ const buffer = this[BUFFER];
104
+ const slicedBuffer = buffer.slice(relativeStart, relativeStart + span);
105
+ const blob = new Blob([], { type: arguments[2] });
106
+ blob[BUFFER] = slicedBuffer;
107
+ return blob;
108
+ }
109
+ }
110
+
111
+ Object.defineProperties(Blob.prototype, {
112
+ size: { enumerable: true },
113
+ type: { enumerable: true },
114
+ slice: { enumerable: true }
115
+ });
116
+
117
+ Object.defineProperty(Blob.prototype, Symbol.toStringTag, {
118
+ value: 'Blob',
119
+ writable: false,
120
+ enumerable: false,
121
+ configurable: true
122
+ });
123
+
124
+ /**
125
+ * fetch-error.js
126
+ *
127
+ * FetchError interface for operational errors
128
+ */
129
+
130
+ /**
131
+ * Create FetchError instance
132
+ *
133
+ * @param String message Error message for human
134
+ * @param String type Error type for machine
135
+ * @param String systemError For Node.js system error
136
+ * @return FetchError
137
+ */
138
+ function FetchError(message, type, systemError) {
139
+ Error.call(this, message);
140
+
141
+ this.message = message;
142
+ this.type = type;
143
+
144
+ // when err.type is `system`, err.code contains system error code
145
+ if (systemError) {
146
+ this.code = this.errno = systemError.code;
147
+ }
148
+
149
+ // hide custom error implementation details from end-users
150
+ Error.captureStackTrace(this, this.constructor);
151
+ }
152
+
153
+ FetchError.prototype = Object.create(Error.prototype);
154
+ FetchError.prototype.constructor = FetchError;
155
+ FetchError.prototype.name = 'FetchError';
156
+
157
+ let convert;
158
+
159
+ const INTERNALS = Symbol('Body internals');
160
+
161
+ // fix an issue where "PassThrough" isn't a named export for node <10
162
+ const PassThrough = Stream.PassThrough;
163
+
164
+ /**
165
+ * Body mixin
166
+ *
167
+ * Ref: https://fetch.spec.whatwg.org/#body
168
+ *
169
+ * @param Stream body Readable stream
170
+ * @param Object opts Response options
171
+ * @return Void
172
+ */
173
+ function Body(body) {
174
+ var _this = this;
175
+
176
+ var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
177
+ _ref$size = _ref.size;
178
+
179
+ let size = _ref$size === undefined ? 0 : _ref$size;
180
+ var _ref$timeout = _ref.timeout;
181
+ let timeout = _ref$timeout === undefined ? 0 : _ref$timeout;
182
+
183
+ if (body == null) {
184
+ // body is undefined or null
185
+ body = null;
186
+ } else if (isURLSearchParams(body)) {
187
+ // body is a URLSearchParams
188
+ body = Buffer.from(body.toString());
189
+ } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') {
190
+ // body is ArrayBuffer
191
+ body = Buffer.from(body);
192
+ } else if (ArrayBuffer.isView(body)) {
193
+ // body is ArrayBufferView
194
+ body = Buffer.from(body.buffer, body.byteOffset, body.byteLength);
195
+ } else if (body instanceof Stream) ; else {
196
+ // none of the above
197
+ // coerce to string then buffer
198
+ body = Buffer.from(String(body));
199
+ }
200
+ this[INTERNALS] = {
201
+ body,
202
+ disturbed: false,
203
+ error: null
204
+ };
205
+ this.size = size;
206
+ this.timeout = timeout;
207
+
208
+ if (body instanceof Stream) {
209
+ body.on('error', function (err) {
210
+ const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err);
211
+ _this[INTERNALS].error = error;
212
+ });
213
+ }
214
+ }
215
+
216
+ Body.prototype = {
217
+ get body() {
218
+ return this[INTERNALS].body;
219
+ },
220
+
221
+ get bodyUsed() {
222
+ return this[INTERNALS].disturbed;
223
+ },
224
+
225
+ /**
226
+ * Decode response as ArrayBuffer
227
+ *
228
+ * @return Promise
229
+ */
230
+ arrayBuffer() {
231
+ return consumeBody.call(this).then(function (buf) {
232
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
233
+ });
234
+ },
235
+
236
+ /**
237
+ * Return raw response as Blob
238
+ *
239
+ * @return Promise
240
+ */
241
+ blob() {
242
+ let ct = this.headers && this.headers.get('content-type') || '';
243
+ return consumeBody.call(this).then(function (buf) {
244
+ return Object.assign(
245
+ // Prevent copying
246
+ new Blob([], {
247
+ type: ct.toLowerCase()
248
+ }), {
249
+ [BUFFER]: buf
250
+ });
251
+ });
252
+ },
253
+
254
+ /**
255
+ * Decode response as json
256
+ *
257
+ * @return Promise
258
+ */
259
+ json() {
260
+ var _this2 = this;
261
+
262
+ return consumeBody.call(this).then(function (buffer) {
263
+ try {
264
+ return JSON.parse(buffer.toString());
265
+ } catch (err) {
266
+ return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json'));
267
+ }
268
+ });
269
+ },
270
+
271
+ /**
272
+ * Decode response as text
273
+ *
274
+ * @return Promise
275
+ */
276
+ text() {
277
+ return consumeBody.call(this).then(function (buffer) {
278
+ return buffer.toString();
279
+ });
280
+ },
281
+
282
+ /**
283
+ * Decode response as buffer (non-spec api)
284
+ *
285
+ * @return Promise
286
+ */
287
+ buffer() {
288
+ return consumeBody.call(this);
289
+ },
290
+
291
+ /**
292
+ * Decode response as text, while automatically detecting the encoding and
293
+ * trying to decode to UTF-8 (non-spec api)
294
+ *
295
+ * @return Promise
296
+ */
297
+ textConverted() {
298
+ var _this3 = this;
299
+
300
+ return consumeBody.call(this).then(function (buffer) {
301
+ return convertBody(buffer, _this3.headers);
302
+ });
303
+ }
304
+ };
305
+
306
+ // In browsers, all properties are enumerable.
307
+ Object.defineProperties(Body.prototype, {
308
+ body: { enumerable: true },
309
+ bodyUsed: { enumerable: true },
310
+ arrayBuffer: { enumerable: true },
311
+ blob: { enumerable: true },
312
+ json: { enumerable: true },
313
+ text: { enumerable: true }
314
+ });
315
+
316
+ Body.mixIn = function (proto) {
317
+ for (const name of Object.getOwnPropertyNames(Body.prototype)) {
318
+ // istanbul ignore else: future proof
319
+ if (!(name in proto)) {
320
+ const desc = Object.getOwnPropertyDescriptor(Body.prototype, name);
321
+ Object.defineProperty(proto, name, desc);
322
+ }
323
+ }
324
+ };
325
+
326
+ /**
327
+ * Consume and convert an entire Body to a Buffer.
328
+ *
329
+ * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body
330
+ *
331
+ * @return Promise
332
+ */
333
+ function consumeBody() {
334
+ var _this4 = this;
335
+
336
+ if (this[INTERNALS].disturbed) {
337
+ return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`));
338
+ }
339
+
340
+ this[INTERNALS].disturbed = true;
341
+
342
+ if (this[INTERNALS].error) {
343
+ return Body.Promise.reject(this[INTERNALS].error);
344
+ }
345
+
346
+ let body = this.body;
347
+
348
+ // body is null
349
+ if (body === null) {
350
+ return Body.Promise.resolve(Buffer.alloc(0));
351
+ }
352
+
353
+ // body is blob
354
+ if (isBlob(body)) {
355
+ body = body.stream();
356
+ }
357
+
358
+ // body is buffer
359
+ if (Buffer.isBuffer(body)) {
360
+ return Body.Promise.resolve(body);
361
+ }
362
+
363
+ // istanbul ignore if: should never happen
364
+ if (!(body instanceof Stream)) {
365
+ return Body.Promise.resolve(Buffer.alloc(0));
366
+ }
367
+
368
+ // body is stream
369
+ // get ready to actually consume the body
370
+ let accum = [];
371
+ let accumBytes = 0;
372
+ let abort = false;
373
+
374
+ return new Body.Promise(function (resolve, reject) {
375
+ let resTimeout;
376
+
377
+ // allow timeout on slow response body
378
+ if (_this4.timeout) {
379
+ resTimeout = setTimeout(function () {
380
+ abort = true;
381
+ reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout'));
382
+ }, _this4.timeout);
383
+ }
384
+
385
+ // handle stream errors
386
+ body.on('error', function (err) {
387
+ if (err.name === 'AbortError') {
388
+ // if the request was aborted, reject with this Error
389
+ abort = true;
390
+ reject(err);
391
+ } else {
392
+ // other errors, such as incorrect content-encoding
393
+ reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err));
394
+ }
395
+ });
396
+
397
+ body.on('data', function (chunk) {
398
+ if (abort || chunk === null) {
399
+ return;
400
+ }
401
+
402
+ if (_this4.size && accumBytes + chunk.length > _this4.size) {
403
+ abort = true;
404
+ reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size'));
405
+ return;
406
+ }
407
+
408
+ accumBytes += chunk.length;
409
+ accum.push(chunk);
410
+ });
411
+
412
+ body.on('end', function () {
413
+ if (abort) {
414
+ return;
415
+ }
416
+
417
+ clearTimeout(resTimeout);
418
+
419
+ try {
420
+ resolve(Buffer.concat(accum, accumBytes));
421
+ } catch (err) {
422
+ // handle streams that have accumulated too much data (issue #414)
423
+ reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err));
424
+ }
425
+ });
426
+ });
427
+ }
428
+
429
+ /**
430
+ * Detect buffer encoding and convert to target encoding
431
+ * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding
432
+ *
433
+ * @param Buffer buffer Incoming buffer
434
+ * @param String encoding Target encoding
435
+ * @return String
436
+ */
437
+ function convertBody(buffer, headers) {
438
+ {
439
+ throw new Error('The package `encoding` must be installed to use the textConverted() function');
440
+ }
441
+
442
+ const ct = headers.get('content-type');
443
+ let charset = 'utf-8';
444
+ let res, str;
445
+
446
+ // header
447
+ if (ct) {
448
+ res = /charset=([^;]*)/i.exec(ct);
449
+ }
450
+
451
+ // no charset in content type, peek at response body for at most 1024 bytes
452
+ str = buffer.slice(0, 1024).toString();
453
+
454
+ // html5
455
+ if (!res && str) {
456
+ res = /<meta.+?charset=(['"])(.+?)\1/i.exec(str);
457
+ }
458
+
459
+ // html4
460
+ if (!res && str) {
461
+ res = /<meta[\s]+?http-equiv=(['"])content-type\1[\s]+?content=(['"])(.+?)\2/i.exec(str);
462
+ if (!res) {
463
+ res = /<meta[\s]+?content=(['"])(.+?)\1[\s]+?http-equiv=(['"])content-type\3/i.exec(str);
464
+ if (res) {
465
+ res.pop(); // drop last quote
466
+ }
467
+ }
468
+
469
+ if (res) {
470
+ res = /charset=(.*)/i.exec(res.pop());
471
+ }
472
+ }
473
+
474
+ // xml
475
+ if (!res && str) {
476
+ res = /<\?xml.+?encoding=(['"])(.+?)\1/i.exec(str);
477
+ }
478
+
479
+ // found charset
480
+ if (res) {
481
+ charset = res.pop();
482
+
483
+ // prevent decode issues when sites use incorrect encoding
484
+ // ref: https://hsivonen.fi/encoding-menu/
485
+ if (charset === 'gb2312' || charset === 'gbk') {
486
+ charset = 'gb18030';
487
+ }
488
+ }
489
+
490
+ // turn raw buffers into a single utf-8 buffer
491
+ return convert(buffer, 'UTF-8', charset).toString();
492
+ }
493
+
494
+ /**
495
+ * Detect a URLSearchParams object
496
+ * ref: https://github.com/bitinn/node-fetch/issues/296#issuecomment-307598143
497
+ *
498
+ * @param Object obj Object to detect by type or brand
499
+ * @return String
500
+ */
501
+ function isURLSearchParams(obj) {
502
+ // Duck-typing as a necessary condition.
503
+ if (typeof obj !== 'object' || typeof obj.append !== 'function' || typeof obj.delete !== 'function' || typeof obj.get !== 'function' || typeof obj.getAll !== 'function' || typeof obj.has !== 'function' || typeof obj.set !== 'function') {
504
+ return false;
505
+ }
506
+
507
+ // Brand-checking and more duck-typing as optional condition.
508
+ return obj.constructor.name === 'URLSearchParams' || Object.prototype.toString.call(obj) === '[object URLSearchParams]' || typeof obj.sort === 'function';
509
+ }
510
+
511
+ /**
512
+ * Check if `obj` is a W3C `Blob` object (which `File` inherits from)
513
+ * @param {*} obj
514
+ * @return {boolean}
515
+ */
516
+ function isBlob(obj) {
517
+ return typeof obj === 'object' && typeof obj.arrayBuffer === 'function' && typeof obj.type === 'string' && typeof obj.stream === 'function' && typeof obj.constructor === 'function' && typeof obj.constructor.name === 'string' && /^(Blob|File)$/.test(obj.constructor.name) && /^(Blob|File)$/.test(obj[Symbol.toStringTag]);
518
+ }
519
+
520
+ /**
521
+ * Clone body given Res/Req instance
522
+ *
523
+ * @param Mixed instance Response or Request instance
524
+ * @return Mixed
525
+ */
526
+ function clone(instance) {
527
+ let p1, p2;
528
+ let body = instance.body;
529
+
530
+ // don't allow cloning a used body
531
+ if (instance.bodyUsed) {
532
+ throw new Error('cannot clone body after it is used');
533
+ }
534
+
535
+ // check that body is a stream and not form-data object
536
+ // note: we can't clone the form-data object without having it as a dependency
537
+ if (body instanceof Stream && typeof body.getBoundary !== 'function') {
538
+ // tee instance body
539
+ p1 = new PassThrough();
540
+ p2 = new PassThrough();
541
+ body.pipe(p1);
542
+ body.pipe(p2);
543
+ // set instance body to teed body and return the other teed body
544
+ instance[INTERNALS].body = p1;
545
+ body = p2;
546
+ }
547
+
548
+ return body;
549
+ }
550
+
551
+ /**
552
+ * Performs the operation "extract a `Content-Type` value from |object|" as
553
+ * specified in the specification:
554
+ * https://fetch.spec.whatwg.org/#concept-bodyinit-extract
555
+ *
556
+ * This function assumes that instance.body is present.
557
+ *
558
+ * @param Mixed instance Any options.body input
559
+ */
560
+ function extractContentType(body) {
561
+ if (body === null) {
562
+ // body is null
563
+ return null;
564
+ } else if (typeof body === 'string') {
565
+ // body is string
566
+ return 'text/plain;charset=UTF-8';
567
+ } else if (isURLSearchParams(body)) {
568
+ // body is a URLSearchParams
569
+ return 'application/x-www-form-urlencoded;charset=UTF-8';
570
+ } else if (isBlob(body)) {
571
+ // body is blob
572
+ return body.type || null;
573
+ } else if (Buffer.isBuffer(body)) {
574
+ // body is buffer
575
+ return null;
576
+ } else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') {
577
+ // body is ArrayBuffer
578
+ return null;
579
+ } else if (ArrayBuffer.isView(body)) {
580
+ // body is ArrayBufferView
581
+ return null;
582
+ } else if (typeof body.getBoundary === 'function') {
583
+ // detect form data input from form-data module
584
+ return `multipart/form-data;boundary=${body.getBoundary()}`;
585
+ } else if (body instanceof Stream) {
586
+ // body is stream
587
+ // can't really do much about this
588
+ return null;
589
+ } else {
590
+ // Body constructor defaults other things to string
591
+ return 'text/plain;charset=UTF-8';
592
+ }
593
+ }
594
+
595
+ /**
596
+ * The Fetch Standard treats this as if "total bytes" is a property on the body.
597
+ * For us, we have to explicitly get it with a function.
598
+ *
599
+ * ref: https://fetch.spec.whatwg.org/#concept-body-total-bytes
600
+ *
601
+ * @param Body instance Instance of Body
602
+ * @return Number? Number of bytes, or null if not possible
603
+ */
604
+ function getTotalBytes(instance) {
605
+ const body = instance.body;
606
+
607
+
608
+ if (body === null) {
609
+ // body is null
610
+ return 0;
611
+ } else if (isBlob(body)) {
612
+ return body.size;
613
+ } else if (Buffer.isBuffer(body)) {
614
+ // body is buffer
615
+ return body.length;
616
+ } else if (body && typeof body.getLengthSync === 'function') {
617
+ // detect form data input from form-data module
618
+ if (body._lengthRetrievers && body._lengthRetrievers.length == 0 || // 1.x
619
+ body.hasKnownLength && body.hasKnownLength()) {
620
+ // 2.x
621
+ return body.getLengthSync();
622
+ }
623
+ return null;
624
+ } else {
625
+ // body is stream
626
+ return null;
627
+ }
628
+ }
629
+
630
+ /**
631
+ * Write a Body to a Node.js WritableStream (e.g. http.Request) object.
632
+ *
633
+ * @param Body instance Instance of Body
634
+ * @return Void
635
+ */
636
+ function writeToStream(dest, instance) {
637
+ const body = instance.body;
638
+
639
+
640
+ if (body === null) {
641
+ // body is null
642
+ dest.end();
643
+ } else if (isBlob(body)) {
644
+ body.stream().pipe(dest);
645
+ } else if (Buffer.isBuffer(body)) {
646
+ // body is buffer
647
+ dest.write(body);
648
+ dest.end();
649
+ } else {
650
+ // body is stream
651
+ body.pipe(dest);
652
+ }
653
+ }
654
+
655
+ // expose Promise
656
+ Body.Promise = global.Promise;
657
+
658
+ /**
659
+ * headers.js
660
+ *
661
+ * Headers class offers convenient helpers
662
+ */
663
+
664
+ const invalidTokenRegex = /[^\^_`a-zA-Z\-0-9!#$%&'*+.|~]/;
665
+ const invalidHeaderCharRegex = /[^\t\x20-\x7e\x80-\xff]/;
666
+
667
+ function validateName(name) {
668
+ name = `${name}`;
669
+ if (invalidTokenRegex.test(name) || name === '') {
670
+ throw new TypeError(`${name} is not a legal HTTP header name`);
671
+ }
672
+ }
673
+
674
+ function validateValue(value) {
675
+ value = `${value}`;
676
+ if (invalidHeaderCharRegex.test(value)) {
677
+ throw new TypeError(`${value} is not a legal HTTP header value`);
678
+ }
679
+ }
680
+
681
+ /**
682
+ * Find the key in the map object given a header name.
683
+ *
684
+ * Returns undefined if not found.
685
+ *
686
+ * @param String name Header name
687
+ * @return String|Undefined
688
+ */
689
+ function find(map, name) {
690
+ name = name.toLowerCase();
691
+ for (const key in map) {
692
+ if (key.toLowerCase() === name) {
693
+ return key;
694
+ }
695
+ }
696
+ return undefined;
697
+ }
698
+
699
+ const MAP = Symbol('map');
700
+ class Headers {
701
+ /**
702
+ * Headers class
703
+ *
704
+ * @param Object headers Response headers
705
+ * @return Void
706
+ */
707
+ constructor() {
708
+ let init = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : undefined;
709
+
710
+ this[MAP] = Object.create(null);
711
+
712
+ if (init instanceof Headers) {
713
+ const rawHeaders = init.raw();
714
+ const headerNames = Object.keys(rawHeaders);
715
+
716
+ for (const headerName of headerNames) {
717
+ for (const value of rawHeaders[headerName]) {
718
+ this.append(headerName, value);
719
+ }
720
+ }
721
+
722
+ return;
723
+ }
724
+
725
+ // We don't worry about converting prop to ByteString here as append()
726
+ // will handle it.
727
+ if (init == null) ; else if (typeof init === 'object') {
728
+ const method = init[Symbol.iterator];
729
+ if (method != null) {
730
+ if (typeof method !== 'function') {
731
+ throw new TypeError('Header pairs must be iterable');
732
+ }
733
+
734
+ // sequence<sequence<ByteString>>
735
+ // Note: per spec we have to first exhaust the lists then process them
736
+ const pairs = [];
737
+ for (const pair of init) {
738
+ if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') {
739
+ throw new TypeError('Each header pair must be iterable');
740
+ }
741
+ pairs.push(Array.from(pair));
742
+ }
743
+
744
+ for (const pair of pairs) {
745
+ if (pair.length !== 2) {
746
+ throw new TypeError('Each header pair must be a name/value tuple');
747
+ }
748
+ this.append(pair[0], pair[1]);
749
+ }
750
+ } else {
751
+ // record<ByteString, ByteString>
752
+ for (const key of Object.keys(init)) {
753
+ const value = init[key];
754
+ this.append(key, value);
755
+ }
756
+ }
757
+ } else {
758
+ throw new TypeError('Provided initializer must be an object');
759
+ }
760
+ }
761
+
762
+ /**
763
+ * Return combined header value given name
764
+ *
765
+ * @param String name Header name
766
+ * @return Mixed
767
+ */
768
+ get(name) {
769
+ name = `${name}`;
770
+ validateName(name);
771
+ const key = find(this[MAP], name);
772
+ if (key === undefined) {
773
+ return null;
774
+ }
775
+
776
+ return this[MAP][key].join(', ');
777
+ }
778
+
779
+ /**
780
+ * Iterate over all headers
781
+ *
782
+ * @param Function callback Executed for each item with parameters (value, name, thisArg)
783
+ * @param Boolean thisArg `this` context for callback function
784
+ * @return Void
785
+ */
786
+ forEach(callback) {
787
+ let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;
788
+
789
+ let pairs = getHeaders(this);
790
+ let i = 0;
791
+ while (i < pairs.length) {
792
+ var _pairs$i = pairs[i];
793
+ const name = _pairs$i[0],
794
+ value = _pairs$i[1];
795
+
796
+ callback.call(thisArg, value, name, this);
797
+ pairs = getHeaders(this);
798
+ i++;
799
+ }
800
+ }
801
+
802
+ /**
803
+ * Overwrite header values given name
804
+ *
805
+ * @param String name Header name
806
+ * @param String value Header value
807
+ * @return Void
808
+ */
809
+ set(name, value) {
810
+ name = `${name}`;
811
+ value = `${value}`;
812
+ validateName(name);
813
+ validateValue(value);
814
+ const key = find(this[MAP], name);
815
+ this[MAP][key !== undefined ? key : name] = [value];
816
+ }
817
+
818
+ /**
819
+ * Append a value onto existing header
820
+ *
821
+ * @param String name Header name
822
+ * @param String value Header value
823
+ * @return Void
824
+ */
825
+ append(name, value) {
826
+ name = `${name}`;
827
+ value = `${value}`;
828
+ validateName(name);
829
+ validateValue(value);
830
+ const key = find(this[MAP], name);
831
+ if (key !== undefined) {
832
+ this[MAP][key].push(value);
833
+ } else {
834
+ this[MAP][name] = [value];
835
+ }
836
+ }
837
+
838
+ /**
839
+ * Check for header name existence
840
+ *
841
+ * @param String name Header name
842
+ * @return Boolean
843
+ */
844
+ has(name) {
845
+ name = `${name}`;
846
+ validateName(name);
847
+ return find(this[MAP], name) !== undefined;
848
+ }
849
+
850
+ /**
851
+ * Delete all header values given name
852
+ *
853
+ * @param String name Header name
854
+ * @return Void
855
+ */
856
+ delete(name) {
857
+ name = `${name}`;
858
+ validateName(name);
859
+ const key = find(this[MAP], name);
860
+ if (key !== undefined) {
861
+ delete this[MAP][key];
862
+ }
863
+ }
864
+
865
+ /**
866
+ * Return raw headers (non-spec api)
867
+ *
868
+ * @return Object
869
+ */
870
+ raw() {
871
+ return this[MAP];
872
+ }
873
+
874
+ /**
875
+ * Get an iterator on keys.
876
+ *
877
+ * @return Iterator
878
+ */
879
+ keys() {
880
+ return createHeadersIterator(this, 'key');
881
+ }
882
+
883
+ /**
884
+ * Get an iterator on values.
885
+ *
886
+ * @return Iterator
887
+ */
888
+ values() {
889
+ return createHeadersIterator(this, 'value');
890
+ }
891
+
892
+ /**
893
+ * Get an iterator on entries.
894
+ *
895
+ * This is the default iterator of the Headers object.
896
+ *
897
+ * @return Iterator
898
+ */
899
+ [Symbol.iterator]() {
900
+ return createHeadersIterator(this, 'key+value');
901
+ }
902
+ }
903
+ Headers.prototype.entries = Headers.prototype[Symbol.iterator];
904
+
905
+ Object.defineProperty(Headers.prototype, Symbol.toStringTag, {
906
+ value: 'Headers',
907
+ writable: false,
908
+ enumerable: false,
909
+ configurable: true
910
+ });
911
+
912
+ Object.defineProperties(Headers.prototype, {
913
+ get: { enumerable: true },
914
+ forEach: { enumerable: true },
915
+ set: { enumerable: true },
916
+ append: { enumerable: true },
917
+ has: { enumerable: true },
918
+ delete: { enumerable: true },
919
+ keys: { enumerable: true },
920
+ values: { enumerable: true },
921
+ entries: { enumerable: true }
922
+ });
923
+
924
+ function getHeaders(headers) {
925
+ let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value';
926
+
927
+ const keys = Object.keys(headers[MAP]).sort();
928
+ return keys.map(kind === 'key' ? function (k) {
929
+ return k.toLowerCase();
930
+ } : kind === 'value' ? function (k) {
931
+ return headers[MAP][k].join(', ');
932
+ } : function (k) {
933
+ return [k.toLowerCase(), headers[MAP][k].join(', ')];
934
+ });
935
+ }
936
+
937
+ const INTERNAL = Symbol('internal');
938
+
939
+ function createHeadersIterator(target, kind) {
940
+ const iterator = Object.create(HeadersIteratorPrototype);
941
+ iterator[INTERNAL] = {
942
+ target,
943
+ kind,
944
+ index: 0
945
+ };
946
+ return iterator;
947
+ }
948
+
949
+ const HeadersIteratorPrototype = Object.setPrototypeOf({
950
+ next() {
951
+ // istanbul ignore if
952
+ if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) {
953
+ throw new TypeError('Value of `this` is not a HeadersIterator');
954
+ }
955
+
956
+ var _INTERNAL = this[INTERNAL];
957
+ const target = _INTERNAL.target,
958
+ kind = _INTERNAL.kind,
959
+ index = _INTERNAL.index;
960
+
961
+ const values = getHeaders(target, kind);
962
+ const len = values.length;
963
+ if (index >= len) {
964
+ return {
965
+ value: undefined,
966
+ done: true
967
+ };
968
+ }
969
+
970
+ this[INTERNAL].index = index + 1;
971
+
972
+ return {
973
+ value: values[index],
974
+ done: false
975
+ };
976
+ }
977
+ }, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())));
978
+
979
+ Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, {
980
+ value: 'HeadersIterator',
981
+ writable: false,
982
+ enumerable: false,
983
+ configurable: true
984
+ });
985
+
986
+ /**
987
+ * Export the Headers object in a form that Node.js can consume.
988
+ *
989
+ * @param Headers headers
990
+ * @return Object
991
+ */
992
+ function exportNodeCompatibleHeaders(headers) {
993
+ const obj = Object.assign({ __proto__: null }, headers[MAP]);
994
+
995
+ // http.request() only supports string as Host header. This hack makes
996
+ // specifying custom Host header possible.
997
+ const hostHeaderKey = find(headers[MAP], 'Host');
998
+ if (hostHeaderKey !== undefined) {
999
+ obj[hostHeaderKey] = obj[hostHeaderKey][0];
1000
+ }
1001
+
1002
+ return obj;
1003
+ }
1004
+
1005
+ /**
1006
+ * Create a Headers object from an object of headers, ignoring those that do
1007
+ * not conform to HTTP grammar productions.
1008
+ *
1009
+ * @param Object obj Object of headers
1010
+ * @return Headers
1011
+ */
1012
+ function createHeadersLenient(obj) {
1013
+ const headers = new Headers();
1014
+ for (const name of Object.keys(obj)) {
1015
+ if (invalidTokenRegex.test(name)) {
1016
+ continue;
1017
+ }
1018
+ if (Array.isArray(obj[name])) {
1019
+ for (const val of obj[name]) {
1020
+ if (invalidHeaderCharRegex.test(val)) {
1021
+ continue;
1022
+ }
1023
+ if (headers[MAP][name] === undefined) {
1024
+ headers[MAP][name] = [val];
1025
+ } else {
1026
+ headers[MAP][name].push(val);
1027
+ }
1028
+ }
1029
+ } else if (!invalidHeaderCharRegex.test(obj[name])) {
1030
+ headers[MAP][name] = [obj[name]];
1031
+ }
1032
+ }
1033
+ return headers;
1034
+ }
1035
+
1036
+ /**
1037
+ * response.js
1038
+ *
1039
+ * Response class provides content decoding
1040
+ */
1041
+
1042
+ const INTERNALS$1 = Symbol('Response internals');
1043
+
1044
+ // fix an issue where "STATUS_CODES" aren't a named export for node <10
1045
+ const STATUS_CODES = http.STATUS_CODES;
1046
+
1047
+ /**
1048
+ * Response class
1049
+ *
1050
+ * @param Stream body Readable stream
1051
+ * @param Object opts Response options
1052
+ * @return Void
1053
+ */
1054
+ class Response {
1055
+ constructor() {
1056
+ let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
1057
+ let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1058
+
1059
+ Body.call(this, body, opts);
1060
+
1061
+ const status = opts.status || 200;
1062
+ const headers = new Headers(opts.headers);
1063
+
1064
+ if (body != null && !headers.has('Content-Type')) {
1065
+ const contentType = extractContentType(body);
1066
+ if (contentType) {
1067
+ headers.append('Content-Type', contentType);
1068
+ }
1069
+ }
1070
+
1071
+ this[INTERNALS$1] = {
1072
+ url: opts.url,
1073
+ status,
1074
+ statusText: opts.statusText || STATUS_CODES[status],
1075
+ headers,
1076
+ counter: opts.counter
1077
+ };
1078
+ }
1079
+
1080
+ get url() {
1081
+ return this[INTERNALS$1].url || '';
1082
+ }
1083
+
1084
+ get status() {
1085
+ return this[INTERNALS$1].status;
1086
+ }
1087
+
1088
+ /**
1089
+ * Convenience property representing if the request ended normally
1090
+ */
1091
+ get ok() {
1092
+ return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300;
1093
+ }
1094
+
1095
+ get redirected() {
1096
+ return this[INTERNALS$1].counter > 0;
1097
+ }
1098
+
1099
+ get statusText() {
1100
+ return this[INTERNALS$1].statusText;
1101
+ }
1102
+
1103
+ get headers() {
1104
+ return this[INTERNALS$1].headers;
1105
+ }
1106
+
1107
+ /**
1108
+ * Clone this response
1109
+ *
1110
+ * @return Response
1111
+ */
1112
+ clone() {
1113
+ return new Response(clone(this), {
1114
+ url: this.url,
1115
+ status: this.status,
1116
+ statusText: this.statusText,
1117
+ headers: this.headers,
1118
+ ok: this.ok,
1119
+ redirected: this.redirected
1120
+ });
1121
+ }
1122
+ }
1123
+
1124
+ Body.mixIn(Response.prototype);
1125
+
1126
+ Object.defineProperties(Response.prototype, {
1127
+ url: { enumerable: true },
1128
+ status: { enumerable: true },
1129
+ ok: { enumerable: true },
1130
+ redirected: { enumerable: true },
1131
+ statusText: { enumerable: true },
1132
+ headers: { enumerable: true },
1133
+ clone: { enumerable: true }
1134
+ });
1135
+
1136
+ Object.defineProperty(Response.prototype, Symbol.toStringTag, {
1137
+ value: 'Response',
1138
+ writable: false,
1139
+ enumerable: false,
1140
+ configurable: true
1141
+ });
1142
+
1143
+ const INTERNALS$2 = Symbol('Request internals');
1144
+ const URL = Url.URL || whatwgUrl.URL;
1145
+
1146
+ // fix an issue where "format", "parse" aren't a named export for node <10
1147
+ const parse_url = Url.parse;
1148
+ const format_url = Url.format;
1149
+
1150
+ /**
1151
+ * Wrapper around `new URL` to handle arbitrary URLs
1152
+ *
1153
+ * @param {string} urlStr
1154
+ * @return {void}
1155
+ */
1156
+ function parseURL(urlStr) {
1157
+ /*
1158
+ Check whether the URL is absolute or not
1159
+ Scheme: https://tools.ietf.org/html/rfc3986#section-3.1
1160
+ Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3
1161
+ */
1162
+ if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.exec(urlStr)) {
1163
+ urlStr = new URL(urlStr).toString();
1164
+ }
1165
+
1166
+ // Fallback to old implementation for arbitrary URLs
1167
+ return parse_url(urlStr);
1168
+ }
1169
+
1170
+ const streamDestructionSupported = 'destroy' in Stream.Readable.prototype;
1171
+
1172
+ /**
1173
+ * Check if a value is an instance of Request.
1174
+ *
1175
+ * @param Mixed input
1176
+ * @return Boolean
1177
+ */
1178
+ function isRequest(input) {
1179
+ return typeof input === 'object' && typeof input[INTERNALS$2] === 'object';
1180
+ }
1181
+
1182
+ function isAbortSignal(signal) {
1183
+ const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal);
1184
+ return !!(proto && proto.constructor.name === 'AbortSignal');
1185
+ }
1186
+
1187
+ /**
1188
+ * Request class
1189
+ *
1190
+ * @param Mixed input Url or Request instance
1191
+ * @param Object init Custom options
1192
+ * @return Void
1193
+ */
1194
+ class Request {
1195
+ constructor(input) {
1196
+ let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1197
+
1198
+ let parsedURL;
1199
+
1200
+ // normalize input
1201
+ if (!isRequest(input)) {
1202
+ if (input && input.href) {
1203
+ // in order to support Node.js' Url objects; though WHATWG's URL objects
1204
+ // will fall into this branch also (since their `toString()` will return
1205
+ // `href` property anyway)
1206
+ parsedURL = parseURL(input.href);
1207
+ } else {
1208
+ // coerce input to a string before attempting to parse
1209
+ parsedURL = parseURL(`${input}`);
1210
+ }
1211
+ input = {};
1212
+ } else {
1213
+ parsedURL = parseURL(input.url);
1214
+ }
1215
+
1216
+ let method = init.method || input.method || 'GET';
1217
+ method = method.toUpperCase();
1218
+
1219
+ if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) {
1220
+ throw new TypeError('Request with GET/HEAD method cannot have body');
1221
+ }
1222
+
1223
+ let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null;
1224
+
1225
+ Body.call(this, inputBody, {
1226
+ timeout: init.timeout || input.timeout || 0,
1227
+ size: init.size || input.size || 0
1228
+ });
1229
+
1230
+ const headers = new Headers(init.headers || input.headers || {});
1231
+
1232
+ if (inputBody != null && !headers.has('Content-Type')) {
1233
+ const contentType = extractContentType(inputBody);
1234
+ if (contentType) {
1235
+ headers.append('Content-Type', contentType);
1236
+ }
1237
+ }
1238
+
1239
+ let signal = isRequest(input) ? input.signal : null;
1240
+ if ('signal' in init) signal = init.signal;
1241
+
1242
+ if (signal != null && !isAbortSignal(signal)) {
1243
+ throw new TypeError('Expected signal to be an instanceof AbortSignal');
1244
+ }
1245
+
1246
+ this[INTERNALS$2] = {
1247
+ method,
1248
+ redirect: init.redirect || input.redirect || 'follow',
1249
+ headers,
1250
+ parsedURL,
1251
+ signal
1252
+ };
1253
+
1254
+ // node-fetch-only options
1255
+ this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20;
1256
+ this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true;
1257
+ this.counter = init.counter || input.counter || 0;
1258
+ this.agent = init.agent || input.agent;
1259
+ }
1260
+
1261
+ get method() {
1262
+ return this[INTERNALS$2].method;
1263
+ }
1264
+
1265
+ get url() {
1266
+ return format_url(this[INTERNALS$2].parsedURL);
1267
+ }
1268
+
1269
+ get headers() {
1270
+ return this[INTERNALS$2].headers;
1271
+ }
1272
+
1273
+ get redirect() {
1274
+ return this[INTERNALS$2].redirect;
1275
+ }
1276
+
1277
+ get signal() {
1278
+ return this[INTERNALS$2].signal;
1279
+ }
1280
+
1281
+ /**
1282
+ * Clone this request
1283
+ *
1284
+ * @return Request
1285
+ */
1286
+ clone() {
1287
+ return new Request(this);
1288
+ }
1289
+ }
1290
+
1291
+ Body.mixIn(Request.prototype);
1292
+
1293
+ Object.defineProperty(Request.prototype, Symbol.toStringTag, {
1294
+ value: 'Request',
1295
+ writable: false,
1296
+ enumerable: false,
1297
+ configurable: true
1298
+ });
1299
+
1300
+ Object.defineProperties(Request.prototype, {
1301
+ method: { enumerable: true },
1302
+ url: { enumerable: true },
1303
+ headers: { enumerable: true },
1304
+ redirect: { enumerable: true },
1305
+ clone: { enumerable: true },
1306
+ signal: { enumerable: true }
1307
+ });
1308
+
1309
+ /**
1310
+ * Convert a Request to Node.js http request options.
1311
+ *
1312
+ * @param Request A Request instance
1313
+ * @return Object The options object to be passed to http.request
1314
+ */
1315
+ function getNodeRequestOptions(request) {
1316
+ const parsedURL = request[INTERNALS$2].parsedURL;
1317
+ const headers = new Headers(request[INTERNALS$2].headers);
1318
+
1319
+ // fetch step 1.3
1320
+ if (!headers.has('Accept')) {
1321
+ headers.set('Accept', '*/*');
1322
+ }
1323
+
1324
+ // Basic fetch
1325
+ if (!parsedURL.protocol || !parsedURL.hostname) {
1326
+ throw new TypeError('Only absolute URLs are supported');
1327
+ }
1328
+
1329
+ if (!/^https?:$/.test(parsedURL.protocol)) {
1330
+ throw new TypeError('Only HTTP(S) protocols are supported');
1331
+ }
1332
+
1333
+ if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) {
1334
+ throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8');
1335
+ }
1336
+
1337
+ // HTTP-network-or-cache fetch steps 2.4-2.7
1338
+ let contentLengthValue = null;
1339
+ if (request.body == null && /^(POST|PUT)$/i.test(request.method)) {
1340
+ contentLengthValue = '0';
1341
+ }
1342
+ if (request.body != null) {
1343
+ const totalBytes = getTotalBytes(request);
1344
+ if (typeof totalBytes === 'number') {
1345
+ contentLengthValue = String(totalBytes);
1346
+ }
1347
+ }
1348
+ if (contentLengthValue) {
1349
+ headers.set('Content-Length', contentLengthValue);
1350
+ }
1351
+
1352
+ // HTTP-network-or-cache fetch step 2.11
1353
+ if (!headers.has('User-Agent')) {
1354
+ headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)');
1355
+ }
1356
+
1357
+ // HTTP-network-or-cache fetch step 2.15
1358
+ if (request.compress && !headers.has('Accept-Encoding')) {
1359
+ headers.set('Accept-Encoding', 'gzip,deflate');
1360
+ }
1361
+
1362
+ let agent = request.agent;
1363
+ if (typeof agent === 'function') {
1364
+ agent = agent(parsedURL);
1365
+ }
1366
+
1367
+ if (!headers.has('Connection') && !agent) {
1368
+ headers.set('Connection', 'close');
1369
+ }
1370
+
1371
+ // HTTP-network fetch step 4.2
1372
+ // chunked encoding is handled by Node.js
1373
+
1374
+ return Object.assign({}, parsedURL, {
1375
+ method: request.method,
1376
+ headers: exportNodeCompatibleHeaders(headers),
1377
+ agent
1378
+ });
1379
+ }
1380
+
1381
+ /**
1382
+ * abort-error.js
1383
+ *
1384
+ * AbortError interface for cancelled requests
1385
+ */
1386
+
1387
+ /**
1388
+ * Create AbortError instance
1389
+ *
1390
+ * @param String message Error message for human
1391
+ * @return AbortError
1392
+ */
1393
+ function AbortError(message) {
1394
+ Error.call(this, message);
1395
+
1396
+ this.type = 'aborted';
1397
+ this.message = message;
1398
+
1399
+ // hide custom error implementation details from end-users
1400
+ Error.captureStackTrace(this, this.constructor);
1401
+ }
1402
+
1403
+ AbortError.prototype = Object.create(Error.prototype);
1404
+ AbortError.prototype.constructor = AbortError;
1405
+ AbortError.prototype.name = 'AbortError';
1406
+
1407
+ /**
1408
+ * index.js
1409
+ *
1410
+ * a request API compatible with window.fetch
1411
+ *
1412
+ * All spec algorithm step numbers are based on https://fetch.spec.whatwg.org/commit-snapshots/ae716822cb3a61843226cd090eefc6589446c1d2/.
1413
+ */
1414
+
1415
+ const URL$1 = Url.URL || whatwgUrl.URL;
1416
+
1417
+ // fix an issue where "PassThrough", "resolve" aren't a named export for node <10
1418
+ const PassThrough$1 = Stream.PassThrough;
1419
+
1420
+ const isDomainOrSubdomain = function isDomainOrSubdomain(destination, original) {
1421
+ const orig = new URL$1(original).hostname;
1422
+ const dest = new URL$1(destination).hostname;
1423
+
1424
+ return orig === dest || orig[orig.length - dest.length - 1] === '.' && orig.endsWith(dest);
1425
+ };
1426
+
1427
+ /**
1428
+ * isSameProtocol reports whether the two provided URLs use the same protocol.
1429
+ *
1430
+ * Both domains must already be in canonical form.
1431
+ * @param {string|URL} original
1432
+ * @param {string|URL} destination
1433
+ */
1434
+ const isSameProtocol = function isSameProtocol(destination, original) {
1435
+ const orig = new URL$1(original).protocol;
1436
+ const dest = new URL$1(destination).protocol;
1437
+
1438
+ return orig === dest;
1439
+ };
1440
+
1441
+ /**
1442
+ * Fetch function
1443
+ *
1444
+ * @param Mixed url Absolute url or Request instance
1445
+ * @param Object opts Fetch options
1446
+ * @return Promise
1447
+ */
1448
+ function fetch(url, opts) {
1449
+ // allow custom promise
1450
+ if (!fetch.Promise) {
1451
+ throw new Error('native promise missing, set fetch.Promise to your favorite alternative');
1452
+ }
1453
+
1454
+ Body.Promise = fetch.Promise;
1455
+
1456
+ // wrap http.request into fetch
1457
+ return new fetch.Promise(function (resolve, reject) {
1458
+ // build request object
1459
+ const request = new Request(url, opts);
1460
+ const options = getNodeRequestOptions(request);
1461
+
1462
+ const send = (options.protocol === 'https:' ? https : http).request;
1463
+ const signal = request.signal;
1464
+
1465
+ let response = null;
1466
+
1467
+ const abort = function abort() {
1468
+ let error = new AbortError('The user aborted a request.');
1469
+ reject(error);
1470
+ if (request.body && request.body instanceof Stream.Readable) {
1471
+ destroyStream(request.body, error);
1472
+ }
1473
+ if (!response || !response.body) return;
1474
+ response.body.emit('error', error);
1475
+ };
1476
+
1477
+ if (signal && signal.aborted) {
1478
+ abort();
1479
+ return;
1480
+ }
1481
+
1482
+ const abortAndFinalize = function abortAndFinalize() {
1483
+ abort();
1484
+ finalize();
1485
+ };
1486
+
1487
+ // send request
1488
+ const req = send(options);
1489
+ let reqTimeout;
1490
+
1491
+ if (signal) {
1492
+ signal.addEventListener('abort', abortAndFinalize);
1493
+ }
1494
+
1495
+ function finalize() {
1496
+ req.abort();
1497
+ if (signal) signal.removeEventListener('abort', abortAndFinalize);
1498
+ clearTimeout(reqTimeout);
1499
+ }
1500
+
1501
+ if (request.timeout) {
1502
+ req.once('socket', function (socket) {
1503
+ reqTimeout = setTimeout(function () {
1504
+ reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout'));
1505
+ finalize();
1506
+ }, request.timeout);
1507
+ });
1508
+ }
1509
+
1510
+ req.on('error', function (err) {
1511
+ reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err));
1512
+
1513
+ if (response && response.body) {
1514
+ destroyStream(response.body, err);
1515
+ }
1516
+
1517
+ finalize();
1518
+ });
1519
+
1520
+ fixResponseChunkedTransferBadEnding(req, function (err) {
1521
+ if (signal && signal.aborted) {
1522
+ return;
1523
+ }
1524
+
1525
+ if (response && response.body) {
1526
+ destroyStream(response.body, err);
1527
+ }
1528
+ });
1529
+
1530
+ /* c8 ignore next 18 */
1531
+ if (parseInt(process.version.substring(1)) < 14) {
1532
+ // Before Node.js 14, pipeline() does not fully support async iterators and does not always
1533
+ // properly handle when the socket close/end events are out of order.
1534
+ req.on('socket', function (s) {
1535
+ s.addListener('close', function (hadError) {
1536
+ // if a data listener is still present we didn't end cleanly
1537
+ const hasDataListener = s.listenerCount('data') > 0;
1538
+
1539
+ // if end happened before close but the socket didn't emit an error, do it now
1540
+ if (response && hasDataListener && !hadError && !(signal && signal.aborted)) {
1541
+ const err = new Error('Premature close');
1542
+ err.code = 'ERR_STREAM_PREMATURE_CLOSE';
1543
+ response.body.emit('error', err);
1544
+ }
1545
+ });
1546
+ });
1547
+ }
1548
+
1549
+ req.on('response', function (res) {
1550
+ clearTimeout(reqTimeout);
1551
+
1552
+ const headers = createHeadersLenient(res.headers);
1553
+
1554
+ // HTTP fetch step 5
1555
+ if (fetch.isRedirect(res.statusCode)) {
1556
+ // HTTP fetch step 5.2
1557
+ const location = headers.get('Location');
1558
+
1559
+ // HTTP fetch step 5.3
1560
+ let locationURL = null;
1561
+ try {
1562
+ locationURL = location === null ? null : new URL$1(location, request.url).toString();
1563
+ } catch (err) {
1564
+ // error here can only be invalid URL in Location: header
1565
+ // do not throw when options.redirect == manual
1566
+ // let the user extract the errorneous redirect URL
1567
+ if (request.redirect !== 'manual') {
1568
+ reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect'));
1569
+ finalize();
1570
+ return;
1571
+ }
1572
+ }
1573
+
1574
+ // HTTP fetch step 5.5
1575
+ switch (request.redirect) {
1576
+ case 'error':
1577
+ reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect'));
1578
+ finalize();
1579
+ return;
1580
+ case 'manual':
1581
+ // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL.
1582
+ if (locationURL !== null) {
1583
+ // handle corrupted header
1584
+ try {
1585
+ headers.set('Location', locationURL);
1586
+ } catch (err) {
1587
+ // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request
1588
+ reject(err);
1589
+ }
1590
+ }
1591
+ break;
1592
+ case 'follow':
1593
+ // HTTP-redirect fetch step 2
1594
+ if (locationURL === null) {
1595
+ break;
1596
+ }
1597
+
1598
+ // HTTP-redirect fetch step 5
1599
+ if (request.counter >= request.follow) {
1600
+ reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect'));
1601
+ finalize();
1602
+ return;
1603
+ }
1604
+
1605
+ // HTTP-redirect fetch step 6 (counter increment)
1606
+ // Create a new Request object.
1607
+ const requestOpts = {
1608
+ headers: new Headers(request.headers),
1609
+ follow: request.follow,
1610
+ counter: request.counter + 1,
1611
+ agent: request.agent,
1612
+ compress: request.compress,
1613
+ method: request.method,
1614
+ body: request.body,
1615
+ signal: request.signal,
1616
+ timeout: request.timeout,
1617
+ size: request.size
1618
+ };
1619
+
1620
+ if (!isDomainOrSubdomain(request.url, locationURL) || !isSameProtocol(request.url, locationURL)) {
1621
+ for (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) {
1622
+ requestOpts.headers.delete(name);
1623
+ }
1624
+ }
1625
+
1626
+ // HTTP-redirect fetch step 9
1627
+ if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) {
1628
+ reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect'));
1629
+ finalize();
1630
+ return;
1631
+ }
1632
+
1633
+ // HTTP-redirect fetch step 11
1634
+ if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') {
1635
+ requestOpts.method = 'GET';
1636
+ requestOpts.body = undefined;
1637
+ requestOpts.headers.delete('content-length');
1638
+ }
1639
+
1640
+ // HTTP-redirect fetch step 15
1641
+ resolve(fetch(new Request(locationURL, requestOpts)));
1642
+ finalize();
1643
+ return;
1644
+ }
1645
+ }
1646
+
1647
+ // prepare response
1648
+ res.once('end', function () {
1649
+ if (signal) signal.removeEventListener('abort', abortAndFinalize);
1650
+ });
1651
+ let body = res.pipe(new PassThrough$1());
1652
+
1653
+ const response_options = {
1654
+ url: request.url,
1655
+ status: res.statusCode,
1656
+ statusText: res.statusMessage,
1657
+ headers: headers,
1658
+ size: request.size,
1659
+ timeout: request.timeout,
1660
+ counter: request.counter
1661
+ };
1662
+
1663
+ // HTTP-network fetch step 12.1.1.3
1664
+ const codings = headers.get('Content-Encoding');
1665
+
1666
+ // HTTP-network fetch step 12.1.1.4: handle content codings
1667
+
1668
+ // in following scenarios we ignore compression support
1669
+ // 1. compression support is disabled
1670
+ // 2. HEAD request
1671
+ // 3. no Content-Encoding header
1672
+ // 4. no content response (204)
1673
+ // 5. content not modified response (304)
1674
+ if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) {
1675
+ response = new Response(body, response_options);
1676
+ resolve(response);
1677
+ return;
1678
+ }
1679
+
1680
+ // For Node v6+
1681
+ // Be less strict when decoding compressed responses, since sometimes
1682
+ // servers send slightly invalid responses that are still accepted
1683
+ // by common browsers.
1684
+ // Always using Z_SYNC_FLUSH is what cURL does.
1685
+ const zlibOptions = {
1686
+ flush: zlib.Z_SYNC_FLUSH,
1687
+ finishFlush: zlib.Z_SYNC_FLUSH
1688
+ };
1689
+
1690
+ // for gzip
1691
+ if (codings == 'gzip' || codings == 'x-gzip') {
1692
+ body = body.pipe(zlib.createGunzip(zlibOptions));
1693
+ response = new Response(body, response_options);
1694
+ resolve(response);
1695
+ return;
1696
+ }
1697
+
1698
+ // for deflate
1699
+ if (codings == 'deflate' || codings == 'x-deflate') {
1700
+ // handle the infamous raw deflate response from old servers
1701
+ // a hack for old IIS and Apache servers
1702
+ const raw = res.pipe(new PassThrough$1());
1703
+ raw.once('data', function (chunk) {
1704
+ // see http://stackoverflow.com/questions/37519828
1705
+ if ((chunk[0] & 0x0f) === 0x08) {
1706
+ body = body.pipe(zlib.createInflate());
1707
+ } else {
1708
+ body = body.pipe(zlib.createInflateRaw());
1709
+ }
1710
+ response = new Response(body, response_options);
1711
+ resolve(response);
1712
+ });
1713
+ raw.on('end', function () {
1714
+ // some old IIS servers return zero-length OK deflate responses, so 'data' is never emitted.
1715
+ if (!response) {
1716
+ response = new Response(body, response_options);
1717
+ resolve(response);
1718
+ }
1719
+ });
1720
+ return;
1721
+ }
1722
+
1723
+ // for br
1724
+ if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') {
1725
+ body = body.pipe(zlib.createBrotliDecompress());
1726
+ response = new Response(body, response_options);
1727
+ resolve(response);
1728
+ return;
1729
+ }
1730
+
1731
+ // otherwise, use response as-is
1732
+ response = new Response(body, response_options);
1733
+ resolve(response);
1734
+ });
1735
+
1736
+ writeToStream(req, request);
1737
+ });
1738
+ }
1739
+
1740
+ function fixResponseChunkedTransferBadEnding(request, errorCallback) {
1741
+ let socket;
1742
+
1743
+ request.on('socket', function (s) {
1744
+ socket = s;
1745
+ });
1746
+
1747
+ request.on('response', function (response) {
1748
+ const headers = response.headers;
1749
+
1750
+ if (headers['transfer-encoding'] === 'chunked' && !headers['content-length']) {
1751
+ response.once('close', function (hadError) {
1752
+ // tests for socket presence, as in some situations the
1753
+ // the 'socket' event is not triggered for the request
1754
+ // (happens in deno), avoids `TypeError`
1755
+ // if a data listener is still present we didn't end cleanly
1756
+ const hasDataListener = socket && socket.listenerCount('data') > 0;
1757
+
1758
+ if (hasDataListener && !hadError) {
1759
+ const err = new Error('Premature close');
1760
+ err.code = 'ERR_STREAM_PREMATURE_CLOSE';
1761
+ errorCallback(err);
1762
+ }
1763
+ });
1764
+ }
1765
+ });
1766
+ }
1767
+
1768
+ function destroyStream(stream, err) {
1769
+ if (stream.destroy) {
1770
+ stream.destroy(err);
1771
+ } else {
1772
+ // node < 8
1773
+ stream.emit('error', err);
1774
+ stream.end();
1775
+ }
1776
+ }
1777
+
1778
+ /**
1779
+ * Redirect code matching
1780
+ *
1781
+ * @param Number code Status code
1782
+ * @return Boolean
1783
+ */
1784
+ fetch.isRedirect = function (code) {
1785
+ return code === 301 || code === 302 || code === 303 || code === 307 || code === 308;
1786
+ };
1787
+
1788
+ // expose Promise
1789
+ fetch.Promise = global.Promise;
1790
+
1791
+ export default fetch;
1792
+ export { Headers, Request, Response, FetchError };