3 Object.defineProperty(exports, '__esModule', { value: true });
5 function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
7 var Stream = _interopDefault(require('stream'));
8 var http = _interopDefault(require('http'));
9 var Url = _interopDefault(require('url'));
10 var whatwgUrl = _interopDefault(require('whatwg-url'));
11 var https = _interopDefault(require('https'));
12 var zlib = _interopDefault(require('zlib'));
14 // Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js
16 // fix for "Readable" isn't a named export issue
17 const Readable = Stream.Readable;
19 const BUFFER = Symbol('buffer');
20 const TYPE = Symbol('type');
26 const blobParts = arguments[0];
27 const options = arguments[1];
34 const length = Number(a.length);
35 for (let i = 0; i < length; i++) {
38 if (element instanceof Buffer) {
40 } else if (ArrayBuffer.isView(element)) {
41 buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength);
42 } else if (element instanceof ArrayBuffer) {
43 buffer = Buffer.from(element);
44 } else if (element instanceof Blob) {
45 buffer = element[BUFFER];
47 buffer = Buffer.from(typeof element === 'string' ? element : String(element));
49 size += buffer.length;
54 this[BUFFER] = Buffer.concat(buffers);
56 let type = options && options.type !== undefined && String(options.type).toLowerCase();
57 if (type && !/[^\u0020-\u007E]/.test(type)) {
62 return this[BUFFER].length;
68 return Promise.resolve(this[BUFFER].toString());
71 const buf = this[BUFFER];
72 const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
73 return Promise.resolve(ab);
76 const readable = new Readable();
77 readable._read = function () {};
78 readable.push(this[BUFFER]);
83 return '[object Blob]';
86 const size = this.size;
88 const start = arguments[0];
89 const end = arguments[1];
90 let relativeStart, relativeEnd;
91 if (start === undefined) {
93 } else if (start < 0) {
94 relativeStart = Math.max(size + start, 0);
96 relativeStart = Math.min(start, size);
98 if (end === undefined) {
100 } else if (end < 0) {
101 relativeEnd = Math.max(size + end, 0);
103 relativeEnd = Math.min(end, size);
105 const span = Math.max(relativeEnd - relativeStart, 0);
107 const buffer = this[BUFFER];
108 const slicedBuffer = buffer.slice(relativeStart, relativeStart + span);
109 const blob = new Blob([], { type: arguments[2] });
110 blob[BUFFER] = slicedBuffer;
115 Object.defineProperties(Blob.prototype, {
116 size: { enumerable: true },
117 type: { enumerable: true },
118 slice: { enumerable: true }
121 Object.defineProperty(Blob.prototype, Symbol.toStringTag, {
131 * FetchError interface for operational errors
135 * Create FetchError instance
137 * @param String message Error message for human
138 * @param String type Error type for machine
139 * @param String systemError For Node.js system error
142 function FetchError(message, type, systemError) {
143 Error.call(this, message);
145 this.message = message;
148 // when err.type is `system`, err.code contains system error code
150 this.code = this.errno = systemError.code;
153 // hide custom error implementation details from end-users
154 Error.captureStackTrace(this, this.constructor);
157 FetchError.prototype = Object.create(Error.prototype);
158 FetchError.prototype.constructor = FetchError;
159 FetchError.prototype.name = 'FetchError';
163 convert = require('encoding').convert;
166 const INTERNALS = Symbol('Body internals');
168 // fix an issue where "PassThrough" isn't a named export for node <10
169 const PassThrough = Stream.PassThrough;
174 * Ref: https://fetch.spec.whatwg.org/#body
176 * @param Stream body Readable stream
177 * @param Object opts Response options
180 function Body(body) {
183 var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
184 _ref$size = _ref.size;
186 let size = _ref$size === undefined ? 0 : _ref$size;
187 var _ref$timeout = _ref.timeout;
188 let timeout = _ref$timeout === undefined ? 0 : _ref$timeout;
191 // body is undefined or null
193 } else if (isURLSearchParams(body)) {
194 // body is a URLSearchParams
195 body = Buffer.from(body.toString());
196 } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') {
197 // body is ArrayBuffer
198 body = Buffer.from(body);
199 } else if (ArrayBuffer.isView(body)) {
200 // body is ArrayBufferView
201 body = Buffer.from(body.buffer, body.byteOffset, body.byteLength);
202 } else if (body instanceof Stream) ; else {
204 // coerce to string then buffer
205 body = Buffer.from(String(body));
213 this.timeout = timeout;
215 if (body instanceof Stream) {
216 body.on('error', function (err) {
217 const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err);
218 _this[INTERNALS].error = error;
225 return this[INTERNALS].body;
229 return this[INTERNALS].disturbed;
233 * Decode response as ArrayBuffer
238 return consumeBody.call(this).then(function (buf) {
239 return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
244 * Return raw response as Blob
249 let ct = this.headers && this.headers.get('content-type') || '';
250 return consumeBody.call(this).then(function (buf) {
251 return Object.assign(
254 type: ct.toLowerCase()
262 * Decode response as json
269 return consumeBody.call(this).then(function (buffer) {
271 return JSON.parse(buffer.toString());
273 return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json'));
279 * Decode response as text
284 return consumeBody.call(this).then(function (buffer) {
285 return buffer.toString();
290 * Decode response as buffer (non-spec api)
295 return consumeBody.call(this);
299 * Decode response as text, while automatically detecting the encoding and
300 * trying to decode to UTF-8 (non-spec api)
307 return consumeBody.call(this).then(function (buffer) {
308 return convertBody(buffer, _this3.headers);
313 // In browsers, all properties are enumerable.
314 Object.defineProperties(Body.prototype, {
315 body: { enumerable: true },
316 bodyUsed: { enumerable: true },
317 arrayBuffer: { enumerable: true },
318 blob: { enumerable: true },
319 json: { enumerable: true },
320 text: { enumerable: true }
323 Body.mixIn = function (proto) {
324 for (const name of Object.getOwnPropertyNames(Body.prototype)) {
325 // istanbul ignore else: future proof
326 if (!(name in proto)) {
327 const desc = Object.getOwnPropertyDescriptor(Body.prototype, name);
328 Object.defineProperty(proto, name, desc);
334 * Consume and convert an entire Body to a Buffer.
336 * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body
340 function consumeBody() {
343 if (this[INTERNALS].disturbed) {
344 return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`));
347 this[INTERNALS].disturbed = true;
349 if (this[INTERNALS].error) {
350 return Body.Promise.reject(this[INTERNALS].error);
353 let body = this.body;
357 return Body.Promise.resolve(Buffer.alloc(0));
362 body = body.stream();
366 if (Buffer.isBuffer(body)) {
367 return Body.Promise.resolve(body);
370 // istanbul ignore if: should never happen
371 if (!(body instanceof Stream)) {
372 return Body.Promise.resolve(Buffer.alloc(0));
376 // get ready to actually consume the body
381 return new Body.Promise(function (resolve, reject) {
384 // allow timeout on slow response body
385 if (_this4.timeout) {
386 resTimeout = setTimeout(function () {
388 reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout'));
392 // handle stream errors
393 body.on('error', function (err) {
394 if (err.name === 'AbortError') {
395 // if the request was aborted, reject with this Error
399 // other errors, such as incorrect content-encoding
400 reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err));
404 body.on('data', function (chunk) {
405 if (abort || chunk === null) {
409 if (_this4.size && accumBytes + chunk.length > _this4.size) {
411 reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size'));
415 accumBytes += chunk.length;
419 body.on('end', function () {
424 clearTimeout(resTimeout);
427 resolve(Buffer.concat(accum, accumBytes));
429 // handle streams that have accumulated too much data (issue #414)
430 reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err));
437 * Detect buffer encoding and convert to target encoding
438 * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding
440 * @param Buffer buffer Incoming buffer
441 * @param String encoding Target encoding
444 function convertBody(buffer, headers) {
445 if (typeof convert !== 'function') {
446 throw new Error('The package `encoding` must be installed to use the textConverted() function');
449 const ct = headers.get('content-type');
450 let charset = 'utf-8';
455 res = /charset=([^;]*)/i.exec(ct);
458 // no charset in content type, peek at response body for at most 1024 bytes
459 str = buffer.slice(0, 1024).toString();
463 res = /<meta.+?charset=(['"])(.+?)\1/i.exec(str);
468 res = /<meta[\s]+?http-equiv=(['"])content-type\1[\s]+?content=(['"])(.+?)\2/i.exec(str);
470 res = /<meta[\s]+?content=(['"])(.+?)\1[\s]+?http-equiv=(['"])content-type\3/i.exec(str);
472 res.pop(); // drop last quote
477 res = /charset=(.*)/i.exec(res.pop());
483 res = /<\?xml.+?encoding=(['"])(.+?)\1/i.exec(str);
490 // prevent decode issues when sites use incorrect encoding
491 // ref: https://hsivonen.fi/encoding-menu/
492 if (charset === 'gb2312' || charset === 'gbk') {
497 // turn raw buffers into a single utf-8 buffer
498 return convert(buffer, 'UTF-8', charset).toString();
502 * Detect a URLSearchParams object
503 * ref: https://github.com/bitinn/node-fetch/issues/296#issuecomment-307598143
505 * @param Object obj Object to detect by type or brand
508 function isURLSearchParams(obj) {
509 // Duck-typing as a necessary condition.
510 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') {
514 // Brand-checking and more duck-typing as optional condition.
515 return obj.constructor.name === 'URLSearchParams' || Object.prototype.toString.call(obj) === '[object URLSearchParams]' || typeof obj.sort === 'function';
519 * Check if `obj` is a W3C `Blob` object (which `File` inherits from)
523 function isBlob(obj) {
524 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]);
528 * Clone body given Res/Req instance
530 * @param Mixed instance Response or Request instance
533 function clone(instance) {
535 let body = instance.body;
537 // don't allow cloning a used body
538 if (instance.bodyUsed) {
539 throw new Error('cannot clone body after it is used');
542 // check that body is a stream and not form-data object
543 // note: we can't clone the form-data object without having it as a dependency
544 if (body instanceof Stream && typeof body.getBoundary !== 'function') {
546 p1 = new PassThrough();
547 p2 = new PassThrough();
550 // set instance body to teed body and return the other teed body
551 instance[INTERNALS].body = p1;
559 * Performs the operation "extract a `Content-Type` value from |object|" as
560 * specified in the specification:
561 * https://fetch.spec.whatwg.org/#concept-bodyinit-extract
563 * This function assumes that instance.body is present.
565 * @param Mixed instance Any options.body input
567 function extractContentType(body) {
571 } else if (typeof body === 'string') {
573 return 'text/plain;charset=UTF-8';
574 } else if (isURLSearchParams(body)) {
575 // body is a URLSearchParams
576 return 'application/x-www-form-urlencoded;charset=UTF-8';
577 } else if (isBlob(body)) {
579 return body.type || null;
580 } else if (Buffer.isBuffer(body)) {
583 } else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') {
584 // body is ArrayBuffer
586 } else if (ArrayBuffer.isView(body)) {
587 // body is ArrayBufferView
589 } else if (typeof body.getBoundary === 'function') {
590 // detect form data input from form-data module
591 return `multipart/form-data;boundary=${body.getBoundary()}`;
592 } else if (body instanceof Stream) {
594 // can't really do much about this
597 // Body constructor defaults other things to string
598 return 'text/plain;charset=UTF-8';
603 * The Fetch Standard treats this as if "total bytes" is a property on the body.
604 * For us, we have to explicitly get it with a function.
606 * ref: https://fetch.spec.whatwg.org/#concept-body-total-bytes
608 * @param Body instance Instance of Body
609 * @return Number? Number of bytes, or null if not possible
611 function getTotalBytes(instance) {
612 const body = instance.body;
618 } else if (isBlob(body)) {
620 } else if (Buffer.isBuffer(body)) {
623 } else if (body && typeof body.getLengthSync === 'function') {
624 // detect form data input from form-data module
625 if (body._lengthRetrievers && body._lengthRetrievers.length == 0 || // 1.x
626 body.hasKnownLength && body.hasKnownLength()) {
628 return body.getLengthSync();
638 * Write a Body to a Node.js WritableStream (e.g. http.Request) object.
640 * @param Body instance Instance of Body
643 function writeToStream(dest, instance) {
644 const body = instance.body;
650 } else if (isBlob(body)) {
651 body.stream().pipe(dest);
652 } else if (Buffer.isBuffer(body)) {
663 Body.Promise = global.Promise;
668 * Headers class offers convenient helpers
671 const invalidTokenRegex = /[^\^_`a-zA-Z\-0-9!#$%&'*+.|~]/;
672 const invalidHeaderCharRegex = /[^\t\x20-\x7e\x80-\xff]/;
674 function validateName(name) {
676 if (invalidTokenRegex.test(name) || name === '') {
677 throw new TypeError(`${name} is not a legal HTTP header name`);
681 function validateValue(value) {
683 if (invalidHeaderCharRegex.test(value)) {
684 throw new TypeError(`${value} is not a legal HTTP header value`);
689 * Find the key in the map object given a header name.
691 * Returns undefined if not found.
693 * @param String name Header name
694 * @return String|Undefined
696 function find(map, name) {
697 name = name.toLowerCase();
698 for (const key in map) {
699 if (key.toLowerCase() === name) {
706 const MAP = Symbol('map');
711 * @param Object headers Response headers
715 let init = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : undefined;
717 this[MAP] = Object.create(null);
719 if (init instanceof Headers) {
720 const rawHeaders = init.raw();
721 const headerNames = Object.keys(rawHeaders);
723 for (const headerName of headerNames) {
724 for (const value of rawHeaders[headerName]) {
725 this.append(headerName, value);
732 // We don't worry about converting prop to ByteString here as append()
734 if (init == null) ; else if (typeof init === 'object') {
735 const method = init[Symbol.iterator];
736 if (method != null) {
737 if (typeof method !== 'function') {
738 throw new TypeError('Header pairs must be iterable');
741 // sequence<sequence<ByteString>>
742 // Note: per spec we have to first exhaust the lists then process them
744 for (const pair of init) {
745 if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') {
746 throw new TypeError('Each header pair must be iterable');
748 pairs.push(Array.from(pair));
751 for (const pair of pairs) {
752 if (pair.length !== 2) {
753 throw new TypeError('Each header pair must be a name/value tuple');
755 this.append(pair[0], pair[1]);
758 // record<ByteString, ByteString>
759 for (const key of Object.keys(init)) {
760 const value = init[key];
761 this.append(key, value);
765 throw new TypeError('Provided initializer must be an object');
770 * Return combined header value given name
772 * @param String name Header name
778 const key = find(this[MAP], name);
779 if (key === undefined) {
783 return this[MAP][key].join(', ');
787 * Iterate over all headers
789 * @param Function callback Executed for each item with parameters (value, name, thisArg)
790 * @param Boolean thisArg `this` context for callback function
794 let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;
796 let pairs = getHeaders(this);
798 while (i < pairs.length) {
799 var _pairs$i = pairs[i];
800 const name = _pairs$i[0],
803 callback.call(thisArg, value, name, this);
804 pairs = getHeaders(this);
810 * Overwrite header values given name
812 * @param String name Header name
813 * @param String value Header value
820 validateValue(value);
821 const key = find(this[MAP], name);
822 this[MAP][key !== undefined ? key : name] = [value];
826 * Append a value onto existing header
828 * @param String name Header name
829 * @param String value Header value
832 append(name, value) {
836 validateValue(value);
837 const key = find(this[MAP], name);
838 if (key !== undefined) {
839 this[MAP][key].push(value);
841 this[MAP][name] = [value];
846 * Check for header name existence
848 * @param String name Header name
854 return find(this[MAP], name) !== undefined;
858 * Delete all header values given name
860 * @param String name Header name
866 const key = find(this[MAP], name);
867 if (key !== undefined) {
868 delete this[MAP][key];
873 * Return raw headers (non-spec api)
882 * Get an iterator on keys.
887 return createHeadersIterator(this, 'key');
891 * Get an iterator on values.
896 return createHeadersIterator(this, 'value');
900 * Get an iterator on entries.
902 * This is the default iterator of the Headers object.
906 [Symbol.iterator]() {
907 return createHeadersIterator(this, 'key+value');
910 Headers.prototype.entries = Headers.prototype[Symbol.iterator];
912 Object.defineProperty(Headers.prototype, Symbol.toStringTag, {
919 Object.defineProperties(Headers.prototype, {
920 get: { enumerable: true },
921 forEach: { enumerable: true },
922 set: { enumerable: true },
923 append: { enumerable: true },
924 has: { enumerable: true },
925 delete: { enumerable: true },
926 keys: { enumerable: true },
927 values: { enumerable: true },
928 entries: { enumerable: true }
931 function getHeaders(headers) {
932 let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value';
934 const keys = Object.keys(headers[MAP]).sort();
935 return keys.map(kind === 'key' ? function (k) {
936 return k.toLowerCase();
937 } : kind === 'value' ? function (k) {
938 return headers[MAP][k].join(', ');
940 return [k.toLowerCase(), headers[MAP][k].join(', ')];
944 const INTERNAL = Symbol('internal');
946 function createHeadersIterator(target, kind) {
947 const iterator = Object.create(HeadersIteratorPrototype);
948 iterator[INTERNAL] = {
956 const HeadersIteratorPrototype = Object.setPrototypeOf({
958 // istanbul ignore if
959 if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) {
960 throw new TypeError('Value of `this` is not a HeadersIterator');
963 var _INTERNAL = this[INTERNAL];
964 const target = _INTERNAL.target,
965 kind = _INTERNAL.kind,
966 index = _INTERNAL.index;
968 const values = getHeaders(target, kind);
969 const len = values.length;
977 this[INTERNAL].index = index + 1;
980 value: values[index],
984 }, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())));
986 Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, {
987 value: 'HeadersIterator',
994 * Export the Headers object in a form that Node.js can consume.
996 * @param Headers headers
999 function exportNodeCompatibleHeaders(headers) {
1000 const obj = Object.assign({ __proto__: null }, headers[MAP]);
1002 // http.request() only supports string as Host header. This hack makes
1003 // specifying custom Host header possible.
1004 const hostHeaderKey = find(headers[MAP], 'Host');
1005 if (hostHeaderKey !== undefined) {
1006 obj[hostHeaderKey] = obj[hostHeaderKey][0];
1013 * Create a Headers object from an object of headers, ignoring those that do
1014 * not conform to HTTP grammar productions.
1016 * @param Object obj Object of headers
1019 function createHeadersLenient(obj) {
1020 const headers = new Headers();
1021 for (const name of Object.keys(obj)) {
1022 if (invalidTokenRegex.test(name)) {
1025 if (Array.isArray(obj[name])) {
1026 for (const val of obj[name]) {
1027 if (invalidHeaderCharRegex.test(val)) {
1030 if (headers[MAP][name] === undefined) {
1031 headers[MAP][name] = [val];
1033 headers[MAP][name].push(val);
1036 } else if (!invalidHeaderCharRegex.test(obj[name])) {
1037 headers[MAP][name] = [obj[name]];
1043 const INTERNALS$1 = Symbol('Response internals');
1045 // fix an issue where "STATUS_CODES" aren't a named export for node <10
1046 const STATUS_CODES = http.STATUS_CODES;
1051 * @param Stream body Readable stream
1052 * @param Object opts Response options
1057 let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
1058 let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1060 Body.call(this, body, opts);
1062 const status = opts.status || 200;
1063 const headers = new Headers(opts.headers);
1065 if (body != null && !headers.has('Content-Type')) {
1066 const contentType = extractContentType(body);
1068 headers.append('Content-Type', contentType);
1072 this[INTERNALS$1] = {
1075 statusText: opts.statusText || STATUS_CODES[status],
1077 counter: opts.counter
1082 return this[INTERNALS$1].url || '';
1086 return this[INTERNALS$1].status;
1090 * Convenience property representing if the request ended normally
1093 return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300;
1097 return this[INTERNALS$1].counter > 0;
1101 return this[INTERNALS$1].statusText;
1105 return this[INTERNALS$1].headers;
1109 * Clone this response
1114 return new Response(clone(this), {
1116 status: this.status,
1117 statusText: this.statusText,
1118 headers: this.headers,
1120 redirected: this.redirected
1125 Body.mixIn(Response.prototype);
1127 Object.defineProperties(Response.prototype, {
1128 url: { enumerable: true },
1129 status: { enumerable: true },
1130 ok: { enumerable: true },
1131 redirected: { enumerable: true },
1132 statusText: { enumerable: true },
1133 headers: { enumerable: true },
1134 clone: { enumerable: true }
1137 Object.defineProperty(Response.prototype, Symbol.toStringTag, {
1144 const INTERNALS$2 = Symbol('Request internals');
1145 const URL = Url.URL || whatwgUrl.URL;
1147 // fix an issue where "format", "parse" aren't a named export for node <10
1148 const parse_url = Url.parse;
1149 const format_url = Url.format;
1152 * Wrapper around `new URL` to handle arbitrary URLs
1154 * @param {string} urlStr
1157 function parseURL(urlStr) {
1159 Check whether the URL is absolute or not
1160 Scheme: https://tools.ietf.org/html/rfc3986#section-3.1
1161 Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3
1163 if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.exec(urlStr)) {
1164 urlStr = new URL(urlStr).toString();
1167 // Fallback to old implementation for arbitrary URLs
1168 return parse_url(urlStr);
1171 const streamDestructionSupported = 'destroy' in Stream.Readable.prototype;
1174 * Check if a value is an instance of Request.
1176 * @param Mixed input
1179 function isRequest(input) {
1180 return typeof input === 'object' && typeof input[INTERNALS$2] === 'object';
1183 function isAbortSignal(signal) {
1184 const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal);
1185 return !!(proto && proto.constructor.name === 'AbortSignal');
1191 * @param Mixed input Url or Request instance
1192 * @param Object init Custom options
1196 constructor(input) {
1197 let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1202 if (!isRequest(input)) {
1203 if (input && input.href) {
1204 // in order to support Node.js' Url objects; though WHATWG's URL objects
1205 // will fall into this branch also (since their `toString()` will return
1206 // `href` property anyway)
1207 parsedURL = parseURL(input.href);
1209 // coerce input to a string before attempting to parse
1210 parsedURL = parseURL(`${input}`);
1214 parsedURL = parseURL(input.url);
1217 let method = init.method || input.method || 'GET';
1218 method = method.toUpperCase();
1220 if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) {
1221 throw new TypeError('Request with GET/HEAD method cannot have body');
1224 let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null;
1226 Body.call(this, inputBody, {
1227 timeout: init.timeout || input.timeout || 0,
1228 size: init.size || input.size || 0
1231 const headers = new Headers(init.headers || input.headers || {});
1233 if (inputBody != null && !headers.has('Content-Type')) {
1234 const contentType = extractContentType(inputBody);
1236 headers.append('Content-Type', contentType);
1240 let signal = isRequest(input) ? input.signal : null;
1241 if ('signal' in init) signal = init.signal;
1243 if (signal != null && !isAbortSignal(signal)) {
1244 throw new TypeError('Expected signal to be an instanceof AbortSignal');
1247 this[INTERNALS$2] = {
1249 redirect: init.redirect || input.redirect || 'follow',
1255 // node-fetch-only options
1256 this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20;
1257 this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true;
1258 this.counter = init.counter || input.counter || 0;
1259 this.agent = init.agent || input.agent;
1263 return this[INTERNALS$2].method;
1267 return format_url(this[INTERNALS$2].parsedURL);
1271 return this[INTERNALS$2].headers;
1275 return this[INTERNALS$2].redirect;
1279 return this[INTERNALS$2].signal;
1283 * Clone this request
1288 return new Request(this);
1292 Body.mixIn(Request.prototype);
1294 Object.defineProperty(Request.prototype, Symbol.toStringTag, {
1301 Object.defineProperties(Request.prototype, {
1302 method: { enumerable: true },
1303 url: { enumerable: true },
1304 headers: { enumerable: true },
1305 redirect: { enumerable: true },
1306 clone: { enumerable: true },
1307 signal: { enumerable: true }
1311 * Convert a Request to Node.js http request options.
1313 * @param Request A Request instance
1314 * @return Object The options object to be passed to http.request
1316 function getNodeRequestOptions(request) {
1317 const parsedURL = request[INTERNALS$2].parsedURL;
1318 const headers = new Headers(request[INTERNALS$2].headers);
1321 if (!headers.has('Accept')) {
1322 headers.set('Accept', '*/*');
1326 if (!parsedURL.protocol || !parsedURL.hostname) {
1327 throw new TypeError('Only absolute URLs are supported');
1330 if (!/^https?:$/.test(parsedURL.protocol)) {
1331 throw new TypeError('Only HTTP(S) protocols are supported');
1334 if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) {
1335 throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8');
1338 // HTTP-network-or-cache fetch steps 2.4-2.7
1339 let contentLengthValue = null;
1340 if (request.body == null && /^(POST|PUT)$/i.test(request.method)) {
1341 contentLengthValue = '0';
1343 if (request.body != null) {
1344 const totalBytes = getTotalBytes(request);
1345 if (typeof totalBytes === 'number') {
1346 contentLengthValue = String(totalBytes);
1349 if (contentLengthValue) {
1350 headers.set('Content-Length', contentLengthValue);
1353 // HTTP-network-or-cache fetch step 2.11
1354 if (!headers.has('User-Agent')) {
1355 headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)');
1358 // HTTP-network-or-cache fetch step 2.15
1359 if (request.compress && !headers.has('Accept-Encoding')) {
1360 headers.set('Accept-Encoding', 'gzip,deflate');
1363 let agent = request.agent;
1364 if (typeof agent === 'function') {
1365 agent = agent(parsedURL);
1368 if (!headers.has('Connection') && !agent) {
1369 headers.set('Connection', 'close');
1372 // HTTP-network fetch step 4.2
1373 // chunked encoding is handled by Node.js
1375 return Object.assign({}, parsedURL, {
1376 method: request.method,
1377 headers: exportNodeCompatibleHeaders(headers),
1385 * AbortError interface for cancelled requests
1389 * Create AbortError instance
1391 * @param String message Error message for human
1392 * @return AbortError
1394 function AbortError(message) {
1395 Error.call(this, message);
1397 this.type = 'aborted';
1398 this.message = message;
1400 // hide custom error implementation details from end-users
1401 Error.captureStackTrace(this, this.constructor);
1404 AbortError.prototype = Object.create(Error.prototype);
1405 AbortError.prototype.constructor = AbortError;
1406 AbortError.prototype.name = 'AbortError';
1408 // fix an issue where "PassThrough", "resolve" aren't a named export for node <10
1409 const PassThrough$1 = Stream.PassThrough;
1410 const resolve_url = Url.resolve;
1415 * @param Mixed url Absolute url or Request instance
1416 * @param Object opts Fetch options
1419 function fetch(url, opts) {
1421 // allow custom promise
1422 if (!fetch.Promise) {
1423 throw new Error('native promise missing, set fetch.Promise to your favorite alternative');
1426 Body.Promise = fetch.Promise;
1428 // wrap http.request into fetch
1429 return new fetch.Promise(function (resolve, reject) {
1430 // build request object
1431 const request = new Request(url, opts);
1432 const options = getNodeRequestOptions(request);
1434 const send = (options.protocol === 'https:' ? https : http).request;
1435 const signal = request.signal;
1437 let response = null;
1439 const abort = function abort() {
1440 let error = new AbortError('The user aborted a request.');
1442 if (request.body && request.body instanceof Stream.Readable) {
1443 request.body.destroy(error);
1445 if (!response || !response.body) return;
1446 response.body.emit('error', error);
1449 if (signal && signal.aborted) {
1454 const abortAndFinalize = function abortAndFinalize() {
1460 const req = send(options);
1464 signal.addEventListener('abort', abortAndFinalize);
1467 function finalize() {
1469 if (signal) signal.removeEventListener('abort', abortAndFinalize);
1470 clearTimeout(reqTimeout);
1473 if (request.timeout) {
1474 req.once('socket', function (socket) {
1475 reqTimeout = setTimeout(function () {
1476 reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout'));
1478 }, request.timeout);
1482 req.on('error', function (err) {
1483 reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err));
1487 req.on('response', function (res) {
1488 clearTimeout(reqTimeout);
1490 const headers = createHeadersLenient(res.headers);
1492 // HTTP fetch step 5
1493 if (fetch.isRedirect(res.statusCode)) {
1494 // HTTP fetch step 5.2
1495 const location = headers.get('Location');
1497 // HTTP fetch step 5.3
1498 const locationURL = location === null ? null : resolve_url(request.url, location);
1500 // HTTP fetch step 5.5
1501 switch (request.redirect) {
1503 reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect'));
1507 // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL.
1508 if (locationURL !== null) {
1509 // handle corrupted header
1511 headers.set('Location', locationURL);
1513 // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request
1519 // HTTP-redirect fetch step 2
1520 if (locationURL === null) {
1524 // HTTP-redirect fetch step 5
1525 if (request.counter >= request.follow) {
1526 reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect'));
1531 // HTTP-redirect fetch step 6 (counter increment)
1532 // Create a new Request object.
1533 const requestOpts = {
1534 headers: new Headers(request.headers),
1535 follow: request.follow,
1536 counter: request.counter + 1,
1537 agent: request.agent,
1538 compress: request.compress,
1539 method: request.method,
1541 signal: request.signal,
1542 timeout: request.timeout,
1546 // HTTP-redirect fetch step 9
1547 if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) {
1548 reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect'));
1553 // HTTP-redirect fetch step 11
1554 if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') {
1555 requestOpts.method = 'GET';
1556 requestOpts.body = undefined;
1557 requestOpts.headers.delete('content-length');
1560 // HTTP-redirect fetch step 15
1561 resolve(fetch(new Request(locationURL, requestOpts)));
1568 res.once('end', function () {
1569 if (signal) signal.removeEventListener('abort', abortAndFinalize);
1571 let body = res.pipe(new PassThrough$1());
1573 const response_options = {
1575 status: res.statusCode,
1576 statusText: res.statusMessage,
1579 timeout: request.timeout,
1580 counter: request.counter
1583 // HTTP-network fetch step 12.1.1.3
1584 const codings = headers.get('Content-Encoding');
1586 // HTTP-network fetch step 12.1.1.4: handle content codings
1588 // in following scenarios we ignore compression support
1589 // 1. compression support is disabled
1591 // 3. no Content-Encoding header
1592 // 4. no content response (204)
1593 // 5. content not modified response (304)
1594 if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) {
1595 response = new Response(body, response_options);
1601 // Be less strict when decoding compressed responses, since sometimes
1602 // servers send slightly invalid responses that are still accepted
1603 // by common browsers.
1604 // Always using Z_SYNC_FLUSH is what cURL does.
1605 const zlibOptions = {
1606 flush: zlib.Z_SYNC_FLUSH,
1607 finishFlush: zlib.Z_SYNC_FLUSH
1611 if (codings == 'gzip' || codings == 'x-gzip') {
1612 body = body.pipe(zlib.createGunzip(zlibOptions));
1613 response = new Response(body, response_options);
1619 if (codings == 'deflate' || codings == 'x-deflate') {
1620 // handle the infamous raw deflate response from old servers
1621 // a hack for old IIS and Apache servers
1622 const raw = res.pipe(new PassThrough$1());
1623 raw.once('data', function (chunk) {
1624 // see http://stackoverflow.com/questions/37519828
1625 if ((chunk[0] & 0x0F) === 0x08) {
1626 body = body.pipe(zlib.createInflate());
1628 body = body.pipe(zlib.createInflateRaw());
1630 response = new Response(body, response_options);
1637 if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') {
1638 body = body.pipe(zlib.createBrotliDecompress());
1639 response = new Response(body, response_options);
1644 // otherwise, use response as-is
1645 response = new Response(body, response_options);
1649 writeToStream(req, request);
1653 * Redirect code matching
1655 * @param Number code Status code
1658 fetch.isRedirect = function (code) {
1659 return code === 301 || code === 302 || code === 303 || code === 307 || code === 308;
1663 fetch.Promise = global.Promise;
1665 module.exports = exports = fetch;
1666 Object.defineProperty(exports, "__esModule", { value: true });
1667 exports.default = exports;
1668 exports.Headers = Headers;
1669 exports.Request = Request;
1670 exports.Response = Response;
1671 exports.FetchError = FetchError;