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