index.js 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. // Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js
  4. // (MIT licensed)
  5. const BUFFER = Symbol('buffer');
  6. const TYPE = Symbol('type');
  7. class Blob {
  8. constructor() {
  9. this[TYPE] = '';
  10. const blobParts = arguments[0];
  11. const options = arguments[1];
  12. const buffers = [];
  13. if (blobParts) {
  14. const a = blobParts;
  15. const length = Number(a.length);
  16. for (let i = 0; i < length; i++) {
  17. const element = a[i];
  18. let buffer;
  19. if (element instanceof Buffer) {
  20. buffer = element;
  21. } else if (ArrayBuffer.isView(element)) {
  22. buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength);
  23. } else if (element instanceof ArrayBuffer) {
  24. buffer = Buffer.from(element);
  25. } else if (element instanceof Blob) {
  26. buffer = element[BUFFER];
  27. } else {
  28. buffer = Buffer.from(typeof element === 'string' ? element : String(element));
  29. }
  30. buffers.push(buffer);
  31. }
  32. }
  33. this[BUFFER] = Buffer.concat(buffers);
  34. let type = options && options.type !== undefined && String(options.type).toLowerCase();
  35. if (type && !/[^\u0020-\u007E]/.test(type)) {
  36. this[TYPE] = type;
  37. }
  38. }
  39. get size() {
  40. return this[BUFFER].length;
  41. }
  42. get type() {
  43. return this[TYPE];
  44. }
  45. slice() {
  46. const size = this.size;
  47. const start = arguments[0];
  48. const end = arguments[1];
  49. let relativeStart, relativeEnd;
  50. if (start === undefined) {
  51. relativeStart = 0;
  52. } else if (start < 0) {
  53. relativeStart = Math.max(size + start, 0);
  54. } else {
  55. relativeStart = Math.min(start, size);
  56. }
  57. if (end === undefined) {
  58. relativeEnd = size;
  59. } else if (end < 0) {
  60. relativeEnd = Math.max(size + end, 0);
  61. } else {
  62. relativeEnd = Math.min(end, size);
  63. }
  64. const span = Math.max(relativeEnd - relativeStart, 0);
  65. const buffer = this[BUFFER];
  66. const slicedBuffer = buffer.slice(relativeStart, relativeStart + span);
  67. const blob = new Blob([], { type: arguments[2] });
  68. blob[BUFFER] = slicedBuffer;
  69. return blob;
  70. }
  71. }
  72. Object.defineProperties(Blob.prototype, {
  73. size: { enumerable: true },
  74. type: { enumerable: true },
  75. slice: { enumerable: true }
  76. });
  77. Object.defineProperty(Blob.prototype, Symbol.toStringTag, {
  78. value: 'Blob',
  79. writable: false,
  80. enumerable: false,
  81. configurable: true
  82. });
  83. /**
  84. * fetch-error.js
  85. *
  86. * FetchError interface for operational errors
  87. */
  88. /**
  89. * Create FetchError instance
  90. *
  91. * @param String message Error message for human
  92. * @param String type Error type for machine
  93. * @param String systemError For Node.js system error
  94. * @return FetchError
  95. */
  96. function FetchError(message, type, systemError) {
  97. Error.call(this, message);
  98. this.message = message;
  99. this.type = type;
  100. // when err.type is `system`, err.code contains system error code
  101. if (systemError) {
  102. this.code = this.errno = systemError.code;
  103. }
  104. // hide custom error implementation details from end-users
  105. Error.captureStackTrace(this, this.constructor);
  106. }
  107. FetchError.prototype = Object.create(Error.prototype);
  108. FetchError.prototype.constructor = FetchError;
  109. FetchError.prototype.name = 'FetchError';
  110. /**
  111. * body.js
  112. *
  113. * Body interface provides common methods for Request and Response
  114. */
  115. const Stream = require('stream');
  116. var _require = require('stream');
  117. const PassThrough = _require.PassThrough;
  118. let convert;
  119. try {
  120. convert = require('encoding').convert;
  121. } catch (e) {}
  122. const INTERNALS = Symbol('Body internals');
  123. /**
  124. * Body mixin
  125. *
  126. * Ref: https://fetch.spec.whatwg.org/#body
  127. *
  128. * @param Stream body Readable stream
  129. * @param Object opts Response options
  130. * @return Void
  131. */
  132. function Body(body) {
  133. var _this = this;
  134. var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
  135. _ref$size = _ref.size;
  136. let size = _ref$size === undefined ? 0 : _ref$size;
  137. var _ref$timeout = _ref.timeout;
  138. let timeout = _ref$timeout === undefined ? 0 : _ref$timeout;
  139. if (body == null) {
  140. // body is undefined or null
  141. body = null;
  142. } else if (typeof body === 'string') {
  143. // body is string
  144. } else if (isURLSearchParams(body)) {
  145. // body is a URLSearchParams
  146. } else if (body instanceof Blob) {
  147. // body is blob
  148. } else if (Buffer.isBuffer(body)) {
  149. // body is buffer
  150. } else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') {
  151. // body is array buffer
  152. } else if (body instanceof Stream) {
  153. // body is stream
  154. } else {
  155. // none of the above
  156. // coerce to string
  157. body = String(body);
  158. }
  159. this[INTERNALS] = {
  160. body,
  161. disturbed: false,
  162. error: null
  163. };
  164. this.size = size;
  165. this.timeout = timeout;
  166. if (body instanceof Stream) {
  167. body.on('error', function (err) {
  168. _this[INTERNALS].error = new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err);
  169. });
  170. }
  171. }
  172. Body.prototype = {
  173. get body() {
  174. return this[INTERNALS].body;
  175. },
  176. get bodyUsed() {
  177. return this[INTERNALS].disturbed;
  178. },
  179. /**
  180. * Decode response as ArrayBuffer
  181. *
  182. * @return Promise
  183. */
  184. arrayBuffer() {
  185. return consumeBody.call(this).then(function (buf) {
  186. return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
  187. });
  188. },
  189. /**
  190. * Return raw response as Blob
  191. *
  192. * @return Promise
  193. */
  194. blob() {
  195. let ct = this.headers && this.headers.get('content-type') || '';
  196. return consumeBody.call(this).then(function (buf) {
  197. return Object.assign(
  198. // Prevent copying
  199. new Blob([], {
  200. type: ct.toLowerCase()
  201. }), {
  202. [BUFFER]: buf
  203. });
  204. });
  205. },
  206. /**
  207. * Decode response as json
  208. *
  209. * @return Promise
  210. */
  211. json() {
  212. var _this2 = this;
  213. return consumeBody.call(this).then(function (buffer) {
  214. try {
  215. return JSON.parse(buffer.toString());
  216. } catch (err) {
  217. return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json'));
  218. }
  219. });
  220. },
  221. /**
  222. * Decode response as text
  223. *
  224. * @return Promise
  225. */
  226. text() {
  227. return consumeBody.call(this).then(function (buffer) {
  228. return buffer.toString();
  229. });
  230. },
  231. /**
  232. * Decode response as buffer (non-spec api)
  233. *
  234. * @return Promise
  235. */
  236. buffer() {
  237. return consumeBody.call(this);
  238. },
  239. /**
  240. * Decode response as text, while automatically detecting the encoding and
  241. * trying to decode to UTF-8 (non-spec api)
  242. *
  243. * @return Promise
  244. */
  245. textConverted() {
  246. var _this3 = this;
  247. return consumeBody.call(this).then(function (buffer) {
  248. return convertBody(buffer, _this3.headers);
  249. });
  250. }
  251. };
  252. // In browsers, all properties are enumerable.
  253. Object.defineProperties(Body.prototype, {
  254. body: { enumerable: true },
  255. bodyUsed: { enumerable: true },
  256. arrayBuffer: { enumerable: true },
  257. blob: { enumerable: true },
  258. json: { enumerable: true },
  259. text: { enumerable: true }
  260. });
  261. Body.mixIn = function (proto) {
  262. for (const name of Object.getOwnPropertyNames(Body.prototype)) {
  263. // istanbul ignore else: future proof
  264. if (!(name in proto)) {
  265. const desc = Object.getOwnPropertyDescriptor(Body.prototype, name);
  266. Object.defineProperty(proto, name, desc);
  267. }
  268. }
  269. };
  270. /**
  271. * Consume and convert an entire Body to a Buffer.
  272. *
  273. * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body
  274. *
  275. * @return Promise
  276. */
  277. function consumeBody() {
  278. var _this4 = this;
  279. if (this[INTERNALS].disturbed) {
  280. return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`));
  281. }
  282. this[INTERNALS].disturbed = true;
  283. if (this[INTERNALS].error) {
  284. return Body.Promise.reject(this[INTERNALS].error);
  285. }
  286. // body is null
  287. if (this.body === null) {
  288. return Body.Promise.resolve(Buffer.alloc(0));
  289. }
  290. // body is string
  291. if (typeof this.body === 'string') {
  292. return Body.Promise.resolve(Buffer.from(this.body));
  293. }
  294. // body is blob
  295. if (this.body instanceof Blob) {
  296. return Body.Promise.resolve(this.body[BUFFER]);
  297. }
  298. // body is buffer
  299. if (Buffer.isBuffer(this.body)) {
  300. return Body.Promise.resolve(this.body);
  301. }
  302. // body is buffer
  303. if (Object.prototype.toString.call(this.body) === '[object ArrayBuffer]') {
  304. return Body.Promise.resolve(Buffer.from(this.body));
  305. }
  306. // istanbul ignore if: should never happen
  307. if (!(this.body instanceof Stream)) {
  308. return Body.Promise.resolve(Buffer.alloc(0));
  309. }
  310. // body is stream
  311. // get ready to actually consume the body
  312. let accum = [];
  313. let accumBytes = 0;
  314. let abort = false;
  315. return new Body.Promise(function (resolve, reject) {
  316. let resTimeout;
  317. // allow timeout on slow response body
  318. if (_this4.timeout) {
  319. resTimeout = setTimeout(function () {
  320. abort = true;
  321. reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout'));
  322. }, _this4.timeout);
  323. }
  324. // handle stream error, such as incorrect content-encoding
  325. _this4.body.on('error', function (err) {
  326. reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err));
  327. });
  328. _this4.body.on('data', function (chunk) {
  329. if (abort || chunk === null) {
  330. return;
  331. }
  332. if (_this4.size && accumBytes + chunk.length > _this4.size) {
  333. abort = true;
  334. reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size'));
  335. return;
  336. }
  337. accumBytes += chunk.length;
  338. accum.push(chunk);
  339. });
  340. _this4.body.on('end', function () {
  341. if (abort) {
  342. return;
  343. }
  344. clearTimeout(resTimeout);
  345. try {
  346. resolve(Buffer.concat(accum));
  347. } catch (err) {
  348. // handle streams that have accumulated too much data (issue #414)
  349. reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err));
  350. }
  351. });
  352. });
  353. }
  354. /**
  355. * Detect buffer encoding and convert to target encoding
  356. * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding
  357. *
  358. * @param Buffer buffer Incoming buffer
  359. * @param String encoding Target encoding
  360. * @return String
  361. */
  362. function convertBody(buffer, headers) {
  363. if (typeof convert !== 'function') {
  364. throw new Error('The package `encoding` must be installed to use the textConverted() function');
  365. }
  366. const ct = headers.get('content-type');
  367. let charset = 'utf-8';
  368. let res, str;
  369. // header
  370. if (ct) {
  371. res = /charset=([^;]*)/i.exec(ct);
  372. }
  373. // no charset in content type, peek at response body for at most 1024 bytes
  374. str = buffer.slice(0, 1024).toString();
  375. // html5
  376. if (!res && str) {
  377. res = /<meta.+?charset=(['"])(.+?)\1/i.exec(str);
  378. }
  379. // html4
  380. if (!res && str) {
  381. res = /<meta[\s]+?http-equiv=(['"])content-type\1[\s]+?content=(['"])(.+?)\2/i.exec(str);
  382. if (res) {
  383. res = /charset=(.*)/i.exec(res.pop());
  384. }
  385. }
  386. // xml
  387. if (!res && str) {
  388. res = /<\?xml.+?encoding=(['"])(.+?)\1/i.exec(str);
  389. }
  390. // found charset
  391. if (res) {
  392. charset = res.pop();
  393. // prevent decode issues when sites use incorrect encoding
  394. // ref: https://hsivonen.fi/encoding-menu/
  395. if (charset === 'gb2312' || charset === 'gbk') {
  396. charset = 'gb18030';
  397. }
  398. }
  399. // turn raw buffers into a single utf-8 buffer
  400. return convert(buffer, 'UTF-8', charset).toString();
  401. }
  402. /**
  403. * Detect a URLSearchParams object
  404. * ref: https://github.com/bitinn/node-fetch/issues/296#issuecomment-307598143
  405. *
  406. * @param Object obj Object to detect by type or brand
  407. * @return String
  408. */
  409. function isURLSearchParams(obj) {
  410. // Duck-typing as a necessary condition.
  411. 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') {
  412. return false;
  413. }
  414. // Brand-checking and more duck-typing as optional condition.
  415. return obj.constructor.name === 'URLSearchParams' || Object.prototype.toString.call(obj) === '[object URLSearchParams]' || typeof obj.sort === 'function';
  416. }
  417. /**
  418. * Clone body given Res/Req instance
  419. *
  420. * @param Mixed instance Response or Request instance
  421. * @return Mixed
  422. */
  423. function clone(instance) {
  424. let p1, p2;
  425. let body = instance.body;
  426. // don't allow cloning a used body
  427. if (instance.bodyUsed) {
  428. throw new Error('cannot clone body after it is used');
  429. }
  430. // check that body is a stream and not form-data object
  431. // note: we can't clone the form-data object without having it as a dependency
  432. if (body instanceof Stream && typeof body.getBoundary !== 'function') {
  433. // tee instance body
  434. p1 = new PassThrough();
  435. p2 = new PassThrough();
  436. body.pipe(p1);
  437. body.pipe(p2);
  438. // set instance body to teed body and return the other teed body
  439. instance[INTERNALS].body = p1;
  440. body = p2;
  441. }
  442. return body;
  443. }
  444. /**
  445. * Performs the operation "extract a `Content-Type` value from |object|" as
  446. * specified in the specification:
  447. * https://fetch.spec.whatwg.org/#concept-bodyinit-extract
  448. *
  449. * This function assumes that instance.body is present.
  450. *
  451. * @param Mixed instance Response or Request instance
  452. */
  453. function extractContentType(instance) {
  454. const body = instance.body;
  455. // istanbul ignore if: Currently, because of a guard in Request, body
  456. // can never be null. Included here for completeness.
  457. if (body === null) {
  458. // body is null
  459. return null;
  460. } else if (typeof body === 'string') {
  461. // body is string
  462. return 'text/plain;charset=UTF-8';
  463. } else if (isURLSearchParams(body)) {
  464. // body is a URLSearchParams
  465. return 'application/x-www-form-urlencoded;charset=UTF-8';
  466. } else if (body instanceof Blob) {
  467. // body is blob
  468. return body.type || null;
  469. } else if (Buffer.isBuffer(body)) {
  470. // body is buffer
  471. return null;
  472. } else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') {
  473. // body is array buffer
  474. return null;
  475. } else if (typeof body.getBoundary === 'function') {
  476. // detect form data input from form-data module
  477. return `multipart/form-data;boundary=${body.getBoundary()}`;
  478. } else {
  479. // body is stream
  480. // can't really do much about this
  481. return null;
  482. }
  483. }
  484. /**
  485. * The Fetch Standard treats this as if "total bytes" is a property on the body.
  486. * For us, we have to explicitly get it with a function.
  487. *
  488. * ref: https://fetch.spec.whatwg.org/#concept-body-total-bytes
  489. *
  490. * @param Body instance Instance of Body
  491. * @return Number? Number of bytes, or null if not possible
  492. */
  493. function getTotalBytes(instance) {
  494. const body = instance.body;
  495. // istanbul ignore if: included for completion
  496. if (body === null) {
  497. // body is null
  498. return 0;
  499. } else if (typeof body === 'string') {
  500. // body is string
  501. return Buffer.byteLength(body);
  502. } else if (isURLSearchParams(body)) {
  503. // body is URLSearchParams
  504. return Buffer.byteLength(String(body));
  505. } else if (body instanceof Blob) {
  506. // body is blob
  507. return body.size;
  508. } else if (Buffer.isBuffer(body)) {
  509. // body is buffer
  510. return body.length;
  511. } else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') {
  512. // body is array buffer
  513. return body.byteLength;
  514. } else if (body && typeof body.getLengthSync === 'function') {
  515. // detect form data input from form-data module
  516. if (body._lengthRetrievers && body._lengthRetrievers.length == 0 || // 1.x
  517. body.hasKnownLength && body.hasKnownLength()) {
  518. // 2.x
  519. return body.getLengthSync();
  520. }
  521. return null;
  522. } else {
  523. // body is stream
  524. // can't really do much about this
  525. return null;
  526. }
  527. }
  528. /**
  529. * Write a Body to a Node.js WritableStream (e.g. http.Request) object.
  530. *
  531. * @param Body instance Instance of Body
  532. * @return Void
  533. */
  534. function writeToStream(dest, instance) {
  535. const body = instance.body;
  536. if (body === null) {
  537. // body is null
  538. dest.end();
  539. } else if (typeof body === 'string') {
  540. // body is string
  541. dest.write(body);
  542. dest.end();
  543. } else if (isURLSearchParams(body)) {
  544. // body is URLSearchParams
  545. dest.write(Buffer.from(String(body)));
  546. dest.end();
  547. } else if (body instanceof Blob) {
  548. // body is blob
  549. dest.write(body[BUFFER]);
  550. dest.end();
  551. } else if (Buffer.isBuffer(body)) {
  552. // body is buffer
  553. dest.write(body);
  554. dest.end();
  555. } else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') {
  556. // body is array buffer
  557. dest.write(Buffer.from(body));
  558. dest.end();
  559. } else {
  560. // body is stream
  561. body.pipe(dest);
  562. }
  563. }
  564. // expose Promise
  565. Body.Promise = global.Promise;
  566. /**
  567. * headers.js
  568. *
  569. * Headers class offers convenient helpers
  570. */
  571. const invalidTokenRegex = /[^\^_`a-zA-Z\-0-9!#$%&'*+.|~]/;
  572. const invalidHeaderCharRegex = /[^\t\x20-\x7e\x80-\xff]/;
  573. function validateName(name) {
  574. name = `${name}`;
  575. if (invalidTokenRegex.test(name)) {
  576. throw new TypeError(`${name} is not a legal HTTP header name`);
  577. }
  578. }
  579. function validateValue(value) {
  580. value = `${value}`;
  581. if (invalidHeaderCharRegex.test(value)) {
  582. throw new TypeError(`${value} is not a legal HTTP header value`);
  583. }
  584. }
  585. /**
  586. * Find the key in the map object given a header name.
  587. *
  588. * Returns undefined if not found.
  589. *
  590. * @param String name Header name
  591. * @return String|Undefined
  592. */
  593. function find(map, name) {
  594. name = name.toLowerCase();
  595. for (const key in map) {
  596. if (key.toLowerCase() === name) {
  597. return key;
  598. }
  599. }
  600. return undefined;
  601. }
  602. const MAP = Symbol('map');
  603. class Headers {
  604. /**
  605. * Headers class
  606. *
  607. * @param Object headers Response headers
  608. * @return Void
  609. */
  610. constructor() {
  611. let init = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : undefined;
  612. this[MAP] = Object.create(null);
  613. if (init instanceof Headers) {
  614. const rawHeaders = init.raw();
  615. const headerNames = Object.keys(rawHeaders);
  616. for (const headerName of headerNames) {
  617. for (const value of rawHeaders[headerName]) {
  618. this.append(headerName, value);
  619. }
  620. }
  621. return;
  622. }
  623. // We don't worry about converting prop to ByteString here as append()
  624. // will handle it.
  625. if (init == null) {
  626. // no op
  627. } 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. /**
  905. * response.js
  906. *
  907. * Response class provides content decoding
  908. */
  909. var _require$1 = require('http');
  910. const STATUS_CODES = _require$1.STATUS_CODES;
  911. const INTERNALS$1 = Symbol('Response internals');
  912. /**
  913. * Response class
  914. *
  915. * @param Stream body Readable stream
  916. * @param Object opts Response options
  917. * @return Void
  918. */
  919. class Response {
  920. constructor() {
  921. let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
  922. let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  923. Body.call(this, body, opts);
  924. const status = opts.status || 200;
  925. this[INTERNALS$1] = {
  926. url: opts.url,
  927. status,
  928. statusText: opts.statusText || STATUS_CODES[status],
  929. headers: new Headers(opts.headers)
  930. };
  931. }
  932. get url() {
  933. return this[INTERNALS$1].url;
  934. }
  935. get status() {
  936. return this[INTERNALS$1].status;
  937. }
  938. /**
  939. * Convenience property representing if the request ended normally
  940. */
  941. get ok() {
  942. return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300;
  943. }
  944. get statusText() {
  945. return this[INTERNALS$1].statusText;
  946. }
  947. get headers() {
  948. return this[INTERNALS$1].headers;
  949. }
  950. /**
  951. * Clone this response
  952. *
  953. * @return Response
  954. */
  955. clone() {
  956. return new Response(clone(this), {
  957. url: this.url,
  958. status: this.status,
  959. statusText: this.statusText,
  960. headers: this.headers,
  961. ok: this.ok
  962. });
  963. }
  964. }
  965. Body.mixIn(Response.prototype);
  966. Object.defineProperties(Response.prototype, {
  967. url: { enumerable: true },
  968. status: { enumerable: true },
  969. ok: { enumerable: true },
  970. statusText: { enumerable: true },
  971. headers: { enumerable: true },
  972. clone: { enumerable: true }
  973. });
  974. Object.defineProperty(Response.prototype, Symbol.toStringTag, {
  975. value: 'Response',
  976. writable: false,
  977. enumerable: false,
  978. configurable: true
  979. });
  980. /**
  981. * request.js
  982. *
  983. * Request class contains server only options
  984. *
  985. * All spec algorithm step numbers are based on https://fetch.spec.whatwg.org/commit-snapshots/ae716822cb3a61843226cd090eefc6589446c1d2/.
  986. */
  987. var _require$2 = require('url');
  988. const format_url = _require$2.format;
  989. const parse_url = _require$2.parse;
  990. const INTERNALS$2 = Symbol('Request internals');
  991. /**
  992. * Check if a value is an instance of Request.
  993. *
  994. * @param Mixed input
  995. * @return Boolean
  996. */
  997. function isRequest(input) {
  998. return typeof input === 'object' && typeof input[INTERNALS$2] === 'object';
  999. }
  1000. /**
  1001. * Request class
  1002. *
  1003. * @param Mixed input Url or Request instance
  1004. * @param Object init Custom options
  1005. * @return Void
  1006. */
  1007. class Request {
  1008. constructor(input) {
  1009. let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  1010. let parsedURL;
  1011. // normalize input
  1012. if (!isRequest(input)) {
  1013. if (input && input.href) {
  1014. // in order to support Node.js' Url objects; though WHATWG's URL objects
  1015. // will fall into this branch also (since their `toString()` will return
  1016. // `href` property anyway)
  1017. parsedURL = parse_url(input.href);
  1018. } else {
  1019. // coerce input to a string before attempting to parse
  1020. parsedURL = parse_url(`${input}`);
  1021. }
  1022. input = {};
  1023. } else {
  1024. parsedURL = parse_url(input.url);
  1025. }
  1026. let method = init.method || input.method || 'GET';
  1027. method = method.toUpperCase();
  1028. if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) {
  1029. throw new TypeError('Request with GET/HEAD method cannot have body');
  1030. }
  1031. let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null;
  1032. Body.call(this, inputBody, {
  1033. timeout: init.timeout || input.timeout || 0,
  1034. size: init.size || input.size || 0
  1035. });
  1036. const headers = new Headers(init.headers || input.headers || {});
  1037. if (init.body != null) {
  1038. const contentType = extractContentType(this);
  1039. if (contentType !== null && !headers.has('Content-Type')) {
  1040. headers.append('Content-Type', contentType);
  1041. }
  1042. }
  1043. this[INTERNALS$2] = {
  1044. method,
  1045. redirect: init.redirect || input.redirect || 'follow',
  1046. headers,
  1047. parsedURL
  1048. };
  1049. // node-fetch-only options
  1050. this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20;
  1051. this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true;
  1052. this.counter = init.counter || input.counter || 0;
  1053. this.agent = init.agent || input.agent;
  1054. }
  1055. get method() {
  1056. return this[INTERNALS$2].method;
  1057. }
  1058. get url() {
  1059. return format_url(this[INTERNALS$2].parsedURL);
  1060. }
  1061. get headers() {
  1062. return this[INTERNALS$2].headers;
  1063. }
  1064. get redirect() {
  1065. return this[INTERNALS$2].redirect;
  1066. }
  1067. /**
  1068. * Clone this request
  1069. *
  1070. * @return Request
  1071. */
  1072. clone() {
  1073. return new Request(this);
  1074. }
  1075. }
  1076. Body.mixIn(Request.prototype);
  1077. Object.defineProperty(Request.prototype, Symbol.toStringTag, {
  1078. value: 'Request',
  1079. writable: false,
  1080. enumerable: false,
  1081. configurable: true
  1082. });
  1083. Object.defineProperties(Request.prototype, {
  1084. method: { enumerable: true },
  1085. url: { enumerable: true },
  1086. headers: { enumerable: true },
  1087. redirect: { enumerable: true },
  1088. clone: { enumerable: true }
  1089. });
  1090. /**
  1091. * Convert a Request to Node.js http request options.
  1092. *
  1093. * @param Request A Request instance
  1094. * @return Object The options object to be passed to http.request
  1095. */
  1096. function getNodeRequestOptions(request) {
  1097. const parsedURL = request[INTERNALS$2].parsedURL;
  1098. const headers = new Headers(request[INTERNALS$2].headers);
  1099. // fetch step 1.3
  1100. if (!headers.has('Accept')) {
  1101. headers.set('Accept', '*/*');
  1102. }
  1103. // Basic fetch
  1104. if (!parsedURL.protocol || !parsedURL.hostname) {
  1105. throw new TypeError('Only absolute URLs are supported');
  1106. }
  1107. if (!/^https?:$/.test(parsedURL.protocol)) {
  1108. throw new TypeError('Only HTTP(S) protocols are supported');
  1109. }
  1110. // HTTP-network-or-cache fetch steps 2.4-2.7
  1111. let contentLengthValue = null;
  1112. if (request.body == null && /^(POST|PUT)$/i.test(request.method)) {
  1113. contentLengthValue = '0';
  1114. }
  1115. if (request.body != null) {
  1116. const totalBytes = getTotalBytes(request);
  1117. if (typeof totalBytes === 'number') {
  1118. contentLengthValue = String(totalBytes);
  1119. }
  1120. }
  1121. if (contentLengthValue) {
  1122. headers.set('Content-Length', contentLengthValue);
  1123. }
  1124. // HTTP-network-or-cache fetch step 2.11
  1125. if (!headers.has('User-Agent')) {
  1126. headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)');
  1127. }
  1128. // HTTP-network-or-cache fetch step 2.15
  1129. if (request.compress) {
  1130. headers.set('Accept-Encoding', 'gzip,deflate');
  1131. }
  1132. if (!headers.has('Connection') && !request.agent) {
  1133. headers.set('Connection', 'close');
  1134. }
  1135. // HTTP-network fetch step 4.2
  1136. // chunked encoding is handled by Node.js
  1137. return Object.assign({}, parsedURL, {
  1138. method: request.method,
  1139. headers: exportNodeCompatibleHeaders(headers),
  1140. agent: request.agent
  1141. });
  1142. }
  1143. /**
  1144. * index.js
  1145. *
  1146. * a request API compatible with window.fetch
  1147. *
  1148. * All spec algorithm step numbers are based on https://fetch.spec.whatwg.org/commit-snapshots/ae716822cb3a61843226cd090eefc6589446c1d2/.
  1149. */
  1150. const http = require('http');
  1151. const https = require('https');
  1152. var _require$3 = require('stream');
  1153. const PassThrough$1 = _require$3.PassThrough;
  1154. var _require2 = require('url');
  1155. const resolve_url = _require2.resolve;
  1156. const zlib = require('zlib');
  1157. /**
  1158. * Fetch function
  1159. *
  1160. * @param Mixed url Absolute url or Request instance
  1161. * @param Object opts Fetch options
  1162. * @return Promise
  1163. */
  1164. function fetch(url, opts) {
  1165. // allow custom promise
  1166. if (!fetch.Promise) {
  1167. throw new Error('native promise missing, set fetch.Promise to your favorite alternative');
  1168. }
  1169. Body.Promise = fetch.Promise;
  1170. // wrap http.request into fetch
  1171. return new fetch.Promise(function (resolve, reject) {
  1172. // build request object
  1173. const request = new Request(url, opts);
  1174. const options = getNodeRequestOptions(request);
  1175. const send = (options.protocol === 'https:' ? https : http).request;
  1176. // send request
  1177. const req = send(options);
  1178. let reqTimeout;
  1179. function finalize() {
  1180. req.abort();
  1181. clearTimeout(reqTimeout);
  1182. }
  1183. if (request.timeout) {
  1184. req.once('socket', function (socket) {
  1185. reqTimeout = setTimeout(function () {
  1186. reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout'));
  1187. finalize();
  1188. }, request.timeout);
  1189. });
  1190. }
  1191. req.on('error', function (err) {
  1192. reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err));
  1193. finalize();
  1194. });
  1195. req.on('response', function (res) {
  1196. clearTimeout(reqTimeout);
  1197. const headers = createHeadersLenient(res.headers);
  1198. // HTTP fetch step 5
  1199. if (fetch.isRedirect(res.statusCode)) {
  1200. // HTTP fetch step 5.2
  1201. const location = headers.get('Location');
  1202. // HTTP fetch step 5.3
  1203. const locationURL = location === null ? null : resolve_url(request.url, location);
  1204. // HTTP fetch step 5.5
  1205. switch (request.redirect) {
  1206. case 'error':
  1207. reject(new FetchError(`redirect mode is set to error: ${request.url}`, 'no-redirect'));
  1208. finalize();
  1209. return;
  1210. case 'manual':
  1211. // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL.
  1212. if (locationURL !== null) {
  1213. headers.set('Location', locationURL);
  1214. }
  1215. break;
  1216. case 'follow':
  1217. // HTTP-redirect fetch step 2
  1218. if (locationURL === null) {
  1219. break;
  1220. }
  1221. // HTTP-redirect fetch step 5
  1222. if (request.counter >= request.follow) {
  1223. reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect'));
  1224. finalize();
  1225. return;
  1226. }
  1227. // HTTP-redirect fetch step 6 (counter increment)
  1228. // Create a new Request object.
  1229. const requestOpts = {
  1230. headers: new Headers(request.headers),
  1231. follow: request.follow,
  1232. counter: request.counter + 1,
  1233. agent: request.agent,
  1234. compress: request.compress,
  1235. method: request.method,
  1236. body: request.body
  1237. };
  1238. // HTTP-redirect fetch step 9
  1239. if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) {
  1240. reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect'));
  1241. finalize();
  1242. return;
  1243. }
  1244. // HTTP-redirect fetch step 11
  1245. if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') {
  1246. requestOpts.method = 'GET';
  1247. requestOpts.body = undefined;
  1248. requestOpts.headers.delete('content-length');
  1249. }
  1250. // HTTP-redirect fetch step 15
  1251. resolve(fetch(new Request(locationURL, requestOpts)));
  1252. finalize();
  1253. return;
  1254. }
  1255. }
  1256. // prepare response
  1257. let body = res.pipe(new PassThrough$1());
  1258. const response_options = {
  1259. url: request.url,
  1260. status: res.statusCode,
  1261. statusText: res.statusMessage,
  1262. headers: headers,
  1263. size: request.size,
  1264. timeout: request.timeout
  1265. };
  1266. // HTTP-network fetch step 12.1.1.3
  1267. const codings = headers.get('Content-Encoding');
  1268. // HTTP-network fetch step 12.1.1.4: handle content codings
  1269. // in following scenarios we ignore compression support
  1270. // 1. compression support is disabled
  1271. // 2. HEAD request
  1272. // 3. no Content-Encoding header
  1273. // 4. no content response (204)
  1274. // 5. content not modified response (304)
  1275. if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) {
  1276. resolve(new Response(body, response_options));
  1277. return;
  1278. }
  1279. // For Node v6+
  1280. // Be less strict when decoding compressed responses, since sometimes
  1281. // servers send slightly invalid responses that are still accepted
  1282. // by common browsers.
  1283. // Always using Z_SYNC_FLUSH is what cURL does.
  1284. const zlibOptions = {
  1285. flush: zlib.Z_SYNC_FLUSH,
  1286. finishFlush: zlib.Z_SYNC_FLUSH
  1287. };
  1288. // for gzip
  1289. if (codings == 'gzip' || codings == 'x-gzip') {
  1290. body = body.pipe(zlib.createGunzip(zlibOptions));
  1291. resolve(new Response(body, response_options));
  1292. return;
  1293. }
  1294. // for deflate
  1295. if (codings == 'deflate' || codings == 'x-deflate') {
  1296. // handle the infamous raw deflate response from old servers
  1297. // a hack for old IIS and Apache servers
  1298. const raw = res.pipe(new PassThrough$1());
  1299. raw.once('data', function (chunk) {
  1300. // see http://stackoverflow.com/questions/37519828
  1301. if ((chunk[0] & 0x0F) === 0x08) {
  1302. body = body.pipe(zlib.createInflate());
  1303. } else {
  1304. body = body.pipe(zlib.createInflateRaw());
  1305. }
  1306. resolve(new Response(body, response_options));
  1307. });
  1308. return;
  1309. }
  1310. // otherwise, use response as-is
  1311. resolve(new Response(body, response_options));
  1312. });
  1313. writeToStream(req, request);
  1314. });
  1315. }
  1316. /**
  1317. * Redirect code matching
  1318. *
  1319. * @param Number code Status code
  1320. * @return Boolean
  1321. */
  1322. fetch.isRedirect = function (code) {
  1323. return code === 301 || code === 302 || code === 303 || code === 307 || code === 308;
  1324. };
  1325. // Needed for TypeScript.
  1326. fetch.default = fetch;
  1327. // expose Promise
  1328. fetch.Promise = global.Promise;
  1329. module.exports = exports = fetch;
  1330. exports.Headers = Headers;
  1331. exports.Request = Request;
  1332. exports.Response = Response;
  1333. exports.FetchError = FetchError;