source: imaps-frontend/node_modules/axios/dist/node/axios.cjs@ d565449

main
Last change on this file since d565449 was d565449, checked in by stefan toskovski <stefantoska84@…>, 4 weeks ago

Update repo after prototype presentation

  • Property mode set to 100644
File size: 126.4 KB
RevLine 
[d565449]1// Axios v1.7.7 Copyright (c) 2024 Matt Zabriskie and contributors
2'use strict';
3
4const FormData$1 = require('form-data');
5const url = require('url');
6const proxyFromEnv = require('proxy-from-env');
7const http = require('http');
8const https = require('https');
9const util = require('util');
10const followRedirects = require('follow-redirects');
11const zlib = require('zlib');
12const stream = require('stream');
13const events = require('events');
14
15function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
16
17const FormData__default = /*#__PURE__*/_interopDefaultLegacy(FormData$1);
18const url__default = /*#__PURE__*/_interopDefaultLegacy(url);
19const http__default = /*#__PURE__*/_interopDefaultLegacy(http);
20const https__default = /*#__PURE__*/_interopDefaultLegacy(https);
21const util__default = /*#__PURE__*/_interopDefaultLegacy(util);
22const followRedirects__default = /*#__PURE__*/_interopDefaultLegacy(followRedirects);
23const zlib__default = /*#__PURE__*/_interopDefaultLegacy(zlib);
24const stream__default = /*#__PURE__*/_interopDefaultLegacy(stream);
25
26function bind(fn, thisArg) {
27 return function wrap() {
28 return fn.apply(thisArg, arguments);
29 };
30}
31
32// utils is a library of generic helper functions non-specific to axios
33
34const {toString} = Object.prototype;
35const {getPrototypeOf} = Object;
36
37const kindOf = (cache => thing => {
38 const str = toString.call(thing);
39 return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
40})(Object.create(null));
41
42const kindOfTest = (type) => {
43 type = type.toLowerCase();
44 return (thing) => kindOf(thing) === type
45};
46
47const typeOfTest = type => thing => typeof thing === type;
48
49/**
50 * Determine if a value is an Array
51 *
52 * @param {Object} val The value to test
53 *
54 * @returns {boolean} True if value is an Array, otherwise false
55 */
56const {isArray} = Array;
57
58/**
59 * Determine if a value is undefined
60 *
61 * @param {*} val The value to test
62 *
63 * @returns {boolean} True if the value is undefined, otherwise false
64 */
65const isUndefined = typeOfTest('undefined');
66
67/**
68 * Determine if a value is a Buffer
69 *
70 * @param {*} val The value to test
71 *
72 * @returns {boolean} True if value is a Buffer, otherwise false
73 */
74function isBuffer(val) {
75 return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)
76 && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val);
77}
78
79/**
80 * Determine if a value is an ArrayBuffer
81 *
82 * @param {*} val The value to test
83 *
84 * @returns {boolean} True if value is an ArrayBuffer, otherwise false
85 */
86const isArrayBuffer = kindOfTest('ArrayBuffer');
87
88
89/**
90 * Determine if a value is a view on an ArrayBuffer
91 *
92 * @param {*} val The value to test
93 *
94 * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
95 */
96function isArrayBufferView(val) {
97 let result;
98 if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {
99 result = ArrayBuffer.isView(val);
100 } else {
101 result = (val) && (val.buffer) && (isArrayBuffer(val.buffer));
102 }
103 return result;
104}
105
106/**
107 * Determine if a value is a String
108 *
109 * @param {*} val The value to test
110 *
111 * @returns {boolean} True if value is a String, otherwise false
112 */
113const isString = typeOfTest('string');
114
115/**
116 * Determine if a value is a Function
117 *
118 * @param {*} val The value to test
119 * @returns {boolean} True if value is a Function, otherwise false
120 */
121const isFunction = typeOfTest('function');
122
123/**
124 * Determine if a value is a Number
125 *
126 * @param {*} val The value to test
127 *
128 * @returns {boolean} True if value is a Number, otherwise false
129 */
130const isNumber = typeOfTest('number');
131
132/**
133 * Determine if a value is an Object
134 *
135 * @param {*} thing The value to test
136 *
137 * @returns {boolean} True if value is an Object, otherwise false
138 */
139const isObject = (thing) => thing !== null && typeof thing === 'object';
140
141/**
142 * Determine if a value is a Boolean
143 *
144 * @param {*} thing The value to test
145 * @returns {boolean} True if value is a Boolean, otherwise false
146 */
147const isBoolean = thing => thing === true || thing === false;
148
149/**
150 * Determine if a value is a plain Object
151 *
152 * @param {*} val The value to test
153 *
154 * @returns {boolean} True if value is a plain Object, otherwise false
155 */
156const isPlainObject = (val) => {
157 if (kindOf(val) !== 'object') {
158 return false;
159 }
160
161 const prototype = getPrototypeOf(val);
162 return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in val) && !(Symbol.iterator in val);
163};
164
165/**
166 * Determine if a value is a Date
167 *
168 * @param {*} val The value to test
169 *
170 * @returns {boolean} True if value is a Date, otherwise false
171 */
172const isDate = kindOfTest('Date');
173
174/**
175 * Determine if a value is a File
176 *
177 * @param {*} val The value to test
178 *
179 * @returns {boolean} True if value is a File, otherwise false
180 */
181const isFile = kindOfTest('File');
182
183/**
184 * Determine if a value is a Blob
185 *
186 * @param {*} val The value to test
187 *
188 * @returns {boolean} True if value is a Blob, otherwise false
189 */
190const isBlob = kindOfTest('Blob');
191
192/**
193 * Determine if a value is a FileList
194 *
195 * @param {*} val The value to test
196 *
197 * @returns {boolean} True if value is a File, otherwise false
198 */
199const isFileList = kindOfTest('FileList');
200
201/**
202 * Determine if a value is a Stream
203 *
204 * @param {*} val The value to test
205 *
206 * @returns {boolean} True if value is a Stream, otherwise false
207 */
208const isStream = (val) => isObject(val) && isFunction(val.pipe);
209
210/**
211 * Determine if a value is a FormData
212 *
213 * @param {*} thing The value to test
214 *
215 * @returns {boolean} True if value is an FormData, otherwise false
216 */
217const isFormData = (thing) => {
218 let kind;
219 return thing && (
220 (typeof FormData === 'function' && thing instanceof FormData) || (
221 isFunction(thing.append) && (
222 (kind = kindOf(thing)) === 'formdata' ||
223 // detect form-data instance
224 (kind === 'object' && isFunction(thing.toString) && thing.toString() === '[object FormData]')
225 )
226 )
227 )
228};
229
230/**
231 * Determine if a value is a URLSearchParams object
232 *
233 * @param {*} val The value to test
234 *
235 * @returns {boolean} True if value is a URLSearchParams object, otherwise false
236 */
237const isURLSearchParams = kindOfTest('URLSearchParams');
238
239const [isReadableStream, isRequest, isResponse, isHeaders] = ['ReadableStream', 'Request', 'Response', 'Headers'].map(kindOfTest);
240
241/**
242 * Trim excess whitespace off the beginning and end of a string
243 *
244 * @param {String} str The String to trim
245 *
246 * @returns {String} The String freed of excess whitespace
247 */
248const trim = (str) => str.trim ?
249 str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
250
251/**
252 * Iterate over an Array or an Object invoking a function for each item.
253 *
254 * If `obj` is an Array callback will be called passing
255 * the value, index, and complete array for each item.
256 *
257 * If 'obj' is an Object callback will be called passing
258 * the value, key, and complete object for each property.
259 *
260 * @param {Object|Array} obj The object to iterate
261 * @param {Function} fn The callback to invoke for each item
262 *
263 * @param {Boolean} [allOwnKeys = false]
264 * @returns {any}
265 */
266function forEach(obj, fn, {allOwnKeys = false} = {}) {
267 // Don't bother if no value provided
268 if (obj === null || typeof obj === 'undefined') {
269 return;
270 }
271
272 let i;
273 let l;
274
275 // Force an array if not already something iterable
276 if (typeof obj !== 'object') {
277 /*eslint no-param-reassign:0*/
278 obj = [obj];
279 }
280
281 if (isArray(obj)) {
282 // Iterate over array values
283 for (i = 0, l = obj.length; i < l; i++) {
284 fn.call(null, obj[i], i, obj);
285 }
286 } else {
287 // Iterate over object keys
288 const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);
289 const len = keys.length;
290 let key;
291
292 for (i = 0; i < len; i++) {
293 key = keys[i];
294 fn.call(null, obj[key], key, obj);
295 }
296 }
297}
298
299function findKey(obj, key) {
300 key = key.toLowerCase();
301 const keys = Object.keys(obj);
302 let i = keys.length;
303 let _key;
304 while (i-- > 0) {
305 _key = keys[i];
306 if (key === _key.toLowerCase()) {
307 return _key;
308 }
309 }
310 return null;
311}
312
313const _global = (() => {
314 /*eslint no-undef:0*/
315 if (typeof globalThis !== "undefined") return globalThis;
316 return typeof self !== "undefined" ? self : (typeof window !== 'undefined' ? window : global)
317})();
318
319const isContextDefined = (context) => !isUndefined(context) && context !== _global;
320
321/**
322 * Accepts varargs expecting each argument to be an object, then
323 * immutably merges the properties of each object and returns result.
324 *
325 * When multiple objects contain the same key the later object in
326 * the arguments list will take precedence.
327 *
328 * Example:
329 *
330 * ```js
331 * var result = merge({foo: 123}, {foo: 456});
332 * console.log(result.foo); // outputs 456
333 * ```
334 *
335 * @param {Object} obj1 Object to merge
336 *
337 * @returns {Object} Result of all merge properties
338 */
339function merge(/* obj1, obj2, obj3, ... */) {
340 const {caseless} = isContextDefined(this) && this || {};
341 const result = {};
342 const assignValue = (val, key) => {
343 const targetKey = caseless && findKey(result, key) || key;
344 if (isPlainObject(result[targetKey]) && isPlainObject(val)) {
345 result[targetKey] = merge(result[targetKey], val);
346 } else if (isPlainObject(val)) {
347 result[targetKey] = merge({}, val);
348 } else if (isArray(val)) {
349 result[targetKey] = val.slice();
350 } else {
351 result[targetKey] = val;
352 }
353 };
354
355 for (let i = 0, l = arguments.length; i < l; i++) {
356 arguments[i] && forEach(arguments[i], assignValue);
357 }
358 return result;
359}
360
361/**
362 * Extends object a by mutably adding to it the properties of object b.
363 *
364 * @param {Object} a The object to be extended
365 * @param {Object} b The object to copy properties from
366 * @param {Object} thisArg The object to bind function to
367 *
368 * @param {Boolean} [allOwnKeys]
369 * @returns {Object} The resulting value of object a
370 */
371const extend = (a, b, thisArg, {allOwnKeys}= {}) => {
372 forEach(b, (val, key) => {
373 if (thisArg && isFunction(val)) {
374 a[key] = bind(val, thisArg);
375 } else {
376 a[key] = val;
377 }
378 }, {allOwnKeys});
379 return a;
380};
381
382/**
383 * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
384 *
385 * @param {string} content with BOM
386 *
387 * @returns {string} content value without BOM
388 */
389const stripBOM = (content) => {
390 if (content.charCodeAt(0) === 0xFEFF) {
391 content = content.slice(1);
392 }
393 return content;
394};
395
396/**
397 * Inherit the prototype methods from one constructor into another
398 * @param {function} constructor
399 * @param {function} superConstructor
400 * @param {object} [props]
401 * @param {object} [descriptors]
402 *
403 * @returns {void}
404 */
405const inherits = (constructor, superConstructor, props, descriptors) => {
406 constructor.prototype = Object.create(superConstructor.prototype, descriptors);
407 constructor.prototype.constructor = constructor;
408 Object.defineProperty(constructor, 'super', {
409 value: superConstructor.prototype
410 });
411 props && Object.assign(constructor.prototype, props);
412};
413
414/**
415 * Resolve object with deep prototype chain to a flat object
416 * @param {Object} sourceObj source object
417 * @param {Object} [destObj]
418 * @param {Function|Boolean} [filter]
419 * @param {Function} [propFilter]
420 *
421 * @returns {Object}
422 */
423const toFlatObject = (sourceObj, destObj, filter, propFilter) => {
424 let props;
425 let i;
426 let prop;
427 const merged = {};
428
429 destObj = destObj || {};
430 // eslint-disable-next-line no-eq-null,eqeqeq
431 if (sourceObj == null) return destObj;
432
433 do {
434 props = Object.getOwnPropertyNames(sourceObj);
435 i = props.length;
436 while (i-- > 0) {
437 prop = props[i];
438 if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {
439 destObj[prop] = sourceObj[prop];
440 merged[prop] = true;
441 }
442 }
443 sourceObj = filter !== false && getPrototypeOf(sourceObj);
444 } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);
445
446 return destObj;
447};
448
449/**
450 * Determines whether a string ends with the characters of a specified string
451 *
452 * @param {String} str
453 * @param {String} searchString
454 * @param {Number} [position= 0]
455 *
456 * @returns {boolean}
457 */
458const endsWith = (str, searchString, position) => {
459 str = String(str);
460 if (position === undefined || position > str.length) {
461 position = str.length;
462 }
463 position -= searchString.length;
464 const lastIndex = str.indexOf(searchString, position);
465 return lastIndex !== -1 && lastIndex === position;
466};
467
468
469/**
470 * Returns new array from array like object or null if failed
471 *
472 * @param {*} [thing]
473 *
474 * @returns {?Array}
475 */
476const toArray = (thing) => {
477 if (!thing) return null;
478 if (isArray(thing)) return thing;
479 let i = thing.length;
480 if (!isNumber(i)) return null;
481 const arr = new Array(i);
482 while (i-- > 0) {
483 arr[i] = thing[i];
484 }
485 return arr;
486};
487
488/**
489 * Checking if the Uint8Array exists and if it does, it returns a function that checks if the
490 * thing passed in is an instance of Uint8Array
491 *
492 * @param {TypedArray}
493 *
494 * @returns {Array}
495 */
496// eslint-disable-next-line func-names
497const isTypedArray = (TypedArray => {
498 // eslint-disable-next-line func-names
499 return thing => {
500 return TypedArray && thing instanceof TypedArray;
501 };
502})(typeof Uint8Array !== 'undefined' && getPrototypeOf(Uint8Array));
503
504/**
505 * For each entry in the object, call the function with the key and value.
506 *
507 * @param {Object<any, any>} obj - The object to iterate over.
508 * @param {Function} fn - The function to call for each entry.
509 *
510 * @returns {void}
511 */
512const forEachEntry = (obj, fn) => {
513 const generator = obj && obj[Symbol.iterator];
514
515 const iterator = generator.call(obj);
516
517 let result;
518
519 while ((result = iterator.next()) && !result.done) {
520 const pair = result.value;
521 fn.call(obj, pair[0], pair[1]);
522 }
523};
524
525/**
526 * It takes a regular expression and a string, and returns an array of all the matches
527 *
528 * @param {string} regExp - The regular expression to match against.
529 * @param {string} str - The string to search.
530 *
531 * @returns {Array<boolean>}
532 */
533const matchAll = (regExp, str) => {
534 let matches;
535 const arr = [];
536
537 while ((matches = regExp.exec(str)) !== null) {
538 arr.push(matches);
539 }
540
541 return arr;
542};
543
544/* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */
545const isHTMLForm = kindOfTest('HTMLFormElement');
546
547const toCamelCase = str => {
548 return str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,
549 function replacer(m, p1, p2) {
550 return p1.toUpperCase() + p2;
551 }
552 );
553};
554
555/* Creating a function that will check if an object has a property. */
556const hasOwnProperty = (({hasOwnProperty}) => (obj, prop) => hasOwnProperty.call(obj, prop))(Object.prototype);
557
558/**
559 * Determine if a value is a RegExp object
560 *
561 * @param {*} val The value to test
562 *
563 * @returns {boolean} True if value is a RegExp object, otherwise false
564 */
565const isRegExp = kindOfTest('RegExp');
566
567const reduceDescriptors = (obj, reducer) => {
568 const descriptors = Object.getOwnPropertyDescriptors(obj);
569 const reducedDescriptors = {};
570
571 forEach(descriptors, (descriptor, name) => {
572 let ret;
573 if ((ret = reducer(descriptor, name, obj)) !== false) {
574 reducedDescriptors[name] = ret || descriptor;
575 }
576 });
577
578 Object.defineProperties(obj, reducedDescriptors);
579};
580
581/**
582 * Makes all methods read-only
583 * @param {Object} obj
584 */
585
586const freezeMethods = (obj) => {
587 reduceDescriptors(obj, (descriptor, name) => {
588 // skip restricted props in strict mode
589 if (isFunction(obj) && ['arguments', 'caller', 'callee'].indexOf(name) !== -1) {
590 return false;
591 }
592
593 const value = obj[name];
594
595 if (!isFunction(value)) return;
596
597 descriptor.enumerable = false;
598
599 if ('writable' in descriptor) {
600 descriptor.writable = false;
601 return;
602 }
603
604 if (!descriptor.set) {
605 descriptor.set = () => {
606 throw Error('Can not rewrite read-only method \'' + name + '\'');
607 };
608 }
609 });
610};
611
612const toObjectSet = (arrayOrString, delimiter) => {
613 const obj = {};
614
615 const define = (arr) => {
616 arr.forEach(value => {
617 obj[value] = true;
618 });
619 };
620
621 isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter));
622
623 return obj;
624};
625
626const noop = () => {};
627
628const toFiniteNumber = (value, defaultValue) => {
629 return value != null && Number.isFinite(value = +value) ? value : defaultValue;
630};
631
632const ALPHA = 'abcdefghijklmnopqrstuvwxyz';
633
634const DIGIT = '0123456789';
635
636const ALPHABET = {
637 DIGIT,
638 ALPHA,
639 ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT
640};
641
642const generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT) => {
643 let str = '';
644 const {length} = alphabet;
645 while (size--) {
646 str += alphabet[Math.random() * length|0];
647 }
648
649 return str;
650};
651
652/**
653 * If the thing is a FormData object, return true, otherwise return false.
654 *
655 * @param {unknown} thing - The thing to check.
656 *
657 * @returns {boolean}
658 */
659function isSpecCompliantForm(thing) {
660 return !!(thing && isFunction(thing.append) && thing[Symbol.toStringTag] === 'FormData' && thing[Symbol.iterator]);
661}
662
663const toJSONObject = (obj) => {
664 const stack = new Array(10);
665
666 const visit = (source, i) => {
667
668 if (isObject(source)) {
669 if (stack.indexOf(source) >= 0) {
670 return;
671 }
672
673 if(!('toJSON' in source)) {
674 stack[i] = source;
675 const target = isArray(source) ? [] : {};
676
677 forEach(source, (value, key) => {
678 const reducedValue = visit(value, i + 1);
679 !isUndefined(reducedValue) && (target[key] = reducedValue);
680 });
681
682 stack[i] = undefined;
683
684 return target;
685 }
686 }
687
688 return source;
689 };
690
691 return visit(obj, 0);
692};
693
694const isAsyncFn = kindOfTest('AsyncFunction');
695
696const isThenable = (thing) =>
697 thing && (isObject(thing) || isFunction(thing)) && isFunction(thing.then) && isFunction(thing.catch);
698
699// original code
700// https://github.com/DigitalBrainJS/AxiosPromise/blob/16deab13710ec09779922131f3fa5954320f83ab/lib/utils.js#L11-L34
701
702const _setImmediate = ((setImmediateSupported, postMessageSupported) => {
703 if (setImmediateSupported) {
704 return setImmediate;
705 }
706
707 return postMessageSupported ? ((token, callbacks) => {
708 _global.addEventListener("message", ({source, data}) => {
709 if (source === _global && data === token) {
710 callbacks.length && callbacks.shift()();
711 }
712 }, false);
713
714 return (cb) => {
715 callbacks.push(cb);
716 _global.postMessage(token, "*");
717 }
718 })(`axios@${Math.random()}`, []) : (cb) => setTimeout(cb);
719})(
720 typeof setImmediate === 'function',
721 isFunction(_global.postMessage)
722);
723
724const asap = typeof queueMicrotask !== 'undefined' ?
725 queueMicrotask.bind(_global) : ( typeof process !== 'undefined' && process.nextTick || _setImmediate);
726
727// *********************
728
729const utils$1 = {
730 isArray,
731 isArrayBuffer,
732 isBuffer,
733 isFormData,
734 isArrayBufferView,
735 isString,
736 isNumber,
737 isBoolean,
738 isObject,
739 isPlainObject,
740 isReadableStream,
741 isRequest,
742 isResponse,
743 isHeaders,
744 isUndefined,
745 isDate,
746 isFile,
747 isBlob,
748 isRegExp,
749 isFunction,
750 isStream,
751 isURLSearchParams,
752 isTypedArray,
753 isFileList,
754 forEach,
755 merge,
756 extend,
757 trim,
758 stripBOM,
759 inherits,
760 toFlatObject,
761 kindOf,
762 kindOfTest,
763 endsWith,
764 toArray,
765 forEachEntry,
766 matchAll,
767 isHTMLForm,
768 hasOwnProperty,
769 hasOwnProp: hasOwnProperty, // an alias to avoid ESLint no-prototype-builtins detection
770 reduceDescriptors,
771 freezeMethods,
772 toObjectSet,
773 toCamelCase,
774 noop,
775 toFiniteNumber,
776 findKey,
777 global: _global,
778 isContextDefined,
779 ALPHABET,
780 generateString,
781 isSpecCompliantForm,
782 toJSONObject,
783 isAsyncFn,
784 isThenable,
785 setImmediate: _setImmediate,
786 asap
787};
788
789/**
790 * Create an Error with the specified message, config, error code, request and response.
791 *
792 * @param {string} message The error message.
793 * @param {string} [code] The error code (for example, 'ECONNABORTED').
794 * @param {Object} [config] The config.
795 * @param {Object} [request] The request.
796 * @param {Object} [response] The response.
797 *
798 * @returns {Error} The created error.
799 */
800function AxiosError(message, code, config, request, response) {
801 Error.call(this);
802
803 if (Error.captureStackTrace) {
804 Error.captureStackTrace(this, this.constructor);
805 } else {
806 this.stack = (new Error()).stack;
807 }
808
809 this.message = message;
810 this.name = 'AxiosError';
811 code && (this.code = code);
812 config && (this.config = config);
813 request && (this.request = request);
814 if (response) {
815 this.response = response;
816 this.status = response.status ? response.status : null;
817 }
818}
819
820utils$1.inherits(AxiosError, Error, {
821 toJSON: function toJSON() {
822 return {
823 // Standard
824 message: this.message,
825 name: this.name,
826 // Microsoft
827 description: this.description,
828 number: this.number,
829 // Mozilla
830 fileName: this.fileName,
831 lineNumber: this.lineNumber,
832 columnNumber: this.columnNumber,
833 stack: this.stack,
834 // Axios
835 config: utils$1.toJSONObject(this.config),
836 code: this.code,
837 status: this.status
838 };
839 }
840});
841
842const prototype$1 = AxiosError.prototype;
843const descriptors = {};
844
845[
846 'ERR_BAD_OPTION_VALUE',
847 'ERR_BAD_OPTION',
848 'ECONNABORTED',
849 'ETIMEDOUT',
850 'ERR_NETWORK',
851 'ERR_FR_TOO_MANY_REDIRECTS',
852 'ERR_DEPRECATED',
853 'ERR_BAD_RESPONSE',
854 'ERR_BAD_REQUEST',
855 'ERR_CANCELED',
856 'ERR_NOT_SUPPORT',
857 'ERR_INVALID_URL'
858// eslint-disable-next-line func-names
859].forEach(code => {
860 descriptors[code] = {value: code};
861});
862
863Object.defineProperties(AxiosError, descriptors);
864Object.defineProperty(prototype$1, 'isAxiosError', {value: true});
865
866// eslint-disable-next-line func-names
867AxiosError.from = (error, code, config, request, response, customProps) => {
868 const axiosError = Object.create(prototype$1);
869
870 utils$1.toFlatObject(error, axiosError, function filter(obj) {
871 return obj !== Error.prototype;
872 }, prop => {
873 return prop !== 'isAxiosError';
874 });
875
876 AxiosError.call(axiosError, error.message, code, config, request, response);
877
878 axiosError.cause = error;
879
880 axiosError.name = error.name;
881
882 customProps && Object.assign(axiosError, customProps);
883
884 return axiosError;
885};
886
887/**
888 * Determines if the given thing is a array or js object.
889 *
890 * @param {string} thing - The object or array to be visited.
891 *
892 * @returns {boolean}
893 */
894function isVisitable(thing) {
895 return utils$1.isPlainObject(thing) || utils$1.isArray(thing);
896}
897
898/**
899 * It removes the brackets from the end of a string
900 *
901 * @param {string} key - The key of the parameter.
902 *
903 * @returns {string} the key without the brackets.
904 */
905function removeBrackets(key) {
906 return utils$1.endsWith(key, '[]') ? key.slice(0, -2) : key;
907}
908
909/**
910 * It takes a path, a key, and a boolean, and returns a string
911 *
912 * @param {string} path - The path to the current key.
913 * @param {string} key - The key of the current object being iterated over.
914 * @param {string} dots - If true, the key will be rendered with dots instead of brackets.
915 *
916 * @returns {string} The path to the current key.
917 */
918function renderKey(path, key, dots) {
919 if (!path) return key;
920 return path.concat(key).map(function each(token, i) {
921 // eslint-disable-next-line no-param-reassign
922 token = removeBrackets(token);
923 return !dots && i ? '[' + token + ']' : token;
924 }).join(dots ? '.' : '');
925}
926
927/**
928 * If the array is an array and none of its elements are visitable, then it's a flat array.
929 *
930 * @param {Array<any>} arr - The array to check
931 *
932 * @returns {boolean}
933 */
934function isFlatArray(arr) {
935 return utils$1.isArray(arr) && !arr.some(isVisitable);
936}
937
938const predicates = utils$1.toFlatObject(utils$1, {}, null, function filter(prop) {
939 return /^is[A-Z]/.test(prop);
940});
941
942/**
943 * Convert a data object to FormData
944 *
945 * @param {Object} obj
946 * @param {?Object} [formData]
947 * @param {?Object} [options]
948 * @param {Function} [options.visitor]
949 * @param {Boolean} [options.metaTokens = true]
950 * @param {Boolean} [options.dots = false]
951 * @param {?Boolean} [options.indexes = false]
952 *
953 * @returns {Object}
954 **/
955
956/**
957 * It converts an object into a FormData object
958 *
959 * @param {Object<any, any>} obj - The object to convert to form data.
960 * @param {string} formData - The FormData object to append to.
961 * @param {Object<string, any>} options
962 *
963 * @returns
964 */
965function toFormData(obj, formData, options) {
966 if (!utils$1.isObject(obj)) {
967 throw new TypeError('target must be an object');
968 }
969
970 // eslint-disable-next-line no-param-reassign
971 formData = formData || new (FormData__default["default"] || FormData)();
972
973 // eslint-disable-next-line no-param-reassign
974 options = utils$1.toFlatObject(options, {
975 metaTokens: true,
976 dots: false,
977 indexes: false
978 }, false, function defined(option, source) {
979 // eslint-disable-next-line no-eq-null,eqeqeq
980 return !utils$1.isUndefined(source[option]);
981 });
982
983 const metaTokens = options.metaTokens;
984 // eslint-disable-next-line no-use-before-define
985 const visitor = options.visitor || defaultVisitor;
986 const dots = options.dots;
987 const indexes = options.indexes;
988 const _Blob = options.Blob || typeof Blob !== 'undefined' && Blob;
989 const useBlob = _Blob && utils$1.isSpecCompliantForm(formData);
990
991 if (!utils$1.isFunction(visitor)) {
992 throw new TypeError('visitor must be a function');
993 }
994
995 function convertValue(value) {
996 if (value === null) return '';
997
998 if (utils$1.isDate(value)) {
999 return value.toISOString();
1000 }
1001
1002 if (!useBlob && utils$1.isBlob(value)) {
1003 throw new AxiosError('Blob is not supported. Use a Buffer instead.');
1004 }
1005
1006 if (utils$1.isArrayBuffer(value) || utils$1.isTypedArray(value)) {
1007 return useBlob && typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value);
1008 }
1009
1010 return value;
1011 }
1012
1013 /**
1014 * Default visitor.
1015 *
1016 * @param {*} value
1017 * @param {String|Number} key
1018 * @param {Array<String|Number>} path
1019 * @this {FormData}
1020 *
1021 * @returns {boolean} return true to visit the each prop of the value recursively
1022 */
1023 function defaultVisitor(value, key, path) {
1024 let arr = value;
1025
1026 if (value && !path && typeof value === 'object') {
1027 if (utils$1.endsWith(key, '{}')) {
1028 // eslint-disable-next-line no-param-reassign
1029 key = metaTokens ? key : key.slice(0, -2);
1030 // eslint-disable-next-line no-param-reassign
1031 value = JSON.stringify(value);
1032 } else if (
1033 (utils$1.isArray(value) && isFlatArray(value)) ||
1034 ((utils$1.isFileList(value) || utils$1.endsWith(key, '[]')) && (arr = utils$1.toArray(value))
1035 )) {
1036 // eslint-disable-next-line no-param-reassign
1037 key = removeBrackets(key);
1038
1039 arr.forEach(function each(el, index) {
1040 !(utils$1.isUndefined(el) || el === null) && formData.append(
1041 // eslint-disable-next-line no-nested-ternary
1042 indexes === true ? renderKey([key], index, dots) : (indexes === null ? key : key + '[]'),
1043 convertValue(el)
1044 );
1045 });
1046 return false;
1047 }
1048 }
1049
1050 if (isVisitable(value)) {
1051 return true;
1052 }
1053
1054 formData.append(renderKey(path, key, dots), convertValue(value));
1055
1056 return false;
1057 }
1058
1059 const stack = [];
1060
1061 const exposedHelpers = Object.assign(predicates, {
1062 defaultVisitor,
1063 convertValue,
1064 isVisitable
1065 });
1066
1067 function build(value, path) {
1068 if (utils$1.isUndefined(value)) return;
1069
1070 if (stack.indexOf(value) !== -1) {
1071 throw Error('Circular reference detected in ' + path.join('.'));
1072 }
1073
1074 stack.push(value);
1075
1076 utils$1.forEach(value, function each(el, key) {
1077 const result = !(utils$1.isUndefined(el) || el === null) && visitor.call(
1078 formData, el, utils$1.isString(key) ? key.trim() : key, path, exposedHelpers
1079 );
1080
1081 if (result === true) {
1082 build(el, path ? path.concat(key) : [key]);
1083 }
1084 });
1085
1086 stack.pop();
1087 }
1088
1089 if (!utils$1.isObject(obj)) {
1090 throw new TypeError('data must be an object');
1091 }
1092
1093 build(obj);
1094
1095 return formData;
1096}
1097
1098/**
1099 * It encodes a string by replacing all characters that are not in the unreserved set with
1100 * their percent-encoded equivalents
1101 *
1102 * @param {string} str - The string to encode.
1103 *
1104 * @returns {string} The encoded string.
1105 */
1106function encode$1(str) {
1107 const charMap = {
1108 '!': '%21',
1109 "'": '%27',
1110 '(': '%28',
1111 ')': '%29',
1112 '~': '%7E',
1113 '%20': '+',
1114 '%00': '\x00'
1115 };
1116 return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) {
1117 return charMap[match];
1118 });
1119}
1120
1121/**
1122 * It takes a params object and converts it to a FormData object
1123 *
1124 * @param {Object<string, any>} params - The parameters to be converted to a FormData object.
1125 * @param {Object<string, any>} options - The options object passed to the Axios constructor.
1126 *
1127 * @returns {void}
1128 */
1129function AxiosURLSearchParams(params, options) {
1130 this._pairs = [];
1131
1132 params && toFormData(params, this, options);
1133}
1134
1135const prototype = AxiosURLSearchParams.prototype;
1136
1137prototype.append = function append(name, value) {
1138 this._pairs.push([name, value]);
1139};
1140
1141prototype.toString = function toString(encoder) {
1142 const _encode = encoder ? function(value) {
1143 return encoder.call(this, value, encode$1);
1144 } : encode$1;
1145
1146 return this._pairs.map(function each(pair) {
1147 return _encode(pair[0]) + '=' + _encode(pair[1]);
1148 }, '').join('&');
1149};
1150
1151/**
1152 * It replaces all instances of the characters `:`, `$`, `,`, `+`, `[`, and `]` with their
1153 * URI encoded counterparts
1154 *
1155 * @param {string} val The value to be encoded.
1156 *
1157 * @returns {string} The encoded value.
1158 */
1159function encode(val) {
1160 return encodeURIComponent(val).
1161 replace(/%3A/gi, ':').
1162 replace(/%24/g, '$').
1163 replace(/%2C/gi, ',').
1164 replace(/%20/g, '+').
1165 replace(/%5B/gi, '[').
1166 replace(/%5D/gi, ']');
1167}
1168
1169/**
1170 * Build a URL by appending params to the end
1171 *
1172 * @param {string} url The base of the url (e.g., http://www.google.com)
1173 * @param {object} [params] The params to be appended
1174 * @param {?object} options
1175 *
1176 * @returns {string} The formatted url
1177 */
1178function buildURL(url, params, options) {
1179 /*eslint no-param-reassign:0*/
1180 if (!params) {
1181 return url;
1182 }
1183
1184 const _encode = options && options.encode || encode;
1185
1186 const serializeFn = options && options.serialize;
1187
1188 let serializedParams;
1189
1190 if (serializeFn) {
1191 serializedParams = serializeFn(params, options);
1192 } else {
1193 serializedParams = utils$1.isURLSearchParams(params) ?
1194 params.toString() :
1195 new AxiosURLSearchParams(params, options).toString(_encode);
1196 }
1197
1198 if (serializedParams) {
1199 const hashmarkIndex = url.indexOf("#");
1200
1201 if (hashmarkIndex !== -1) {
1202 url = url.slice(0, hashmarkIndex);
1203 }
1204 url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
1205 }
1206
1207 return url;
1208}
1209
1210class InterceptorManager {
1211 constructor() {
1212 this.handlers = [];
1213 }
1214
1215 /**
1216 * Add a new interceptor to the stack
1217 *
1218 * @param {Function} fulfilled The function to handle `then` for a `Promise`
1219 * @param {Function} rejected The function to handle `reject` for a `Promise`
1220 *
1221 * @return {Number} An ID used to remove interceptor later
1222 */
1223 use(fulfilled, rejected, options) {
1224 this.handlers.push({
1225 fulfilled,
1226 rejected,
1227 synchronous: options ? options.synchronous : false,
1228 runWhen: options ? options.runWhen : null
1229 });
1230 return this.handlers.length - 1;
1231 }
1232
1233 /**
1234 * Remove an interceptor from the stack
1235 *
1236 * @param {Number} id The ID that was returned by `use`
1237 *
1238 * @returns {Boolean} `true` if the interceptor was removed, `false` otherwise
1239 */
1240 eject(id) {
1241 if (this.handlers[id]) {
1242 this.handlers[id] = null;
1243 }
1244 }
1245
1246 /**
1247 * Clear all interceptors from the stack
1248 *
1249 * @returns {void}
1250 */
1251 clear() {
1252 if (this.handlers) {
1253 this.handlers = [];
1254 }
1255 }
1256
1257 /**
1258 * Iterate over all the registered interceptors
1259 *
1260 * This method is particularly useful for skipping over any
1261 * interceptors that may have become `null` calling `eject`.
1262 *
1263 * @param {Function} fn The function to call for each interceptor
1264 *
1265 * @returns {void}
1266 */
1267 forEach(fn) {
1268 utils$1.forEach(this.handlers, function forEachHandler(h) {
1269 if (h !== null) {
1270 fn(h);
1271 }
1272 });
1273 }
1274}
1275
1276const InterceptorManager$1 = InterceptorManager;
1277
1278const transitionalDefaults = {
1279 silentJSONParsing: true,
1280 forcedJSONParsing: true,
1281 clarifyTimeoutError: false
1282};
1283
1284const URLSearchParams = url__default["default"].URLSearchParams;
1285
1286const platform$1 = {
1287 isNode: true,
1288 classes: {
1289 URLSearchParams,
1290 FormData: FormData__default["default"],
1291 Blob: typeof Blob !== 'undefined' && Blob || null
1292 },
1293 protocols: [ 'http', 'https', 'file', 'data' ]
1294};
1295
1296const hasBrowserEnv = typeof window !== 'undefined' && typeof document !== 'undefined';
1297
1298const _navigator = typeof navigator === 'object' && navigator || undefined;
1299
1300/**
1301 * Determine if we're running in a standard browser environment
1302 *
1303 * This allows axios to run in a web worker, and react-native.
1304 * Both environments support XMLHttpRequest, but not fully standard globals.
1305 *
1306 * web workers:
1307 * typeof window -> undefined
1308 * typeof document -> undefined
1309 *
1310 * react-native:
1311 * navigator.product -> 'ReactNative'
1312 * nativescript
1313 * navigator.product -> 'NativeScript' or 'NS'
1314 *
1315 * @returns {boolean}
1316 */
1317const hasStandardBrowserEnv = hasBrowserEnv &&
1318 (!_navigator || ['ReactNative', 'NativeScript', 'NS'].indexOf(_navigator.product) < 0);
1319
1320/**
1321 * Determine if we're running in a standard browser webWorker environment
1322 *
1323 * Although the `isStandardBrowserEnv` method indicates that
1324 * `allows axios to run in a web worker`, the WebWorker will still be
1325 * filtered out due to its judgment standard
1326 * `typeof window !== 'undefined' && typeof document !== 'undefined'`.
1327 * This leads to a problem when axios post `FormData` in webWorker
1328 */
1329const hasStandardBrowserWebWorkerEnv = (() => {
1330 return (
1331 typeof WorkerGlobalScope !== 'undefined' &&
1332 // eslint-disable-next-line no-undef
1333 self instanceof WorkerGlobalScope &&
1334 typeof self.importScripts === 'function'
1335 );
1336})();
1337
1338const origin = hasBrowserEnv && window.location.href || 'http://localhost';
1339
1340const utils = /*#__PURE__*/Object.freeze({
1341 __proto__: null,
1342 hasBrowserEnv: hasBrowserEnv,
1343 hasStandardBrowserWebWorkerEnv: hasStandardBrowserWebWorkerEnv,
1344 hasStandardBrowserEnv: hasStandardBrowserEnv,
1345 navigator: _navigator,
1346 origin: origin
1347});
1348
1349const platform = {
1350 ...utils,
1351 ...platform$1
1352};
1353
1354function toURLEncodedForm(data, options) {
1355 return toFormData(data, new platform.classes.URLSearchParams(), Object.assign({
1356 visitor: function(value, key, path, helpers) {
1357 if (platform.isNode && utils$1.isBuffer(value)) {
1358 this.append(key, value.toString('base64'));
1359 return false;
1360 }
1361
1362 return helpers.defaultVisitor.apply(this, arguments);
1363 }
1364 }, options));
1365}
1366
1367/**
1368 * It takes a string like `foo[x][y][z]` and returns an array like `['foo', 'x', 'y', 'z']
1369 *
1370 * @param {string} name - The name of the property to get.
1371 *
1372 * @returns An array of strings.
1373 */
1374function parsePropPath(name) {
1375 // foo[x][y][z]
1376 // foo.x.y.z
1377 // foo-x-y-z
1378 // foo x y z
1379 return utils$1.matchAll(/\w+|\[(\w*)]/g, name).map(match => {
1380 return match[0] === '[]' ? '' : match[1] || match[0];
1381 });
1382}
1383
1384/**
1385 * Convert an array to an object.
1386 *
1387 * @param {Array<any>} arr - The array to convert to an object.
1388 *
1389 * @returns An object with the same keys and values as the array.
1390 */
1391function arrayToObject(arr) {
1392 const obj = {};
1393 const keys = Object.keys(arr);
1394 let i;
1395 const len = keys.length;
1396 let key;
1397 for (i = 0; i < len; i++) {
1398 key = keys[i];
1399 obj[key] = arr[key];
1400 }
1401 return obj;
1402}
1403
1404/**
1405 * It takes a FormData object and returns a JavaScript object
1406 *
1407 * @param {string} formData The FormData object to convert to JSON.
1408 *
1409 * @returns {Object<string, any> | null} The converted object.
1410 */
1411function formDataToJSON(formData) {
1412 function buildPath(path, value, target, index) {
1413 let name = path[index++];
1414
1415 if (name === '__proto__') return true;
1416
1417 const isNumericKey = Number.isFinite(+name);
1418 const isLast = index >= path.length;
1419 name = !name && utils$1.isArray(target) ? target.length : name;
1420
1421 if (isLast) {
1422 if (utils$1.hasOwnProp(target, name)) {
1423 target[name] = [target[name], value];
1424 } else {
1425 target[name] = value;
1426 }
1427
1428 return !isNumericKey;
1429 }
1430
1431 if (!target[name] || !utils$1.isObject(target[name])) {
1432 target[name] = [];
1433 }
1434
1435 const result = buildPath(path, value, target[name], index);
1436
1437 if (result && utils$1.isArray(target[name])) {
1438 target[name] = arrayToObject(target[name]);
1439 }
1440
1441 return !isNumericKey;
1442 }
1443
1444 if (utils$1.isFormData(formData) && utils$1.isFunction(formData.entries)) {
1445 const obj = {};
1446
1447 utils$1.forEachEntry(formData, (name, value) => {
1448 buildPath(parsePropPath(name), value, obj, 0);
1449 });
1450
1451 return obj;
1452 }
1453
1454 return null;
1455}
1456
1457/**
1458 * It takes a string, tries to parse it, and if it fails, it returns the stringified version
1459 * of the input
1460 *
1461 * @param {any} rawValue - The value to be stringified.
1462 * @param {Function} parser - A function that parses a string into a JavaScript object.
1463 * @param {Function} encoder - A function that takes a value and returns a string.
1464 *
1465 * @returns {string} A stringified version of the rawValue.
1466 */
1467function stringifySafely(rawValue, parser, encoder) {
1468 if (utils$1.isString(rawValue)) {
1469 try {
1470 (parser || JSON.parse)(rawValue);
1471 return utils$1.trim(rawValue);
1472 } catch (e) {
1473 if (e.name !== 'SyntaxError') {
1474 throw e;
1475 }
1476 }
1477 }
1478
1479 return (encoder || JSON.stringify)(rawValue);
1480}
1481
1482const defaults = {
1483
1484 transitional: transitionalDefaults,
1485
1486 adapter: ['xhr', 'http', 'fetch'],
1487
1488 transformRequest: [function transformRequest(data, headers) {
1489 const contentType = headers.getContentType() || '';
1490 const hasJSONContentType = contentType.indexOf('application/json') > -1;
1491 const isObjectPayload = utils$1.isObject(data);
1492
1493 if (isObjectPayload && utils$1.isHTMLForm(data)) {
1494 data = new FormData(data);
1495 }
1496
1497 const isFormData = utils$1.isFormData(data);
1498
1499 if (isFormData) {
1500 return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data;
1501 }
1502
1503 if (utils$1.isArrayBuffer(data) ||
1504 utils$1.isBuffer(data) ||
1505 utils$1.isStream(data) ||
1506 utils$1.isFile(data) ||
1507 utils$1.isBlob(data) ||
1508 utils$1.isReadableStream(data)
1509 ) {
1510 return data;
1511 }
1512 if (utils$1.isArrayBufferView(data)) {
1513 return data.buffer;
1514 }
1515 if (utils$1.isURLSearchParams(data)) {
1516 headers.setContentType('application/x-www-form-urlencoded;charset=utf-8', false);
1517 return data.toString();
1518 }
1519
1520 let isFileList;
1521
1522 if (isObjectPayload) {
1523 if (contentType.indexOf('application/x-www-form-urlencoded') > -1) {
1524 return toURLEncodedForm(data, this.formSerializer).toString();
1525 }
1526
1527 if ((isFileList = utils$1.isFileList(data)) || contentType.indexOf('multipart/form-data') > -1) {
1528 const _FormData = this.env && this.env.FormData;
1529
1530 return toFormData(
1531 isFileList ? {'files[]': data} : data,
1532 _FormData && new _FormData(),
1533 this.formSerializer
1534 );
1535 }
1536 }
1537
1538 if (isObjectPayload || hasJSONContentType ) {
1539 headers.setContentType('application/json', false);
1540 return stringifySafely(data);
1541 }
1542
1543 return data;
1544 }],
1545
1546 transformResponse: [function transformResponse(data) {
1547 const transitional = this.transitional || defaults.transitional;
1548 const forcedJSONParsing = transitional && transitional.forcedJSONParsing;
1549 const JSONRequested = this.responseType === 'json';
1550
1551 if (utils$1.isResponse(data) || utils$1.isReadableStream(data)) {
1552 return data;
1553 }
1554
1555 if (data && utils$1.isString(data) && ((forcedJSONParsing && !this.responseType) || JSONRequested)) {
1556 const silentJSONParsing = transitional && transitional.silentJSONParsing;
1557 const strictJSONParsing = !silentJSONParsing && JSONRequested;
1558
1559 try {
1560 return JSON.parse(data);
1561 } catch (e) {
1562 if (strictJSONParsing) {
1563 if (e.name === 'SyntaxError') {
1564 throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, this.response);
1565 }
1566 throw e;
1567 }
1568 }
1569 }
1570
1571 return data;
1572 }],
1573
1574 /**
1575 * A timeout in milliseconds to abort a request. If set to 0 (default) a
1576 * timeout is not created.
1577 */
1578 timeout: 0,
1579
1580 xsrfCookieName: 'XSRF-TOKEN',
1581 xsrfHeaderName: 'X-XSRF-TOKEN',
1582
1583 maxContentLength: -1,
1584 maxBodyLength: -1,
1585
1586 env: {
1587 FormData: platform.classes.FormData,
1588 Blob: platform.classes.Blob
1589 },
1590
1591 validateStatus: function validateStatus(status) {
1592 return status >= 200 && status < 300;
1593 },
1594
1595 headers: {
1596 common: {
1597 'Accept': 'application/json, text/plain, */*',
1598 'Content-Type': undefined
1599 }
1600 }
1601};
1602
1603utils$1.forEach(['delete', 'get', 'head', 'post', 'put', 'patch'], (method) => {
1604 defaults.headers[method] = {};
1605});
1606
1607const defaults$1 = defaults;
1608
1609// RawAxiosHeaders whose duplicates are ignored by node
1610// c.f. https://nodejs.org/api/http.html#http_message_headers
1611const ignoreDuplicateOf = utils$1.toObjectSet([
1612 'age', 'authorization', 'content-length', 'content-type', 'etag',
1613 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',
1614 'last-modified', 'location', 'max-forwards', 'proxy-authorization',
1615 'referer', 'retry-after', 'user-agent'
1616]);
1617
1618/**
1619 * Parse headers into an object
1620 *
1621 * ```
1622 * Date: Wed, 27 Aug 2014 08:58:49 GMT
1623 * Content-Type: application/json
1624 * Connection: keep-alive
1625 * Transfer-Encoding: chunked
1626 * ```
1627 *
1628 * @param {String} rawHeaders Headers needing to be parsed
1629 *
1630 * @returns {Object} Headers parsed into an object
1631 */
1632const parseHeaders = rawHeaders => {
1633 const parsed = {};
1634 let key;
1635 let val;
1636 let i;
1637
1638 rawHeaders && rawHeaders.split('\n').forEach(function parser(line) {
1639 i = line.indexOf(':');
1640 key = line.substring(0, i).trim().toLowerCase();
1641 val = line.substring(i + 1).trim();
1642
1643 if (!key || (parsed[key] && ignoreDuplicateOf[key])) {
1644 return;
1645 }
1646
1647 if (key === 'set-cookie') {
1648 if (parsed[key]) {
1649 parsed[key].push(val);
1650 } else {
1651 parsed[key] = [val];
1652 }
1653 } else {
1654 parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
1655 }
1656 });
1657
1658 return parsed;
1659};
1660
1661const $internals = Symbol('internals');
1662
1663function normalizeHeader(header) {
1664 return header && String(header).trim().toLowerCase();
1665}
1666
1667function normalizeValue(value) {
1668 if (value === false || value == null) {
1669 return value;
1670 }
1671
1672 return utils$1.isArray(value) ? value.map(normalizeValue) : String(value);
1673}
1674
1675function parseTokens(str) {
1676 const tokens = Object.create(null);
1677 const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;
1678 let match;
1679
1680 while ((match = tokensRE.exec(str))) {
1681 tokens[match[1]] = match[2];
1682 }
1683
1684 return tokens;
1685}
1686
1687const isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim());
1688
1689function matchHeaderValue(context, value, header, filter, isHeaderNameFilter) {
1690 if (utils$1.isFunction(filter)) {
1691 return filter.call(this, value, header);
1692 }
1693
1694 if (isHeaderNameFilter) {
1695 value = header;
1696 }
1697
1698 if (!utils$1.isString(value)) return;
1699
1700 if (utils$1.isString(filter)) {
1701 return value.indexOf(filter) !== -1;
1702 }
1703
1704 if (utils$1.isRegExp(filter)) {
1705 return filter.test(value);
1706 }
1707}
1708
1709function formatHeader(header) {
1710 return header.trim()
1711 .toLowerCase().replace(/([a-z\d])(\w*)/g, (w, char, str) => {
1712 return char.toUpperCase() + str;
1713 });
1714}
1715
1716function buildAccessors(obj, header) {
1717 const accessorName = utils$1.toCamelCase(' ' + header);
1718
1719 ['get', 'set', 'has'].forEach(methodName => {
1720 Object.defineProperty(obj, methodName + accessorName, {
1721 value: function(arg1, arg2, arg3) {
1722 return this[methodName].call(this, header, arg1, arg2, arg3);
1723 },
1724 configurable: true
1725 });
1726 });
1727}
1728
1729class AxiosHeaders {
1730 constructor(headers) {
1731 headers && this.set(headers);
1732 }
1733
1734 set(header, valueOrRewrite, rewrite) {
1735 const self = this;
1736
1737 function setHeader(_value, _header, _rewrite) {
1738 const lHeader = normalizeHeader(_header);
1739
1740 if (!lHeader) {
1741 throw new Error('header name must be a non-empty string');
1742 }
1743
1744 const key = utils$1.findKey(self, lHeader);
1745
1746 if(!key || self[key] === undefined || _rewrite === true || (_rewrite === undefined && self[key] !== false)) {
1747 self[key || _header] = normalizeValue(_value);
1748 }
1749 }
1750
1751 const setHeaders = (headers, _rewrite) =>
1752 utils$1.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite));
1753
1754 if (utils$1.isPlainObject(header) || header instanceof this.constructor) {
1755 setHeaders(header, valueOrRewrite);
1756 } else if(utils$1.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) {
1757 setHeaders(parseHeaders(header), valueOrRewrite);
1758 } else if (utils$1.isHeaders(header)) {
1759 for (const [key, value] of header.entries()) {
1760 setHeader(value, key, rewrite);
1761 }
1762 } else {
1763 header != null && setHeader(valueOrRewrite, header, rewrite);
1764 }
1765
1766 return this;
1767 }
1768
1769 get(header, parser) {
1770 header = normalizeHeader(header);
1771
1772 if (header) {
1773 const key = utils$1.findKey(this, header);
1774
1775 if (key) {
1776 const value = this[key];
1777
1778 if (!parser) {
1779 return value;
1780 }
1781
1782 if (parser === true) {
1783 return parseTokens(value);
1784 }
1785
1786 if (utils$1.isFunction(parser)) {
1787 return parser.call(this, value, key);
1788 }
1789
1790 if (utils$1.isRegExp(parser)) {
1791 return parser.exec(value);
1792 }
1793
1794 throw new TypeError('parser must be boolean|regexp|function');
1795 }
1796 }
1797 }
1798
1799 has(header, matcher) {
1800 header = normalizeHeader(header);
1801
1802 if (header) {
1803 const key = utils$1.findKey(this, header);
1804
1805 return !!(key && this[key] !== undefined && (!matcher || matchHeaderValue(this, this[key], key, matcher)));
1806 }
1807
1808 return false;
1809 }
1810
1811 delete(header, matcher) {
1812 const self = this;
1813 let deleted = false;
1814
1815 function deleteHeader(_header) {
1816 _header = normalizeHeader(_header);
1817
1818 if (_header) {
1819 const key = utils$1.findKey(self, _header);
1820
1821 if (key && (!matcher || matchHeaderValue(self, self[key], key, matcher))) {
1822 delete self[key];
1823
1824 deleted = true;
1825 }
1826 }
1827 }
1828
1829 if (utils$1.isArray(header)) {
1830 header.forEach(deleteHeader);
1831 } else {
1832 deleteHeader(header);
1833 }
1834
1835 return deleted;
1836 }
1837
1838 clear(matcher) {
1839 const keys = Object.keys(this);
1840 let i = keys.length;
1841 let deleted = false;
1842
1843 while (i--) {
1844 const key = keys[i];
1845 if(!matcher || matchHeaderValue(this, this[key], key, matcher, true)) {
1846 delete this[key];
1847 deleted = true;
1848 }
1849 }
1850
1851 return deleted;
1852 }
1853
1854 normalize(format) {
1855 const self = this;
1856 const headers = {};
1857
1858 utils$1.forEach(this, (value, header) => {
1859 const key = utils$1.findKey(headers, header);
1860
1861 if (key) {
1862 self[key] = normalizeValue(value);
1863 delete self[header];
1864 return;
1865 }
1866
1867 const normalized = format ? formatHeader(header) : String(header).trim();
1868
1869 if (normalized !== header) {
1870 delete self[header];
1871 }
1872
1873 self[normalized] = normalizeValue(value);
1874
1875 headers[normalized] = true;
1876 });
1877
1878 return this;
1879 }
1880
1881 concat(...targets) {
1882 return this.constructor.concat(this, ...targets);
1883 }
1884
1885 toJSON(asStrings) {
1886 const obj = Object.create(null);
1887
1888 utils$1.forEach(this, (value, header) => {
1889 value != null && value !== false && (obj[header] = asStrings && utils$1.isArray(value) ? value.join(', ') : value);
1890 });
1891
1892 return obj;
1893 }
1894
1895 [Symbol.iterator]() {
1896 return Object.entries(this.toJSON())[Symbol.iterator]();
1897 }
1898
1899 toString() {
1900 return Object.entries(this.toJSON()).map(([header, value]) => header + ': ' + value).join('\n');
1901 }
1902
1903 get [Symbol.toStringTag]() {
1904 return 'AxiosHeaders';
1905 }
1906
1907 static from(thing) {
1908 return thing instanceof this ? thing : new this(thing);
1909 }
1910
1911 static concat(first, ...targets) {
1912 const computed = new this(first);
1913
1914 targets.forEach((target) => computed.set(target));
1915
1916 return computed;
1917 }
1918
1919 static accessor(header) {
1920 const internals = this[$internals] = (this[$internals] = {
1921 accessors: {}
1922 });
1923
1924 const accessors = internals.accessors;
1925 const prototype = this.prototype;
1926
1927 function defineAccessor(_header) {
1928 const lHeader = normalizeHeader(_header);
1929
1930 if (!accessors[lHeader]) {
1931 buildAccessors(prototype, _header);
1932 accessors[lHeader] = true;
1933 }
1934 }
1935
1936 utils$1.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header);
1937
1938 return this;
1939 }
1940}
1941
1942AxiosHeaders.accessor(['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent', 'Authorization']);
1943
1944// reserved names hotfix
1945utils$1.reduceDescriptors(AxiosHeaders.prototype, ({value}, key) => {
1946 let mapped = key[0].toUpperCase() + key.slice(1); // map `set` => `Set`
1947 return {
1948 get: () => value,
1949 set(headerValue) {
1950 this[mapped] = headerValue;
1951 }
1952 }
1953});
1954
1955utils$1.freezeMethods(AxiosHeaders);
1956
1957const AxiosHeaders$1 = AxiosHeaders;
1958
1959/**
1960 * Transform the data for a request or a response
1961 *
1962 * @param {Array|Function} fns A single function or Array of functions
1963 * @param {?Object} response The response object
1964 *
1965 * @returns {*} The resulting transformed data
1966 */
1967function transformData(fns, response) {
1968 const config = this || defaults$1;
1969 const context = response || config;
1970 const headers = AxiosHeaders$1.from(context.headers);
1971 let data = context.data;
1972
1973 utils$1.forEach(fns, function transform(fn) {
1974 data = fn.call(config, data, headers.normalize(), response ? response.status : undefined);
1975 });
1976
1977 headers.normalize();
1978
1979 return data;
1980}
1981
1982function isCancel(value) {
1983 return !!(value && value.__CANCEL__);
1984}
1985
1986/**
1987 * A `CanceledError` is an object that is thrown when an operation is canceled.
1988 *
1989 * @param {string=} message The message.
1990 * @param {Object=} config The config.
1991 * @param {Object=} request The request.
1992 *
1993 * @returns {CanceledError} The created error.
1994 */
1995function CanceledError(message, config, request) {
1996 // eslint-disable-next-line no-eq-null,eqeqeq
1997 AxiosError.call(this, message == null ? 'canceled' : message, AxiosError.ERR_CANCELED, config, request);
1998 this.name = 'CanceledError';
1999}
2000
2001utils$1.inherits(CanceledError, AxiosError, {
2002 __CANCEL__: true
2003});
2004
2005/**
2006 * Resolve or reject a Promise based on response status.
2007 *
2008 * @param {Function} resolve A function that resolves the promise.
2009 * @param {Function} reject A function that rejects the promise.
2010 * @param {object} response The response.
2011 *
2012 * @returns {object} The response.
2013 */
2014function settle(resolve, reject, response) {
2015 const validateStatus = response.config.validateStatus;
2016 if (!response.status || !validateStatus || validateStatus(response.status)) {
2017 resolve(response);
2018 } else {
2019 reject(new AxiosError(
2020 'Request failed with status code ' + response.status,
2021 [AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4],
2022 response.config,
2023 response.request,
2024 response
2025 ));
2026 }
2027}
2028
2029/**
2030 * Determines whether the specified URL is absolute
2031 *
2032 * @param {string} url The URL to test
2033 *
2034 * @returns {boolean} True if the specified URL is absolute, otherwise false
2035 */
2036function isAbsoluteURL(url) {
2037 // A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
2038 // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
2039 // by any combination of letters, digits, plus, period, or hyphen.
2040 return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url);
2041}
2042
2043/**
2044 * Creates a new URL by combining the specified URLs
2045 *
2046 * @param {string} baseURL The base URL
2047 * @param {string} relativeURL The relative URL
2048 *
2049 * @returns {string} The combined URL
2050 */
2051function combineURLs(baseURL, relativeURL) {
2052 return relativeURL
2053 ? baseURL.replace(/\/?\/$/, '') + '/' + relativeURL.replace(/^\/+/, '')
2054 : baseURL;
2055}
2056
2057/**
2058 * Creates a new URL by combining the baseURL with the requestedURL,
2059 * only when the requestedURL is not already an absolute URL.
2060 * If the requestURL is absolute, this function returns the requestedURL untouched.
2061 *
2062 * @param {string} baseURL The base URL
2063 * @param {string} requestedURL Absolute or relative URL to combine
2064 *
2065 * @returns {string} The combined full path
2066 */
2067function buildFullPath(baseURL, requestedURL) {
2068 if (baseURL && !isAbsoluteURL(requestedURL)) {
2069 return combineURLs(baseURL, requestedURL);
2070 }
2071 return requestedURL;
2072}
2073
2074const VERSION = "1.7.7";
2075
2076function parseProtocol(url) {
2077 const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url);
2078 return match && match[1] || '';
2079}
2080
2081const DATA_URL_PATTERN = /^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;
2082
2083/**
2084 * Parse data uri to a Buffer or Blob
2085 *
2086 * @param {String} uri
2087 * @param {?Boolean} asBlob
2088 * @param {?Object} options
2089 * @param {?Function} options.Blob
2090 *
2091 * @returns {Buffer|Blob}
2092 */
2093function fromDataURI(uri, asBlob, options) {
2094 const _Blob = options && options.Blob || platform.classes.Blob;
2095 const protocol = parseProtocol(uri);
2096
2097 if (asBlob === undefined && _Blob) {
2098 asBlob = true;
2099 }
2100
2101 if (protocol === 'data') {
2102 uri = protocol.length ? uri.slice(protocol.length + 1) : uri;
2103
2104 const match = DATA_URL_PATTERN.exec(uri);
2105
2106 if (!match) {
2107 throw new AxiosError('Invalid URL', AxiosError.ERR_INVALID_URL);
2108 }
2109
2110 const mime = match[1];
2111 const isBase64 = match[2];
2112 const body = match[3];
2113 const buffer = Buffer.from(decodeURIComponent(body), isBase64 ? 'base64' : 'utf8');
2114
2115 if (asBlob) {
2116 if (!_Blob) {
2117 throw new AxiosError('Blob is not supported', AxiosError.ERR_NOT_SUPPORT);
2118 }
2119
2120 return new _Blob([buffer], {type: mime});
2121 }
2122
2123 return buffer;
2124 }
2125
2126 throw new AxiosError('Unsupported protocol ' + protocol, AxiosError.ERR_NOT_SUPPORT);
2127}
2128
2129const kInternals = Symbol('internals');
2130
2131class AxiosTransformStream extends stream__default["default"].Transform{
2132 constructor(options) {
2133 options = utils$1.toFlatObject(options, {
2134 maxRate: 0,
2135 chunkSize: 64 * 1024,
2136 minChunkSize: 100,
2137 timeWindow: 500,
2138 ticksRate: 2,
2139 samplesCount: 15
2140 }, null, (prop, source) => {
2141 return !utils$1.isUndefined(source[prop]);
2142 });
2143
2144 super({
2145 readableHighWaterMark: options.chunkSize
2146 });
2147
2148 const internals = this[kInternals] = {
2149 timeWindow: options.timeWindow,
2150 chunkSize: options.chunkSize,
2151 maxRate: options.maxRate,
2152 minChunkSize: options.minChunkSize,
2153 bytesSeen: 0,
2154 isCaptured: false,
2155 notifiedBytesLoaded: 0,
2156 ts: Date.now(),
2157 bytes: 0,
2158 onReadCallback: null
2159 };
2160
2161 this.on('newListener', event => {
2162 if (event === 'progress') {
2163 if (!internals.isCaptured) {
2164 internals.isCaptured = true;
2165 }
2166 }
2167 });
2168 }
2169
2170 _read(size) {
2171 const internals = this[kInternals];
2172
2173 if (internals.onReadCallback) {
2174 internals.onReadCallback();
2175 }
2176
2177 return super._read(size);
2178 }
2179
2180 _transform(chunk, encoding, callback) {
2181 const internals = this[kInternals];
2182 const maxRate = internals.maxRate;
2183
2184 const readableHighWaterMark = this.readableHighWaterMark;
2185
2186 const timeWindow = internals.timeWindow;
2187
2188 const divider = 1000 / timeWindow;
2189 const bytesThreshold = (maxRate / divider);
2190 const minChunkSize = internals.minChunkSize !== false ? Math.max(internals.minChunkSize, bytesThreshold * 0.01) : 0;
2191
2192 const pushChunk = (_chunk, _callback) => {
2193 const bytes = Buffer.byteLength(_chunk);
2194 internals.bytesSeen += bytes;
2195 internals.bytes += bytes;
2196
2197 internals.isCaptured && this.emit('progress', internals.bytesSeen);
2198
2199 if (this.push(_chunk)) {
2200 process.nextTick(_callback);
2201 } else {
2202 internals.onReadCallback = () => {
2203 internals.onReadCallback = null;
2204 process.nextTick(_callback);
2205 };
2206 }
2207 };
2208
2209 const transformChunk = (_chunk, _callback) => {
2210 const chunkSize = Buffer.byteLength(_chunk);
2211 let chunkRemainder = null;
2212 let maxChunkSize = readableHighWaterMark;
2213 let bytesLeft;
2214 let passed = 0;
2215
2216 if (maxRate) {
2217 const now = Date.now();
2218
2219 if (!internals.ts || (passed = (now - internals.ts)) >= timeWindow) {
2220 internals.ts = now;
2221 bytesLeft = bytesThreshold - internals.bytes;
2222 internals.bytes = bytesLeft < 0 ? -bytesLeft : 0;
2223 passed = 0;
2224 }
2225
2226 bytesLeft = bytesThreshold - internals.bytes;
2227 }
2228
2229 if (maxRate) {
2230 if (bytesLeft <= 0) {
2231 // next time window
2232 return setTimeout(() => {
2233 _callback(null, _chunk);
2234 }, timeWindow - passed);
2235 }
2236
2237 if (bytesLeft < maxChunkSize) {
2238 maxChunkSize = bytesLeft;
2239 }
2240 }
2241
2242 if (maxChunkSize && chunkSize > maxChunkSize && (chunkSize - maxChunkSize) > minChunkSize) {
2243 chunkRemainder = _chunk.subarray(maxChunkSize);
2244 _chunk = _chunk.subarray(0, maxChunkSize);
2245 }
2246
2247 pushChunk(_chunk, chunkRemainder ? () => {
2248 process.nextTick(_callback, null, chunkRemainder);
2249 } : _callback);
2250 };
2251
2252 transformChunk(chunk, function transformNextChunk(err, _chunk) {
2253 if (err) {
2254 return callback(err);
2255 }
2256
2257 if (_chunk) {
2258 transformChunk(_chunk, transformNextChunk);
2259 } else {
2260 callback(null);
2261 }
2262 });
2263 }
2264}
2265
2266const AxiosTransformStream$1 = AxiosTransformStream;
2267
2268const {asyncIterator} = Symbol;
2269
2270const readBlob = async function* (blob) {
2271 if (blob.stream) {
2272 yield* blob.stream();
2273 } else if (blob.arrayBuffer) {
2274 yield await blob.arrayBuffer();
2275 } else if (blob[asyncIterator]) {
2276 yield* blob[asyncIterator]();
2277 } else {
2278 yield blob;
2279 }
2280};
2281
2282const readBlob$1 = readBlob;
2283
2284const BOUNDARY_ALPHABET = utils$1.ALPHABET.ALPHA_DIGIT + '-_';
2285
2286const textEncoder = new util.TextEncoder();
2287
2288const CRLF = '\r\n';
2289const CRLF_BYTES = textEncoder.encode(CRLF);
2290const CRLF_BYTES_COUNT = 2;
2291
2292class FormDataPart {
2293 constructor(name, value) {
2294 const {escapeName} = this.constructor;
2295 const isStringValue = utils$1.isString(value);
2296
2297 let headers = `Content-Disposition: form-data; name="${escapeName(name)}"${
2298 !isStringValue && value.name ? `; filename="${escapeName(value.name)}"` : ''
2299 }${CRLF}`;
2300
2301 if (isStringValue) {
2302 value = textEncoder.encode(String(value).replace(/\r?\n|\r\n?/g, CRLF));
2303 } else {
2304 headers += `Content-Type: ${value.type || "application/octet-stream"}${CRLF}`;
2305 }
2306
2307 this.headers = textEncoder.encode(headers + CRLF);
2308
2309 this.contentLength = isStringValue ? value.byteLength : value.size;
2310
2311 this.size = this.headers.byteLength + this.contentLength + CRLF_BYTES_COUNT;
2312
2313 this.name = name;
2314 this.value = value;
2315 }
2316
2317 async *encode(){
2318 yield this.headers;
2319
2320 const {value} = this;
2321
2322 if(utils$1.isTypedArray(value)) {
2323 yield value;
2324 } else {
2325 yield* readBlob$1(value);
2326 }
2327
2328 yield CRLF_BYTES;
2329 }
2330
2331 static escapeName(name) {
2332 return String(name).replace(/[\r\n"]/g, (match) => ({
2333 '\r' : '%0D',
2334 '\n' : '%0A',
2335 '"' : '%22',
2336 }[match]));
2337 }
2338}
2339
2340const formDataToStream = (form, headersHandler, options) => {
2341 const {
2342 tag = 'form-data-boundary',
2343 size = 25,
2344 boundary = tag + '-' + utils$1.generateString(size, BOUNDARY_ALPHABET)
2345 } = options || {};
2346
2347 if(!utils$1.isFormData(form)) {
2348 throw TypeError('FormData instance required');
2349 }
2350
2351 if (boundary.length < 1 || boundary.length > 70) {
2352 throw Error('boundary must be 10-70 characters long')
2353 }
2354
2355 const boundaryBytes = textEncoder.encode('--' + boundary + CRLF);
2356 const footerBytes = textEncoder.encode('--' + boundary + '--' + CRLF + CRLF);
2357 let contentLength = footerBytes.byteLength;
2358
2359 const parts = Array.from(form.entries()).map(([name, value]) => {
2360 const part = new FormDataPart(name, value);
2361 contentLength += part.size;
2362 return part;
2363 });
2364
2365 contentLength += boundaryBytes.byteLength * parts.length;
2366
2367 contentLength = utils$1.toFiniteNumber(contentLength);
2368
2369 const computedHeaders = {
2370 'Content-Type': `multipart/form-data; boundary=${boundary}`
2371 };
2372
2373 if (Number.isFinite(contentLength)) {
2374 computedHeaders['Content-Length'] = contentLength;
2375 }
2376
2377 headersHandler && headersHandler(computedHeaders);
2378
2379 return stream.Readable.from((async function *() {
2380 for(const part of parts) {
2381 yield boundaryBytes;
2382 yield* part.encode();
2383 }
2384
2385 yield footerBytes;
2386 })());
2387};
2388
2389const formDataToStream$1 = formDataToStream;
2390
2391class ZlibHeaderTransformStream extends stream__default["default"].Transform {
2392 __transform(chunk, encoding, callback) {
2393 this.push(chunk);
2394 callback();
2395 }
2396
2397 _transform(chunk, encoding, callback) {
2398 if (chunk.length !== 0) {
2399 this._transform = this.__transform;
2400
2401 // Add Default Compression headers if no zlib headers are present
2402 if (chunk[0] !== 120) { // Hex: 78
2403 const header = Buffer.alloc(2);
2404 header[0] = 120; // Hex: 78
2405 header[1] = 156; // Hex: 9C
2406 this.push(header, encoding);
2407 }
2408 }
2409
2410 this.__transform(chunk, encoding, callback);
2411 }
2412}
2413
2414const ZlibHeaderTransformStream$1 = ZlibHeaderTransformStream;
2415
2416const callbackify = (fn, reducer) => {
2417 return utils$1.isAsyncFn(fn) ? function (...args) {
2418 const cb = args.pop();
2419 fn.apply(this, args).then((value) => {
2420 try {
2421 reducer ? cb(null, ...reducer(value)) : cb(null, value);
2422 } catch (err) {
2423 cb(err);
2424 }
2425 }, cb);
2426 } : fn;
2427};
2428
2429const callbackify$1 = callbackify;
2430
2431/**
2432 * Calculate data maxRate
2433 * @param {Number} [samplesCount= 10]
2434 * @param {Number} [min= 1000]
2435 * @returns {Function}
2436 */
2437function speedometer(samplesCount, min) {
2438 samplesCount = samplesCount || 10;
2439 const bytes = new Array(samplesCount);
2440 const timestamps = new Array(samplesCount);
2441 let head = 0;
2442 let tail = 0;
2443 let firstSampleTS;
2444
2445 min = min !== undefined ? min : 1000;
2446
2447 return function push(chunkLength) {
2448 const now = Date.now();
2449
2450 const startedAt = timestamps[tail];
2451
2452 if (!firstSampleTS) {
2453 firstSampleTS = now;
2454 }
2455
2456 bytes[head] = chunkLength;
2457 timestamps[head] = now;
2458
2459 let i = tail;
2460 let bytesCount = 0;
2461
2462 while (i !== head) {
2463 bytesCount += bytes[i++];
2464 i = i % samplesCount;
2465 }
2466
2467 head = (head + 1) % samplesCount;
2468
2469 if (head === tail) {
2470 tail = (tail + 1) % samplesCount;
2471 }
2472
2473 if (now - firstSampleTS < min) {
2474 return;
2475 }
2476
2477 const passed = startedAt && now - startedAt;
2478
2479 return passed ? Math.round(bytesCount * 1000 / passed) : undefined;
2480 };
2481}
2482
2483/**
2484 * Throttle decorator
2485 * @param {Function} fn
2486 * @param {Number} freq
2487 * @return {Function}
2488 */
2489function throttle(fn, freq) {
2490 let timestamp = 0;
2491 let threshold = 1000 / freq;
2492 let lastArgs;
2493 let timer;
2494
2495 const invoke = (args, now = Date.now()) => {
2496 timestamp = now;
2497 lastArgs = null;
2498 if (timer) {
2499 clearTimeout(timer);
2500 timer = null;
2501 }
2502 fn.apply(null, args);
2503 };
2504
2505 const throttled = (...args) => {
2506 const now = Date.now();
2507 const passed = now - timestamp;
2508 if ( passed >= threshold) {
2509 invoke(args, now);
2510 } else {
2511 lastArgs = args;
2512 if (!timer) {
2513 timer = setTimeout(() => {
2514 timer = null;
2515 invoke(lastArgs);
2516 }, threshold - passed);
2517 }
2518 }
2519 };
2520
2521 const flush = () => lastArgs && invoke(lastArgs);
2522
2523 return [throttled, flush];
2524}
2525
2526const progressEventReducer = (listener, isDownloadStream, freq = 3) => {
2527 let bytesNotified = 0;
2528 const _speedometer = speedometer(50, 250);
2529
2530 return throttle(e => {
2531 const loaded = e.loaded;
2532 const total = e.lengthComputable ? e.total : undefined;
2533 const progressBytes = loaded - bytesNotified;
2534 const rate = _speedometer(progressBytes);
2535 const inRange = loaded <= total;
2536
2537 bytesNotified = loaded;
2538
2539 const data = {
2540 loaded,
2541 total,
2542 progress: total ? (loaded / total) : undefined,
2543 bytes: progressBytes,
2544 rate: rate ? rate : undefined,
2545 estimated: rate && total && inRange ? (total - loaded) / rate : undefined,
2546 event: e,
2547 lengthComputable: total != null,
2548 [isDownloadStream ? 'download' : 'upload']: true
2549 };
2550
2551 listener(data);
2552 }, freq);
2553};
2554
2555const progressEventDecorator = (total, throttled) => {
2556 const lengthComputable = total != null;
2557
2558 return [(loaded) => throttled[0]({
2559 lengthComputable,
2560 total,
2561 loaded
2562 }), throttled[1]];
2563};
2564
2565const asyncDecorator = (fn) => (...args) => utils$1.asap(() => fn(...args));
2566
2567const zlibOptions = {
2568 flush: zlib__default["default"].constants.Z_SYNC_FLUSH,
2569 finishFlush: zlib__default["default"].constants.Z_SYNC_FLUSH
2570};
2571
2572const brotliOptions = {
2573 flush: zlib__default["default"].constants.BROTLI_OPERATION_FLUSH,
2574 finishFlush: zlib__default["default"].constants.BROTLI_OPERATION_FLUSH
2575};
2576
2577const isBrotliSupported = utils$1.isFunction(zlib__default["default"].createBrotliDecompress);
2578
2579const {http: httpFollow, https: httpsFollow} = followRedirects__default["default"];
2580
2581const isHttps = /https:?/;
2582
2583const supportedProtocols = platform.protocols.map(protocol => {
2584 return protocol + ':';
2585});
2586
2587const flushOnFinish = (stream, [throttled, flush]) => {
2588 stream
2589 .on('end', flush)
2590 .on('error', flush);
2591
2592 return throttled;
2593};
2594
2595/**
2596 * If the proxy or config beforeRedirects functions are defined, call them with the options
2597 * object.
2598 *
2599 * @param {Object<string, any>} options - The options object that was passed to the request.
2600 *
2601 * @returns {Object<string, any>}
2602 */
2603function dispatchBeforeRedirect(options, responseDetails) {
2604 if (options.beforeRedirects.proxy) {
2605 options.beforeRedirects.proxy(options);
2606 }
2607 if (options.beforeRedirects.config) {
2608 options.beforeRedirects.config(options, responseDetails);
2609 }
2610}
2611
2612/**
2613 * If the proxy or config afterRedirects functions are defined, call them with the options
2614 *
2615 * @param {http.ClientRequestArgs} options
2616 * @param {AxiosProxyConfig} configProxy configuration from Axios options object
2617 * @param {string} location
2618 *
2619 * @returns {http.ClientRequestArgs}
2620 */
2621function setProxy(options, configProxy, location) {
2622 let proxy = configProxy;
2623 if (!proxy && proxy !== false) {
2624 const proxyUrl = proxyFromEnv.getProxyForUrl(location);
2625 if (proxyUrl) {
2626 proxy = new URL(proxyUrl);
2627 }
2628 }
2629 if (proxy) {
2630 // Basic proxy authorization
2631 if (proxy.username) {
2632 proxy.auth = (proxy.username || '') + ':' + (proxy.password || '');
2633 }
2634
2635 if (proxy.auth) {
2636 // Support proxy auth object form
2637 if (proxy.auth.username || proxy.auth.password) {
2638 proxy.auth = (proxy.auth.username || '') + ':' + (proxy.auth.password || '');
2639 }
2640 const base64 = Buffer
2641 .from(proxy.auth, 'utf8')
2642 .toString('base64');
2643 options.headers['Proxy-Authorization'] = 'Basic ' + base64;
2644 }
2645
2646 options.headers.host = options.hostname + (options.port ? ':' + options.port : '');
2647 const proxyHost = proxy.hostname || proxy.host;
2648 options.hostname = proxyHost;
2649 // Replace 'host' since options is not a URL object
2650 options.host = proxyHost;
2651 options.port = proxy.port;
2652 options.path = location;
2653 if (proxy.protocol) {
2654 options.protocol = proxy.protocol.includes(':') ? proxy.protocol : `${proxy.protocol}:`;
2655 }
2656 }
2657
2658 options.beforeRedirects.proxy = function beforeRedirect(redirectOptions) {
2659 // Configure proxy for redirected request, passing the original config proxy to apply
2660 // the exact same logic as if the redirected request was performed by axios directly.
2661 setProxy(redirectOptions, configProxy, redirectOptions.href);
2662 };
2663}
2664
2665const isHttpAdapterSupported = typeof process !== 'undefined' && utils$1.kindOf(process) === 'process';
2666
2667// temporary hotfix
2668
2669const wrapAsync = (asyncExecutor) => {
2670 return new Promise((resolve, reject) => {
2671 let onDone;
2672 let isDone;
2673
2674 const done = (value, isRejected) => {
2675 if (isDone) return;
2676 isDone = true;
2677 onDone && onDone(value, isRejected);
2678 };
2679
2680 const _resolve = (value) => {
2681 done(value);
2682 resolve(value);
2683 };
2684
2685 const _reject = (reason) => {
2686 done(reason, true);
2687 reject(reason);
2688 };
2689
2690 asyncExecutor(_resolve, _reject, (onDoneHandler) => (onDone = onDoneHandler)).catch(_reject);
2691 })
2692};
2693
2694const resolveFamily = ({address, family}) => {
2695 if (!utils$1.isString(address)) {
2696 throw TypeError('address must be a string');
2697 }
2698 return ({
2699 address,
2700 family: family || (address.indexOf('.') < 0 ? 6 : 4)
2701 });
2702};
2703
2704const buildAddressEntry = (address, family) => resolveFamily(utils$1.isObject(address) ? address : {address, family});
2705
2706/*eslint consistent-return:0*/
2707const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) {
2708 return wrapAsync(async function dispatchHttpRequest(resolve, reject, onDone) {
2709 let {data, lookup, family} = config;
2710 const {responseType, responseEncoding} = config;
2711 const method = config.method.toUpperCase();
2712 let isDone;
2713 let rejected = false;
2714 let req;
2715
2716 if (lookup) {
2717 const _lookup = callbackify$1(lookup, (value) => utils$1.isArray(value) ? value : [value]);
2718 // hotfix to support opt.all option which is required for node 20.x
2719 lookup = (hostname, opt, cb) => {
2720 _lookup(hostname, opt, (err, arg0, arg1) => {
2721 if (err) {
2722 return cb(err);
2723 }
2724
2725 const addresses = utils$1.isArray(arg0) ? arg0.map(addr => buildAddressEntry(addr)) : [buildAddressEntry(arg0, arg1)];
2726
2727 opt.all ? cb(err, addresses) : cb(err, addresses[0].address, addresses[0].family);
2728 });
2729 };
2730 }
2731
2732 // temporary internal emitter until the AxiosRequest class will be implemented
2733 const emitter = new events.EventEmitter();
2734
2735 const onFinished = () => {
2736 if (config.cancelToken) {
2737 config.cancelToken.unsubscribe(abort);
2738 }
2739
2740 if (config.signal) {
2741 config.signal.removeEventListener('abort', abort);
2742 }
2743
2744 emitter.removeAllListeners();
2745 };
2746
2747 onDone((value, isRejected) => {
2748 isDone = true;
2749 if (isRejected) {
2750 rejected = true;
2751 onFinished();
2752 }
2753 });
2754
2755 function abort(reason) {
2756 emitter.emit('abort', !reason || reason.type ? new CanceledError(null, config, req) : reason);
2757 }
2758
2759 emitter.once('abort', reject);
2760
2761 if (config.cancelToken || config.signal) {
2762 config.cancelToken && config.cancelToken.subscribe(abort);
2763 if (config.signal) {
2764 config.signal.aborted ? abort() : config.signal.addEventListener('abort', abort);
2765 }
2766 }
2767
2768 // Parse url
2769 const fullPath = buildFullPath(config.baseURL, config.url);
2770 const parsed = new URL(fullPath, platform.hasBrowserEnv ? platform.origin : undefined);
2771 const protocol = parsed.protocol || supportedProtocols[0];
2772
2773 if (protocol === 'data:') {
2774 let convertedData;
2775
2776 if (method !== 'GET') {
2777 return settle(resolve, reject, {
2778 status: 405,
2779 statusText: 'method not allowed',
2780 headers: {},
2781 config
2782 });
2783 }
2784
2785 try {
2786 convertedData = fromDataURI(config.url, responseType === 'blob', {
2787 Blob: config.env && config.env.Blob
2788 });
2789 } catch (err) {
2790 throw AxiosError.from(err, AxiosError.ERR_BAD_REQUEST, config);
2791 }
2792
2793 if (responseType === 'text') {
2794 convertedData = convertedData.toString(responseEncoding);
2795
2796 if (!responseEncoding || responseEncoding === 'utf8') {
2797 convertedData = utils$1.stripBOM(convertedData);
2798 }
2799 } else if (responseType === 'stream') {
2800 convertedData = stream__default["default"].Readable.from(convertedData);
2801 }
2802
2803 return settle(resolve, reject, {
2804 data: convertedData,
2805 status: 200,
2806 statusText: 'OK',
2807 headers: new AxiosHeaders$1(),
2808 config
2809 });
2810 }
2811
2812 if (supportedProtocols.indexOf(protocol) === -1) {
2813 return reject(new AxiosError(
2814 'Unsupported protocol ' + protocol,
2815 AxiosError.ERR_BAD_REQUEST,
2816 config
2817 ));
2818 }
2819
2820 const headers = AxiosHeaders$1.from(config.headers).normalize();
2821
2822 // Set User-Agent (required by some servers)
2823 // See https://github.com/axios/axios/issues/69
2824 // User-Agent is specified; handle case where no UA header is desired
2825 // Only set header if it hasn't been set in config
2826 headers.set('User-Agent', 'axios/' + VERSION, false);
2827
2828 const {onUploadProgress, onDownloadProgress} = config;
2829 const maxRate = config.maxRate;
2830 let maxUploadRate = undefined;
2831 let maxDownloadRate = undefined;
2832
2833 // support for spec compliant FormData objects
2834 if (utils$1.isSpecCompliantForm(data)) {
2835 const userBoundary = headers.getContentType(/boundary=([-_\w\d]{10,70})/i);
2836
2837 data = formDataToStream$1(data, (formHeaders) => {
2838 headers.set(formHeaders);
2839 }, {
2840 tag: `axios-${VERSION}-boundary`,
2841 boundary: userBoundary && userBoundary[1] || undefined
2842 });
2843 // support for https://www.npmjs.com/package/form-data api
2844 } else if (utils$1.isFormData(data) && utils$1.isFunction(data.getHeaders)) {
2845 headers.set(data.getHeaders());
2846
2847 if (!headers.hasContentLength()) {
2848 try {
2849 const knownLength = await util__default["default"].promisify(data.getLength).call(data);
2850 Number.isFinite(knownLength) && knownLength >= 0 && headers.setContentLength(knownLength);
2851 /*eslint no-empty:0*/
2852 } catch (e) {
2853 }
2854 }
2855 } else if (utils$1.isBlob(data)) {
2856 data.size && headers.setContentType(data.type || 'application/octet-stream');
2857 headers.setContentLength(data.size || 0);
2858 data = stream__default["default"].Readable.from(readBlob$1(data));
2859 } else if (data && !utils$1.isStream(data)) {
2860 if (Buffer.isBuffer(data)) ; else if (utils$1.isArrayBuffer(data)) {
2861 data = Buffer.from(new Uint8Array(data));
2862 } else if (utils$1.isString(data)) {
2863 data = Buffer.from(data, 'utf-8');
2864 } else {
2865 return reject(new AxiosError(
2866 'Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream',
2867 AxiosError.ERR_BAD_REQUEST,
2868 config
2869 ));
2870 }
2871
2872 // Add Content-Length header if data exists
2873 headers.setContentLength(data.length, false);
2874
2875 if (config.maxBodyLength > -1 && data.length > config.maxBodyLength) {
2876 return reject(new AxiosError(
2877 'Request body larger than maxBodyLength limit',
2878 AxiosError.ERR_BAD_REQUEST,
2879 config
2880 ));
2881 }
2882 }
2883
2884 const contentLength = utils$1.toFiniteNumber(headers.getContentLength());
2885
2886 if (utils$1.isArray(maxRate)) {
2887 maxUploadRate = maxRate[0];
2888 maxDownloadRate = maxRate[1];
2889 } else {
2890 maxUploadRate = maxDownloadRate = maxRate;
2891 }
2892
2893 if (data && (onUploadProgress || maxUploadRate)) {
2894 if (!utils$1.isStream(data)) {
2895 data = stream__default["default"].Readable.from(data, {objectMode: false});
2896 }
2897
2898 data = stream__default["default"].pipeline([data, new AxiosTransformStream$1({
2899 maxRate: utils$1.toFiniteNumber(maxUploadRate)
2900 })], utils$1.noop);
2901
2902 onUploadProgress && data.on('progress', flushOnFinish(
2903 data,
2904 progressEventDecorator(
2905 contentLength,
2906 progressEventReducer(asyncDecorator(onUploadProgress), false, 3)
2907 )
2908 ));
2909 }
2910
2911 // HTTP basic authentication
2912 let auth = undefined;
2913 if (config.auth) {
2914 const username = config.auth.username || '';
2915 const password = config.auth.password || '';
2916 auth = username + ':' + password;
2917 }
2918
2919 if (!auth && parsed.username) {
2920 const urlUsername = parsed.username;
2921 const urlPassword = parsed.password;
2922 auth = urlUsername + ':' + urlPassword;
2923 }
2924
2925 auth && headers.delete('authorization');
2926
2927 let path;
2928
2929 try {
2930 path = buildURL(
2931 parsed.pathname + parsed.search,
2932 config.params,
2933 config.paramsSerializer
2934 ).replace(/^\?/, '');
2935 } catch (err) {
2936 const customErr = new Error(err.message);
2937 customErr.config = config;
2938 customErr.url = config.url;
2939 customErr.exists = true;
2940 return reject(customErr);
2941 }
2942
2943 headers.set(
2944 'Accept-Encoding',
2945 'gzip, compress, deflate' + (isBrotliSupported ? ', br' : ''), false
2946 );
2947
2948 const options = {
2949 path,
2950 method: method,
2951 headers: headers.toJSON(),
2952 agents: { http: config.httpAgent, https: config.httpsAgent },
2953 auth,
2954 protocol,
2955 family,
2956 beforeRedirect: dispatchBeforeRedirect,
2957 beforeRedirects: {}
2958 };
2959
2960 // cacheable-lookup integration hotfix
2961 !utils$1.isUndefined(lookup) && (options.lookup = lookup);
2962
2963 if (config.socketPath) {
2964 options.socketPath = config.socketPath;
2965 } else {
2966 options.hostname = parsed.hostname.startsWith("[") ? parsed.hostname.slice(1, -1) : parsed.hostname;
2967 options.port = parsed.port;
2968 setProxy(options, config.proxy, protocol + '//' + parsed.hostname + (parsed.port ? ':' + parsed.port : '') + options.path);
2969 }
2970
2971 let transport;
2972 const isHttpsRequest = isHttps.test(options.protocol);
2973 options.agent = isHttpsRequest ? config.httpsAgent : config.httpAgent;
2974 if (config.transport) {
2975 transport = config.transport;
2976 } else if (config.maxRedirects === 0) {
2977 transport = isHttpsRequest ? https__default["default"] : http__default["default"];
2978 } else {
2979 if (config.maxRedirects) {
2980 options.maxRedirects = config.maxRedirects;
2981 }
2982 if (config.beforeRedirect) {
2983 options.beforeRedirects.config = config.beforeRedirect;
2984 }
2985 transport = isHttpsRequest ? httpsFollow : httpFollow;
2986 }
2987
2988 if (config.maxBodyLength > -1) {
2989 options.maxBodyLength = config.maxBodyLength;
2990 } else {
2991 // follow-redirects does not skip comparison, so it should always succeed for axios -1 unlimited
2992 options.maxBodyLength = Infinity;
2993 }
2994
2995 if (config.insecureHTTPParser) {
2996 options.insecureHTTPParser = config.insecureHTTPParser;
2997 }
2998
2999 // Create the request
3000 req = transport.request(options, function handleResponse(res) {
3001 if (req.destroyed) return;
3002
3003 const streams = [res];
3004
3005 const responseLength = +res.headers['content-length'];
3006
3007 if (onDownloadProgress || maxDownloadRate) {
3008 const transformStream = new AxiosTransformStream$1({
3009 maxRate: utils$1.toFiniteNumber(maxDownloadRate)
3010 });
3011
3012 onDownloadProgress && transformStream.on('progress', flushOnFinish(
3013 transformStream,
3014 progressEventDecorator(
3015 responseLength,
3016 progressEventReducer(asyncDecorator(onDownloadProgress), true, 3)
3017 )
3018 ));
3019
3020 streams.push(transformStream);
3021 }
3022
3023 // decompress the response body transparently if required
3024 let responseStream = res;
3025
3026 // return the last request in case of redirects
3027 const lastRequest = res.req || req;
3028
3029 // if decompress disabled we should not decompress
3030 if (config.decompress !== false && res.headers['content-encoding']) {
3031 // if no content, but headers still say that it is encoded,
3032 // remove the header not confuse downstream operations
3033 if (method === 'HEAD' || res.statusCode === 204) {
3034 delete res.headers['content-encoding'];
3035 }
3036
3037 switch ((res.headers['content-encoding'] || '').toLowerCase()) {
3038 /*eslint default-case:0*/
3039 case 'gzip':
3040 case 'x-gzip':
3041 case 'compress':
3042 case 'x-compress':
3043 // add the unzipper to the body stream processing pipeline
3044 streams.push(zlib__default["default"].createUnzip(zlibOptions));
3045
3046 // remove the content-encoding in order to not confuse downstream operations
3047 delete res.headers['content-encoding'];
3048 break;
3049 case 'deflate':
3050 streams.push(new ZlibHeaderTransformStream$1());
3051
3052 // add the unzipper to the body stream processing pipeline
3053 streams.push(zlib__default["default"].createUnzip(zlibOptions));
3054
3055 // remove the content-encoding in order to not confuse downstream operations
3056 delete res.headers['content-encoding'];
3057 break;
3058 case 'br':
3059 if (isBrotliSupported) {
3060 streams.push(zlib__default["default"].createBrotliDecompress(brotliOptions));
3061 delete res.headers['content-encoding'];
3062 }
3063 }
3064 }
3065
3066 responseStream = streams.length > 1 ? stream__default["default"].pipeline(streams, utils$1.noop) : streams[0];
3067
3068 const offListeners = stream__default["default"].finished(responseStream, () => {
3069 offListeners();
3070 onFinished();
3071 });
3072
3073 const response = {
3074 status: res.statusCode,
3075 statusText: res.statusMessage,
3076 headers: new AxiosHeaders$1(res.headers),
3077 config,
3078 request: lastRequest
3079 };
3080
3081 if (responseType === 'stream') {
3082 response.data = responseStream;
3083 settle(resolve, reject, response);
3084 } else {
3085 const responseBuffer = [];
3086 let totalResponseBytes = 0;
3087
3088 responseStream.on('data', function handleStreamData(chunk) {
3089 responseBuffer.push(chunk);
3090 totalResponseBytes += chunk.length;
3091
3092 // make sure the content length is not over the maxContentLength if specified
3093 if (config.maxContentLength > -1 && totalResponseBytes > config.maxContentLength) {
3094 // stream.destroy() emit aborted event before calling reject() on Node.js v16
3095 rejected = true;
3096 responseStream.destroy();
3097 reject(new AxiosError('maxContentLength size of ' + config.maxContentLength + ' exceeded',
3098 AxiosError.ERR_BAD_RESPONSE, config, lastRequest));
3099 }
3100 });
3101
3102 responseStream.on('aborted', function handlerStreamAborted() {
3103 if (rejected) {
3104 return;
3105 }
3106
3107 const err = new AxiosError(
3108 'maxContentLength size of ' + config.maxContentLength + ' exceeded',
3109 AxiosError.ERR_BAD_RESPONSE,
3110 config,
3111 lastRequest
3112 );
3113 responseStream.destroy(err);
3114 reject(err);
3115 });
3116
3117 responseStream.on('error', function handleStreamError(err) {
3118 if (req.destroyed) return;
3119 reject(AxiosError.from(err, null, config, lastRequest));
3120 });
3121
3122 responseStream.on('end', function handleStreamEnd() {
3123 try {
3124 let responseData = responseBuffer.length === 1 ? responseBuffer[0] : Buffer.concat(responseBuffer);
3125 if (responseType !== 'arraybuffer') {
3126 responseData = responseData.toString(responseEncoding);
3127 if (!responseEncoding || responseEncoding === 'utf8') {
3128 responseData = utils$1.stripBOM(responseData);
3129 }
3130 }
3131 response.data = responseData;
3132 } catch (err) {
3133 return reject(AxiosError.from(err, null, config, response.request, response));
3134 }
3135 settle(resolve, reject, response);
3136 });
3137 }
3138
3139 emitter.once('abort', err => {
3140 if (!responseStream.destroyed) {
3141 responseStream.emit('error', err);
3142 responseStream.destroy();
3143 }
3144 });
3145 });
3146
3147 emitter.once('abort', err => {
3148 reject(err);
3149 req.destroy(err);
3150 });
3151
3152 // Handle errors
3153 req.on('error', function handleRequestError(err) {
3154 // @todo remove
3155 // if (req.aborted && err.code !== AxiosError.ERR_FR_TOO_MANY_REDIRECTS) return;
3156 reject(AxiosError.from(err, null, config, req));
3157 });
3158
3159 // set tcp keep alive to prevent drop connection by peer
3160 req.on('socket', function handleRequestSocket(socket) {
3161 // default interval of sending ack packet is 1 minute
3162 socket.setKeepAlive(true, 1000 * 60);
3163 });
3164
3165 // Handle request timeout
3166 if (config.timeout) {
3167 // This is forcing a int timeout to avoid problems if the `req` interface doesn't handle other types.
3168 const timeout = parseInt(config.timeout, 10);
3169
3170 if (Number.isNaN(timeout)) {
3171 reject(new AxiosError(
3172 'error trying to parse `config.timeout` to int',
3173 AxiosError.ERR_BAD_OPTION_VALUE,
3174 config,
3175 req
3176 ));
3177
3178 return;
3179 }
3180
3181 // Sometime, the response will be very slow, and does not respond, the connect event will be block by event loop system.
3182 // And timer callback will be fired, and abort() will be invoked before connection, then get "socket hang up" and code ECONNRESET.
3183 // At this time, if we have a large number of request, nodejs will hang up some socket on background. and the number will up and up.
3184 // And then these socket which be hang up will devouring CPU little by little.
3185 // ClientRequest.setTimeout will be fired on the specify milliseconds, and can make sure that abort() will be fired after connect.
3186 req.setTimeout(timeout, function handleRequestTimeout() {
3187 if (isDone) return;
3188 let timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded';
3189 const transitional = config.transitional || transitionalDefaults;
3190 if (config.timeoutErrorMessage) {
3191 timeoutErrorMessage = config.timeoutErrorMessage;
3192 }
3193 reject(new AxiosError(
3194 timeoutErrorMessage,
3195 transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED,
3196 config,
3197 req
3198 ));
3199 abort();
3200 });
3201 }
3202
3203
3204 // Send the request
3205 if (utils$1.isStream(data)) {
3206 let ended = false;
3207 let errored = false;
3208
3209 data.on('end', () => {
3210 ended = true;
3211 });
3212
3213 data.once('error', err => {
3214 errored = true;
3215 req.destroy(err);
3216 });
3217
3218 data.on('close', () => {
3219 if (!ended && !errored) {
3220 abort(new CanceledError('Request stream has been aborted', config, req));
3221 }
3222 });
3223
3224 data.pipe(req);
3225 } else {
3226 req.end(data);
3227 }
3228 });
3229};
3230
3231const isURLSameOrigin = platform.hasStandardBrowserEnv ?
3232
3233// Standard browser envs have full support of the APIs needed to test
3234// whether the request URL is of the same origin as current location.
3235 (function standardBrowserEnv() {
3236 const msie = platform.navigator && /(msie|trident)/i.test(platform.navigator.userAgent);
3237 const urlParsingNode = document.createElement('a');
3238 let originURL;
3239
3240 /**
3241 * Parse a URL to discover its components
3242 *
3243 * @param {String} url The URL to be parsed
3244 * @returns {Object}
3245 */
3246 function resolveURL(url) {
3247 let href = url;
3248
3249 if (msie) {
3250 // IE needs attribute set twice to normalize properties
3251 urlParsingNode.setAttribute('href', href);
3252 href = urlParsingNode.href;
3253 }
3254
3255 urlParsingNode.setAttribute('href', href);
3256
3257 // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
3258 return {
3259 href: urlParsingNode.href,
3260 protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
3261 host: urlParsingNode.host,
3262 search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
3263 hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
3264 hostname: urlParsingNode.hostname,
3265 port: urlParsingNode.port,
3266 pathname: (urlParsingNode.pathname.charAt(0) === '/') ?
3267 urlParsingNode.pathname :
3268 '/' + urlParsingNode.pathname
3269 };
3270 }
3271
3272 originURL = resolveURL(window.location.href);
3273
3274 /**
3275 * Determine if a URL shares the same origin as the current location
3276 *
3277 * @param {String} requestURL The URL to test
3278 * @returns {boolean} True if URL shares the same origin, otherwise false
3279 */
3280 return function isURLSameOrigin(requestURL) {
3281 const parsed = (utils$1.isString(requestURL)) ? resolveURL(requestURL) : requestURL;
3282 return (parsed.protocol === originURL.protocol &&
3283 parsed.host === originURL.host);
3284 };
3285 })() :
3286
3287 // Non standard browser envs (web workers, react-native) lack needed support.
3288 (function nonStandardBrowserEnv() {
3289 return function isURLSameOrigin() {
3290 return true;
3291 };
3292 })();
3293
3294const cookies = platform.hasStandardBrowserEnv ?
3295
3296 // Standard browser envs support document.cookie
3297 {
3298 write(name, value, expires, path, domain, secure) {
3299 const cookie = [name + '=' + encodeURIComponent(value)];
3300
3301 utils$1.isNumber(expires) && cookie.push('expires=' + new Date(expires).toGMTString());
3302
3303 utils$1.isString(path) && cookie.push('path=' + path);
3304
3305 utils$1.isString(domain) && cookie.push('domain=' + domain);
3306
3307 secure === true && cookie.push('secure');
3308
3309 document.cookie = cookie.join('; ');
3310 },
3311
3312 read(name) {
3313 const match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
3314 return (match ? decodeURIComponent(match[3]) : null);
3315 },
3316
3317 remove(name) {
3318 this.write(name, '', Date.now() - 86400000);
3319 }
3320 }
3321
3322 :
3323
3324 // Non-standard browser env (web workers, react-native) lack needed support.
3325 {
3326 write() {},
3327 read() {
3328 return null;
3329 },
3330 remove() {}
3331 };
3332
3333const headersToObject = (thing) => thing instanceof AxiosHeaders$1 ? { ...thing } : thing;
3334
3335/**
3336 * Config-specific merge-function which creates a new config-object
3337 * by merging two configuration objects together.
3338 *
3339 * @param {Object} config1
3340 * @param {Object} config2
3341 *
3342 * @returns {Object} New object resulting from merging config2 to config1
3343 */
3344function mergeConfig(config1, config2) {
3345 // eslint-disable-next-line no-param-reassign
3346 config2 = config2 || {};
3347 const config = {};
3348
3349 function getMergedValue(target, source, caseless) {
3350 if (utils$1.isPlainObject(target) && utils$1.isPlainObject(source)) {
3351 return utils$1.merge.call({caseless}, target, source);
3352 } else if (utils$1.isPlainObject(source)) {
3353 return utils$1.merge({}, source);
3354 } else if (utils$1.isArray(source)) {
3355 return source.slice();
3356 }
3357 return source;
3358 }
3359
3360 // eslint-disable-next-line consistent-return
3361 function mergeDeepProperties(a, b, caseless) {
3362 if (!utils$1.isUndefined(b)) {
3363 return getMergedValue(a, b, caseless);
3364 } else if (!utils$1.isUndefined(a)) {
3365 return getMergedValue(undefined, a, caseless);
3366 }
3367 }
3368
3369 // eslint-disable-next-line consistent-return
3370 function valueFromConfig2(a, b) {
3371 if (!utils$1.isUndefined(b)) {
3372 return getMergedValue(undefined, b);
3373 }
3374 }
3375
3376 // eslint-disable-next-line consistent-return
3377 function defaultToConfig2(a, b) {
3378 if (!utils$1.isUndefined(b)) {
3379 return getMergedValue(undefined, b);
3380 } else if (!utils$1.isUndefined(a)) {
3381 return getMergedValue(undefined, a);
3382 }
3383 }
3384
3385 // eslint-disable-next-line consistent-return
3386 function mergeDirectKeys(a, b, prop) {
3387 if (prop in config2) {
3388 return getMergedValue(a, b);
3389 } else if (prop in config1) {
3390 return getMergedValue(undefined, a);
3391 }
3392 }
3393
3394 const mergeMap = {
3395 url: valueFromConfig2,
3396 method: valueFromConfig2,
3397 data: valueFromConfig2,
3398 baseURL: defaultToConfig2,
3399 transformRequest: defaultToConfig2,
3400 transformResponse: defaultToConfig2,
3401 paramsSerializer: defaultToConfig2,
3402 timeout: defaultToConfig2,
3403 timeoutMessage: defaultToConfig2,
3404 withCredentials: defaultToConfig2,
3405 withXSRFToken: defaultToConfig2,
3406 adapter: defaultToConfig2,
3407 responseType: defaultToConfig2,
3408 xsrfCookieName: defaultToConfig2,
3409 xsrfHeaderName: defaultToConfig2,
3410 onUploadProgress: defaultToConfig2,
3411 onDownloadProgress: defaultToConfig2,
3412 decompress: defaultToConfig2,
3413 maxContentLength: defaultToConfig2,
3414 maxBodyLength: defaultToConfig2,
3415 beforeRedirect: defaultToConfig2,
3416 transport: defaultToConfig2,
3417 httpAgent: defaultToConfig2,
3418 httpsAgent: defaultToConfig2,
3419 cancelToken: defaultToConfig2,
3420 socketPath: defaultToConfig2,
3421 responseEncoding: defaultToConfig2,
3422 validateStatus: mergeDirectKeys,
3423 headers: (a, b) => mergeDeepProperties(headersToObject(a), headersToObject(b), true)
3424 };
3425
3426 utils$1.forEach(Object.keys(Object.assign({}, config1, config2)), function computeConfigValue(prop) {
3427 const merge = mergeMap[prop] || mergeDeepProperties;
3428 const configValue = merge(config1[prop], config2[prop], prop);
3429 (utils$1.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue);
3430 });
3431
3432 return config;
3433}
3434
3435const resolveConfig = (config) => {
3436 const newConfig = mergeConfig({}, config);
3437
3438 let {data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth} = newConfig;
3439
3440 newConfig.headers = headers = AxiosHeaders$1.from(headers);
3441
3442 newConfig.url = buildURL(buildFullPath(newConfig.baseURL, newConfig.url), config.params, config.paramsSerializer);
3443
3444 // HTTP basic authentication
3445 if (auth) {
3446 headers.set('Authorization', 'Basic ' +
3447 btoa((auth.username || '') + ':' + (auth.password ? unescape(encodeURIComponent(auth.password)) : ''))
3448 );
3449 }
3450
3451 let contentType;
3452
3453 if (utils$1.isFormData(data)) {
3454 if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv) {
3455 headers.setContentType(undefined); // Let the browser set it
3456 } else if ((contentType = headers.getContentType()) !== false) {
3457 // fix semicolon duplication issue for ReactNative FormData implementation
3458 const [type, ...tokens] = contentType ? contentType.split(';').map(token => token.trim()).filter(Boolean) : [];
3459 headers.setContentType([type || 'multipart/form-data', ...tokens].join('; '));
3460 }
3461 }
3462
3463 // Add xsrf header
3464 // This is only done if running in a standard browser environment.
3465 // Specifically not if we're in a web worker, or react-native.
3466
3467 if (platform.hasStandardBrowserEnv) {
3468 withXSRFToken && utils$1.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(newConfig));
3469
3470 if (withXSRFToken || (withXSRFToken !== false && isURLSameOrigin(newConfig.url))) {
3471 // Add xsrf header
3472 const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName);
3473
3474 if (xsrfValue) {
3475 headers.set(xsrfHeaderName, xsrfValue);
3476 }
3477 }
3478 }
3479
3480 return newConfig;
3481};
3482
3483const isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined';
3484
3485const xhrAdapter = isXHRAdapterSupported && function (config) {
3486 return new Promise(function dispatchXhrRequest(resolve, reject) {
3487 const _config = resolveConfig(config);
3488 let requestData = _config.data;
3489 const requestHeaders = AxiosHeaders$1.from(_config.headers).normalize();
3490 let {responseType, onUploadProgress, onDownloadProgress} = _config;
3491 let onCanceled;
3492 let uploadThrottled, downloadThrottled;
3493 let flushUpload, flushDownload;
3494
3495 function done() {
3496 flushUpload && flushUpload(); // flush events
3497 flushDownload && flushDownload(); // flush events
3498
3499 _config.cancelToken && _config.cancelToken.unsubscribe(onCanceled);
3500
3501 _config.signal && _config.signal.removeEventListener('abort', onCanceled);
3502 }
3503
3504 let request = new XMLHttpRequest();
3505
3506 request.open(_config.method.toUpperCase(), _config.url, true);
3507
3508 // Set the request timeout in MS
3509 request.timeout = _config.timeout;
3510
3511 function onloadend() {
3512 if (!request) {
3513 return;
3514 }
3515 // Prepare the response
3516 const responseHeaders = AxiosHeaders$1.from(
3517 'getAllResponseHeaders' in request && request.getAllResponseHeaders()
3518 );
3519 const responseData = !responseType || responseType === 'text' || responseType === 'json' ?
3520 request.responseText : request.response;
3521 const response = {
3522 data: responseData,
3523 status: request.status,
3524 statusText: request.statusText,
3525 headers: responseHeaders,
3526 config,
3527 request
3528 };
3529
3530 settle(function _resolve(value) {
3531 resolve(value);
3532 done();
3533 }, function _reject(err) {
3534 reject(err);
3535 done();
3536 }, response);
3537
3538 // Clean up request
3539 request = null;
3540 }
3541
3542 if ('onloadend' in request) {
3543 // Use onloadend if available
3544 request.onloadend = onloadend;
3545 } else {
3546 // Listen for ready state to emulate onloadend
3547 request.onreadystatechange = function handleLoad() {
3548 if (!request || request.readyState !== 4) {
3549 return;
3550 }
3551
3552 // The request errored out and we didn't get a response, this will be
3553 // handled by onerror instead
3554 // With one exception: request that using file: protocol, most browsers
3555 // will return status as 0 even though it's a successful request
3556 if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {
3557 return;
3558 }
3559 // readystate handler is calling before onerror or ontimeout handlers,
3560 // so we should call onloadend on the next 'tick'
3561 setTimeout(onloadend);
3562 };
3563 }
3564
3565 // Handle browser request cancellation (as opposed to a manual cancellation)
3566 request.onabort = function handleAbort() {
3567 if (!request) {
3568 return;
3569 }
3570
3571 reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request));
3572
3573 // Clean up request
3574 request = null;
3575 };
3576
3577 // Handle low level network errors
3578 request.onerror = function handleError() {
3579 // Real errors are hidden from us by the browser
3580 // onerror should only fire if it's a network error
3581 reject(new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request));
3582
3583 // Clean up request
3584 request = null;
3585 };
3586
3587 // Handle timeout
3588 request.ontimeout = function handleTimeout() {
3589 let timeoutErrorMessage = _config.timeout ? 'timeout of ' + _config.timeout + 'ms exceeded' : 'timeout exceeded';
3590 const transitional = _config.transitional || transitionalDefaults;
3591 if (_config.timeoutErrorMessage) {
3592 timeoutErrorMessage = _config.timeoutErrorMessage;
3593 }
3594 reject(new AxiosError(
3595 timeoutErrorMessage,
3596 transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED,
3597 config,
3598 request));
3599
3600 // Clean up request
3601 request = null;
3602 };
3603
3604 // Remove Content-Type if data is undefined
3605 requestData === undefined && requestHeaders.setContentType(null);
3606
3607 // Add headers to the request
3608 if ('setRequestHeader' in request) {
3609 utils$1.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) {
3610 request.setRequestHeader(key, val);
3611 });
3612 }
3613
3614 // Add withCredentials to request if needed
3615 if (!utils$1.isUndefined(_config.withCredentials)) {
3616 request.withCredentials = !!_config.withCredentials;
3617 }
3618
3619 // Add responseType to request if needed
3620 if (responseType && responseType !== 'json') {
3621 request.responseType = _config.responseType;
3622 }
3623
3624 // Handle progress if needed
3625 if (onDownloadProgress) {
3626 ([downloadThrottled, flushDownload] = progressEventReducer(onDownloadProgress, true));
3627 request.addEventListener('progress', downloadThrottled);
3628 }
3629
3630 // Not all browsers support upload events
3631 if (onUploadProgress && request.upload) {
3632 ([uploadThrottled, flushUpload] = progressEventReducer(onUploadProgress));
3633
3634 request.upload.addEventListener('progress', uploadThrottled);
3635
3636 request.upload.addEventListener('loadend', flushUpload);
3637 }
3638
3639 if (_config.cancelToken || _config.signal) {
3640 // Handle cancellation
3641 // eslint-disable-next-line func-names
3642 onCanceled = cancel => {
3643 if (!request) {
3644 return;
3645 }
3646 reject(!cancel || cancel.type ? new CanceledError(null, config, request) : cancel);
3647 request.abort();
3648 request = null;
3649 };
3650
3651 _config.cancelToken && _config.cancelToken.subscribe(onCanceled);
3652 if (_config.signal) {
3653 _config.signal.aborted ? onCanceled() : _config.signal.addEventListener('abort', onCanceled);
3654 }
3655 }
3656
3657 const protocol = parseProtocol(_config.url);
3658
3659 if (protocol && platform.protocols.indexOf(protocol) === -1) {
3660 reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config));
3661 return;
3662 }
3663
3664
3665 // Send the request
3666 request.send(requestData || null);
3667 });
3668};
3669
3670const composeSignals = (signals, timeout) => {
3671 const {length} = (signals = signals ? signals.filter(Boolean) : []);
3672
3673 if (timeout || length) {
3674 let controller = new AbortController();
3675
3676 let aborted;
3677
3678 const onabort = function (reason) {
3679 if (!aborted) {
3680 aborted = true;
3681 unsubscribe();
3682 const err = reason instanceof Error ? reason : this.reason;
3683 controller.abort(err instanceof AxiosError ? err : new CanceledError(err instanceof Error ? err.message : err));
3684 }
3685 };
3686
3687 let timer = timeout && setTimeout(() => {
3688 timer = null;
3689 onabort(new AxiosError(`timeout ${timeout} of ms exceeded`, AxiosError.ETIMEDOUT));
3690 }, timeout);
3691
3692 const unsubscribe = () => {
3693 if (signals) {
3694 timer && clearTimeout(timer);
3695 timer = null;
3696 signals.forEach(signal => {
3697 signal.unsubscribe ? signal.unsubscribe(onabort) : signal.removeEventListener('abort', onabort);
3698 });
3699 signals = null;
3700 }
3701 };
3702
3703 signals.forEach((signal) => signal.addEventListener('abort', onabort));
3704
3705 const {signal} = controller;
3706
3707 signal.unsubscribe = () => utils$1.asap(unsubscribe);
3708
3709 return signal;
3710 }
3711};
3712
3713const composeSignals$1 = composeSignals;
3714
3715const streamChunk = function* (chunk, chunkSize) {
3716 let len = chunk.byteLength;
3717
3718 if (!chunkSize || len < chunkSize) {
3719 yield chunk;
3720 return;
3721 }
3722
3723 let pos = 0;
3724 let end;
3725
3726 while (pos < len) {
3727 end = pos + chunkSize;
3728 yield chunk.slice(pos, end);
3729 pos = end;
3730 }
3731};
3732
3733const readBytes = async function* (iterable, chunkSize) {
3734 for await (const chunk of readStream(iterable)) {
3735 yield* streamChunk(chunk, chunkSize);
3736 }
3737};
3738
3739const readStream = async function* (stream) {
3740 if (stream[Symbol.asyncIterator]) {
3741 yield* stream;
3742 return;
3743 }
3744
3745 const reader = stream.getReader();
3746 try {
3747 for (;;) {
3748 const {done, value} = await reader.read();
3749 if (done) {
3750 break;
3751 }
3752 yield value;
3753 }
3754 } finally {
3755 await reader.cancel();
3756 }
3757};
3758
3759const trackStream = (stream, chunkSize, onProgress, onFinish) => {
3760 const iterator = readBytes(stream, chunkSize);
3761
3762 let bytes = 0;
3763 let done;
3764 let _onFinish = (e) => {
3765 if (!done) {
3766 done = true;
3767 onFinish && onFinish(e);
3768 }
3769 };
3770
3771 return new ReadableStream({
3772 async pull(controller) {
3773 try {
3774 const {done, value} = await iterator.next();
3775
3776 if (done) {
3777 _onFinish();
3778 controller.close();
3779 return;
3780 }
3781
3782 let len = value.byteLength;
3783 if (onProgress) {
3784 let loadedBytes = bytes += len;
3785 onProgress(loadedBytes);
3786 }
3787 controller.enqueue(new Uint8Array(value));
3788 } catch (err) {
3789 _onFinish(err);
3790 throw err;
3791 }
3792 },
3793 cancel(reason) {
3794 _onFinish(reason);
3795 return iterator.return();
3796 }
3797 }, {
3798 highWaterMark: 2
3799 })
3800};
3801
3802const isFetchSupported = typeof fetch === 'function' && typeof Request === 'function' && typeof Response === 'function';
3803const isReadableStreamSupported = isFetchSupported && typeof ReadableStream === 'function';
3804
3805// used only inside the fetch adapter
3806const encodeText = isFetchSupported && (typeof TextEncoder === 'function' ?
3807 ((encoder) => (str) => encoder.encode(str))(new TextEncoder()) :
3808 async (str) => new Uint8Array(await new Response(str).arrayBuffer())
3809);
3810
3811const test = (fn, ...args) => {
3812 try {
3813 return !!fn(...args);
3814 } catch (e) {
3815 return false
3816 }
3817};
3818
3819const supportsRequestStream = isReadableStreamSupported && test(() => {
3820 let duplexAccessed = false;
3821
3822 const hasContentType = new Request(platform.origin, {
3823 body: new ReadableStream(),
3824 method: 'POST',
3825 get duplex() {
3826 duplexAccessed = true;
3827 return 'half';
3828 },
3829 }).headers.has('Content-Type');
3830
3831 return duplexAccessed && !hasContentType;
3832});
3833
3834const DEFAULT_CHUNK_SIZE = 64 * 1024;
3835
3836const supportsResponseStream = isReadableStreamSupported &&
3837 test(() => utils$1.isReadableStream(new Response('').body));
3838
3839
3840const resolvers = {
3841 stream: supportsResponseStream && ((res) => res.body)
3842};
3843
3844isFetchSupported && (((res) => {
3845 ['text', 'arrayBuffer', 'blob', 'formData', 'stream'].forEach(type => {
3846 !resolvers[type] && (resolvers[type] = utils$1.isFunction(res[type]) ? (res) => res[type]() :
3847 (_, config) => {
3848 throw new AxiosError(`Response type '${type}' is not supported`, AxiosError.ERR_NOT_SUPPORT, config);
3849 });
3850 });
3851})(new Response));
3852
3853const getBodyLength = async (body) => {
3854 if (body == null) {
3855 return 0;
3856 }
3857
3858 if(utils$1.isBlob(body)) {
3859 return body.size;
3860 }
3861
3862 if(utils$1.isSpecCompliantForm(body)) {
3863 const _request = new Request(platform.origin, {
3864 method: 'POST',
3865 body,
3866 });
3867 return (await _request.arrayBuffer()).byteLength;
3868 }
3869
3870 if(utils$1.isArrayBufferView(body) || utils$1.isArrayBuffer(body)) {
3871 return body.byteLength;
3872 }
3873
3874 if(utils$1.isURLSearchParams(body)) {
3875 body = body + '';
3876 }
3877
3878 if(utils$1.isString(body)) {
3879 return (await encodeText(body)).byteLength;
3880 }
3881};
3882
3883const resolveBodyLength = async (headers, body) => {
3884 const length = utils$1.toFiniteNumber(headers.getContentLength());
3885
3886 return length == null ? getBodyLength(body) : length;
3887};
3888
3889const fetchAdapter = isFetchSupported && (async (config) => {
3890 let {
3891 url,
3892 method,
3893 data,
3894 signal,
3895 cancelToken,
3896 timeout,
3897 onDownloadProgress,
3898 onUploadProgress,
3899 responseType,
3900 headers,
3901 withCredentials = 'same-origin',
3902 fetchOptions
3903 } = resolveConfig(config);
3904
3905 responseType = responseType ? (responseType + '').toLowerCase() : 'text';
3906
3907 let composedSignal = composeSignals$1([signal, cancelToken && cancelToken.toAbortSignal()], timeout);
3908
3909 let request;
3910
3911 const unsubscribe = composedSignal && composedSignal.unsubscribe && (() => {
3912 composedSignal.unsubscribe();
3913 });
3914
3915 let requestContentLength;
3916
3917 try {
3918 if (
3919 onUploadProgress && supportsRequestStream && method !== 'get' && method !== 'head' &&
3920 (requestContentLength = await resolveBodyLength(headers, data)) !== 0
3921 ) {
3922 let _request = new Request(url, {
3923 method: 'POST',
3924 body: data,
3925 duplex: "half"
3926 });
3927
3928 let contentTypeHeader;
3929
3930 if (utils$1.isFormData(data) && (contentTypeHeader = _request.headers.get('content-type'))) {
3931 headers.setContentType(contentTypeHeader);
3932 }
3933
3934 if (_request.body) {
3935 const [onProgress, flush] = progressEventDecorator(
3936 requestContentLength,
3937 progressEventReducer(asyncDecorator(onUploadProgress))
3938 );
3939
3940 data = trackStream(_request.body, DEFAULT_CHUNK_SIZE, onProgress, flush);
3941 }
3942 }
3943
3944 if (!utils$1.isString(withCredentials)) {
3945 withCredentials = withCredentials ? 'include' : 'omit';
3946 }
3947
3948 // Cloudflare Workers throws when credentials are defined
3949 // see https://github.com/cloudflare/workerd/issues/902
3950 const isCredentialsSupported = "credentials" in Request.prototype;
3951 request = new Request(url, {
3952 ...fetchOptions,
3953 signal: composedSignal,
3954 method: method.toUpperCase(),
3955 headers: headers.normalize().toJSON(),
3956 body: data,
3957 duplex: "half",
3958 credentials: isCredentialsSupported ? withCredentials : undefined
3959 });
3960
3961 let response = await fetch(request);
3962
3963 const isStreamResponse = supportsResponseStream && (responseType === 'stream' || responseType === 'response');
3964
3965 if (supportsResponseStream && (onDownloadProgress || (isStreamResponse && unsubscribe))) {
3966 const options = {};
3967
3968 ['status', 'statusText', 'headers'].forEach(prop => {
3969 options[prop] = response[prop];
3970 });
3971
3972 const responseContentLength = utils$1.toFiniteNumber(response.headers.get('content-length'));
3973
3974 const [onProgress, flush] = onDownloadProgress && progressEventDecorator(
3975 responseContentLength,
3976 progressEventReducer(asyncDecorator(onDownloadProgress), true)
3977 ) || [];
3978
3979 response = new Response(
3980 trackStream(response.body, DEFAULT_CHUNK_SIZE, onProgress, () => {
3981 flush && flush();
3982 unsubscribe && unsubscribe();
3983 }),
3984 options
3985 );
3986 }
3987
3988 responseType = responseType || 'text';
3989
3990 let responseData = await resolvers[utils$1.findKey(resolvers, responseType) || 'text'](response, config);
3991
3992 !isStreamResponse && unsubscribe && unsubscribe();
3993
3994 return await new Promise((resolve, reject) => {
3995 settle(resolve, reject, {
3996 data: responseData,
3997 headers: AxiosHeaders$1.from(response.headers),
3998 status: response.status,
3999 statusText: response.statusText,
4000 config,
4001 request
4002 });
4003 })
4004 } catch (err) {
4005 unsubscribe && unsubscribe();
4006
4007 if (err && err.name === 'TypeError' && /fetch/i.test(err.message)) {
4008 throw Object.assign(
4009 new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request),
4010 {
4011 cause: err.cause || err
4012 }
4013 )
4014 }
4015
4016 throw AxiosError.from(err, err && err.code, config, request);
4017 }
4018});
4019
4020const knownAdapters = {
4021 http: httpAdapter,
4022 xhr: xhrAdapter,
4023 fetch: fetchAdapter
4024};
4025
4026utils$1.forEach(knownAdapters, (fn, value) => {
4027 if (fn) {
4028 try {
4029 Object.defineProperty(fn, 'name', {value});
4030 } catch (e) {
4031 // eslint-disable-next-line no-empty
4032 }
4033 Object.defineProperty(fn, 'adapterName', {value});
4034 }
4035});
4036
4037const renderReason = (reason) => `- ${reason}`;
4038
4039const isResolvedHandle = (adapter) => utils$1.isFunction(adapter) || adapter === null || adapter === false;
4040
4041const adapters = {
4042 getAdapter: (adapters) => {
4043 adapters = utils$1.isArray(adapters) ? adapters : [adapters];
4044
4045 const {length} = adapters;
4046 let nameOrAdapter;
4047 let adapter;
4048
4049 const rejectedReasons = {};
4050
4051 for (let i = 0; i < length; i++) {
4052 nameOrAdapter = adapters[i];
4053 let id;
4054
4055 adapter = nameOrAdapter;
4056
4057 if (!isResolvedHandle(nameOrAdapter)) {
4058 adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()];
4059
4060 if (adapter === undefined) {
4061 throw new AxiosError(`Unknown adapter '${id}'`);
4062 }
4063 }
4064
4065 if (adapter) {
4066 break;
4067 }
4068
4069 rejectedReasons[id || '#' + i] = adapter;
4070 }
4071
4072 if (!adapter) {
4073
4074 const reasons = Object.entries(rejectedReasons)
4075 .map(([id, state]) => `adapter ${id} ` +
4076 (state === false ? 'is not supported by the environment' : 'is not available in the build')
4077 );
4078
4079 let s = length ?
4080 (reasons.length > 1 ? 'since :\n' + reasons.map(renderReason).join('\n') : ' ' + renderReason(reasons[0])) :
4081 'as no adapter specified';
4082
4083 throw new AxiosError(
4084 `There is no suitable adapter to dispatch the request ` + s,
4085 'ERR_NOT_SUPPORT'
4086 );
4087 }
4088
4089 return adapter;
4090 },
4091 adapters: knownAdapters
4092};
4093
4094/**
4095 * Throws a `CanceledError` if cancellation has been requested.
4096 *
4097 * @param {Object} config The config that is to be used for the request
4098 *
4099 * @returns {void}
4100 */
4101function throwIfCancellationRequested(config) {
4102 if (config.cancelToken) {
4103 config.cancelToken.throwIfRequested();
4104 }
4105
4106 if (config.signal && config.signal.aborted) {
4107 throw new CanceledError(null, config);
4108 }
4109}
4110
4111/**
4112 * Dispatch a request to the server using the configured adapter.
4113 *
4114 * @param {object} config The config that is to be used for the request
4115 *
4116 * @returns {Promise} The Promise to be fulfilled
4117 */
4118function dispatchRequest(config) {
4119 throwIfCancellationRequested(config);
4120
4121 config.headers = AxiosHeaders$1.from(config.headers);
4122
4123 // Transform request data
4124 config.data = transformData.call(
4125 config,
4126 config.transformRequest
4127 );
4128
4129 if (['post', 'put', 'patch'].indexOf(config.method) !== -1) {
4130 config.headers.setContentType('application/x-www-form-urlencoded', false);
4131 }
4132
4133 const adapter = adapters.getAdapter(config.adapter || defaults$1.adapter);
4134
4135 return adapter(config).then(function onAdapterResolution(response) {
4136 throwIfCancellationRequested(config);
4137
4138 // Transform response data
4139 response.data = transformData.call(
4140 config,
4141 config.transformResponse,
4142 response
4143 );
4144
4145 response.headers = AxiosHeaders$1.from(response.headers);
4146
4147 return response;
4148 }, function onAdapterRejection(reason) {
4149 if (!isCancel(reason)) {
4150 throwIfCancellationRequested(config);
4151
4152 // Transform response data
4153 if (reason && reason.response) {
4154 reason.response.data = transformData.call(
4155 config,
4156 config.transformResponse,
4157 reason.response
4158 );
4159 reason.response.headers = AxiosHeaders$1.from(reason.response.headers);
4160 }
4161 }
4162
4163 return Promise.reject(reason);
4164 });
4165}
4166
4167const validators$1 = {};
4168
4169// eslint-disable-next-line func-names
4170['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach((type, i) => {
4171 validators$1[type] = function validator(thing) {
4172 return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type;
4173 };
4174});
4175
4176const deprecatedWarnings = {};
4177
4178/**
4179 * Transitional option validator
4180 *
4181 * @param {function|boolean?} validator - set to false if the transitional option has been removed
4182 * @param {string?} version - deprecated version / removed since version
4183 * @param {string?} message - some message with additional info
4184 *
4185 * @returns {function}
4186 */
4187validators$1.transitional = function transitional(validator, version, message) {
4188 function formatMessage(opt, desc) {
4189 return '[Axios v' + VERSION + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : '');
4190 }
4191
4192 // eslint-disable-next-line func-names
4193 return (value, opt, opts) => {
4194 if (validator === false) {
4195 throw new AxiosError(
4196 formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')),
4197 AxiosError.ERR_DEPRECATED
4198 );
4199 }
4200
4201 if (version && !deprecatedWarnings[opt]) {
4202 deprecatedWarnings[opt] = true;
4203 // eslint-disable-next-line no-console
4204 console.warn(
4205 formatMessage(
4206 opt,
4207 ' has been deprecated since v' + version + ' and will be removed in the near future'
4208 )
4209 );
4210 }
4211
4212 return validator ? validator(value, opt, opts) : true;
4213 };
4214};
4215
4216/**
4217 * Assert object's properties type
4218 *
4219 * @param {object} options
4220 * @param {object} schema
4221 * @param {boolean?} allowUnknown
4222 *
4223 * @returns {object}
4224 */
4225
4226function assertOptions(options, schema, allowUnknown) {
4227 if (typeof options !== 'object') {
4228 throw new AxiosError('options must be an object', AxiosError.ERR_BAD_OPTION_VALUE);
4229 }
4230 const keys = Object.keys(options);
4231 let i = keys.length;
4232 while (i-- > 0) {
4233 const opt = keys[i];
4234 const validator = schema[opt];
4235 if (validator) {
4236 const value = options[opt];
4237 const result = value === undefined || validator(value, opt, options);
4238 if (result !== true) {
4239 throw new AxiosError('option ' + opt + ' must be ' + result, AxiosError.ERR_BAD_OPTION_VALUE);
4240 }
4241 continue;
4242 }
4243 if (allowUnknown !== true) {
4244 throw new AxiosError('Unknown option ' + opt, AxiosError.ERR_BAD_OPTION);
4245 }
4246 }
4247}
4248
4249const validator = {
4250 assertOptions,
4251 validators: validators$1
4252};
4253
4254const validators = validator.validators;
4255
4256/**
4257 * Create a new instance of Axios
4258 *
4259 * @param {Object} instanceConfig The default config for the instance
4260 *
4261 * @return {Axios} A new instance of Axios
4262 */
4263class Axios {
4264 constructor(instanceConfig) {
4265 this.defaults = instanceConfig;
4266 this.interceptors = {
4267 request: new InterceptorManager$1(),
4268 response: new InterceptorManager$1()
4269 };
4270 }
4271
4272 /**
4273 * Dispatch a request
4274 *
4275 * @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults)
4276 * @param {?Object} config
4277 *
4278 * @returns {Promise} The Promise to be fulfilled
4279 */
4280 async request(configOrUrl, config) {
4281 try {
4282 return await this._request(configOrUrl, config);
4283 } catch (err) {
4284 if (err instanceof Error) {
4285 let dummy;
4286
4287 Error.captureStackTrace ? Error.captureStackTrace(dummy = {}) : (dummy = new Error());
4288
4289 // slice off the Error: ... line
4290 const stack = dummy.stack ? dummy.stack.replace(/^.+\n/, '') : '';
4291 try {
4292 if (!err.stack) {
4293 err.stack = stack;
4294 // match without the 2 top stack lines
4295 } else if (stack && !String(err.stack).endsWith(stack.replace(/^.+\n.+\n/, ''))) {
4296 err.stack += '\n' + stack;
4297 }
4298 } catch (e) {
4299 // ignore the case where "stack" is an un-writable property
4300 }
4301 }
4302
4303 throw err;
4304 }
4305 }
4306
4307 _request(configOrUrl, config) {
4308 /*eslint no-param-reassign:0*/
4309 // Allow for axios('example/url'[, config]) a la fetch API
4310 if (typeof configOrUrl === 'string') {
4311 config = config || {};
4312 config.url = configOrUrl;
4313 } else {
4314 config = configOrUrl || {};
4315 }
4316
4317 config = mergeConfig(this.defaults, config);
4318
4319 const {transitional, paramsSerializer, headers} = config;
4320
4321 if (transitional !== undefined) {
4322 validator.assertOptions(transitional, {
4323 silentJSONParsing: validators.transitional(validators.boolean),
4324 forcedJSONParsing: validators.transitional(validators.boolean),
4325 clarifyTimeoutError: validators.transitional(validators.boolean)
4326 }, false);
4327 }
4328
4329 if (paramsSerializer != null) {
4330 if (utils$1.isFunction(paramsSerializer)) {
4331 config.paramsSerializer = {
4332 serialize: paramsSerializer
4333 };
4334 } else {
4335 validator.assertOptions(paramsSerializer, {
4336 encode: validators.function,
4337 serialize: validators.function
4338 }, true);
4339 }
4340 }
4341
4342 // Set config.method
4343 config.method = (config.method || this.defaults.method || 'get').toLowerCase();
4344
4345 // Flatten headers
4346 let contextHeaders = headers && utils$1.merge(
4347 headers.common,
4348 headers[config.method]
4349 );
4350
4351 headers && utils$1.forEach(
4352 ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
4353 (method) => {
4354 delete headers[method];
4355 }
4356 );
4357
4358 config.headers = AxiosHeaders$1.concat(contextHeaders, headers);
4359
4360 // filter out skipped interceptors
4361 const requestInterceptorChain = [];
4362 let synchronousRequestInterceptors = true;
4363 this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
4364 if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {
4365 return;
4366 }
4367
4368 synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
4369
4370 requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
4371 });
4372
4373 const responseInterceptorChain = [];
4374 this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
4375 responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
4376 });
4377
4378 let promise;
4379 let i = 0;
4380 let len;
4381
4382 if (!synchronousRequestInterceptors) {
4383 const chain = [dispatchRequest.bind(this), undefined];
4384 chain.unshift.apply(chain, requestInterceptorChain);
4385 chain.push.apply(chain, responseInterceptorChain);
4386 len = chain.length;
4387
4388 promise = Promise.resolve(config);
4389
4390 while (i < len) {
4391 promise = promise.then(chain[i++], chain[i++]);
4392 }
4393
4394 return promise;
4395 }
4396
4397 len = requestInterceptorChain.length;
4398
4399 let newConfig = config;
4400
4401 i = 0;
4402
4403 while (i < len) {
4404 const onFulfilled = requestInterceptorChain[i++];
4405 const onRejected = requestInterceptorChain[i++];
4406 try {
4407 newConfig = onFulfilled(newConfig);
4408 } catch (error) {
4409 onRejected.call(this, error);
4410 break;
4411 }
4412 }
4413
4414 try {
4415 promise = dispatchRequest.call(this, newConfig);
4416 } catch (error) {
4417 return Promise.reject(error);
4418 }
4419
4420 i = 0;
4421 len = responseInterceptorChain.length;
4422
4423 while (i < len) {
4424 promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);
4425 }
4426
4427 return promise;
4428 }
4429
4430 getUri(config) {
4431 config = mergeConfig(this.defaults, config);
4432 const fullPath = buildFullPath(config.baseURL, config.url);
4433 return buildURL(fullPath, config.params, config.paramsSerializer);
4434 }
4435}
4436
4437// Provide aliases for supported request methods
4438utils$1.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
4439 /*eslint func-names:0*/
4440 Axios.prototype[method] = function(url, config) {
4441 return this.request(mergeConfig(config || {}, {
4442 method,
4443 url,
4444 data: (config || {}).data
4445 }));
4446 };
4447});
4448
4449utils$1.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
4450 /*eslint func-names:0*/
4451
4452 function generateHTTPMethod(isForm) {
4453 return function httpMethod(url, data, config) {
4454 return this.request(mergeConfig(config || {}, {
4455 method,
4456 headers: isForm ? {
4457 'Content-Type': 'multipart/form-data'
4458 } : {},
4459 url,
4460 data
4461 }));
4462 };
4463 }
4464
4465 Axios.prototype[method] = generateHTTPMethod();
4466
4467 Axios.prototype[method + 'Form'] = generateHTTPMethod(true);
4468});
4469
4470const Axios$1 = Axios;
4471
4472/**
4473 * A `CancelToken` is an object that can be used to request cancellation of an operation.
4474 *
4475 * @param {Function} executor The executor function.
4476 *
4477 * @returns {CancelToken}
4478 */
4479class CancelToken {
4480 constructor(executor) {
4481 if (typeof executor !== 'function') {
4482 throw new TypeError('executor must be a function.');
4483 }
4484
4485 let resolvePromise;
4486
4487 this.promise = new Promise(function promiseExecutor(resolve) {
4488 resolvePromise = resolve;
4489 });
4490
4491 const token = this;
4492
4493 // eslint-disable-next-line func-names
4494 this.promise.then(cancel => {
4495 if (!token._listeners) return;
4496
4497 let i = token._listeners.length;
4498
4499 while (i-- > 0) {
4500 token._listeners[i](cancel);
4501 }
4502 token._listeners = null;
4503 });
4504
4505 // eslint-disable-next-line func-names
4506 this.promise.then = onfulfilled => {
4507 let _resolve;
4508 // eslint-disable-next-line func-names
4509 const promise = new Promise(resolve => {
4510 token.subscribe(resolve);
4511 _resolve = resolve;
4512 }).then(onfulfilled);
4513
4514 promise.cancel = function reject() {
4515 token.unsubscribe(_resolve);
4516 };
4517
4518 return promise;
4519 };
4520
4521 executor(function cancel(message, config, request) {
4522 if (token.reason) {
4523 // Cancellation has already been requested
4524 return;
4525 }
4526
4527 token.reason = new CanceledError(message, config, request);
4528 resolvePromise(token.reason);
4529 });
4530 }
4531
4532 /**
4533 * Throws a `CanceledError` if cancellation has been requested.
4534 */
4535 throwIfRequested() {
4536 if (this.reason) {
4537 throw this.reason;
4538 }
4539 }
4540
4541 /**
4542 * Subscribe to the cancel signal
4543 */
4544
4545 subscribe(listener) {
4546 if (this.reason) {
4547 listener(this.reason);
4548 return;
4549 }
4550
4551 if (this._listeners) {
4552 this._listeners.push(listener);
4553 } else {
4554 this._listeners = [listener];
4555 }
4556 }
4557
4558 /**
4559 * Unsubscribe from the cancel signal
4560 */
4561
4562 unsubscribe(listener) {
4563 if (!this._listeners) {
4564 return;
4565 }
4566 const index = this._listeners.indexOf(listener);
4567 if (index !== -1) {
4568 this._listeners.splice(index, 1);
4569 }
4570 }
4571
4572 toAbortSignal() {
4573 const controller = new AbortController();
4574
4575 const abort = (err) => {
4576 controller.abort(err);
4577 };
4578
4579 this.subscribe(abort);
4580
4581 controller.signal.unsubscribe = () => this.unsubscribe(abort);
4582
4583 return controller.signal;
4584 }
4585
4586 /**
4587 * Returns an object that contains a new `CancelToken` and a function that, when called,
4588 * cancels the `CancelToken`.
4589 */
4590 static source() {
4591 let cancel;
4592 const token = new CancelToken(function executor(c) {
4593 cancel = c;
4594 });
4595 return {
4596 token,
4597 cancel
4598 };
4599 }
4600}
4601
4602const CancelToken$1 = CancelToken;
4603
4604/**
4605 * Syntactic sugar for invoking a function and expanding an array for arguments.
4606 *
4607 * Common use case would be to use `Function.prototype.apply`.
4608 *
4609 * ```js
4610 * function f(x, y, z) {}
4611 * var args = [1, 2, 3];
4612 * f.apply(null, args);
4613 * ```
4614 *
4615 * With `spread` this example can be re-written.
4616 *
4617 * ```js
4618 * spread(function(x, y, z) {})([1, 2, 3]);
4619 * ```
4620 *
4621 * @param {Function} callback
4622 *
4623 * @returns {Function}
4624 */
4625function spread(callback) {
4626 return function wrap(arr) {
4627 return callback.apply(null, arr);
4628 };
4629}
4630
4631/**
4632 * Determines whether the payload is an error thrown by Axios
4633 *
4634 * @param {*} payload The value to test
4635 *
4636 * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
4637 */
4638function isAxiosError(payload) {
4639 return utils$1.isObject(payload) && (payload.isAxiosError === true);
4640}
4641
4642const HttpStatusCode = {
4643 Continue: 100,
4644 SwitchingProtocols: 101,
4645 Processing: 102,
4646 EarlyHints: 103,
4647 Ok: 200,
4648 Created: 201,
4649 Accepted: 202,
4650 NonAuthoritativeInformation: 203,
4651 NoContent: 204,
4652 ResetContent: 205,
4653 PartialContent: 206,
4654 MultiStatus: 207,
4655 AlreadyReported: 208,
4656 ImUsed: 226,
4657 MultipleChoices: 300,
4658 MovedPermanently: 301,
4659 Found: 302,
4660 SeeOther: 303,
4661 NotModified: 304,
4662 UseProxy: 305,
4663 Unused: 306,
4664 TemporaryRedirect: 307,
4665 PermanentRedirect: 308,
4666 BadRequest: 400,
4667 Unauthorized: 401,
4668 PaymentRequired: 402,
4669 Forbidden: 403,
4670 NotFound: 404,
4671 MethodNotAllowed: 405,
4672 NotAcceptable: 406,
4673 ProxyAuthenticationRequired: 407,
4674 RequestTimeout: 408,
4675 Conflict: 409,
4676 Gone: 410,
4677 LengthRequired: 411,
4678 PreconditionFailed: 412,
4679 PayloadTooLarge: 413,
4680 UriTooLong: 414,
4681 UnsupportedMediaType: 415,
4682 RangeNotSatisfiable: 416,
4683 ExpectationFailed: 417,
4684 ImATeapot: 418,
4685 MisdirectedRequest: 421,
4686 UnprocessableEntity: 422,
4687 Locked: 423,
4688 FailedDependency: 424,
4689 TooEarly: 425,
4690 UpgradeRequired: 426,
4691 PreconditionRequired: 428,
4692 TooManyRequests: 429,
4693 RequestHeaderFieldsTooLarge: 431,
4694 UnavailableForLegalReasons: 451,
4695 InternalServerError: 500,
4696 NotImplemented: 501,
4697 BadGateway: 502,
4698 ServiceUnavailable: 503,
4699 GatewayTimeout: 504,
4700 HttpVersionNotSupported: 505,
4701 VariantAlsoNegotiates: 506,
4702 InsufficientStorage: 507,
4703 LoopDetected: 508,
4704 NotExtended: 510,
4705 NetworkAuthenticationRequired: 511,
4706};
4707
4708Object.entries(HttpStatusCode).forEach(([key, value]) => {
4709 HttpStatusCode[value] = key;
4710});
4711
4712const HttpStatusCode$1 = HttpStatusCode;
4713
4714/**
4715 * Create an instance of Axios
4716 *
4717 * @param {Object} defaultConfig The default config for the instance
4718 *
4719 * @returns {Axios} A new instance of Axios
4720 */
4721function createInstance(defaultConfig) {
4722 const context = new Axios$1(defaultConfig);
4723 const instance = bind(Axios$1.prototype.request, context);
4724
4725 // Copy axios.prototype to instance
4726 utils$1.extend(instance, Axios$1.prototype, context, {allOwnKeys: true});
4727
4728 // Copy context to instance
4729 utils$1.extend(instance, context, null, {allOwnKeys: true});
4730
4731 // Factory for creating new instances
4732 instance.create = function create(instanceConfig) {
4733 return createInstance(mergeConfig(defaultConfig, instanceConfig));
4734 };
4735
4736 return instance;
4737}
4738
4739// Create the default instance to be exported
4740const axios = createInstance(defaults$1);
4741
4742// Expose Axios class to allow class inheritance
4743axios.Axios = Axios$1;
4744
4745// Expose Cancel & CancelToken
4746axios.CanceledError = CanceledError;
4747axios.CancelToken = CancelToken$1;
4748axios.isCancel = isCancel;
4749axios.VERSION = VERSION;
4750axios.toFormData = toFormData;
4751
4752// Expose AxiosError class
4753axios.AxiosError = AxiosError;
4754
4755// alias for CanceledError for backward compatibility
4756axios.Cancel = axios.CanceledError;
4757
4758// Expose all/spread
4759axios.all = function all(promises) {
4760 return Promise.all(promises);
4761};
4762
4763axios.spread = spread;
4764
4765// Expose isAxiosError
4766axios.isAxiosError = isAxiosError;
4767
4768// Expose mergeConfig
4769axios.mergeConfig = mergeConfig;
4770
4771axios.AxiosHeaders = AxiosHeaders$1;
4772
4773axios.formToJSON = thing => formDataToJSON(utils$1.isHTMLForm(thing) ? new FormData(thing) : thing);
4774
4775axios.getAdapter = adapters.getAdapter;
4776
4777axios.HttpStatusCode = HttpStatusCode$1;
4778
4779axios.default = axios;
4780
4781module.exports = axios;
4782//# sourceMappingURL=axios.cjs.map
Note: See TracBrowser for help on using the repository browser.