@wiajs/req 1.7.7

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