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.mjs 41KB

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