Software zum Installieren eines Smart-Mirror Frameworks , zum Nutzen von hochschulrelevanten Informationen, auf einem Raspberry-Pi.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.js 41KB

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