source: node_modules/axios/dist/node/axios.cjs

main
Last change on this file was d24f17c, checked in by Aleksandar Panovski <apano77@…>, 15 months ago

Initial commit

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