1634 lines
40KB

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