browser-ponyfill.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647
  1. // Save global object in a variable
  2. var __global__ =
  3. (typeof globalThis !== 'undefined' && globalThis) ||
  4. (typeof self !== 'undefined' && self) ||
  5. (typeof global !== 'undefined' && global);
  6. // Create an object that extends from __global__ without the fetch function
  7. var __globalThis__ = (function () {
  8. function F() {
  9. this.fetch = false;
  10. this.DOMException = __global__.DOMException
  11. }
  12. F.prototype = __global__; // Needed for feature detection on whatwg-fetch's code
  13. return new F();
  14. })();
  15. // Wraps whatwg-fetch with a function scope to hijack the global object
  16. // "globalThis" that's going to be patched
  17. (function(globalThis) {
  18. var irrelevant = (function (exports) {
  19. var global =
  20. (typeof globalThis !== 'undefined' && globalThis) ||
  21. (typeof self !== 'undefined' && self) ||
  22. (typeof global !== 'undefined' && global);
  23. var support = {
  24. searchParams: 'URLSearchParams' in global,
  25. iterable: 'Symbol' in global && 'iterator' in Symbol,
  26. blob:
  27. 'FileReader' in global &&
  28. 'Blob' in global &&
  29. (function() {
  30. try {
  31. new Blob();
  32. return true
  33. } catch (e) {
  34. return false
  35. }
  36. })(),
  37. formData: 'FormData' in global,
  38. arrayBuffer: 'ArrayBuffer' in global
  39. };
  40. function isDataView(obj) {
  41. return obj && DataView.prototype.isPrototypeOf(obj)
  42. }
  43. if (support.arrayBuffer) {
  44. var viewClasses = [
  45. '[object Int8Array]',
  46. '[object Uint8Array]',
  47. '[object Uint8ClampedArray]',
  48. '[object Int16Array]',
  49. '[object Uint16Array]',
  50. '[object Int32Array]',
  51. '[object Uint32Array]',
  52. '[object Float32Array]',
  53. '[object Float64Array]'
  54. ];
  55. var isArrayBufferView =
  56. ArrayBuffer.isView ||
  57. function(obj) {
  58. return obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1
  59. };
  60. }
  61. function normalizeName(name) {
  62. if (typeof name !== 'string') {
  63. name = String(name);
  64. }
  65. if (/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(name) || name === '') {
  66. throw new TypeError('Invalid character in header field name: "' + name + '"')
  67. }
  68. return name.toLowerCase()
  69. }
  70. function normalizeValue(value) {
  71. if (typeof value !== 'string') {
  72. value = String(value);
  73. }
  74. return value
  75. }
  76. // Build a destructive iterator for the value list
  77. function iteratorFor(items) {
  78. var iterator = {
  79. next: function() {
  80. var value = items.shift();
  81. return {done: value === undefined, value: value}
  82. }
  83. };
  84. if (support.iterable) {
  85. iterator[Symbol.iterator] = function() {
  86. return iterator
  87. };
  88. }
  89. return iterator
  90. }
  91. function Headers(headers) {
  92. this.map = {};
  93. if (headers instanceof Headers) {
  94. headers.forEach(function(value, name) {
  95. this.append(name, value);
  96. }, this);
  97. } else if (Array.isArray(headers)) {
  98. headers.forEach(function(header) {
  99. this.append(header[0], header[1]);
  100. }, this);
  101. } else if (headers) {
  102. Object.getOwnPropertyNames(headers).forEach(function(name) {
  103. this.append(name, headers[name]);
  104. }, this);
  105. }
  106. }
  107. Headers.prototype.append = function(name, value) {
  108. name = normalizeName(name);
  109. value = normalizeValue(value);
  110. var oldValue = this.map[name];
  111. this.map[name] = oldValue ? oldValue + ', ' + value : value;
  112. };
  113. Headers.prototype['delete'] = function(name) {
  114. delete this.map[normalizeName(name)];
  115. };
  116. Headers.prototype.get = function(name) {
  117. name = normalizeName(name);
  118. return this.has(name) ? this.map[name] : null
  119. };
  120. Headers.prototype.has = function(name) {
  121. return this.map.hasOwnProperty(normalizeName(name))
  122. };
  123. Headers.prototype.set = function(name, value) {
  124. this.map[normalizeName(name)] = normalizeValue(value);
  125. };
  126. Headers.prototype.forEach = function(callback, thisArg) {
  127. for (var name in this.map) {
  128. if (this.map.hasOwnProperty(name)) {
  129. callback.call(thisArg, this.map[name], name, this);
  130. }
  131. }
  132. };
  133. Headers.prototype.keys = function() {
  134. var items = [];
  135. this.forEach(function(value, name) {
  136. items.push(name);
  137. });
  138. return iteratorFor(items)
  139. };
  140. Headers.prototype.values = function() {
  141. var items = [];
  142. this.forEach(function(value) {
  143. items.push(value);
  144. });
  145. return iteratorFor(items)
  146. };
  147. Headers.prototype.entries = function() {
  148. var items = [];
  149. this.forEach(function(value, name) {
  150. items.push([name, value]);
  151. });
  152. return iteratorFor(items)
  153. };
  154. if (support.iterable) {
  155. Headers.prototype[Symbol.iterator] = Headers.prototype.entries;
  156. }
  157. function consumed(body) {
  158. if (body.bodyUsed) {
  159. return Promise.reject(new TypeError('Already read'))
  160. }
  161. body.bodyUsed = true;
  162. }
  163. function fileReaderReady(reader) {
  164. return new Promise(function(resolve, reject) {
  165. reader.onload = function() {
  166. resolve(reader.result);
  167. };
  168. reader.onerror = function() {
  169. reject(reader.error);
  170. };
  171. })
  172. }
  173. function readBlobAsArrayBuffer(blob) {
  174. var reader = new FileReader();
  175. var promise = fileReaderReady(reader);
  176. reader.readAsArrayBuffer(blob);
  177. return promise
  178. }
  179. function readBlobAsText(blob) {
  180. var reader = new FileReader();
  181. var promise = fileReaderReady(reader);
  182. reader.readAsText(blob);
  183. return promise
  184. }
  185. function readArrayBufferAsText(buf) {
  186. var view = new Uint8Array(buf);
  187. var chars = new Array(view.length);
  188. for (var i = 0; i < view.length; i++) {
  189. chars[i] = String.fromCharCode(view[i]);
  190. }
  191. return chars.join('')
  192. }
  193. function bufferClone(buf) {
  194. if (buf.slice) {
  195. return buf.slice(0)
  196. } else {
  197. var view = new Uint8Array(buf.byteLength);
  198. view.set(new Uint8Array(buf));
  199. return view.buffer
  200. }
  201. }
  202. function Body() {
  203. this.bodyUsed = false;
  204. this._initBody = function(body) {
  205. /*
  206. fetch-mock wraps the Response object in an ES6 Proxy to
  207. provide useful test harness features such as flush. However, on
  208. ES5 browsers without fetch or Proxy support pollyfills must be used;
  209. the proxy-pollyfill is unable to proxy an attribute unless it exists
  210. on the object before the Proxy is created. This change ensures
  211. Response.bodyUsed exists on the instance, while maintaining the
  212. semantic of setting Request.bodyUsed in the constructor before
  213. _initBody is called.
  214. */
  215. this.bodyUsed = this.bodyUsed;
  216. this._bodyInit = body;
  217. if (!body) {
  218. this._bodyText = '';
  219. } else if (typeof body === 'string') {
  220. this._bodyText = body;
  221. } else if (support.blob && Blob.prototype.isPrototypeOf(body)) {
  222. this._bodyBlob = body;
  223. } else if (support.formData && FormData.prototype.isPrototypeOf(body)) {
  224. this._bodyFormData = body;
  225. } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {
  226. this._bodyText = body.toString();
  227. } else if (support.arrayBuffer && support.blob && isDataView(body)) {
  228. this._bodyArrayBuffer = bufferClone(body.buffer);
  229. // IE 10-11 can't handle a DataView body.
  230. this._bodyInit = new Blob([this._bodyArrayBuffer]);
  231. } else if (support.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))) {
  232. this._bodyArrayBuffer = bufferClone(body);
  233. } else {
  234. this._bodyText = body = Object.prototype.toString.call(body);
  235. }
  236. if (!this.headers.get('content-type')) {
  237. if (typeof body === 'string') {
  238. this.headers.set('content-type', 'text/plain;charset=UTF-8');
  239. } else if (this._bodyBlob && this._bodyBlob.type) {
  240. this.headers.set('content-type', this._bodyBlob.type);
  241. } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {
  242. this.headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8');
  243. }
  244. }
  245. };
  246. if (support.blob) {
  247. this.blob = function() {
  248. var rejected = consumed(this);
  249. if (rejected) {
  250. return rejected
  251. }
  252. if (this._bodyBlob) {
  253. return Promise.resolve(this._bodyBlob)
  254. } else if (this._bodyArrayBuffer) {
  255. return Promise.resolve(new Blob([this._bodyArrayBuffer]))
  256. } else if (this._bodyFormData) {
  257. throw new Error('could not read FormData body as blob')
  258. } else {
  259. return Promise.resolve(new Blob([this._bodyText]))
  260. }
  261. };
  262. this.arrayBuffer = function() {
  263. if (this._bodyArrayBuffer) {
  264. var isConsumed = consumed(this);
  265. if (isConsumed) {
  266. return isConsumed
  267. }
  268. if (ArrayBuffer.isView(this._bodyArrayBuffer)) {
  269. return Promise.resolve(
  270. this._bodyArrayBuffer.buffer.slice(
  271. this._bodyArrayBuffer.byteOffset,
  272. this._bodyArrayBuffer.byteOffset + this._bodyArrayBuffer.byteLength
  273. )
  274. )
  275. } else {
  276. return Promise.resolve(this._bodyArrayBuffer)
  277. }
  278. } else {
  279. return this.blob().then(readBlobAsArrayBuffer)
  280. }
  281. };
  282. }
  283. this.text = function() {
  284. var rejected = consumed(this);
  285. if (rejected) {
  286. return rejected
  287. }
  288. if (this._bodyBlob) {
  289. return readBlobAsText(this._bodyBlob)
  290. } else if (this._bodyArrayBuffer) {
  291. return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer))
  292. } else if (this._bodyFormData) {
  293. throw new Error('could not read FormData body as text')
  294. } else {
  295. return Promise.resolve(this._bodyText)
  296. }
  297. };
  298. if (support.formData) {
  299. this.formData = function() {
  300. return this.text().then(decode)
  301. };
  302. }
  303. this.json = function() {
  304. return this.text().then(JSON.parse)
  305. };
  306. return this
  307. }
  308. // HTTP methods whose capitalization should be normalized
  309. var methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT'];
  310. function normalizeMethod(method) {
  311. var upcased = method.toUpperCase();
  312. return methods.indexOf(upcased) > -1 ? upcased : method
  313. }
  314. function Request(input, options) {
  315. if (!(this instanceof Request)) {
  316. throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.')
  317. }
  318. options = options || {};
  319. var body = options.body;
  320. if (input instanceof Request) {
  321. if (input.bodyUsed) {
  322. throw new TypeError('Already read')
  323. }
  324. this.url = input.url;
  325. this.credentials = input.credentials;
  326. if (!options.headers) {
  327. this.headers = new Headers(input.headers);
  328. }
  329. this.method = input.method;
  330. this.mode = input.mode;
  331. this.signal = input.signal;
  332. if (!body && input._bodyInit != null) {
  333. body = input._bodyInit;
  334. input.bodyUsed = true;
  335. }
  336. } else {
  337. this.url = String(input);
  338. }
  339. this.credentials = options.credentials || this.credentials || 'same-origin';
  340. if (options.headers || !this.headers) {
  341. this.headers = new Headers(options.headers);
  342. }
  343. this.method = normalizeMethod(options.method || this.method || 'GET');
  344. this.mode = options.mode || this.mode || null;
  345. this.signal = options.signal || this.signal;
  346. this.referrer = null;
  347. if ((this.method === 'GET' || this.method === 'HEAD') && body) {
  348. throw new TypeError('Body not allowed for GET or HEAD requests')
  349. }
  350. this._initBody(body);
  351. if (this.method === 'GET' || this.method === 'HEAD') {
  352. if (options.cache === 'no-store' || options.cache === 'no-cache') {
  353. // Search for a '_' parameter in the query string
  354. var reParamSearch = /([?&])_=[^&]*/;
  355. if (reParamSearch.test(this.url)) {
  356. // If it already exists then set the value with the current time
  357. this.url = this.url.replace(reParamSearch, '$1_=' + new Date().getTime());
  358. } else {
  359. // Otherwise add a new '_' parameter to the end with the current time
  360. var reQueryString = /\?/;
  361. this.url += (reQueryString.test(this.url) ? '&' : '?') + '_=' + new Date().getTime();
  362. }
  363. }
  364. }
  365. }
  366. Request.prototype.clone = function() {
  367. return new Request(this, {body: this._bodyInit})
  368. };
  369. function decode(body) {
  370. var form = new FormData();
  371. body
  372. .trim()
  373. .split('&')
  374. .forEach(function(bytes) {
  375. if (bytes) {
  376. var split = bytes.split('=');
  377. var name = split.shift().replace(/\+/g, ' ');
  378. var value = split.join('=').replace(/\+/g, ' ');
  379. form.append(decodeURIComponent(name), decodeURIComponent(value));
  380. }
  381. });
  382. return form
  383. }
  384. function parseHeaders(rawHeaders) {
  385. var headers = new Headers();
  386. // Replace instances of \r\n and \n followed by at least one space or horizontal tab with a space
  387. // https://tools.ietf.org/html/rfc7230#section-3.2
  388. var preProcessedHeaders = rawHeaders.replace(/\r?\n[\t ]+/g, ' ');
  389. // Avoiding split via regex to work around a common IE11 bug with the core-js 3.6.0 regex polyfill
  390. // https://github.com/github/fetch/issues/748
  391. // https://github.com/zloirock/core-js/issues/751
  392. preProcessedHeaders
  393. .split('\r')
  394. .map(function(header) {
  395. return header.indexOf('\n') === 0 ? header.substr(1, header.length) : header
  396. })
  397. .forEach(function(line) {
  398. var parts = line.split(':');
  399. var key = parts.shift().trim();
  400. if (key) {
  401. var value = parts.join(':').trim();
  402. headers.append(key, value);
  403. }
  404. });
  405. return headers
  406. }
  407. Body.call(Request.prototype);
  408. function Response(bodyInit, options) {
  409. if (!(this instanceof Response)) {
  410. throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.')
  411. }
  412. if (!options) {
  413. options = {};
  414. }
  415. this.type = 'default';
  416. this.status = options.status === undefined ? 200 : options.status;
  417. this.ok = this.status >= 200 && this.status < 300;
  418. this.statusText = options.statusText === undefined ? '' : '' + options.statusText;
  419. this.headers = new Headers(options.headers);
  420. this.url = options.url || '';
  421. this._initBody(bodyInit);
  422. }
  423. Body.call(Response.prototype);
  424. Response.prototype.clone = function() {
  425. return new Response(this._bodyInit, {
  426. status: this.status,
  427. statusText: this.statusText,
  428. headers: new Headers(this.headers),
  429. url: this.url
  430. })
  431. };
  432. Response.error = function() {
  433. var response = new Response(null, {status: 0, statusText: ''});
  434. response.type = 'error';
  435. return response
  436. };
  437. var redirectStatuses = [301, 302, 303, 307, 308];
  438. Response.redirect = function(url, status) {
  439. if (redirectStatuses.indexOf(status) === -1) {
  440. throw new RangeError('Invalid status code')
  441. }
  442. return new Response(null, {status: status, headers: {location: url}})
  443. };
  444. exports.DOMException = global.DOMException;
  445. try {
  446. new exports.DOMException();
  447. } catch (err) {
  448. exports.DOMException = function(message, name) {
  449. this.message = message;
  450. this.name = name;
  451. var error = Error(message);
  452. this.stack = error.stack;
  453. };
  454. exports.DOMException.prototype = Object.create(Error.prototype);
  455. exports.DOMException.prototype.constructor = exports.DOMException;
  456. }
  457. function fetch(input, init) {
  458. return new Promise(function(resolve, reject) {
  459. var request = new Request(input, init);
  460. if (request.signal && request.signal.aborted) {
  461. return reject(new exports.DOMException('Aborted', 'AbortError'))
  462. }
  463. var xhr = new XMLHttpRequest();
  464. function abortXhr() {
  465. xhr.abort();
  466. }
  467. xhr.onload = function() {
  468. var options = {
  469. status: xhr.status,
  470. statusText: xhr.statusText,
  471. headers: parseHeaders(xhr.getAllResponseHeaders() || '')
  472. };
  473. options.url = 'responseURL' in xhr ? xhr.responseURL : options.headers.get('X-Request-URL');
  474. var body = 'response' in xhr ? xhr.response : xhr.responseText;
  475. setTimeout(function() {
  476. resolve(new Response(body, options));
  477. }, 0);
  478. };
  479. xhr.onerror = function() {
  480. setTimeout(function() {
  481. reject(new TypeError('Network request failed'));
  482. }, 0);
  483. };
  484. xhr.ontimeout = function() {
  485. setTimeout(function() {
  486. reject(new TypeError('Network request failed'));
  487. }, 0);
  488. };
  489. xhr.onabort = function() {
  490. setTimeout(function() {
  491. reject(new exports.DOMException('Aborted', 'AbortError'));
  492. }, 0);
  493. };
  494. function fixUrl(url) {
  495. try {
  496. return url === '' && global.location.href ? global.location.href : url
  497. } catch (e) {
  498. return url
  499. }
  500. }
  501. xhr.open(request.method, fixUrl(request.url), true);
  502. if (request.credentials === 'include') {
  503. xhr.withCredentials = true;
  504. } else if (request.credentials === 'omit') {
  505. xhr.withCredentials = false;
  506. }
  507. if ('responseType' in xhr) {
  508. if (support.blob) {
  509. xhr.responseType = 'blob';
  510. } else if (
  511. support.arrayBuffer &&
  512. request.headers.get('Content-Type') &&
  513. request.headers.get('Content-Type').indexOf('application/octet-stream') !== -1
  514. ) {
  515. xhr.responseType = 'arraybuffer';
  516. }
  517. }
  518. if (init && typeof init.headers === 'object' && !(init.headers instanceof Headers)) {
  519. Object.getOwnPropertyNames(init.headers).forEach(function(name) {
  520. xhr.setRequestHeader(name, normalizeValue(init.headers[name]));
  521. });
  522. } else {
  523. request.headers.forEach(function(value, name) {
  524. xhr.setRequestHeader(name, value);
  525. });
  526. }
  527. if (request.signal) {
  528. request.signal.addEventListener('abort', abortXhr);
  529. xhr.onreadystatechange = function() {
  530. // DONE (success or failure)
  531. if (xhr.readyState === 4) {
  532. request.signal.removeEventListener('abort', abortXhr);
  533. }
  534. };
  535. }
  536. xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit);
  537. })
  538. }
  539. fetch.polyfill = true;
  540. if (!global.fetch) {
  541. global.fetch = fetch;
  542. global.Headers = Headers;
  543. global.Request = Request;
  544. global.Response = Response;
  545. }
  546. exports.Headers = Headers;
  547. exports.Request = Request;
  548. exports.Response = Response;
  549. exports.fetch = fetch;
  550. return exports;
  551. })({});
  552. })(__globalThis__);
  553. // This is a ponyfill, so...
  554. __globalThis__.fetch.ponyfill = true;
  555. delete __globalThis__.fetch.polyfill;
  556. // Choose between native implementation (__global__) or custom implementation (__globalThis__)
  557. var ctx = __global__.fetch ? __global__ : __globalThis__;
  558. exports = ctx.fetch // To enable: import fetch from 'cross-fetch'
  559. exports.default = ctx.fetch // For TypeScript consumers without esModuleInterop.
  560. exports.fetch = ctx.fetch // To enable: import {fetch} from 'cross-fetch'
  561. exports.Headers = ctx.Headers
  562. exports.Request = ctx.Request
  563. exports.Response = ctx.Response
  564. module.exports = exports