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.

3708 lines
94 KiB

  1. /*! Axios v1.8.4 Copyright (c) 2025 Matt Zabriskie and contributors */
  2. 'use strict';
  3. function bind(fn, thisArg) {
  4. return function wrap() {
  5. return fn.apply(thisArg, arguments);
  6. };
  7. }
  8. // utils is a library of generic helper functions non-specific to axios
  9. const {toString} = Object.prototype;
  10. const {getPrototypeOf} = Object;
  11. const kindOf = (cache => thing => {
  12. const str = toString.call(thing);
  13. return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
  14. })(Object.create(null));
  15. const kindOfTest = (type) => {
  16. type = type.toLowerCase();
  17. return (thing) => kindOf(thing) === type
  18. };
  19. const typeOfTest = type => thing => typeof thing === type;
  20. /**
  21. * Determine if a value is an Array
  22. *
  23. * @param {Object} val The value to test
  24. *
  25. * @returns {boolean} True if value is an Array, otherwise false
  26. */
  27. const {isArray} = Array;
  28. /**
  29. * Determine if a value is undefined
  30. *
  31. * @param {*} val The value to test
  32. *
  33. * @returns {boolean} True if the value is undefined, otherwise false
  34. */
  35. const isUndefined = typeOfTest('undefined');
  36. /**
  37. * Determine if a value is a Buffer
  38. *
  39. * @param {*} val The value to test
  40. *
  41. * @returns {boolean} True if value is a Buffer, otherwise false
  42. */
  43. function isBuffer(val) {
  44. return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)
  45. && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val);
  46. }
  47. /**
  48. * Determine if a value is an ArrayBuffer
  49. *
  50. * @param {*} val The value to test
  51. *
  52. * @returns {boolean} True if value is an ArrayBuffer, otherwise false
  53. */
  54. const isArrayBuffer = kindOfTest('ArrayBuffer');
  55. /**
  56. * Determine if a value is a view on an ArrayBuffer
  57. *
  58. * @param {*} val The value to test
  59. *
  60. * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
  61. */
  62. function isArrayBufferView(val) {
  63. let result;
  64. if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {
  65. result = ArrayBuffer.isView(val);
  66. } else {
  67. result = (val) && (val.buffer) && (isArrayBuffer(val.buffer));
  68. }
  69. return result;
  70. }
  71. /**
  72. * Determine if a value is a String
  73. *
  74. * @param {*} val The value to test
  75. *
  76. * @returns {boolean} True if value is a String, otherwise false
  77. */
  78. const isString = typeOfTest('string');
  79. /**
  80. * Determine if a value is a Function
  81. *
  82. * @param {*} val The value to test
  83. * @returns {boolean} True if value is a Function, otherwise false
  84. */
  85. const isFunction = typeOfTest('function');
  86. /**
  87. * Determine if a value is a Number
  88. *
  89. * @param {*} val The value to test
  90. *
  91. * @returns {boolean} True if value is a Number, otherwise false
  92. */
  93. const isNumber = typeOfTest('number');
  94. /**
  95. * Determine if a value is an Object
  96. *
  97. * @param {*} thing The value to test
  98. *
  99. * @returns {boolean} True if value is an Object, otherwise false
  100. */
  101. const isObject = (thing) => thing !== null && typeof thing === 'object';
  102. /**
  103. * Determine if a value is a Boolean
  104. *
  105. * @param {*} thing The value to test
  106. * @returns {boolean} True if value is a Boolean, otherwise false
  107. */
  108. const isBoolean = thing => thing === true || thing === false;
  109. /**
  110. * Determine if a value is a plain Object
  111. *
  112. * @param {*} val The value to test
  113. *
  114. * @returns {boolean} True if value is a plain Object, otherwise false
  115. */
  116. const isPlainObject = (val) => {
  117. if (kindOf(val) !== 'object') {
  118. return false;
  119. }
  120. const prototype = getPrototypeOf(val);
  121. return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in val) && !(Symbol.iterator in val);
  122. };
  123. /**
  124. * Determine if a value is a Date
  125. *
  126. * @param {*} val The value to test
  127. *
  128. * @returns {boolean} True if value is a Date, otherwise false
  129. */
  130. const isDate = kindOfTest('Date');
  131. /**
  132. * Determine if a value is a File
  133. *
  134. * @param {*} val The value to test
  135. *
  136. * @returns {boolean} True if value is a File, otherwise false
  137. */
  138. const isFile = kindOfTest('File');
  139. /**
  140. * Determine if a value is a Blob
  141. *
  142. * @param {*} val The value to test
  143. *
  144. * @returns {boolean} True if value is a Blob, otherwise false
  145. */
  146. const isBlob = kindOfTest('Blob');
  147. /**
  148. * Determine if a value is a FileList
  149. *
  150. * @param {*} val The value to test
  151. *
  152. * @returns {boolean} True if value is a File, otherwise false
  153. */
  154. const isFileList = kindOfTest('FileList');
  155. /**
  156. * Determine if a value is a Stream
  157. *
  158. * @param {*} val The value to test
  159. *
  160. * @returns {boolean} True if value is a Stream, otherwise false
  161. */
  162. const isStream = (val) => isObject(val) && isFunction(val.pipe);
  163. /**
  164. * Determine if a value is a FormData
  165. *
  166. * @param {*} thing The value to test
  167. *
  168. * @returns {boolean} True if value is an FormData, otherwise false
  169. */
  170. const isFormData = (thing) => {
  171. let kind;
  172. return thing && (
  173. (typeof FormData === 'function' && thing instanceof FormData) || (
  174. isFunction(thing.append) && (
  175. (kind = kindOf(thing)) === 'formdata' ||
  176. // detect form-data instance
  177. (kind === 'object' && isFunction(thing.toString) && thing.toString() === '[object FormData]')
  178. )
  179. )
  180. )
  181. };
  182. /**
  183. * Determine if a value is a URLSearchParams object
  184. *
  185. * @param {*} val The value to test
  186. *
  187. * @returns {boolean} True if value is a URLSearchParams object, otherwise false
  188. */
  189. const isURLSearchParams = kindOfTest('URLSearchParams');
  190. const [isReadableStream, isRequest, isResponse, isHeaders] = ['ReadableStream', 'Request', 'Response', 'Headers'].map(kindOfTest);
  191. /**
  192. * Trim excess whitespace off the beginning and end of a string
  193. *
  194. * @param {String} str The String to trim
  195. *
  196. * @returns {String} The String freed of excess whitespace
  197. */
  198. const trim = (str) => str.trim ?
  199. str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
  200. /**
  201. * Iterate over an Array or an Object invoking a function for each item.
  202. *
  203. * If `obj` is an Array callback will be called passing
  204. * the value, index, and complete array for each item.
  205. *
  206. * If 'obj' is an Object callback will be called passing
  207. * the value, key, and complete object for each property.
  208. *
  209. * @param {Object|Array} obj The object to iterate
  210. * @param {Function} fn The callback to invoke for each item
  211. *
  212. * @param {Boolean} [allOwnKeys = false]
  213. * @returns {any}
  214. */
  215. function forEach(obj, fn, {allOwnKeys = false} = {}) {
  216. // Don't bother if no value provided
  217. if (obj === null || typeof obj === 'undefined') {
  218. return;
  219. }
  220. let i;
  221. let l;
  222. // Force an array if not already something iterable
  223. if (typeof obj !== 'object') {
  224. /*eslint no-param-reassign:0*/
  225. obj = [obj];
  226. }
  227. if (isArray(obj)) {
  228. // Iterate over array values
  229. for (i = 0, l = obj.length; i < l; i++) {
  230. fn.call(null, obj[i], i, obj);
  231. }
  232. } else {
  233. // Iterate over object keys
  234. const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);
  235. const len = keys.length;
  236. let key;
  237. for (i = 0; i < len; i++) {
  238. key = keys[i];
  239. fn.call(null, obj[key], key, obj);
  240. }
  241. }
  242. }
  243. function findKey(obj, key) {
  244. key = key.toLowerCase();
  245. const keys = Object.keys(obj);
  246. let i = keys.length;
  247. let _key;
  248. while (i-- > 0) {
  249. _key = keys[i];
  250. if (key === _key.toLowerCase()) {
  251. return _key;
  252. }
  253. }
  254. return null;
  255. }
  256. const _global = (() => {
  257. /*eslint no-undef:0*/
  258. if (typeof globalThis !== "undefined") return globalThis;
  259. return typeof self !== "undefined" ? self : (typeof window !== 'undefined' ? window : global)
  260. })();
  261. const isContextDefined = (context) => !isUndefined(context) && context !== _global;
  262. /**
  263. * Accepts varargs expecting each argument to be an object, then
  264. * immutably merges the properties of each object and returns result.
  265. *
  266. * When multiple objects contain the same key the later object in
  267. * the arguments list will take precedence.
  268. *
  269. * Example:
  270. *
  271. * ```js
  272. * var result = merge({foo: 123}, {foo: 456});
  273. * console.log(result.foo); // outputs 456
  274. * ```
  275. *
  276. * @param {Object} obj1 Object to merge
  277. *
  278. * @returns {Object} Result of all merge properties
  279. */
  280. function merge(/* obj1, obj2, obj3, ... */) {
  281. const {caseless} = isContextDefined(this) && this || {};
  282. const result = {};
  283. const assignValue = (val, key) => {
  284. const targetKey = caseless && findKey(result, key) || key;
  285. if (isPlainObject(result[targetKey]) && isPlainObject(val)) {
  286. result[targetKey] = merge(result[targetKey], val);
  287. } else if (isPlainObject(val)) {
  288. result[targetKey] = merge({}, val);
  289. } else if (isArray(val)) {
  290. result[targetKey] = val.slice();
  291. } else {
  292. result[targetKey] = val;
  293. }
  294. };
  295. for (let i = 0, l = arguments.length; i < l; i++) {
  296. arguments[i] && forEach(arguments[i], assignValue);
  297. }
  298. return result;
  299. }
  300. /**
  301. * Extends object a by mutably adding to it the properties of object b.
  302. *
  303. * @param {Object} a The object to be extended
  304. * @param {Object} b The object to copy properties from
  305. * @param {Object} thisArg The object to bind function to
  306. *
  307. * @param {Boolean} [allOwnKeys]
  308. * @returns {Object} The resulting value of object a
  309. */
  310. const extend = (a, b, thisArg, {allOwnKeys}= {}) => {
  311. forEach(b, (val, key) => {
  312. if (thisArg && isFunction(val)) {
  313. a[key] = bind(val, thisArg);
  314. } else {
  315. a[key] = val;
  316. }
  317. }, {allOwnKeys});
  318. return a;
  319. };
  320. /**
  321. * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
  322. *
  323. * @param {string} content with BOM
  324. *
  325. * @returns {string} content value without BOM
  326. */
  327. const stripBOM = (content) => {
  328. if (content.charCodeAt(0) === 0xFEFF) {
  329. content = content.slice(1);
  330. }
  331. return content;
  332. };
  333. /**
  334. * Inherit the prototype methods from one constructor into another
  335. * @param {function} constructor
  336. * @param {function} superConstructor
  337. * @param {object} [props]
  338. * @param {object} [descriptors]
  339. *
  340. * @returns {void}
  341. */
  342. const inherits = (constructor, superConstructor, props, descriptors) => {
  343. constructor.prototype = Object.create(superConstructor.prototype, descriptors);
  344. constructor.prototype.constructor = constructor;
  345. Object.defineProperty(constructor, 'super', {
  346. value: superConstructor.prototype
  347. });
  348. props && Object.assign(constructor.prototype, props);
  349. };
  350. /**
  351. * Resolve object with deep prototype chain to a flat object
  352. * @param {Object} sourceObj source object
  353. * @param {Object} [destObj]
  354. * @param {Function|Boolean} [filter]
  355. * @param {Function} [propFilter]
  356. *
  357. * @returns {Object}
  358. */
  359. const toFlatObject = (sourceObj, destObj, filter, propFilter) => {
  360. let props;
  361. let i;
  362. let prop;
  363. const merged = {};
  364. destObj = destObj || {};
  365. // eslint-disable-next-line no-eq-null,eqeqeq
  366. if (sourceObj == null) return destObj;
  367. do {
  368. props = Object.getOwnPropertyNames(sourceObj);
  369. i = props.length;
  370. while (i-- > 0) {
  371. prop = props[i];
  372. if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {
  373. destObj[prop] = sourceObj[prop];
  374. merged[prop] = true;
  375. }
  376. }
  377. sourceObj = filter !== false && getPrototypeOf(sourceObj);
  378. } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);
  379. return destObj;
  380. };
  381. /**
  382. * Determines whether a string ends with the characters of a specified string
  383. *
  384. * @param {String} str
  385. * @param {String} searchString
  386. * @param {Number} [position= 0]
  387. *
  388. * @returns {boolean}
  389. */
  390. const endsWith = (str, searchString, position) => {
  391. str = String(str);
  392. if (position === undefined || position > str.length) {
  393. position = str.length;
  394. }
  395. position -= searchString.length;
  396. const lastIndex = str.indexOf(searchString, position);
  397. return lastIndex !== -1 && lastIndex === position;
  398. };
  399. /**
  400. * Returns new array from array like object or null if failed
  401. *
  402. * @param {*} [thing]
  403. *
  404. * @returns {?Array}
  405. */
  406. const toArray = (thing) => {
  407. if (!thing) return null;
  408. if (isArray(thing)) return thing;
  409. let i = thing.length;
  410. if (!isNumber(i)) return null;
  411. const arr = new Array(i);
  412. while (i-- > 0) {
  413. arr[i] = thing[i];
  414. }
  415. return arr;
  416. };
  417. /**
  418. * Checking if the Uint8Array exists and if it does, it returns a function that checks if the
  419. * thing passed in is an instance of Uint8Array
  420. *
  421. * @param {TypedArray}
  422. *
  423. * @returns {Array}
  424. */
  425. // eslint-disable-next-line func-names
  426. const isTypedArray = (TypedArray => {
  427. // eslint-disable-next-line func-names
  428. return thing => {
  429. return TypedArray && thing instanceof TypedArray;
  430. };
  431. })(typeof Uint8Array !== 'undefined' && getPrototypeOf(Uint8Array));
  432. /**
  433. * For each entry in the object, call the function with the key and value.
  434. *
  435. * @param {Object<any, any>} obj - The object to iterate over.
  436. * @param {Function} fn - The function to call for each entry.
  437. *
  438. * @returns {void}
  439. */
  440. const forEachEntry = (obj, fn) => {
  441. const generator = obj && obj[Symbol.iterator];
  442. const iterator = generator.call(obj);
  443. let result;
  444. while ((result = iterator.next()) && !result.done) {
  445. const pair = result.value;
  446. fn.call(obj, pair[0], pair[1]);
  447. }
  448. };
  449. /**
  450. * It takes a regular expression and a string, and returns an array of all the matches
  451. *
  452. * @param {string} regExp - The regular expression to match against.
  453. * @param {string} str - The string to search.
  454. *
  455. * @returns {Array<boolean>}
  456. */
  457. const matchAll = (regExp, str) => {
  458. let matches;
  459. const arr = [];
  460. while ((matches = regExp.exec(str)) !== null) {
  461. arr.push(matches);
  462. }
  463. return arr;
  464. };
  465. /* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */
  466. const isHTMLForm = kindOfTest('HTMLFormElement');
  467. const toCamelCase = str => {
  468. return str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,
  469. function replacer(m, p1, p2) {
  470. return p1.toUpperCase() + p2;
  471. }
  472. );
  473. };
  474. /* Creating a function that will check if an object has a property. */
  475. const hasOwnProperty = (({hasOwnProperty}) => (obj, prop) => hasOwnProperty.call(obj, prop))(Object.prototype);
  476. /**
  477. * Determine if a value is a RegExp object
  478. *
  479. * @param {*} val The value to test
  480. *
  481. * @returns {boolean} True if value is a RegExp object, otherwise false
  482. */
  483. const isRegExp = kindOfTest('RegExp');
  484. const reduceDescriptors = (obj, reducer) => {
  485. const descriptors = Object.getOwnPropertyDescriptors(obj);
  486. const reducedDescriptors = {};
  487. forEach(descriptors, (descriptor, name) => {
  488. let ret;
  489. if ((ret = reducer(descriptor, name, obj)) !== false) {
  490. reducedDescriptors[name] = ret || descriptor;
  491. }
  492. });
  493. Object.defineProperties(obj, reducedDescriptors);
  494. };
  495. /**
  496. * Makes all methods read-only
  497. * @param {Object} obj
  498. */
  499. const freezeMethods = (obj) => {
  500. reduceDescriptors(obj, (descriptor, name) => {
  501. // skip restricted props in strict mode
  502. if (isFunction(obj) && ['arguments', 'caller', 'callee'].indexOf(name) !== -1) {
  503. return false;
  504. }
  505. const value = obj[name];
  506. if (!isFunction(value)) return;
  507. descriptor.enumerable = false;
  508. if ('writable' in descriptor) {
  509. descriptor.writable = false;
  510. return;
  511. }
  512. if (!descriptor.set) {
  513. descriptor.set = () => {
  514. throw Error('Can not rewrite read-only method \'' + name + '\'');
  515. };
  516. }
  517. });
  518. };
  519. const toObjectSet = (arrayOrString, delimiter) => {
  520. const obj = {};
  521. const define = (arr) => {
  522. arr.forEach(value => {
  523. obj[value] = true;
  524. });
  525. };
  526. isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter));
  527. return obj;
  528. };
  529. const noop = () => {};
  530. const toFiniteNumber = (value, defaultValue) => {
  531. return value != null && Number.isFinite(value = +value) ? value : defaultValue;
  532. };
  533. /**
  534. * If the thing is a FormData object, return true, otherwise return false.
  535. *
  536. * @param {unknown} thing - The thing to check.
  537. *
  538. * @returns {boolean}
  539. */
  540. function isSpecCompliantForm(thing) {
  541. return !!(thing && isFunction(thing.append) && thing[Symbol.toStringTag] === 'FormData' && thing[Symbol.iterator]);
  542. }
  543. const toJSONObject = (obj) => {
  544. const stack = new Array(10);
  545. const visit = (source, i) => {
  546. if (isObject(source)) {
  547. if (stack.indexOf(source) >= 0) {
  548. return;
  549. }
  550. if(!('toJSON' in source)) {
  551. stack[i] = source;
  552. const target = isArray(source) ? [] : {};
  553. forEach(source, (value, key) => {
  554. const reducedValue = visit(value, i + 1);
  555. !isUndefined(reducedValue) && (target[key] = reducedValue);
  556. });
  557. stack[i] = undefined;
  558. return target;
  559. }
  560. }
  561. return source;
  562. };
  563. return visit(obj, 0);
  564. };
  565. const isAsyncFn = kindOfTest('AsyncFunction');
  566. const isThenable = (thing) =>
  567. thing && (isObject(thing) || isFunction(thing)) && isFunction(thing.then) && isFunction(thing.catch);
  568. // original code
  569. // https://github.com/DigitalBrainJS/AxiosPromise/blob/16deab13710ec09779922131f3fa5954320f83ab/lib/utils.js#L11-L34
  570. const _setImmediate = ((setImmediateSupported, postMessageSupported) => {
  571. if (setImmediateSupported) {
  572. return setImmediate;
  573. }
  574. return postMessageSupported ? ((token, callbacks) => {
  575. _global.addEventListener("message", ({source, data}) => {
  576. if (source === _global && data === token) {
  577. callbacks.length && callbacks.shift()();
  578. }
  579. }, false);
  580. return (cb) => {
  581. callbacks.push(cb);
  582. _global.postMessage(token, "*");
  583. }
  584. })(`axios@${Math.random()}`, []) : (cb) => setTimeout(cb);
  585. })(
  586. typeof setImmediate === 'function',
  587. isFunction(_global.postMessage)
  588. );
  589. const asap = typeof queueMicrotask !== 'undefined' ?
  590. queueMicrotask.bind(_global) : ( typeof process !== 'undefined' && process.nextTick || _setImmediate);
  591. // *********************
  592. var utils$1 = {
  593. isArray,
  594. isArrayBuffer,
  595. isBuffer,
  596. isFormData,
  597. isArrayBufferView,
  598. isString,
  599. isNumber,
  600. isBoolean,
  601. isObject,
  602. isPlainObject,
  603. isReadableStream,
  604. isRequest,
  605. isResponse,
  606. isHeaders,
  607. isUndefined,
  608. isDate,
  609. isFile,
  610. isBlob,
  611. isRegExp,
  612. isFunction,
  613. isStream,
  614. isURLSearchParams,
  615. isTypedArray,
  616. isFileList,
  617. forEach,
  618. merge,
  619. extend,
  620. trim,
  621. stripBOM,
  622. inherits,
  623. toFlatObject,
  624. kindOf,
  625. kindOfTest,
  626. endsWith,
  627. toArray,
  628. forEachEntry,
  629. matchAll,
  630. isHTMLForm,
  631. hasOwnProperty,
  632. hasOwnProp: hasOwnProperty, // an alias to avoid ESLint no-prototype-builtins detection
  633. reduceDescriptors,
  634. freezeMethods,
  635. toObjectSet,
  636. toCamelCase,
  637. noop,
  638. toFiniteNumber,
  639. findKey,
  640. global: _global,
  641. isContextDefined,
  642. isSpecCompliantForm,
  643. toJSONObject,
  644. isAsyncFn,
  645. isThenable,
  646. setImmediate: _setImmediate,
  647. asap
  648. };
  649. /**
  650. * Create an Error with the specified message, config, error code, request and response.
  651. *
  652. * @param {string} message The error message.
  653. * @param {string} [code] The error code (for example, 'ECONNABORTED').
  654. * @param {Object} [config] The config.
  655. * @param {Object} [request] The request.
  656. * @param {Object} [response] The response.
  657. *
  658. * @returns {Error} The created error.
  659. */
  660. function AxiosError(message, code, config, request, response) {
  661. Error.call(this);
  662. if (Error.captureStackTrace) {
  663. Error.captureStackTrace(this, this.constructor);
  664. } else {
  665. this.stack = (new Error()).stack;
  666. }
  667. this.message = message;
  668. this.name = 'AxiosError';
  669. code && (this.code = code);
  670. config && (this.config = config);
  671. request && (this.request = request);
  672. if (response) {
  673. this.response = response;
  674. this.status = response.status ? response.status : null;
  675. }
  676. }
  677. utils$1.inherits(AxiosError, Error, {
  678. toJSON: function toJSON() {
  679. return {
  680. // Standard
  681. message: this.message,
  682. name: this.name,
  683. // Microsoft
  684. description: this.description,
  685. number: this.number,
  686. // Mozilla
  687. fileName: this.fileName,
  688. lineNumber: this.lineNumber,
  689. columnNumber: this.columnNumber,
  690. stack: this.stack,
  691. // Axios
  692. config: utils$1.toJSONObject(this.config),
  693. code: this.code,
  694. status: this.status
  695. };
  696. }
  697. });
  698. const prototype$1 = AxiosError.prototype;
  699. const descriptors = {};
  700. [
  701. 'ERR_BAD_OPTION_VALUE',
  702. 'ERR_BAD_OPTION',
  703. 'ECONNABORTED',
  704. 'ETIMEDOUT',
  705. 'ERR_NETWORK',
  706. 'ERR_FR_TOO_MANY_REDIRECTS',
  707. 'ERR_DEPRECATED',
  708. 'ERR_BAD_RESPONSE',
  709. 'ERR_BAD_REQUEST',
  710. 'ERR_CANCELED',
  711. 'ERR_NOT_SUPPORT',
  712. 'ERR_INVALID_URL'
  713. // eslint-disable-next-line func-names
  714. ].forEach(code => {
  715. descriptors[code] = {value: code};
  716. });
  717. Object.defineProperties(AxiosError, descriptors);
  718. Object.defineProperty(prototype$1, 'isAxiosError', {value: true});
  719. // eslint-disable-next-line func-names
  720. AxiosError.from = (error, code, config, request, response, customProps) => {
  721. const axiosError = Object.create(prototype$1);
  722. utils$1.toFlatObject(error, axiosError, function filter(obj) {
  723. return obj !== Error.prototype;
  724. }, prop => {
  725. return prop !== 'isAxiosError';
  726. });
  727. AxiosError.call(axiosError, error.message, code, config, request, response);
  728. axiosError.cause = error;
  729. axiosError.name = error.name;
  730. customProps && Object.assign(axiosError, customProps);
  731. return axiosError;
  732. };
  733. // eslint-disable-next-line strict
  734. var httpAdapter = null;
  735. /**
  736. * Determines if the given thing is a array or js object.
  737. *
  738. * @param {string} thing - The object or array to be visited.
  739. *
  740. * @returns {boolean}
  741. */
  742. function isVisitable(thing) {
  743. return utils$1.isPlainObject(thing) || utils$1.isArray(thing);
  744. }
  745. /**
  746. * It removes the brackets from the end of a string
  747. *
  748. * @param {string} key - The key of the parameter.
  749. *
  750. * @returns {string} the key without the brackets.
  751. */
  752. function removeBrackets(key) {
  753. return utils$1.endsWith(key, '[]') ? key.slice(0, -2) : key;
  754. }
  755. /**
  756. * It takes a path, a key, and a boolean, and returns a string
  757. *
  758. * @param {string} path - The path to the current key.
  759. * @param {string} key - The key of the current object being iterated over.
  760. * @param {string} dots - If true, the key will be rendered with dots instead of brackets.
  761. *
  762. * @returns {string} The path to the current key.
  763. */
  764. function renderKey(path, key, dots) {
  765. if (!path) return key;
  766. return path.concat(key).map(function each(token, i) {
  767. // eslint-disable-next-line no-param-reassign
  768. token = removeBrackets(token);
  769. return !dots && i ? '[' + token + ']' : token;
  770. }).join(dots ? '.' : '');
  771. }
  772. /**
  773. * If the array is an array and none of its elements are visitable, then it's a flat array.
  774. *
  775. * @param {Array<any>} arr - The array to check
  776. *
  777. * @returns {boolean}
  778. */
  779. function isFlatArray(arr) {
  780. return utils$1.isArray(arr) && !arr.some(isVisitable);
  781. }
  782. const predicates = utils$1.toFlatObject(utils$1, {}, null, function filter(prop) {
  783. return /^is[A-Z]/.test(prop);
  784. });
  785. /**
  786. * Convert a data object to FormData
  787. *
  788. * @param {Object} obj
  789. * @param {?Object} [formData]
  790. * @param {?Object} [options]
  791. * @param {Function} [options.visitor]
  792. * @param {Boolean} [options.metaTokens = true]
  793. * @param {Boolean} [options.dots = false]
  794. * @param {?Boolean} [options.indexes = false]
  795. *
  796. * @returns {Object}
  797. **/
  798. /**
  799. * It converts an object into a FormData object
  800. *
  801. * @param {Object<any, any>} obj - The object to convert to form data.
  802. * @param {string} formData - The FormData object to append to.
  803. * @param {Object<string, any>} options
  804. *
  805. * @returns
  806. */
  807. function toFormData(obj, formData, options) {
  808. if (!utils$1.isObject(obj)) {
  809. throw new TypeError('target must be an object');
  810. }
  811. // eslint-disable-next-line no-param-reassign
  812. formData = formData || new (FormData)();
  813. // eslint-disable-next-line no-param-reassign
  814. options = utils$1.toFlatObject(options, {
  815. metaTokens: true,
  816. dots: false,
  817. indexes: false
  818. }, false, function defined(option, source) {
  819. // eslint-disable-next-line no-eq-null,eqeqeq
  820. return !utils$1.isUndefined(source[option]);
  821. });
  822. const metaTokens = options.metaTokens;
  823. // eslint-disable-next-line no-use-before-define
  824. const visitor = options.visitor || defaultVisitor;
  825. const dots = options.dots;
  826. const indexes = options.indexes;
  827. const _Blob = options.Blob || typeof Blob !== 'undefined' && Blob;
  828. const useBlob = _Blob && utils$1.isSpecCompliantForm(formData);
  829. if (!utils$1.isFunction(visitor)) {
  830. throw new TypeError('visitor must be a function');
  831. }
  832. function convertValue(value) {
  833. if (value === null) return '';
  834. if (utils$1.isDate(value)) {
  835. return value.toISOString();
  836. }
  837. if (!useBlob && utils$1.isBlob(value)) {
  838. throw new AxiosError('Blob is not supported. Use a Buffer instead.');
  839. }
  840. if (utils$1.isArrayBuffer(value) || utils$1.isTypedArray(value)) {
  841. return useBlob && typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value);
  842. }
  843. return value;
  844. }
  845. /**
  846. * Default visitor.
  847. *
  848. * @param {*} value
  849. * @param {String|Number} key
  850. * @param {Array<String|Number>} path
  851. * @this {FormData}
  852. *
  853. * @returns {boolean} return true to visit the each prop of the value recursively
  854. */
  855. function defaultVisitor(value, key, path) {
  856. let arr = value;
  857. if (value && !path && typeof value === 'object') {
  858. if (utils$1.endsWith(key, '{}')) {
  859. // eslint-disable-next-line no-param-reassign
  860. key = metaTokens ? key : key.slice(0, -2);
  861. // eslint-disable-next-line no-param-reassign
  862. value = JSON.stringify(value);
  863. } else if (
  864. (utils$1.isArray(value) && isFlatArray(value)) ||
  865. ((utils$1.isFileList(value) || utils$1.endsWith(key, '[]')) && (arr = utils$1.toArray(value))
  866. )) {
  867. // eslint-disable-next-line no-param-reassign
  868. key = removeBrackets(key);
  869. arr.forEach(function each(el, index) {
  870. !(utils$1.isUndefined(el) || el === null) && formData.append(
  871. // eslint-disable-next-line no-nested-ternary
  872. indexes === true ? renderKey([key], index, dots) : (indexes === null ? key : key + '[]'),
  873. convertValue(el)
  874. );
  875. });
  876. return false;
  877. }
  878. }
  879. if (isVisitable(value)) {
  880. return true;
  881. }
  882. formData.append(renderKey(path, key, dots), convertValue(value));
  883. return false;
  884. }
  885. const stack = [];
  886. const exposedHelpers = Object.assign(predicates, {
  887. defaultVisitor,
  888. convertValue,
  889. isVisitable
  890. });
  891. function build(value, path) {
  892. if (utils$1.isUndefined(value)) return;
  893. if (stack.indexOf(value) !== -1) {
  894. throw Error('Circular reference detected in ' + path.join('.'));
  895. }
  896. stack.push(value);
  897. utils$1.forEach(value, function each(el, key) {
  898. const result = !(utils$1.isUndefined(el) || el === null) && visitor.call(
  899. formData, el, utils$1.isString(key) ? key.trim() : key, path, exposedHelpers
  900. );
  901. if (result === true) {
  902. build(el, path ? path.concat(key) : [key]);
  903. }
  904. });
  905. stack.pop();
  906. }
  907. if (!utils$1.isObject(obj)) {
  908. throw new TypeError('data must be an object');
  909. }
  910. build(obj);
  911. return formData;
  912. }
  913. /**
  914. * It encodes a string by replacing all characters that are not in the unreserved set with
  915. * their percent-encoded equivalents
  916. *
  917. * @param {string} str - The string to encode.
  918. *
  919. * @returns {string} The encoded string.
  920. */
  921. function encode$1(str) {
  922. const charMap = {
  923. '!': '%21',
  924. "'": '%27',
  925. '(': '%28',
  926. ')': '%29',
  927. '~': '%7E',
  928. '%20': '+',
  929. '%00': '\x00'
  930. };
  931. return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) {
  932. return charMap[match];
  933. });
  934. }
  935. /**
  936. * It takes a params object and converts it to a FormData object
  937. *
  938. * @param {Object<string, any>} params - The parameters to be converted to a FormData object.
  939. * @param {Object<string, any>} options - The options object passed to the Axios constructor.
  940. *
  941. * @returns {void}
  942. */
  943. function AxiosURLSearchParams(params, options) {
  944. this._pairs = [];
  945. params && toFormData(params, this, options);
  946. }
  947. const prototype = AxiosURLSearchParams.prototype;
  948. prototype.append = function append(name, value) {
  949. this._pairs.push([name, value]);
  950. };
  951. prototype.toString = function toString(encoder) {
  952. const _encode = encoder ? function(value) {
  953. return encoder.call(this, value, encode$1);
  954. } : encode$1;
  955. return this._pairs.map(function each(pair) {
  956. return _encode(pair[0]) + '=' + _encode(pair[1]);
  957. }, '').join('&');
  958. };
  959. /**
  960. * It replaces all instances of the characters `:`, `$`, `,`, `+`, `[`, and `]` with their
  961. * URI encoded counterparts
  962. *
  963. * @param {string} val The value to be encoded.
  964. *
  965. * @returns {string} The encoded value.
  966. */
  967. function encode(val) {
  968. return encodeURIComponent(val).
  969. replace(/%3A/gi, ':').
  970. replace(/%24/g, '$').
  971. replace(/%2C/gi, ',').
  972. replace(/%20/g, '+').
  973. replace(/%5B/gi, '[').
  974. replace(/%5D/gi, ']');
  975. }
  976. /**
  977. * Build a URL by appending params to the end
  978. *
  979. * @param {string} url The base of the url (e.g., http://www.google.com)
  980. * @param {object} [params] The params to be appended
  981. * @param {?(object|Function)} options
  982. *
  983. * @returns {string} The formatted url
  984. */
  985. function buildURL(url, params, options) {
  986. /*eslint no-param-reassign:0*/
  987. if (!params) {
  988. return url;
  989. }
  990. const _encode = options && options.encode || encode;
  991. if (utils$1.isFunction(options)) {
  992. options = {
  993. serialize: options
  994. };
  995. }
  996. const serializeFn = options && options.serialize;
  997. let serializedParams;
  998. if (serializeFn) {
  999. serializedParams = serializeFn(params, options);
  1000. } else {
  1001. serializedParams = utils$1.isURLSearchParams(params) ?
  1002. params.toString() :
  1003. new AxiosURLSearchParams(params, options).toString(_encode);
  1004. }
  1005. if (serializedParams) {
  1006. const hashmarkIndex = url.indexOf("#");
  1007. if (hashmarkIndex !== -1) {
  1008. url = url.slice(0, hashmarkIndex);
  1009. }
  1010. url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
  1011. }
  1012. return url;
  1013. }
  1014. class InterceptorManager {
  1015. constructor() {
  1016. this.handlers = [];
  1017. }
  1018. /**
  1019. * Add a new interceptor to the stack
  1020. *
  1021. * @param {Function} fulfilled The function to handle `then` for a `Promise`
  1022. * @param {Function} rejected The function to handle `reject` for a `Promise`
  1023. *
  1024. * @return {Number} An ID used to remove interceptor later
  1025. */
  1026. use(fulfilled, rejected, options) {
  1027. this.handlers.push({
  1028. fulfilled,
  1029. rejected,
  1030. synchronous: options ? options.synchronous : false,
  1031. runWhen: options ? options.runWhen : null
  1032. });
  1033. return this.handlers.length - 1;
  1034. }
  1035. /**
  1036. * Remove an interceptor from the stack
  1037. *
  1038. * @param {Number} id The ID that was returned by `use`
  1039. *
  1040. * @returns {Boolean} `true` if the interceptor was removed, `false` otherwise
  1041. */
  1042. eject(id) {
  1043. if (this.handlers[id]) {
  1044. this.handlers[id] = null;
  1045. }
  1046. }
  1047. /**
  1048. * Clear all interceptors from the stack
  1049. *
  1050. * @returns {void}
  1051. */
  1052. clear() {
  1053. if (this.handlers) {
  1054. this.handlers = [];
  1055. }
  1056. }
  1057. /**
  1058. * Iterate over all the registered interceptors
  1059. *
  1060. * This method is particularly useful for skipping over any
  1061. * interceptors that may have become `null` calling `eject`.
  1062. *
  1063. * @param {Function} fn The function to call for each interceptor
  1064. *
  1065. * @returns {void}
  1066. */
  1067. forEach(fn) {
  1068. utils$1.forEach(this.handlers, function forEachHandler(h) {
  1069. if (h !== null) {
  1070. fn(h);
  1071. }
  1072. });
  1073. }
  1074. }
  1075. var InterceptorManager$1 = InterceptorManager;
  1076. var transitionalDefaults = {
  1077. silentJSONParsing: true,
  1078. forcedJSONParsing: true,
  1079. clarifyTimeoutError: false
  1080. };
  1081. var URLSearchParams$1 = typeof URLSearchParams !== 'undefined' ? URLSearchParams : AxiosURLSearchParams;
  1082. var FormData$1 = typeof FormData !== 'undefined' ? FormData : null;
  1083. var Blob$1 = typeof Blob !== 'undefined' ? Blob : null;
  1084. var platform$1 = {
  1085. isBrowser: true,
  1086. classes: {
  1087. URLSearchParams: URLSearchParams$1,
  1088. FormData: FormData$1,
  1089. Blob: Blob$1
  1090. },
  1091. protocols: ['http', 'https', 'file', 'blob', 'url', 'data']
  1092. };
  1093. const hasBrowserEnv = typeof window !== 'undefined' && typeof document !== 'undefined';
  1094. const _navigator = typeof navigator === 'object' && navigator || undefined;
  1095. /**
  1096. * Determine if we're running in a standard browser environment
  1097. *
  1098. * This allows axios to run in a web worker, and react-native.
  1099. * Both environments support XMLHttpRequest, but not fully standard globals.
  1100. *
  1101. * web workers:
  1102. * typeof window -> undefined
  1103. * typeof document -> undefined
  1104. *
  1105. * react-native:
  1106. * navigator.product -> 'ReactNative'
  1107. * nativescript
  1108. * navigator.product -> 'NativeScript' or 'NS'
  1109. *
  1110. * @returns {boolean}
  1111. */
  1112. const hasStandardBrowserEnv = hasBrowserEnv &&
  1113. (!_navigator || ['ReactNative', 'NativeScript', 'NS'].indexOf(_navigator.product) < 0);
  1114. /**
  1115. * Determine if we're running in a standard browser webWorker environment
  1116. *
  1117. * Although the `isStandardBrowserEnv` method indicates that
  1118. * `allows axios to run in a web worker`, the WebWorker will still be
  1119. * filtered out due to its judgment standard
  1120. * `typeof window !== 'undefined' && typeof document !== 'undefined'`.
  1121. * This leads to a problem when axios post `FormData` in webWorker
  1122. */
  1123. const hasStandardBrowserWebWorkerEnv = (() => {
  1124. return (
  1125. typeof WorkerGlobalScope !== 'undefined' &&
  1126. // eslint-disable-next-line no-undef
  1127. self instanceof WorkerGlobalScope &&
  1128. typeof self.importScripts === 'function'
  1129. );
  1130. })();
  1131. const origin = hasBrowserEnv && window.location.href || 'http://localhost';
  1132. var utils = /*#__PURE__*/Object.freeze({
  1133. __proto__: null,
  1134. hasBrowserEnv: hasBrowserEnv,
  1135. hasStandardBrowserWebWorkerEnv: hasStandardBrowserWebWorkerEnv,
  1136. hasStandardBrowserEnv: hasStandardBrowserEnv,
  1137. navigator: _navigator,
  1138. origin: origin
  1139. });
  1140. var platform = {
  1141. ...utils,
  1142. ...platform$1
  1143. };
  1144. function toURLEncodedForm(data, options) {
  1145. return toFormData(data, new platform.classes.URLSearchParams(), Object.assign({
  1146. visitor: function(value, key, path, helpers) {
  1147. if (platform.isNode && utils$1.isBuffer(value)) {
  1148. this.append(key, value.toString('base64'));
  1149. return false;
  1150. }
  1151. return helpers.defaultVisitor.apply(this, arguments);
  1152. }
  1153. }, options));
  1154. }
  1155. /**
  1156. * It takes a string like `foo[x][y][z]` and returns an array like `['foo', 'x', 'y', 'z']
  1157. *
  1158. * @param {string} name - The name of the property to get.
  1159. *
  1160. * @returns An array of strings.
  1161. */
  1162. function parsePropPath(name) {
  1163. // foo[x][y][z]
  1164. // foo.x.y.z
  1165. // foo-x-y-z
  1166. // foo x y z
  1167. return utils$1.matchAll(/\w+|\[(\w*)]/g, name).map(match => {
  1168. return match[0] === '[]' ? '' : match[1] || match[0];
  1169. });
  1170. }
  1171. /**
  1172. * Convert an array to an object.
  1173. *
  1174. * @param {Array<any>} arr - The array to convert to an object.
  1175. *
  1176. * @returns An object with the same keys and values as the array.
  1177. */
  1178. function arrayToObject(arr) {
  1179. const obj = {};
  1180. const keys = Object.keys(arr);
  1181. let i;
  1182. const len = keys.length;
  1183. let key;
  1184. for (i = 0; i < len; i++) {
  1185. key = keys[i];
  1186. obj[key] = arr[key];
  1187. }
  1188. return obj;
  1189. }
  1190. /**
  1191. * It takes a FormData object and returns a JavaScript object
  1192. *
  1193. * @param {string} formData The FormData object to convert to JSON.
  1194. *
  1195. * @returns {Object<string, any> | null} The converted object.
  1196. */
  1197. function formDataToJSON(formData) {
  1198. function buildPath(path, value, target, index) {
  1199. let name = path[index++];
  1200. if (name === '__proto__') return true;
  1201. const isNumericKey = Number.isFinite(+name);
  1202. const isLast = index >= path.length;
  1203. name = !name && utils$1.isArray(target) ? target.length : name;
  1204. if (isLast) {
  1205. if (utils$1.hasOwnProp(target, name)) {
  1206. target[name] = [target[name], value];
  1207. } else {
  1208. target[name] = value;
  1209. }
  1210. return !isNumericKey;
  1211. }
  1212. if (!target[name] || !utils$1.isObject(target[name])) {
  1213. target[name] = [];
  1214. }
  1215. const result = buildPath(path, value, target[name], index);
  1216. if (result && utils$1.isArray(target[name])) {
  1217. target[name] = arrayToObject(target[name]);
  1218. }
  1219. return !isNumericKey;
  1220. }
  1221. if (utils$1.isFormData(formData) && utils$1.isFunction(formData.entries)) {
  1222. const obj = {};
  1223. utils$1.forEachEntry(formData, (name, value) => {
  1224. buildPath(parsePropPath(name), value, obj, 0);
  1225. });
  1226. return obj;
  1227. }
  1228. return null;
  1229. }
  1230. /**
  1231. * It takes a string, tries to parse it, and if it fails, it returns the stringified version
  1232. * of the input
  1233. *
  1234. * @param {any} rawValue - The value to be stringified.
  1235. * @param {Function} parser - A function that parses a string into a JavaScript object.
  1236. * @param {Function} encoder - A function that takes a value and returns a string.
  1237. *
  1238. * @returns {string} A stringified version of the rawValue.
  1239. */
  1240. function stringifySafely(rawValue, parser, encoder) {
  1241. if (utils$1.isString(rawValue)) {
  1242. try {
  1243. (parser || JSON.parse)(rawValue);
  1244. return utils$1.trim(rawValue);
  1245. } catch (e) {
  1246. if (e.name !== 'SyntaxError') {
  1247. throw e;
  1248. }
  1249. }
  1250. }
  1251. return (encoder || JSON.stringify)(rawValue);
  1252. }
  1253. const defaults = {
  1254. transitional: transitionalDefaults,
  1255. adapter: ['xhr', 'http', 'fetch'],
  1256. transformRequest: [function transformRequest(data, headers) {
  1257. const contentType = headers.getContentType() || '';
  1258. const hasJSONContentType = contentType.indexOf('application/json') > -1;
  1259. const isObjectPayload = utils$1.isObject(data);
  1260. if (isObjectPayload && utils$1.isHTMLForm(data)) {
  1261. data = new FormData(data);
  1262. }
  1263. const isFormData = utils$1.isFormData(data);
  1264. if (isFormData) {
  1265. return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data;
  1266. }
  1267. if (utils$1.isArrayBuffer(data) ||
  1268. utils$1.isBuffer(data) ||
  1269. utils$1.isStream(data) ||
  1270. utils$1.isFile(data) ||
  1271. utils$1.isBlob(data) ||
  1272. utils$1.isReadableStream(data)
  1273. ) {
  1274. return data;
  1275. }
  1276. if (utils$1.isArrayBufferView(data)) {
  1277. return data.buffer;
  1278. }
  1279. if (utils$1.isURLSearchParams(data)) {
  1280. headers.setContentType('application/x-www-form-urlencoded;charset=utf-8', false);
  1281. return data.toString();
  1282. }
  1283. let isFileList;
  1284. if (isObjectPayload) {
  1285. if (contentType.indexOf('application/x-www-form-urlencoded') > -1) {
  1286. return toURLEncodedForm(data, this.formSerializer).toString();
  1287. }
  1288. if ((isFileList = utils$1.isFileList(data)) || contentType.indexOf('multipart/form-data') > -1) {
  1289. const _FormData = this.env && this.env.FormData;
  1290. return toFormData(
  1291. isFileList ? {'files[]': data} : data,
  1292. _FormData && new _FormData(),
  1293. this.formSerializer
  1294. );
  1295. }
  1296. }
  1297. if (isObjectPayload || hasJSONContentType ) {
  1298. headers.setContentType('application/json', false);
  1299. return stringifySafely(data);
  1300. }
  1301. return data;
  1302. }],
  1303. transformResponse: [function transformResponse(data) {
  1304. const transitional = this.transitional || defaults.transitional;
  1305. const forcedJSONParsing = transitional && transitional.forcedJSONParsing;
  1306. const JSONRequested = this.responseType === 'json';
  1307. if (utils$1.isResponse(data) || utils$1.isReadableStream(data)) {
  1308. return data;
  1309. }
  1310. if (data && utils$1.isString(data) && ((forcedJSONParsing && !this.responseType) || JSONRequested)) {
  1311. const silentJSONParsing = transitional && transitional.silentJSONParsing;
  1312. const strictJSONParsing = !silentJSONParsing && JSONRequested;
  1313. try {
  1314. return JSON.parse(data);
  1315. } catch (e) {
  1316. if (strictJSONParsing) {
  1317. if (e.name === 'SyntaxError') {
  1318. throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, this.response);
  1319. }
  1320. throw e;
  1321. }
  1322. }
  1323. }
  1324. return data;
  1325. }],
  1326. /**
  1327. * A timeout in milliseconds to abort a request. If set to 0 (default) a
  1328. * timeout is not created.
  1329. */
  1330. timeout: 0,
  1331. xsrfCookieName: 'XSRF-TOKEN',
  1332. xsrfHeaderName: 'X-XSRF-TOKEN',
  1333. maxContentLength: -1,
  1334. maxBodyLength: -1,
  1335. env: {
  1336. FormData: platform.classes.FormData,
  1337. Blob: platform.classes.Blob
  1338. },
  1339. validateStatus: function validateStatus(status) {
  1340. return status >= 200 && status < 300;
  1341. },
  1342. headers: {
  1343. common: {
  1344. 'Accept': 'application/json, text/plain, */*',
  1345. 'Content-Type': undefined
  1346. }
  1347. }
  1348. };
  1349. utils$1.forEach(['delete', 'get', 'head', 'post', 'put', 'patch'], (method) => {
  1350. defaults.headers[method] = {};
  1351. });
  1352. var defaults$1 = defaults;
  1353. // RawAxiosHeaders whose duplicates are ignored by node
  1354. // c.f. https://nodejs.org/api/http.html#http_message_headers
  1355. const ignoreDuplicateOf = utils$1.toObjectSet([
  1356. 'age', 'authorization', 'content-length', 'content-type', 'etag',
  1357. 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',
  1358. 'last-modified', 'location', 'max-forwards', 'proxy-authorization',
  1359. 'referer', 'retry-after', 'user-agent'
  1360. ]);
  1361. /**
  1362. * Parse headers into an object
  1363. *
  1364. * ```
  1365. * Date: Wed, 27 Aug 2014 08:58:49 GMT
  1366. * Content-Type: application/json
  1367. * Connection: keep-alive
  1368. * Transfer-Encoding: chunked
  1369. * ```
  1370. *
  1371. * @param {String} rawHeaders Headers needing to be parsed
  1372. *
  1373. * @returns {Object} Headers parsed into an object
  1374. */
  1375. var parseHeaders = rawHeaders => {
  1376. const parsed = {};
  1377. let key;
  1378. let val;
  1379. let i;
  1380. rawHeaders && rawHeaders.split('\n').forEach(function parser(line) {
  1381. i = line.indexOf(':');
  1382. key = line.substring(0, i).trim().toLowerCase();
  1383. val = line.substring(i + 1).trim();
  1384. if (!key || (parsed[key] && ignoreDuplicateOf[key])) {
  1385. return;
  1386. }
  1387. if (key === 'set-cookie') {
  1388. if (parsed[key]) {
  1389. parsed[key].push(val);
  1390. } else {
  1391. parsed[key] = [val];
  1392. }
  1393. } else {
  1394. parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
  1395. }
  1396. });
  1397. return parsed;
  1398. };
  1399. const $internals = Symbol('internals');
  1400. function normalizeHeader(header) {
  1401. return header && String(header).trim().toLowerCase();
  1402. }
  1403. function normalizeValue(value) {
  1404. if (value === false || value == null) {
  1405. return value;
  1406. }
  1407. return utils$1.isArray(value) ? value.map(normalizeValue) : String(value);
  1408. }
  1409. function parseTokens(str) {
  1410. const tokens = Object.create(null);
  1411. const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;
  1412. let match;
  1413. while ((match = tokensRE.exec(str))) {
  1414. tokens[match[1]] = match[2];
  1415. }
  1416. return tokens;
  1417. }
  1418. const isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim());
  1419. function matchHeaderValue(context, value, header, filter, isHeaderNameFilter) {
  1420. if (utils$1.isFunction(filter)) {
  1421. return filter.call(this, value, header);
  1422. }
  1423. if (isHeaderNameFilter) {
  1424. value = header;
  1425. }
  1426. if (!utils$1.isString(value)) return;
  1427. if (utils$1.isString(filter)) {
  1428. return value.indexOf(filter) !== -1;
  1429. }
  1430. if (utils$1.isRegExp(filter)) {
  1431. return filter.test(value);
  1432. }
  1433. }
  1434. function formatHeader(header) {
  1435. return header.trim()
  1436. .toLowerCase().replace(/([a-z\d])(\w*)/g, (w, char, str) => {
  1437. return char.toUpperCase() + str;
  1438. });
  1439. }
  1440. function buildAccessors(obj, header) {
  1441. const accessorName = utils$1.toCamelCase(' ' + header);
  1442. ['get', 'set', 'has'].forEach(methodName => {
  1443. Object.defineProperty(obj, methodName + accessorName, {
  1444. value: function(arg1, arg2, arg3) {
  1445. return this[methodName].call(this, header, arg1, arg2, arg3);
  1446. },
  1447. configurable: true
  1448. });
  1449. });
  1450. }
  1451. class AxiosHeaders {
  1452. constructor(headers) {
  1453. headers && this.set(headers);
  1454. }
  1455. set(header, valueOrRewrite, rewrite) {
  1456. const self = this;
  1457. function setHeader(_value, _header, _rewrite) {
  1458. const lHeader = normalizeHeader(_header);
  1459. if (!lHeader) {
  1460. throw new Error('header name must be a non-empty string');
  1461. }
  1462. const key = utils$1.findKey(self, lHeader);
  1463. if(!key || self[key] === undefined || _rewrite === true || (_rewrite === undefined && self[key] !== false)) {
  1464. self[key || _header] = normalizeValue(_value);
  1465. }
  1466. }
  1467. const setHeaders = (headers, _rewrite) =>
  1468. utils$1.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite));
  1469. if (utils$1.isPlainObject(header) || header instanceof this.constructor) {
  1470. setHeaders(header, valueOrRewrite);
  1471. } else if(utils$1.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) {
  1472. setHeaders(parseHeaders(header), valueOrRewrite);
  1473. } else if (utils$1.isHeaders(header)) {
  1474. for (const [key, value] of header.entries()) {
  1475. setHeader(value, key, rewrite);
  1476. }
  1477. } else {
  1478. header != null && setHeader(valueOrRewrite, header, rewrite);
  1479. }
  1480. return this;
  1481. }
  1482. get(header, parser) {
  1483. header = normalizeHeader(header);
  1484. if (header) {
  1485. const key = utils$1.findKey(this, header);
  1486. if (key) {
  1487. const value = this[key];
  1488. if (!parser) {
  1489. return value;
  1490. }
  1491. if (parser === true) {
  1492. return parseTokens(value);
  1493. }
  1494. if (utils$1.isFunction(parser)) {
  1495. return parser.call(this, value, key);
  1496. }
  1497. if (utils$1.isRegExp(parser)) {
  1498. return parser.exec(value);
  1499. }
  1500. throw new TypeError('parser must be boolean|regexp|function');
  1501. }
  1502. }
  1503. }
  1504. has(header, matcher) {
  1505. header = normalizeHeader(header);
  1506. if (header) {
  1507. const key = utils$1.findKey(this, header);
  1508. return !!(key && this[key] !== undefined && (!matcher || matchHeaderValue(this, this[key], key, matcher)));
  1509. }
  1510. return false;
  1511. }
  1512. delete(header, matcher) {
  1513. const self = this;
  1514. let deleted = false;
  1515. function deleteHeader(_header) {
  1516. _header = normalizeHeader(_header);
  1517. if (_header) {
  1518. const key = utils$1.findKey(self, _header);
  1519. if (key && (!matcher || matchHeaderValue(self, self[key], key, matcher))) {
  1520. delete self[key];
  1521. deleted = true;
  1522. }
  1523. }
  1524. }
  1525. if (utils$1.isArray(header)) {
  1526. header.forEach(deleteHeader);
  1527. } else {
  1528. deleteHeader(header);
  1529. }
  1530. return deleted;
  1531. }
  1532. clear(matcher) {
  1533. const keys = Object.keys(this);
  1534. let i = keys.length;
  1535. let deleted = false;
  1536. while (i--) {
  1537. const key = keys[i];
  1538. if(!matcher || matchHeaderValue(this, this[key], key, matcher, true)) {
  1539. delete this[key];
  1540. deleted = true;
  1541. }
  1542. }
  1543. return deleted;
  1544. }
  1545. normalize(format) {
  1546. const self = this;
  1547. const headers = {};
  1548. utils$1.forEach(this, (value, header) => {
  1549. const key = utils$1.findKey(headers, header);
  1550. if (key) {
  1551. self[key] = normalizeValue(value);
  1552. delete self[header];
  1553. return;
  1554. }
  1555. const normalized = format ? formatHeader(header) : String(header).trim();
  1556. if (normalized !== header) {
  1557. delete self[header];
  1558. }
  1559. self[normalized] = normalizeValue(value);
  1560. headers[normalized] = true;
  1561. });
  1562. return this;
  1563. }
  1564. concat(...targets) {
  1565. return this.constructor.concat(this, ...targets);
  1566. }
  1567. toJSON(asStrings) {
  1568. const obj = Object.create(null);
  1569. utils$1.forEach(this, (value, header) => {
  1570. value != null && value !== false && (obj[header] = asStrings && utils$1.isArray(value) ? value.join(', ') : value);
  1571. });
  1572. return obj;
  1573. }
  1574. [Symbol.iterator]() {
  1575. return Object.entries(this.toJSON())[Symbol.iterator]();
  1576. }
  1577. toString() {
  1578. return Object.entries(this.toJSON()).map(([header, value]) => header + ': ' + value).join('\n');
  1579. }
  1580. get [Symbol.toStringTag]() {
  1581. return 'AxiosHeaders';
  1582. }
  1583. static from(thing) {
  1584. return thing instanceof this ? thing : new this(thing);
  1585. }
  1586. static concat(first, ...targets) {
  1587. const computed = new this(first);
  1588. targets.forEach((target) => computed.set(target));
  1589. return computed;
  1590. }
  1591. static accessor(header) {
  1592. const internals = this[$internals] = (this[$internals] = {
  1593. accessors: {}
  1594. });
  1595. const accessors = internals.accessors;
  1596. const prototype = this.prototype;
  1597. function defineAccessor(_header) {
  1598. const lHeader = normalizeHeader(_header);
  1599. if (!accessors[lHeader]) {
  1600. buildAccessors(prototype, _header);
  1601. accessors[lHeader] = true;
  1602. }
  1603. }
  1604. utils$1.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header);
  1605. return this;
  1606. }
  1607. }
  1608. AxiosHeaders.accessor(['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent', 'Authorization']);
  1609. // reserved names hotfix
  1610. utils$1.reduceDescriptors(AxiosHeaders.prototype, ({value}, key) => {
  1611. let mapped = key[0].toUpperCase() + key.slice(1); // map `set` => `Set`
  1612. return {
  1613. get: () => value,
  1614. set(headerValue) {
  1615. this[mapped] = headerValue;
  1616. }
  1617. }
  1618. });
  1619. utils$1.freezeMethods(AxiosHeaders);
  1620. var AxiosHeaders$1 = AxiosHeaders;
  1621. /**
  1622. * Transform the data for a request or a response
  1623. *
  1624. * @param {Array|Function} fns A single function or Array of functions
  1625. * @param {?Object} response The response object
  1626. *
  1627. * @returns {*} The resulting transformed data
  1628. */
  1629. function transformData(fns, response) {
  1630. const config = this || defaults$1;
  1631. const context = response || config;
  1632. const headers = AxiosHeaders$1.from(context.headers);
  1633. let data = context.data;
  1634. utils$1.forEach(fns, function transform(fn) {
  1635. data = fn.call(config, data, headers.normalize(), response ? response.status : undefined);
  1636. });
  1637. headers.normalize();
  1638. return data;
  1639. }
  1640. function isCancel(value) {
  1641. return !!(value && value.__CANCEL__);
  1642. }
  1643. /**
  1644. * A `CanceledError` is an object that is thrown when an operation is canceled.
  1645. *
  1646. * @param {string=} message The message.
  1647. * @param {Object=} config The config.
  1648. * @param {Object=} request The request.
  1649. *
  1650. * @returns {CanceledError} The created error.
  1651. */
  1652. function CanceledError(message, config, request) {
  1653. // eslint-disable-next-line no-eq-null,eqeqeq
  1654. AxiosError.call(this, message == null ? 'canceled' : message, AxiosError.ERR_CANCELED, config, request);
  1655. this.name = 'CanceledError';
  1656. }
  1657. utils$1.inherits(CanceledError, AxiosError, {
  1658. __CANCEL__: true
  1659. });
  1660. /**
  1661. * Resolve or reject a Promise based on response status.
  1662. *
  1663. * @param {Function} resolve A function that resolves the promise.
  1664. * @param {Function} reject A function that rejects the promise.
  1665. * @param {object} response The response.
  1666. *
  1667. * @returns {object} The response.
  1668. */
  1669. function settle(resolve, reject, response) {
  1670. const validateStatus = response.config.validateStatus;
  1671. if (!response.status || !validateStatus || validateStatus(response.status)) {
  1672. resolve(response);
  1673. } else {
  1674. reject(new AxiosError(
  1675. 'Request failed with status code ' + response.status,
  1676. [AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4],
  1677. response.config,
  1678. response.request,
  1679. response
  1680. ));
  1681. }
  1682. }
  1683. function parseProtocol(url) {
  1684. const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url);
  1685. return match && match[1] || '';
  1686. }
  1687. /**
  1688. * Calculate data maxRate
  1689. * @param {Number} [samplesCount= 10]
  1690. * @param {Number} [min= 1000]
  1691. * @returns {Function}
  1692. */
  1693. function speedometer(samplesCount, min) {
  1694. samplesCount = samplesCount || 10;
  1695. const bytes = new Array(samplesCount);
  1696. const timestamps = new Array(samplesCount);
  1697. let head = 0;
  1698. let tail = 0;
  1699. let firstSampleTS;
  1700. min = min !== undefined ? min : 1000;
  1701. return function push(chunkLength) {
  1702. const now = Date.now();
  1703. const startedAt = timestamps[tail];
  1704. if (!firstSampleTS) {
  1705. firstSampleTS = now;
  1706. }
  1707. bytes[head] = chunkLength;
  1708. timestamps[head] = now;
  1709. let i = tail;
  1710. let bytesCount = 0;
  1711. while (i !== head) {
  1712. bytesCount += bytes[i++];
  1713. i = i % samplesCount;
  1714. }
  1715. head = (head + 1) % samplesCount;
  1716. if (head === tail) {
  1717. tail = (tail + 1) % samplesCount;
  1718. }
  1719. if (now - firstSampleTS < min) {
  1720. return;
  1721. }
  1722. const passed = startedAt && now - startedAt;
  1723. return passed ? Math.round(bytesCount * 1000 / passed) : undefined;
  1724. };
  1725. }
  1726. /**
  1727. * Throttle decorator
  1728. * @param {Function} fn
  1729. * @param {Number} freq
  1730. * @return {Function}
  1731. */
  1732. function throttle(fn, freq) {
  1733. let timestamp = 0;
  1734. let threshold = 1000 / freq;
  1735. let lastArgs;
  1736. let timer;
  1737. const invoke = (args, now = Date.now()) => {
  1738. timestamp = now;
  1739. lastArgs = null;
  1740. if (timer) {
  1741. clearTimeout(timer);
  1742. timer = null;
  1743. }
  1744. fn.apply(null, args);
  1745. };
  1746. const throttled = (...args) => {
  1747. const now = Date.now();
  1748. const passed = now - timestamp;
  1749. if ( passed >= threshold) {
  1750. invoke(args, now);
  1751. } else {
  1752. lastArgs = args;
  1753. if (!timer) {
  1754. timer = setTimeout(() => {
  1755. timer = null;
  1756. invoke(lastArgs);
  1757. }, threshold - passed);
  1758. }
  1759. }
  1760. };
  1761. const flush = () => lastArgs && invoke(lastArgs);
  1762. return [throttled, flush];
  1763. }
  1764. const progressEventReducer = (listener, isDownloadStream, freq = 3) => {
  1765. let bytesNotified = 0;
  1766. const _speedometer = speedometer(50, 250);
  1767. return throttle(e => {
  1768. const loaded = e.loaded;
  1769. const total = e.lengthComputable ? e.total : undefined;
  1770. const progressBytes = loaded - bytesNotified;
  1771. const rate = _speedometer(progressBytes);
  1772. const inRange = loaded <= total;
  1773. bytesNotified = loaded;
  1774. const data = {
  1775. loaded,
  1776. total,
  1777. progress: total ? (loaded / total) : undefined,
  1778. bytes: progressBytes,
  1779. rate: rate ? rate : undefined,
  1780. estimated: rate && total && inRange ? (total - loaded) / rate : undefined,
  1781. event: e,
  1782. lengthComputable: total != null,
  1783. [isDownloadStream ? 'download' : 'upload']: true
  1784. };
  1785. listener(data);
  1786. }, freq);
  1787. };
  1788. const progressEventDecorator = (total, throttled) => {
  1789. const lengthComputable = total != null;
  1790. return [(loaded) => throttled[0]({
  1791. lengthComputable,
  1792. total,
  1793. loaded
  1794. }), throttled[1]];
  1795. };
  1796. const asyncDecorator = (fn) => (...args) => utils$1.asap(() => fn(...args));
  1797. var isURLSameOrigin = platform.hasStandardBrowserEnv ? ((origin, isMSIE) => (url) => {
  1798. url = new URL(url, platform.origin);
  1799. return (
  1800. origin.protocol === url.protocol &&
  1801. origin.host === url.host &&
  1802. (isMSIE || origin.port === url.port)
  1803. );
  1804. })(
  1805. new URL(platform.origin),
  1806. platform.navigator && /(msie|trident)/i.test(platform.navigator.userAgent)
  1807. ) : () => true;
  1808. var cookies = platform.hasStandardBrowserEnv ?
  1809. // Standard browser envs support document.cookie
  1810. {
  1811. write(name, value, expires, path, domain, secure) {
  1812. const cookie = [name + '=' + encodeURIComponent(value)];
  1813. utils$1.isNumber(expires) && cookie.push('expires=' + new Date(expires).toGMTString());
  1814. utils$1.isString(path) && cookie.push('path=' + path);
  1815. utils$1.isString(domain) && cookie.push('domain=' + domain);
  1816. secure === true && cookie.push('secure');
  1817. document.cookie = cookie.join('; ');
  1818. },
  1819. read(name) {
  1820. const match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
  1821. return (match ? decodeURIComponent(match[3]) : null);
  1822. },
  1823. remove(name) {
  1824. this.write(name, '', Date.now() - 86400000);
  1825. }
  1826. }
  1827. :
  1828. // Non-standard browser env (web workers, react-native) lack needed support.
  1829. {
  1830. write() {},
  1831. read() {
  1832. return null;
  1833. },
  1834. remove() {}
  1835. };
  1836. /**
  1837. * Determines whether the specified URL is absolute
  1838. *
  1839. * @param {string} url The URL to test
  1840. *
  1841. * @returns {boolean} True if the specified URL is absolute, otherwise false
  1842. */
  1843. function isAbsoluteURL(url) {
  1844. // A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
  1845. // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
  1846. // by any combination of letters, digits, plus, period, or hyphen.
  1847. return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url);
  1848. }
  1849. /**
  1850. * Creates a new URL by combining the specified URLs
  1851. *
  1852. * @param {string} baseURL The base URL
  1853. * @param {string} relativeURL The relative URL
  1854. *
  1855. * @returns {string} The combined URL
  1856. */
  1857. function combineURLs(baseURL, relativeURL) {
  1858. return relativeURL
  1859. ? baseURL.replace(/\/?\/$/, '') + '/' + relativeURL.replace(/^\/+/, '')
  1860. : baseURL;
  1861. }
  1862. /**
  1863. * Creates a new URL by combining the baseURL with the requestedURL,
  1864. * only when the requestedURL is not already an absolute URL.
  1865. * If the requestURL is absolute, this function returns the requestedURL untouched.
  1866. *
  1867. * @param {string} baseURL The base URL
  1868. * @param {string} requestedURL Absolute or relative URL to combine
  1869. *
  1870. * @returns {string} The combined full path
  1871. */
  1872. function buildFullPath(baseURL, requestedURL, allowAbsoluteUrls) {
  1873. let isRelativeUrl = !isAbsoluteURL(requestedURL);
  1874. if (baseURL && (isRelativeUrl || allowAbsoluteUrls == false)) {
  1875. return combineURLs(baseURL, requestedURL);
  1876. }
  1877. return requestedURL;
  1878. }
  1879. const headersToObject = (thing) => thing instanceof AxiosHeaders$1 ? { ...thing } : thing;
  1880. /**
  1881. * Config-specific merge-function which creates a new config-object
  1882. * by merging two configuration objects together.
  1883. *
  1884. * @param {Object} config1
  1885. * @param {Object} config2
  1886. *
  1887. * @returns {Object} New object resulting from merging config2 to config1
  1888. */
  1889. function mergeConfig(config1, config2) {
  1890. // eslint-disable-next-line no-param-reassign
  1891. config2 = config2 || {};
  1892. const config = {};
  1893. function getMergedValue(target, source, prop, caseless) {
  1894. if (utils$1.isPlainObject(target) && utils$1.isPlainObject(source)) {
  1895. return utils$1.merge.call({caseless}, target, source);
  1896. } else if (utils$1.isPlainObject(source)) {
  1897. return utils$1.merge({}, source);
  1898. } else if (utils$1.isArray(source)) {
  1899. return source.slice();
  1900. }
  1901. return source;
  1902. }
  1903. // eslint-disable-next-line consistent-return
  1904. function mergeDeepProperties(a, b, prop , caseless) {
  1905. if (!utils$1.isUndefined(b)) {
  1906. return getMergedValue(a, b, prop , caseless);
  1907. } else if (!utils$1.isUndefined(a)) {
  1908. return getMergedValue(undefined, a, prop , caseless);
  1909. }
  1910. }
  1911. // eslint-disable-next-line consistent-return
  1912. function valueFromConfig2(a, b) {
  1913. if (!utils$1.isUndefined(b)) {
  1914. return getMergedValue(undefined, b);
  1915. }
  1916. }
  1917. // eslint-disable-next-line consistent-return
  1918. function defaultToConfig2(a, b) {
  1919. if (!utils$1.isUndefined(b)) {
  1920. return getMergedValue(undefined, b);
  1921. } else if (!utils$1.isUndefined(a)) {
  1922. return getMergedValue(undefined, a);
  1923. }
  1924. }
  1925. // eslint-disable-next-line consistent-return
  1926. function mergeDirectKeys(a, b, prop) {
  1927. if (prop in config2) {
  1928. return getMergedValue(a, b);
  1929. } else if (prop in config1) {
  1930. return getMergedValue(undefined, a);
  1931. }
  1932. }
  1933. const mergeMap = {
  1934. url: valueFromConfig2,
  1935. method: valueFromConfig2,
  1936. data: valueFromConfig2,
  1937. baseURL: defaultToConfig2,
  1938. transformRequest: defaultToConfig2,
  1939. transformResponse: defaultToConfig2,
  1940. paramsSerializer: defaultToConfig2,
  1941. timeout: defaultToConfig2,
  1942. timeoutMessage: defaultToConfig2,
  1943. withCredentials: defaultToConfig2,
  1944. withXSRFToken: defaultToConfig2,
  1945. adapter: defaultToConfig2,
  1946. responseType: defaultToConfig2,
  1947. xsrfCookieName: defaultToConfig2,
  1948. xsrfHeaderName: defaultToConfig2,
  1949. onUploadProgress: defaultToConfig2,
  1950. onDownloadProgress: defaultToConfig2,
  1951. decompress: defaultToConfig2,
  1952. maxContentLength: defaultToConfig2,
  1953. maxBodyLength: defaultToConfig2,
  1954. beforeRedirect: defaultToConfig2,
  1955. transport: defaultToConfig2,
  1956. httpAgent: defaultToConfig2,
  1957. httpsAgent: defaultToConfig2,
  1958. cancelToken: defaultToConfig2,
  1959. socketPath: defaultToConfig2,
  1960. responseEncoding: defaultToConfig2,
  1961. validateStatus: mergeDirectKeys,
  1962. headers: (a, b , prop) => mergeDeepProperties(headersToObject(a), headersToObject(b),prop, true)
  1963. };
  1964. utils$1.forEach(Object.keys(Object.assign({}, config1, config2)), function computeConfigValue(prop) {
  1965. const merge = mergeMap[prop] || mergeDeepProperties;
  1966. const configValue = merge(config1[prop], config2[prop], prop);
  1967. (utils$1.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue);
  1968. });
  1969. return config;
  1970. }
  1971. var resolveConfig = (config) => {
  1972. const newConfig = mergeConfig({}, config);
  1973. let {data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth} = newConfig;
  1974. newConfig.headers = headers = AxiosHeaders$1.from(headers);
  1975. newConfig.url = buildURL(buildFullPath(newConfig.baseURL, newConfig.url, newConfig.allowAbsoluteUrls), config.params, config.paramsSerializer);
  1976. // HTTP basic authentication
  1977. if (auth) {
  1978. headers.set('Authorization', 'Basic ' +
  1979. btoa((auth.username || '') + ':' + (auth.password ? unescape(encodeURIComponent(auth.password)) : ''))
  1980. );
  1981. }
  1982. let contentType;
  1983. if (utils$1.isFormData(data)) {
  1984. if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv) {
  1985. headers.setContentType(undefined); // Let the browser set it
  1986. } else if ((contentType = headers.getContentType()) !== false) {
  1987. // fix semicolon duplication issue for ReactNative FormData implementation
  1988. const [type, ...tokens] = contentType ? contentType.split(';').map(token => token.trim()).filter(Boolean) : [];
  1989. headers.setContentType([type || 'multipart/form-data', ...tokens].join('; '));
  1990. }
  1991. }
  1992. // Add xsrf header
  1993. // This is only done if running in a standard browser environment.
  1994. // Specifically not if we're in a web worker, or react-native.
  1995. if (platform.hasStandardBrowserEnv) {
  1996. withXSRFToken && utils$1.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(newConfig));
  1997. if (withXSRFToken || (withXSRFToken !== false && isURLSameOrigin(newConfig.url))) {
  1998. // Add xsrf header
  1999. const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName);
  2000. if (xsrfValue) {
  2001. headers.set(xsrfHeaderName, xsrfValue);
  2002. }
  2003. }
  2004. }
  2005. return newConfig;
  2006. };
  2007. const isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined';
  2008. var xhrAdapter = isXHRAdapterSupported && function (config) {
  2009. return new Promise(function dispatchXhrRequest(resolve, reject) {
  2010. const _config = resolveConfig(config);
  2011. let requestData = _config.data;
  2012. const requestHeaders = AxiosHeaders$1.from(_config.headers).normalize();
  2013. let {responseType, onUploadProgress, onDownloadProgress} = _config;
  2014. let onCanceled;
  2015. let uploadThrottled, downloadThrottled;
  2016. let flushUpload, flushDownload;
  2017. function done() {
  2018. flushUpload && flushUpload(); // flush events
  2019. flushDownload && flushDownload(); // flush events
  2020. _config.cancelToken && _config.cancelToken.unsubscribe(onCanceled);
  2021. _config.signal && _config.signal.removeEventListener('abort', onCanceled);
  2022. }
  2023. let request = new XMLHttpRequest();
  2024. request.open(_config.method.toUpperCase(), _config.url, true);
  2025. // Set the request timeout in MS
  2026. request.timeout = _config.timeout;
  2027. function onloadend() {
  2028. if (!request) {
  2029. return;
  2030. }
  2031. // Prepare the response
  2032. const responseHeaders = AxiosHeaders$1.from(
  2033. 'getAllResponseHeaders' in request && request.getAllResponseHeaders()
  2034. );
  2035. const responseData = !responseType || responseType === 'text' || responseType === 'json' ?
  2036. request.responseText : request.response;
  2037. const response = {
  2038. data: responseData,
  2039. status: request.status,
  2040. statusText: request.statusText,
  2041. headers: responseHeaders,
  2042. config,
  2043. request
  2044. };
  2045. settle(function _resolve(value) {
  2046. resolve(value);
  2047. done();
  2048. }, function _reject(err) {
  2049. reject(err);
  2050. done();
  2051. }, response);
  2052. // Clean up request
  2053. request = null;
  2054. }
  2055. if ('onloadend' in request) {
  2056. // Use onloadend if available
  2057. request.onloadend = onloadend;
  2058. } else {
  2059. // Listen for ready state to emulate onloadend
  2060. request.onreadystatechange = function handleLoad() {
  2061. if (!request || request.readyState !== 4) {
  2062. return;
  2063. }
  2064. // The request errored out and we didn't get a response, this will be
  2065. // handled by onerror instead
  2066. // With one exception: request that using file: protocol, most browsers
  2067. // will return status as 0 even though it's a successful request
  2068. if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {
  2069. return;
  2070. }
  2071. // readystate handler is calling before onerror or ontimeout handlers,
  2072. // so we should call onloadend on the next 'tick'
  2073. setTimeout(onloadend);
  2074. };
  2075. }
  2076. // Handle browser request cancellation (as opposed to a manual cancellation)
  2077. request.onabort = function handleAbort() {
  2078. if (!request) {
  2079. return;
  2080. }
  2081. reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request));
  2082. // Clean up request
  2083. request = null;
  2084. };
  2085. // Handle low level network errors
  2086. request.onerror = function handleError() {
  2087. // Real errors are hidden from us by the browser
  2088. // onerror should only fire if it's a network error
  2089. reject(new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request));
  2090. // Clean up request
  2091. request = null;
  2092. };
  2093. // Handle timeout
  2094. request.ontimeout = function handleTimeout() {
  2095. let timeoutErrorMessage = _config.timeout ? 'timeout of ' + _config.timeout + 'ms exceeded' : 'timeout exceeded';
  2096. const transitional = _config.transitional || transitionalDefaults;
  2097. if (_config.timeoutErrorMessage) {
  2098. timeoutErrorMessage = _config.timeoutErrorMessage;
  2099. }
  2100. reject(new AxiosError(
  2101. timeoutErrorMessage,
  2102. transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED,
  2103. config,
  2104. request));
  2105. // Clean up request
  2106. request = null;
  2107. };
  2108. // Remove Content-Type if data is undefined
  2109. requestData === undefined && requestHeaders.setContentType(null);
  2110. // Add headers to the request
  2111. if ('setRequestHeader' in request) {
  2112. utils$1.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) {
  2113. request.setRequestHeader(key, val);
  2114. });
  2115. }
  2116. // Add withCredentials to request if needed
  2117. if (!utils$1.isUndefined(_config.withCredentials)) {
  2118. request.withCredentials = !!_config.withCredentials;
  2119. }
  2120. // Add responseType to request if needed
  2121. if (responseType && responseType !== 'json') {
  2122. request.responseType = _config.responseType;
  2123. }
  2124. // Handle progress if needed
  2125. if (onDownloadProgress) {
  2126. ([downloadThrottled, flushDownload] = progressEventReducer(onDownloadProgress, true));
  2127. request.addEventListener('progress', downloadThrottled);
  2128. }
  2129. // Not all browsers support upload events
  2130. if (onUploadProgress && request.upload) {
  2131. ([uploadThrottled, flushUpload] = progressEventReducer(onUploadProgress));
  2132. request.upload.addEventListener('progress', uploadThrottled);
  2133. request.upload.addEventListener('loadend', flushUpload);
  2134. }
  2135. if (_config.cancelToken || _config.signal) {
  2136. // Handle cancellation
  2137. // eslint-disable-next-line func-names
  2138. onCanceled = cancel => {
  2139. if (!request) {
  2140. return;
  2141. }
  2142. reject(!cancel || cancel.type ? new CanceledError(null, config, request) : cancel);
  2143. request.abort();
  2144. request = null;
  2145. };
  2146. _config.cancelToken && _config.cancelToken.subscribe(onCanceled);
  2147. if (_config.signal) {
  2148. _config.signal.aborted ? onCanceled() : _config.signal.addEventListener('abort', onCanceled);
  2149. }
  2150. }
  2151. const protocol = parseProtocol(_config.url);
  2152. if (protocol && platform.protocols.indexOf(protocol) === -1) {
  2153. reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config));
  2154. return;
  2155. }
  2156. // Send the request
  2157. request.send(requestData || null);
  2158. });
  2159. };
  2160. const composeSignals = (signals, timeout) => {
  2161. const {length} = (signals = signals ? signals.filter(Boolean) : []);
  2162. if (timeout || length) {
  2163. let controller = new AbortController();
  2164. let aborted;
  2165. const onabort = function (reason) {
  2166. if (!aborted) {
  2167. aborted = true;
  2168. unsubscribe();
  2169. const err = reason instanceof Error ? reason : this.reason;
  2170. controller.abort(err instanceof AxiosError ? err : new CanceledError(err instanceof Error ? err.message : err));
  2171. }
  2172. };
  2173. let timer = timeout && setTimeout(() => {
  2174. timer = null;
  2175. onabort(new AxiosError(`timeout ${timeout} of ms exceeded`, AxiosError.ETIMEDOUT));
  2176. }, timeout);
  2177. const unsubscribe = () => {
  2178. if (signals) {
  2179. timer && clearTimeout(timer);
  2180. timer = null;
  2181. signals.forEach(signal => {
  2182. signal.unsubscribe ? signal.unsubscribe(onabort) : signal.removeEventListener('abort', onabort);
  2183. });
  2184. signals = null;
  2185. }
  2186. };
  2187. signals.forEach((signal) => signal.addEventListener('abort', onabort));
  2188. const {signal} = controller;
  2189. signal.unsubscribe = () => utils$1.asap(unsubscribe);
  2190. return signal;
  2191. }
  2192. };
  2193. var composeSignals$1 = composeSignals;
  2194. const streamChunk = function* (chunk, chunkSize) {
  2195. let len = chunk.byteLength;
  2196. if (!chunkSize || len < chunkSize) {
  2197. yield chunk;
  2198. return;
  2199. }
  2200. let pos = 0;
  2201. let end;
  2202. while (pos < len) {
  2203. end = pos + chunkSize;
  2204. yield chunk.slice(pos, end);
  2205. pos = end;
  2206. }
  2207. };
  2208. const readBytes = async function* (iterable, chunkSize) {
  2209. for await (const chunk of readStream(iterable)) {
  2210. yield* streamChunk(chunk, chunkSize);
  2211. }
  2212. };
  2213. const readStream = async function* (stream) {
  2214. if (stream[Symbol.asyncIterator]) {
  2215. yield* stream;
  2216. return;
  2217. }
  2218. const reader = stream.getReader();
  2219. try {
  2220. for (;;) {
  2221. const {done, value} = await reader.read();
  2222. if (done) {
  2223. break;
  2224. }
  2225. yield value;
  2226. }
  2227. } finally {
  2228. await reader.cancel();
  2229. }
  2230. };
  2231. const trackStream = (stream, chunkSize, onProgress, onFinish) => {
  2232. const iterator = readBytes(stream, chunkSize);
  2233. let bytes = 0;
  2234. let done;
  2235. let _onFinish = (e) => {
  2236. if (!done) {
  2237. done = true;
  2238. onFinish && onFinish(e);
  2239. }
  2240. };
  2241. return new ReadableStream({
  2242. async pull(controller) {
  2243. try {
  2244. const {done, value} = await iterator.next();
  2245. if (done) {
  2246. _onFinish();
  2247. controller.close();
  2248. return;
  2249. }
  2250. let len = value.byteLength;
  2251. if (onProgress) {
  2252. let loadedBytes = bytes += len;
  2253. onProgress(loadedBytes);
  2254. }
  2255. controller.enqueue(new Uint8Array(value));
  2256. } catch (err) {
  2257. _onFinish(err);
  2258. throw err;
  2259. }
  2260. },
  2261. cancel(reason) {
  2262. _onFinish(reason);
  2263. return iterator.return();
  2264. }
  2265. }, {
  2266. highWaterMark: 2
  2267. })
  2268. };
  2269. const isFetchSupported = typeof fetch === 'function' && typeof Request === 'function' && typeof Response === 'function';
  2270. const isReadableStreamSupported = isFetchSupported && typeof ReadableStream === 'function';
  2271. // used only inside the fetch adapter
  2272. const encodeText = isFetchSupported && (typeof TextEncoder === 'function' ?
  2273. ((encoder) => (str) => encoder.encode(str))(new TextEncoder()) :
  2274. async (str) => new Uint8Array(await new Response(str).arrayBuffer())
  2275. );
  2276. const test = (fn, ...args) => {
  2277. try {
  2278. return !!fn(...args);
  2279. } catch (e) {
  2280. return false
  2281. }
  2282. };
  2283. const supportsRequestStream = isReadableStreamSupported && test(() => {
  2284. let duplexAccessed = false;
  2285. const hasContentType = new Request(platform.origin, {
  2286. body: new ReadableStream(),
  2287. method: 'POST',
  2288. get duplex() {
  2289. duplexAccessed = true;
  2290. return 'half';
  2291. },
  2292. }).headers.has('Content-Type');
  2293. return duplexAccessed && !hasContentType;
  2294. });
  2295. const DEFAULT_CHUNK_SIZE = 64 * 1024;
  2296. const supportsResponseStream = isReadableStreamSupported &&
  2297. test(() => utils$1.isReadableStream(new Response('').body));
  2298. const resolvers = {
  2299. stream: supportsResponseStream && ((res) => res.body)
  2300. };
  2301. isFetchSupported && (((res) => {
  2302. ['text', 'arrayBuffer', 'blob', 'formData', 'stream'].forEach(type => {
  2303. !resolvers[type] && (resolvers[type] = utils$1.isFunction(res[type]) ? (res) => res[type]() :
  2304. (_, config) => {
  2305. throw new AxiosError(`Response type '${type}' is not supported`, AxiosError.ERR_NOT_SUPPORT, config);
  2306. });
  2307. });
  2308. })(new Response));
  2309. const getBodyLength = async (body) => {
  2310. if (body == null) {
  2311. return 0;
  2312. }
  2313. if(utils$1.isBlob(body)) {
  2314. return body.size;
  2315. }
  2316. if(utils$1.isSpecCompliantForm(body)) {
  2317. const _request = new Request(platform.origin, {
  2318. method: 'POST',
  2319. body,
  2320. });
  2321. return (await _request.arrayBuffer()).byteLength;
  2322. }
  2323. if(utils$1.isArrayBufferView(body) || utils$1.isArrayBuffer(body)) {
  2324. return body.byteLength;
  2325. }
  2326. if(utils$1.isURLSearchParams(body)) {
  2327. body = body + '';
  2328. }
  2329. if(utils$1.isString(body)) {
  2330. return (await encodeText(body)).byteLength;
  2331. }
  2332. };
  2333. const resolveBodyLength = async (headers, body) => {
  2334. const length = utils$1.toFiniteNumber(headers.getContentLength());
  2335. return length == null ? getBodyLength(body) : length;
  2336. };
  2337. var fetchAdapter = isFetchSupported && (async (config) => {
  2338. let {
  2339. url,
  2340. method,
  2341. data,
  2342. signal,
  2343. cancelToken,
  2344. timeout,
  2345. onDownloadProgress,
  2346. onUploadProgress,
  2347. responseType,
  2348. headers,
  2349. withCredentials = 'same-origin',
  2350. fetchOptions
  2351. } = resolveConfig(config);
  2352. responseType = responseType ? (responseType + '').toLowerCase() : 'text';
  2353. let composedSignal = composeSignals$1([signal, cancelToken && cancelToken.toAbortSignal()], timeout);
  2354. let request;
  2355. const unsubscribe = composedSignal && composedSignal.unsubscribe && (() => {
  2356. composedSignal.unsubscribe();
  2357. });
  2358. let requestContentLength;
  2359. try {
  2360. if (
  2361. onUploadProgress && supportsRequestStream && method !== 'get' && method !== 'head' &&
  2362. (requestContentLength = await resolveBodyLength(headers, data)) !== 0
  2363. ) {
  2364. let _request = new Request(url, {
  2365. method: 'POST',
  2366. body: data,
  2367. duplex: "half"
  2368. });
  2369. let contentTypeHeader;
  2370. if (utils$1.isFormData(data) && (contentTypeHeader = _request.headers.get('content-type'))) {
  2371. headers.setContentType(contentTypeHeader);
  2372. }
  2373. if (_request.body) {
  2374. const [onProgress, flush] = progressEventDecorator(
  2375. requestContentLength,
  2376. progressEventReducer(asyncDecorator(onUploadProgress))
  2377. );
  2378. data = trackStream(_request.body, DEFAULT_CHUNK_SIZE, onProgress, flush);
  2379. }
  2380. }
  2381. if (!utils$1.isString(withCredentials)) {
  2382. withCredentials = withCredentials ? 'include' : 'omit';
  2383. }
  2384. // Cloudflare Workers throws when credentials are defined
  2385. // see https://github.com/cloudflare/workerd/issues/902
  2386. const isCredentialsSupported = "credentials" in Request.prototype;
  2387. request = new Request(url, {
  2388. ...fetchOptions,
  2389. signal: composedSignal,
  2390. method: method.toUpperCase(),
  2391. headers: headers.normalize().toJSON(),
  2392. body: data,
  2393. duplex: "half",
  2394. credentials: isCredentialsSupported ? withCredentials : undefined
  2395. });
  2396. let response = await fetch(request);
  2397. const isStreamResponse = supportsResponseStream && (responseType === 'stream' || responseType === 'response');
  2398. if (supportsResponseStream && (onDownloadProgress || (isStreamResponse && unsubscribe))) {
  2399. const options = {};
  2400. ['status', 'statusText', 'headers'].forEach(prop => {
  2401. options[prop] = response[prop];
  2402. });
  2403. const responseContentLength = utils$1.toFiniteNumber(response.headers.get('content-length'));
  2404. const [onProgress, flush] = onDownloadProgress && progressEventDecorator(
  2405. responseContentLength,
  2406. progressEventReducer(asyncDecorator(onDownloadProgress), true)
  2407. ) || [];
  2408. response = new Response(
  2409. trackStream(response.body, DEFAULT_CHUNK_SIZE, onProgress, () => {
  2410. flush && flush();
  2411. unsubscribe && unsubscribe();
  2412. }),
  2413. options
  2414. );
  2415. }
  2416. responseType = responseType || 'text';
  2417. let responseData = await resolvers[utils$1.findKey(resolvers, responseType) || 'text'](response, config);
  2418. !isStreamResponse && unsubscribe && unsubscribe();
  2419. return await new Promise((resolve, reject) => {
  2420. settle(resolve, reject, {
  2421. data: responseData,
  2422. headers: AxiosHeaders$1.from(response.headers),
  2423. status: response.status,
  2424. statusText: response.statusText,
  2425. config,
  2426. request
  2427. });
  2428. })
  2429. } catch (err) {
  2430. unsubscribe && unsubscribe();
  2431. if (err && err.name === 'TypeError' && /fetch/i.test(err.message)) {
  2432. throw Object.assign(
  2433. new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request),
  2434. {
  2435. cause: err.cause || err
  2436. }
  2437. )
  2438. }
  2439. throw AxiosError.from(err, err && err.code, config, request);
  2440. }
  2441. });
  2442. const knownAdapters = {
  2443. http: httpAdapter,
  2444. xhr: xhrAdapter,
  2445. fetch: fetchAdapter
  2446. };
  2447. utils$1.forEach(knownAdapters, (fn, value) => {
  2448. if (fn) {
  2449. try {
  2450. Object.defineProperty(fn, 'name', {value});
  2451. } catch (e) {
  2452. // eslint-disable-next-line no-empty
  2453. }
  2454. Object.defineProperty(fn, 'adapterName', {value});
  2455. }
  2456. });
  2457. const renderReason = (reason) => `- ${reason}`;
  2458. const isResolvedHandle = (adapter) => utils$1.isFunction(adapter) || adapter === null || adapter === false;
  2459. var adapters = {
  2460. getAdapter: (adapters) => {
  2461. adapters = utils$1.isArray(adapters) ? adapters : [adapters];
  2462. const {length} = adapters;
  2463. let nameOrAdapter;
  2464. let adapter;
  2465. const rejectedReasons = {};
  2466. for (let i = 0; i < length; i++) {
  2467. nameOrAdapter = adapters[i];
  2468. let id;
  2469. adapter = nameOrAdapter;
  2470. if (!isResolvedHandle(nameOrAdapter)) {
  2471. adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()];
  2472. if (adapter === undefined) {
  2473. throw new AxiosError(`Unknown adapter '${id}'`);
  2474. }
  2475. }
  2476. if (adapter) {
  2477. break;
  2478. }
  2479. rejectedReasons[id || '#' + i] = adapter;
  2480. }
  2481. if (!adapter) {
  2482. const reasons = Object.entries(rejectedReasons)
  2483. .map(([id, state]) => `adapter ${id} ` +
  2484. (state === false ? 'is not supported by the environment' : 'is not available in the build')
  2485. );
  2486. let s = length ?
  2487. (reasons.length > 1 ? 'since :\n' + reasons.map(renderReason).join('\n') : ' ' + renderReason(reasons[0])) :
  2488. 'as no adapter specified';
  2489. throw new AxiosError(
  2490. `There is no suitable adapter to dispatch the request ` + s,
  2491. 'ERR_NOT_SUPPORT'
  2492. );
  2493. }
  2494. return adapter;
  2495. },
  2496. adapters: knownAdapters
  2497. };
  2498. /**
  2499. * Throws a `CanceledError` if cancellation has been requested.
  2500. *
  2501. * @param {Object} config The config that is to be used for the request
  2502. *
  2503. * @returns {void}
  2504. */
  2505. function throwIfCancellationRequested(config) {
  2506. if (config.cancelToken) {
  2507. config.cancelToken.throwIfRequested();
  2508. }
  2509. if (config.signal && config.signal.aborted) {
  2510. throw new CanceledError(null, config);
  2511. }
  2512. }
  2513. /**
  2514. * Dispatch a request to the server using the configured adapter.
  2515. *
  2516. * @param {object} config The config that is to be used for the request
  2517. *
  2518. * @returns {Promise} The Promise to be fulfilled
  2519. */
  2520. function dispatchRequest(config) {
  2521. throwIfCancellationRequested(config);
  2522. config.headers = AxiosHeaders$1.from(config.headers);
  2523. // Transform request data
  2524. config.data = transformData.call(
  2525. config,
  2526. config.transformRequest
  2527. );
  2528. if (['post', 'put', 'patch'].indexOf(config.method) !== -1) {
  2529. config.headers.setContentType('application/x-www-form-urlencoded', false);
  2530. }
  2531. const adapter = adapters.getAdapter(config.adapter || defaults$1.adapter);
  2532. return adapter(config).then(function onAdapterResolution(response) {
  2533. throwIfCancellationRequested(config);
  2534. // Transform response data
  2535. response.data = transformData.call(
  2536. config,
  2537. config.transformResponse,
  2538. response
  2539. );
  2540. response.headers = AxiosHeaders$1.from(response.headers);
  2541. return response;
  2542. }, function onAdapterRejection(reason) {
  2543. if (!isCancel(reason)) {
  2544. throwIfCancellationRequested(config);
  2545. // Transform response data
  2546. if (reason && reason.response) {
  2547. reason.response.data = transformData.call(
  2548. config,
  2549. config.transformResponse,
  2550. reason.response
  2551. );
  2552. reason.response.headers = AxiosHeaders$1.from(reason.response.headers);
  2553. }
  2554. }
  2555. return Promise.reject(reason);
  2556. });
  2557. }
  2558. const VERSION = "1.8.4";
  2559. const validators$1 = {};
  2560. // eslint-disable-next-line func-names
  2561. ['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach((type, i) => {
  2562. validators$1[type] = function validator(thing) {
  2563. return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type;
  2564. };
  2565. });
  2566. const deprecatedWarnings = {};
  2567. /**
  2568. * Transitional option validator
  2569. *
  2570. * @param {function|boolean?} validator - set to false if the transitional option has been removed
  2571. * @param {string?} version - deprecated version / removed since version
  2572. * @param {string?} message - some message with additional info
  2573. *
  2574. * @returns {function}
  2575. */
  2576. validators$1.transitional = function transitional(validator, version, message) {
  2577. function formatMessage(opt, desc) {
  2578. return '[Axios v' + VERSION + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : '');
  2579. }
  2580. // eslint-disable-next-line func-names
  2581. return (value, opt, opts) => {
  2582. if (validator === false) {
  2583. throw new AxiosError(
  2584. formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')),
  2585. AxiosError.ERR_DEPRECATED
  2586. );
  2587. }
  2588. if (version && !deprecatedWarnings[opt]) {
  2589. deprecatedWarnings[opt] = true;
  2590. // eslint-disable-next-line no-console
  2591. console.warn(
  2592. formatMessage(
  2593. opt,
  2594. ' has been deprecated since v' + version + ' and will be removed in the near future'
  2595. )
  2596. );
  2597. }
  2598. return validator ? validator(value, opt, opts) : true;
  2599. };
  2600. };
  2601. validators$1.spelling = function spelling(correctSpelling) {
  2602. return (value, opt) => {
  2603. // eslint-disable-next-line no-console
  2604. console.warn(`${opt} is likely a misspelling of ${correctSpelling}`);
  2605. return true;
  2606. }
  2607. };
  2608. /**
  2609. * Assert object's properties type
  2610. *
  2611. * @param {object} options
  2612. * @param {object} schema
  2613. * @param {boolean?} allowUnknown
  2614. *
  2615. * @returns {object}
  2616. */
  2617. function assertOptions(options, schema, allowUnknown) {
  2618. if (typeof options !== 'object') {
  2619. throw new AxiosError('options must be an object', AxiosError.ERR_BAD_OPTION_VALUE);
  2620. }
  2621. const keys = Object.keys(options);
  2622. let i = keys.length;
  2623. while (i-- > 0) {
  2624. const opt = keys[i];
  2625. const validator = schema[opt];
  2626. if (validator) {
  2627. const value = options[opt];
  2628. const result = value === undefined || validator(value, opt, options);
  2629. if (result !== true) {
  2630. throw new AxiosError('option ' + opt + ' must be ' + result, AxiosError.ERR_BAD_OPTION_VALUE);
  2631. }
  2632. continue;
  2633. }
  2634. if (allowUnknown !== true) {
  2635. throw new AxiosError('Unknown option ' + opt, AxiosError.ERR_BAD_OPTION);
  2636. }
  2637. }
  2638. }
  2639. var validator = {
  2640. assertOptions,
  2641. validators: validators$1
  2642. };
  2643. const validators = validator.validators;
  2644. /**
  2645. * Create a new instance of Axios
  2646. *
  2647. * @param {Object} instanceConfig The default config for the instance
  2648. *
  2649. * @return {Axios} A new instance of Axios
  2650. */
  2651. class Axios {
  2652. constructor(instanceConfig) {
  2653. this.defaults = instanceConfig;
  2654. this.interceptors = {
  2655. request: new InterceptorManager$1(),
  2656. response: new InterceptorManager$1()
  2657. };
  2658. }
  2659. /**
  2660. * Dispatch a request
  2661. *
  2662. * @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults)
  2663. * @param {?Object} config
  2664. *
  2665. * @returns {Promise} The Promise to be fulfilled
  2666. */
  2667. async request(configOrUrl, config) {
  2668. try {
  2669. return await this._request(configOrUrl, config);
  2670. } catch (err) {
  2671. if (err instanceof Error) {
  2672. let dummy = {};
  2673. Error.captureStackTrace ? Error.captureStackTrace(dummy) : (dummy = new Error());
  2674. // slice off the Error: ... line
  2675. const stack = dummy.stack ? dummy.stack.replace(/^.+\n/, '') : '';
  2676. try {
  2677. if (!err.stack) {
  2678. err.stack = stack;
  2679. // match without the 2 top stack lines
  2680. } else if (stack && !String(err.stack).endsWith(stack.replace(/^.+\n.+\n/, ''))) {
  2681. err.stack += '\n' + stack;
  2682. }
  2683. } catch (e) {
  2684. // ignore the case where "stack" is an un-writable property
  2685. }
  2686. }
  2687. throw err;
  2688. }
  2689. }
  2690. _request(configOrUrl, config) {
  2691. /*eslint no-param-reassign:0*/
  2692. // Allow for axios('example/url'[, config]) a la fetch API
  2693. if (typeof configOrUrl === 'string') {
  2694. config = config || {};
  2695. config.url = configOrUrl;
  2696. } else {
  2697. config = configOrUrl || {};
  2698. }
  2699. config = mergeConfig(this.defaults, config);
  2700. const {transitional, paramsSerializer, headers} = config;
  2701. if (transitional !== undefined) {
  2702. validator.assertOptions(transitional, {
  2703. silentJSONParsing: validators.transitional(validators.boolean),
  2704. forcedJSONParsing: validators.transitional(validators.boolean),
  2705. clarifyTimeoutError: validators.transitional(validators.boolean)
  2706. }, false);
  2707. }
  2708. if (paramsSerializer != null) {
  2709. if (utils$1.isFunction(paramsSerializer)) {
  2710. config.paramsSerializer = {
  2711. serialize: paramsSerializer
  2712. };
  2713. } else {
  2714. validator.assertOptions(paramsSerializer, {
  2715. encode: validators.function,
  2716. serialize: validators.function
  2717. }, true);
  2718. }
  2719. }
  2720. // Set config.allowAbsoluteUrls
  2721. if (config.allowAbsoluteUrls !== undefined) ; else if (this.defaults.allowAbsoluteUrls !== undefined) {
  2722. config.allowAbsoluteUrls = this.defaults.allowAbsoluteUrls;
  2723. } else {
  2724. config.allowAbsoluteUrls = true;
  2725. }
  2726. validator.assertOptions(config, {
  2727. baseUrl: validators.spelling('baseURL'),
  2728. withXsrfToken: validators.spelling('withXSRFToken')
  2729. }, true);
  2730. // Set config.method
  2731. config.method = (config.method || this.defaults.method || 'get').toLowerCase();
  2732. // Flatten headers
  2733. let contextHeaders = headers && utils$1.merge(
  2734. headers.common,
  2735. headers[config.method]
  2736. );
  2737. headers && utils$1.forEach(
  2738. ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
  2739. (method) => {
  2740. delete headers[method];
  2741. }
  2742. );
  2743. config.headers = AxiosHeaders$1.concat(contextHeaders, headers);
  2744. // filter out skipped interceptors
  2745. const requestInterceptorChain = [];
  2746. let synchronousRequestInterceptors = true;
  2747. this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
  2748. if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {
  2749. return;
  2750. }
  2751. synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
  2752. requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
  2753. });
  2754. const responseInterceptorChain = [];
  2755. this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
  2756. responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
  2757. });
  2758. let promise;
  2759. let i = 0;
  2760. let len;
  2761. if (!synchronousRequestInterceptors) {
  2762. const chain = [dispatchRequest.bind(this), undefined];
  2763. chain.unshift.apply(chain, requestInterceptorChain);
  2764. chain.push.apply(chain, responseInterceptorChain);
  2765. len = chain.length;
  2766. promise = Promise.resolve(config);
  2767. while (i < len) {
  2768. promise = promise.then(chain[i++], chain[i++]);
  2769. }
  2770. return promise;
  2771. }
  2772. len = requestInterceptorChain.length;
  2773. let newConfig = config;
  2774. i = 0;
  2775. while (i < len) {
  2776. const onFulfilled = requestInterceptorChain[i++];
  2777. const onRejected = requestInterceptorChain[i++];
  2778. try {
  2779. newConfig = onFulfilled(newConfig);
  2780. } catch (error) {
  2781. onRejected.call(this, error);
  2782. break;
  2783. }
  2784. }
  2785. try {
  2786. promise = dispatchRequest.call(this, newConfig);
  2787. } catch (error) {
  2788. return Promise.reject(error);
  2789. }
  2790. i = 0;
  2791. len = responseInterceptorChain.length;
  2792. while (i < len) {
  2793. promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);
  2794. }
  2795. return promise;
  2796. }
  2797. getUri(config) {
  2798. config = mergeConfig(this.defaults, config);
  2799. const fullPath = buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls);
  2800. return buildURL(fullPath, config.params, config.paramsSerializer);
  2801. }
  2802. }
  2803. // Provide aliases for supported request methods
  2804. utils$1.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
  2805. /*eslint func-names:0*/
  2806. Axios.prototype[method] = function(url, config) {
  2807. return this.request(mergeConfig(config || {}, {
  2808. method,
  2809. url,
  2810. data: (config || {}).data
  2811. }));
  2812. };
  2813. });
  2814. utils$1.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
  2815. /*eslint func-names:0*/
  2816. function generateHTTPMethod(isForm) {
  2817. return function httpMethod(url, data, config) {
  2818. return this.request(mergeConfig(config || {}, {
  2819. method,
  2820. headers: isForm ? {
  2821. 'Content-Type': 'multipart/form-data'
  2822. } : {},
  2823. url,
  2824. data
  2825. }));
  2826. };
  2827. }
  2828. Axios.prototype[method] = generateHTTPMethod();
  2829. Axios.prototype[method + 'Form'] = generateHTTPMethod(true);
  2830. });
  2831. var Axios$1 = Axios;
  2832. /**
  2833. * A `CancelToken` is an object that can be used to request cancellation of an operation.
  2834. *
  2835. * @param {Function} executor The executor function.
  2836. *
  2837. * @returns {CancelToken}
  2838. */
  2839. class CancelToken {
  2840. constructor(executor) {
  2841. if (typeof executor !== 'function') {
  2842. throw new TypeError('executor must be a function.');
  2843. }
  2844. let resolvePromise;
  2845. this.promise = new Promise(function promiseExecutor(resolve) {
  2846. resolvePromise = resolve;
  2847. });
  2848. const token = this;
  2849. // eslint-disable-next-line func-names
  2850. this.promise.then(cancel => {
  2851. if (!token._listeners) return;
  2852. let i = token._listeners.length;
  2853. while (i-- > 0) {
  2854. token._listeners[i](cancel);
  2855. }
  2856. token._listeners = null;
  2857. });
  2858. // eslint-disable-next-line func-names
  2859. this.promise.then = onfulfilled => {
  2860. let _resolve;
  2861. // eslint-disable-next-line func-names
  2862. const promise = new Promise(resolve => {
  2863. token.subscribe(resolve);
  2864. _resolve = resolve;
  2865. }).then(onfulfilled);
  2866. promise.cancel = function reject() {
  2867. token.unsubscribe(_resolve);
  2868. };
  2869. return promise;
  2870. };
  2871. executor(function cancel(message, config, request) {
  2872. if (token.reason) {
  2873. // Cancellation has already been requested
  2874. return;
  2875. }
  2876. token.reason = new CanceledError(message, config, request);
  2877. resolvePromise(token.reason);
  2878. });
  2879. }
  2880. /**
  2881. * Throws a `CanceledError` if cancellation has been requested.
  2882. */
  2883. throwIfRequested() {
  2884. if (this.reason) {
  2885. throw this.reason;
  2886. }
  2887. }
  2888. /**
  2889. * Subscribe to the cancel signal
  2890. */
  2891. subscribe(listener) {
  2892. if (this.reason) {
  2893. listener(this.reason);
  2894. return;
  2895. }
  2896. if (this._listeners) {
  2897. this._listeners.push(listener);
  2898. } else {
  2899. this._listeners = [listener];
  2900. }
  2901. }
  2902. /**
  2903. * Unsubscribe from the cancel signal
  2904. */
  2905. unsubscribe(listener) {
  2906. if (!this._listeners) {
  2907. return;
  2908. }
  2909. const index = this._listeners.indexOf(listener);
  2910. if (index !== -1) {
  2911. this._listeners.splice(index, 1);
  2912. }
  2913. }
  2914. toAbortSignal() {
  2915. const controller = new AbortController();
  2916. const abort = (err) => {
  2917. controller.abort(err);
  2918. };
  2919. this.subscribe(abort);
  2920. controller.signal.unsubscribe = () => this.unsubscribe(abort);
  2921. return controller.signal;
  2922. }
  2923. /**
  2924. * Returns an object that contains a new `CancelToken` and a function that, when called,
  2925. * cancels the `CancelToken`.
  2926. */
  2927. static source() {
  2928. let cancel;
  2929. const token = new CancelToken(function executor(c) {
  2930. cancel = c;
  2931. });
  2932. return {
  2933. token,
  2934. cancel
  2935. };
  2936. }
  2937. }
  2938. var CancelToken$1 = CancelToken;
  2939. /**
  2940. * Syntactic sugar for invoking a function and expanding an array for arguments.
  2941. *
  2942. * Common use case would be to use `Function.prototype.apply`.
  2943. *
  2944. * ```js
  2945. * function f(x, y, z) {}
  2946. * var args = [1, 2, 3];
  2947. * f.apply(null, args);
  2948. * ```
  2949. *
  2950. * With `spread` this example can be re-written.
  2951. *
  2952. * ```js
  2953. * spread(function(x, y, z) {})([1, 2, 3]);
  2954. * ```
  2955. *
  2956. * @param {Function} callback
  2957. *
  2958. * @returns {Function}
  2959. */
  2960. function spread(callback) {
  2961. return function wrap(arr) {
  2962. return callback.apply(null, arr);
  2963. };
  2964. }
  2965. /**
  2966. * Determines whether the payload is an error thrown by Axios
  2967. *
  2968. * @param {*} payload The value to test
  2969. *
  2970. * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
  2971. */
  2972. function isAxiosError(payload) {
  2973. return utils$1.isObject(payload) && (payload.isAxiosError === true);
  2974. }
  2975. const HttpStatusCode = {
  2976. Continue: 100,
  2977. SwitchingProtocols: 101,
  2978. Processing: 102,
  2979. EarlyHints: 103,
  2980. Ok: 200,
  2981. Created: 201,
  2982. Accepted: 202,
  2983. NonAuthoritativeInformation: 203,
  2984. NoContent: 204,
  2985. ResetContent: 205,
  2986. PartialContent: 206,
  2987. MultiStatus: 207,
  2988. AlreadyReported: 208,
  2989. ImUsed: 226,
  2990. MultipleChoices: 300,
  2991. MovedPermanently: 301,
  2992. Found: 302,
  2993. SeeOther: 303,
  2994. NotModified: 304,
  2995. UseProxy: 305,
  2996. Unused: 306,
  2997. TemporaryRedirect: 307,
  2998. PermanentRedirect: 308,
  2999. BadRequest: 400,
  3000. Unauthorized: 401,
  3001. PaymentRequired: 402,
  3002. Forbidden: 403,
  3003. NotFound: 404,
  3004. MethodNotAllowed: 405,
  3005. NotAcceptable: 406,
  3006. ProxyAuthenticationRequired: 407,
  3007. RequestTimeout: 408,
  3008. Conflict: 409,
  3009. Gone: 410,
  3010. LengthRequired: 411,
  3011. PreconditionFailed: 412,
  3012. PayloadTooLarge: 413,
  3013. UriTooLong: 414,
  3014. UnsupportedMediaType: 415,
  3015. RangeNotSatisfiable: 416,
  3016. ExpectationFailed: 417,
  3017. ImATeapot: 418,
  3018. MisdirectedRequest: 421,
  3019. UnprocessableEntity: 422,
  3020. Locked: 423,
  3021. FailedDependency: 424,
  3022. TooEarly: 425,
  3023. UpgradeRequired: 426,
  3024. PreconditionRequired: 428,
  3025. TooManyRequests: 429,
  3026. RequestHeaderFieldsTooLarge: 431,
  3027. UnavailableForLegalReasons: 451,
  3028. InternalServerError: 500,
  3029. NotImplemented: 501,
  3030. BadGateway: 502,
  3031. ServiceUnavailable: 503,
  3032. GatewayTimeout: 504,
  3033. HttpVersionNotSupported: 505,
  3034. VariantAlsoNegotiates: 506,
  3035. InsufficientStorage: 507,
  3036. LoopDetected: 508,
  3037. NotExtended: 510,
  3038. NetworkAuthenticationRequired: 511,
  3039. };
  3040. Object.entries(HttpStatusCode).forEach(([key, value]) => {
  3041. HttpStatusCode[value] = key;
  3042. });
  3043. var HttpStatusCode$1 = HttpStatusCode;
  3044. /**
  3045. * Create an instance of Axios
  3046. *
  3047. * @param {Object} defaultConfig The default config for the instance
  3048. *
  3049. * @returns {Axios} A new instance of Axios
  3050. */
  3051. function createInstance(defaultConfig) {
  3052. const context = new Axios$1(defaultConfig);
  3053. const instance = bind(Axios$1.prototype.request, context);
  3054. // Copy axios.prototype to instance
  3055. utils$1.extend(instance, Axios$1.prototype, context, {allOwnKeys: true});
  3056. // Copy context to instance
  3057. utils$1.extend(instance, context, null, {allOwnKeys: true});
  3058. // Factory for creating new instances
  3059. instance.create = function create(instanceConfig) {
  3060. return createInstance(mergeConfig(defaultConfig, instanceConfig));
  3061. };
  3062. return instance;
  3063. }
  3064. // Create the default instance to be exported
  3065. const axios = createInstance(defaults$1);
  3066. // Expose Axios class to allow class inheritance
  3067. axios.Axios = Axios$1;
  3068. // Expose Cancel & CancelToken
  3069. axios.CanceledError = CanceledError;
  3070. axios.CancelToken = CancelToken$1;
  3071. axios.isCancel = isCancel;
  3072. axios.VERSION = VERSION;
  3073. axios.toFormData = toFormData;
  3074. // Expose AxiosError class
  3075. axios.AxiosError = AxiosError;
  3076. // alias for CanceledError for backward compatibility
  3077. axios.Cancel = axios.CanceledError;
  3078. // Expose all/spread
  3079. axios.all = function all(promises) {
  3080. return Promise.all(promises);
  3081. };
  3082. axios.spread = spread;
  3083. // Expose isAxiosError
  3084. axios.isAxiosError = isAxiosError;
  3085. // Expose mergeConfig
  3086. axios.mergeConfig = mergeConfig;
  3087. axios.AxiosHeaders = AxiosHeaders$1;
  3088. axios.formToJSON = thing => formDataToJSON(utils$1.isHTMLForm(thing) ? new FormData(thing) : thing);
  3089. axios.getAdapter = adapters.getAdapter;
  3090. axios.HttpStatusCode = HttpStatusCode$1;
  3091. axios.default = axios;
  3092. module.exports = axios;
  3093. //# sourceMappingURL=axios.cjs.map