axios 0.27.2 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of axios might be problematic. Click here for more details.

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