wp-polyfill-fetch.js 18 KB

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