@wiajs/req 1.7.12 → 1.7.13

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