axios 1.9.0 → 1.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- /*! Axios v1.9.0 Copyright (c) 2025 Matt Zabriskie and contributors */
1
+ /*! Axios v1.12.0 Copyright (c) 2025 Matt Zabriskie and contributors */
2
2
  'use strict';
3
3
 
4
4
  const FormData$1 = require('form-data');
@@ -77,7 +77,7 @@ const isUndefined = typeOfTest('undefined');
77
77
  */
78
78
  function isBuffer(val) {
79
79
  return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)
80
- && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val);
80
+ && isFunction$1(val.constructor.isBuffer) && val.constructor.isBuffer(val);
81
81
  }
82
82
 
83
83
  /**
@@ -122,7 +122,7 @@ const isString = typeOfTest('string');
122
122
  * @param {*} val The value to test
123
123
  * @returns {boolean} True if value is a Function, otherwise false
124
124
  */
125
- const isFunction = typeOfTest('function');
125
+ const isFunction$1 = typeOfTest('function');
126
126
 
127
127
  /**
128
128
  * Determine if a value is a Number
@@ -166,6 +166,27 @@ const isPlainObject = (val) => {
166
166
  return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(toStringTag in val) && !(iterator in val);
167
167
  };
168
168
 
169
+ /**
170
+ * Determine if a value is an empty object (safely handles Buffers)
171
+ *
172
+ * @param {*} val The value to test
173
+ *
174
+ * @returns {boolean} True if value is an empty object, otherwise false
175
+ */
176
+ const isEmptyObject = (val) => {
177
+ // Early return for non-objects or Buffers to prevent RangeError
178
+ if (!isObject(val) || isBuffer(val)) {
179
+ return false;
180
+ }
181
+
182
+ try {
183
+ return Object.keys(val).length === 0 && Object.getPrototypeOf(val) === Object.prototype;
184
+ } catch (e) {
185
+ // Fallback for any other objects that might cause RangeError with Object.keys()
186
+ return false;
187
+ }
188
+ };
189
+
169
190
  /**
170
191
  * Determine if a value is a Date
171
192
  *
@@ -209,7 +230,7 @@ const isFileList = kindOfTest('FileList');
209
230
  *
210
231
  * @returns {boolean} True if value is a Stream, otherwise false
211
232
  */
212
- const isStream = (val) => isObject(val) && isFunction(val.pipe);
233
+ const isStream = (val) => isObject(val) && isFunction$1(val.pipe);
213
234
 
214
235
  /**
215
236
  * Determine if a value is a FormData
@@ -222,10 +243,10 @@ const isFormData = (thing) => {
222
243
  let kind;
223
244
  return thing && (
224
245
  (typeof FormData === 'function' && thing instanceof FormData) || (
225
- isFunction(thing.append) && (
246
+ isFunction$1(thing.append) && (
226
247
  (kind = kindOf(thing)) === 'formdata' ||
227
248
  // detect form-data instance
228
- (kind === 'object' && isFunction(thing.toString) && thing.toString() === '[object FormData]')
249
+ (kind === 'object' && isFunction$1(thing.toString) && thing.toString() === '[object FormData]')
229
250
  )
230
251
  )
231
252
  )
@@ -288,6 +309,11 @@ function forEach(obj, fn, {allOwnKeys = false} = {}) {
288
309
  fn.call(null, obj[i], i, obj);
289
310
  }
290
311
  } else {
312
+ // Buffer check
313
+ if (isBuffer(obj)) {
314
+ return;
315
+ }
316
+
291
317
  // Iterate over object keys
292
318
  const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);
293
319
  const len = keys.length;
@@ -301,6 +327,10 @@ function forEach(obj, fn, {allOwnKeys = false} = {}) {
301
327
  }
302
328
 
303
329
  function findKey(obj, key) {
330
+ if (isBuffer(obj)){
331
+ return null;
332
+ }
333
+
304
334
  key = key.toLowerCase();
305
335
  const keys = Object.keys(obj);
306
336
  let i = keys.length;
@@ -341,7 +371,7 @@ const isContextDefined = (context) => !isUndefined(context) && context !== _glob
341
371
  * @returns {Object} Result of all merge properties
342
372
  */
343
373
  function merge(/* obj1, obj2, obj3, ... */) {
344
- const {caseless} = isContextDefined(this) && this || {};
374
+ const {caseless, skipUndefined} = isContextDefined(this) && this || {};
345
375
  const result = {};
346
376
  const assignValue = (val, key) => {
347
377
  const targetKey = caseless && findKey(result, key) || key;
@@ -352,7 +382,9 @@ function merge(/* obj1, obj2, obj3, ... */) {
352
382
  } else if (isArray(val)) {
353
383
  result[targetKey] = val.slice();
354
384
  } else {
355
- result[targetKey] = val;
385
+ if (!skipUndefined || !isUndefined(val)) {
386
+ result[targetKey] = val;
387
+ }
356
388
  }
357
389
  };
358
390
 
@@ -374,7 +406,7 @@ function merge(/* obj1, obj2, obj3, ... */) {
374
406
  */
375
407
  const extend = (a, b, thisArg, {allOwnKeys}= {}) => {
376
408
  forEach(b, (val, key) => {
377
- if (thisArg && isFunction(val)) {
409
+ if (thisArg && isFunction$1(val)) {
378
410
  a[key] = bind(val, thisArg);
379
411
  } else {
380
412
  a[key] = val;
@@ -590,13 +622,13 @@ const reduceDescriptors = (obj, reducer) => {
590
622
  const freezeMethods = (obj) => {
591
623
  reduceDescriptors(obj, (descriptor, name) => {
592
624
  // skip restricted props in strict mode
593
- if (isFunction(obj) && ['arguments', 'caller', 'callee'].indexOf(name) !== -1) {
625
+ if (isFunction$1(obj) && ['arguments', 'caller', 'callee'].indexOf(name) !== -1) {
594
626
  return false;
595
627
  }
596
628
 
597
629
  const value = obj[name];
598
630
 
599
- if (!isFunction(value)) return;
631
+ if (!isFunction$1(value)) return;
600
632
 
601
633
  descriptor.enumerable = false;
602
634
 
@@ -633,6 +665,8 @@ const toFiniteNumber = (value, defaultValue) => {
633
665
  return value != null && Number.isFinite(value = +value) ? value : defaultValue;
634
666
  };
635
667
 
668
+
669
+
636
670
  /**
637
671
  * If the thing is a FormData object, return true, otherwise return false.
638
672
  *
@@ -641,7 +675,7 @@ const toFiniteNumber = (value, defaultValue) => {
641
675
  * @returns {boolean}
642
676
  */
643
677
  function isSpecCompliantForm(thing) {
644
- return !!(thing && isFunction(thing.append) && thing[toStringTag] === 'FormData' && thing[iterator]);
678
+ return !!(thing && isFunction$1(thing.append) && thing[toStringTag] === 'FormData' && thing[iterator]);
645
679
  }
646
680
 
647
681
  const toJSONObject = (obj) => {
@@ -654,6 +688,11 @@ const toJSONObject = (obj) => {
654
688
  return;
655
689
  }
656
690
 
691
+ //Buffer check
692
+ if (isBuffer(source)) {
693
+ return source;
694
+ }
695
+
657
696
  if(!('toJSON' in source)) {
658
697
  stack[i] = source;
659
698
  const target = isArray(source) ? [] : {};
@@ -678,7 +717,7 @@ const toJSONObject = (obj) => {
678
717
  const isAsyncFn = kindOfTest('AsyncFunction');
679
718
 
680
719
  const isThenable = (thing) =>
681
- thing && (isObject(thing) || isFunction(thing)) && isFunction(thing.then) && isFunction(thing.catch);
720
+ thing && (isObject(thing) || isFunction$1(thing)) && isFunction$1(thing.then) && isFunction$1(thing.catch);
682
721
 
683
722
  // original code
684
723
  // https://github.com/DigitalBrainJS/AxiosPromise/blob/16deab13710ec09779922131f3fa5954320f83ab/lib/utils.js#L11-L34
@@ -702,7 +741,7 @@ const _setImmediate = ((setImmediateSupported, postMessageSupported) => {
702
741
  })(`axios@${Math.random()}`, []) : (cb) => setTimeout(cb);
703
742
  })(
704
743
  typeof setImmediate === 'function',
705
- isFunction(_global.postMessage)
744
+ isFunction$1(_global.postMessage)
706
745
  );
707
746
 
708
747
  const asap = typeof queueMicrotask !== 'undefined' ?
@@ -711,7 +750,7 @@ const asap = typeof queueMicrotask !== 'undefined' ?
711
750
  // *********************
712
751
 
713
752
 
714
- const isIterable = (thing) => thing != null && isFunction(thing[iterator]);
753
+ const isIterable = (thing) => thing != null && isFunction$1(thing[iterator]);
715
754
 
716
755
 
717
756
  const utils$1 = {
@@ -725,6 +764,7 @@ const utils$1 = {
725
764
  isBoolean,
726
765
  isObject,
727
766
  isPlainObject,
767
+ isEmptyObject,
728
768
  isReadableStream,
729
769
  isRequest,
730
770
  isResponse,
@@ -734,7 +774,7 @@ const utils$1 = {
734
774
  isFile,
735
775
  isBlob,
736
776
  isRegExp,
737
- isFunction,
777
+ isFunction: isFunction$1,
738
778
  isStream,
739
779
  isURLSearchParams,
740
780
  isTypedArray,
@@ -860,11 +900,18 @@ AxiosError.from = (error, code, config, request, response, customProps) => {
860
900
  return prop !== 'isAxiosError';
861
901
  });
862
902
 
863
- AxiosError.call(axiosError, error.message, code, config, request, response);
903
+ const msg = error && error.message ? error.message : 'Error';
904
+
905
+ // Prefer explicit code; otherwise copy the low-level error's code (e.g. ECONNREFUSED)
906
+ const errCode = code == null && error ? error.code : code;
907
+ AxiosError.call(axiosError, msg, errCode, config, request, response);
864
908
 
865
- axiosError.cause = error;
909
+ // Chain the original error on the standard field; non-enumerable to avoid JSON noise
910
+ if (error && axiosError.cause == null) {
911
+ Object.defineProperty(axiosError, 'cause', { value: error, configurable: true });
912
+ }
866
913
 
867
- axiosError.name = error.name;
914
+ axiosError.name = (error && error.name) || 'Error';
868
915
 
869
916
  customProps && Object.assign(axiosError, customProps);
870
917
 
@@ -986,6 +1033,10 @@ function toFormData(obj, formData, options) {
986
1033
  return value.toISOString();
987
1034
  }
988
1035
 
1036
+ if (utils$1.isBoolean(value)) {
1037
+ return value.toString();
1038
+ }
1039
+
989
1040
  if (!useBlob && utils$1.isBlob(value)) {
990
1041
  throw new AxiosError('Blob is not supported. Use a Buffer instead.');
991
1042
  }
@@ -1148,9 +1199,7 @@ function encode(val) {
1148
1199
  replace(/%3A/gi, ':').
1149
1200
  replace(/%24/g, '$').
1150
1201
  replace(/%2C/gi, ',').
1151
- replace(/%20/g, '+').
1152
- replace(/%5B/gi, '[').
1153
- replace(/%5D/gi, ']');
1202
+ replace(/%20/g, '+');
1154
1203
  }
1155
1204
 
1156
1205
  /**
@@ -1370,7 +1419,7 @@ const platform = {
1370
1419
  };
1371
1420
 
1372
1421
  function toURLEncodedForm(data, options) {
1373
- return toFormData(data, new platform.classes.URLSearchParams(), Object.assign({
1422
+ return toFormData(data, new platform.classes.URLSearchParams(), {
1374
1423
  visitor: function(value, key, path, helpers) {
1375
1424
  if (platform.isNode && utils$1.isBuffer(value)) {
1376
1425
  this.append(key, value.toString('base64'));
@@ -1378,8 +1427,9 @@ function toURLEncodedForm(data, options) {
1378
1427
  }
1379
1428
 
1380
1429
  return helpers.defaultVisitor.apply(this, arguments);
1381
- }
1382
- }, options));
1430
+ },
1431
+ ...options
1432
+ });
1383
1433
  }
1384
1434
 
1385
1435
  /**
@@ -1575,7 +1625,7 @@ const defaults = {
1575
1625
  const strictJSONParsing = !silentJSONParsing && JSONRequested;
1576
1626
 
1577
1627
  try {
1578
- return JSON.parse(data);
1628
+ return JSON.parse(data, this.parseReviver);
1579
1629
  } catch (e) {
1580
1630
  if (strictJSONParsing) {
1581
1631
  if (e.name === 'SyntaxError') {
@@ -2102,7 +2152,7 @@ function buildFullPath(baseURL, requestedURL, allowAbsoluteUrls) {
2102
2152
  return requestedURL;
2103
2153
  }
2104
2154
 
2105
- const VERSION = "1.9.0";
2155
+ const VERSION = "1.12.0";
2106
2156
 
2107
2157
  function parseProtocol(url) {
2108
2158
  const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url);
@@ -2530,7 +2580,7 @@ function throttle(fn, freq) {
2530
2580
  clearTimeout(timer);
2531
2581
  timer = null;
2532
2582
  }
2533
- fn.apply(null, args);
2583
+ fn(...args);
2534
2584
  };
2535
2585
 
2536
2586
  const throttled = (...args) => {
@@ -2595,6 +2645,80 @@ const progressEventDecorator = (total, throttled) => {
2595
2645
 
2596
2646
  const asyncDecorator = (fn) => (...args) => utils$1.asap(() => fn(...args));
2597
2647
 
2648
+ /**
2649
+ * Estimate decoded byte length of a data:// URL *without* allocating large buffers.
2650
+ * - For base64: compute exact decoded size using length and padding;
2651
+ * handle %XX at the character-count level (no string allocation).
2652
+ * - For non-base64: use UTF-8 byteLength of the encoded body as a safe upper bound.
2653
+ *
2654
+ * @param {string} url
2655
+ * @returns {number}
2656
+ */
2657
+ function estimateDataURLDecodedBytes(url) {
2658
+ if (!url || typeof url !== 'string') return 0;
2659
+ if (!url.startsWith('data:')) return 0;
2660
+
2661
+ const comma = url.indexOf(',');
2662
+ if (comma < 0) return 0;
2663
+
2664
+ const meta = url.slice(5, comma);
2665
+ const body = url.slice(comma + 1);
2666
+ const isBase64 = /;base64/i.test(meta);
2667
+
2668
+ if (isBase64) {
2669
+ let effectiveLen = body.length;
2670
+ const len = body.length; // cache length
2671
+
2672
+ for (let i = 0; i < len; i++) {
2673
+ if (body.charCodeAt(i) === 37 /* '%' */ && i + 2 < len) {
2674
+ const a = body.charCodeAt(i + 1);
2675
+ const b = body.charCodeAt(i + 2);
2676
+ const isHex =
2677
+ ((a >= 48 && a <= 57) || (a >= 65 && a <= 70) || (a >= 97 && a <= 102)) &&
2678
+ ((b >= 48 && b <= 57) || (b >= 65 && b <= 70) || (b >= 97 && b <= 102));
2679
+
2680
+ if (isHex) {
2681
+ effectiveLen -= 2;
2682
+ i += 2;
2683
+ }
2684
+ }
2685
+ }
2686
+
2687
+ let pad = 0;
2688
+ let idx = len - 1;
2689
+
2690
+ const tailIsPct3D = (j) =>
2691
+ j >= 2 &&
2692
+ body.charCodeAt(j - 2) === 37 && // '%'
2693
+ body.charCodeAt(j - 1) === 51 && // '3'
2694
+ (body.charCodeAt(j) === 68 || body.charCodeAt(j) === 100); // 'D' or 'd'
2695
+
2696
+ if (idx >= 0) {
2697
+ if (body.charCodeAt(idx) === 61 /* '=' */) {
2698
+ pad++;
2699
+ idx--;
2700
+ } else if (tailIsPct3D(idx)) {
2701
+ pad++;
2702
+ idx -= 3;
2703
+ }
2704
+ }
2705
+
2706
+ if (pad === 1 && idx >= 0) {
2707
+ if (body.charCodeAt(idx) === 61 /* '=' */) {
2708
+ pad++;
2709
+ } else if (tailIsPct3D(idx)) {
2710
+ pad++;
2711
+ }
2712
+ }
2713
+
2714
+ const groups = Math.floor(effectiveLen / 4);
2715
+ const bytes = groups * 3 - (pad || 0);
2716
+ return bytes > 0 ? bytes : 0;
2717
+ }
2718
+
2719
+ return Buffer.byteLength(body, 'utf8');
2720
+ }
2721
+
2598
2722
  const zlibOptions = {
2599
2723
  flush: zlib__default["default"].constants.Z_SYNC_FLUSH,
2600
2724
  finishFlush: zlib__default["default"].constants.Z_SYNC_FLUSH
@@ -2615,6 +2739,7 @@ const supportedProtocols = platform.protocols.map(protocol => {
2615
2739
  return protocol + ':';
2616
2740
  });
2617
2741
 
2742
+
2618
2743
  const flushOnFinish = (stream, [throttled, flush]) => {
2619
2744
  stream
2620
2745
  .on('end', flush)
@@ -2623,6 +2748,7 @@ const flushOnFinish = (stream, [throttled, flush]) => {
2623
2748
  return throttled;
2624
2749
  };
2625
2750
 
2751
+
2626
2752
  /**
2627
2753
  * If the proxy or config beforeRedirects functions are defined, call them with the options
2628
2754
  * object.
@@ -2802,6 +2928,21 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) {
2802
2928
  const protocol = parsed.protocol || supportedProtocols[0];
2803
2929
 
2804
2930
  if (protocol === 'data:') {
2931
+ // Apply the same semantics as HTTP: only enforce if a finite, non-negative cap is set.
2932
+ if (config.maxContentLength > -1) {
2933
+ // Use the exact string passed to fromDataURI (config.url); fall back to fullPath if needed.
2934
+ const dataUrl = String(config.url || fullPath || '');
2935
+ const estimated = estimateDataURLDecodedBytes(dataUrl);
2936
+
2937
+ if (estimated > config.maxContentLength) {
2938
+ return reject(new AxiosError(
2939
+ 'maxContentLength size of ' + config.maxContentLength + ' exceeded',
2940
+ AxiosError.ERR_BAD_RESPONSE,
2941
+ config
2942
+ ));
2943
+ }
2944
+ }
2945
+
2805
2946
  let convertedData;
2806
2947
 
2807
2948
  if (method !== 'GET') {
@@ -3404,7 +3545,7 @@ function mergeConfig(config1, config2) {
3404
3545
  headers: (a, b , prop) => mergeDeepProperties(headersToObject(a), headersToObject(b),prop, true)
3405
3546
  };
3406
3547
 
3407
- utils$1.forEach(Object.keys(Object.assign({}, config1, config2)), function computeConfigValue(prop) {
3548
+ utils$1.forEach(Object.keys({...config1, ...config2}), function computeConfigValue(prop) {
3408
3549
  const merge = mergeMap[prop] || mergeDeepProperties;
3409
3550
  const configValue = merge(config1[prop], config2[prop], prop);
3410
3551
  (utils$1.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue);
@@ -3416,7 +3557,7 @@ function mergeConfig(config1, config2) {
3416
3557
  const resolveConfig = (config) => {
3417
3558
  const newConfig = mergeConfig({}, config);
3418
3559
 
3419
- let {data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth} = newConfig;
3560
+ let { data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth } = newConfig;
3420
3561
 
3421
3562
  newConfig.headers = headers = AxiosHeaders$1.from(headers);
3422
3563
 
@@ -3429,17 +3570,21 @@ const resolveConfig = (config) => {
3429
3570
  );
3430
3571
  }
3431
3572
 
3432
- let contentType;
3433
-
3434
3573
  if (utils$1.isFormData(data)) {
3435
3574
  if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv) {
3436
- headers.setContentType(undefined); // Let the browser set it
3437
- } else if ((contentType = headers.getContentType()) !== false) {
3438
- // fix semicolon duplication issue for ReactNative FormData implementation
3439
- const [type, ...tokens] = contentType ? contentType.split(';').map(token => token.trim()).filter(Boolean) : [];
3440
- headers.setContentType([type || 'multipart/form-data', ...tokens].join('; '));
3575
+ headers.setContentType(undefined); // browser handles it
3576
+ } else if (utils$1.isFunction(data.getHeaders)) {
3577
+ // Node.js FormData (like form-data package)
3578
+ const formHeaders = data.getHeaders();
3579
+ // Only set safe headers to avoid overwriting security headers
3580
+ const allowedHeaders = ['content-type', 'content-length'];
3581
+ Object.entries(formHeaders).forEach(([key, val]) => {
3582
+ if (allowedHeaders.includes(key.toLowerCase())) {
3583
+ headers.set(key, val);
3584
+ }
3585
+ });
3441
3586
  }
3442
- }
3587
+ }
3443
3588
 
3444
3589
  // Add xsrf header
3445
3590
  // This is only done if running in a standard browser environment.
@@ -3556,15 +3701,18 @@ const xhrAdapter = isXHRAdapterSupported && function (config) {
3556
3701
  };
3557
3702
 
3558
3703
  // Handle low level network errors
3559
- request.onerror = function handleError() {
3560
- // Real errors are hidden from us by the browser
3561
- // onerror should only fire if it's a network error
3562
- reject(new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request));
3563
-
3564
- // Clean up request
3565
- request = null;
3704
+ request.onerror = function handleError(event) {
3705
+ // Browsers deliver a ProgressEvent in XHR onerror
3706
+ // (message may be empty; when present, surface it)
3707
+ // See https://developer.mozilla.org/docs/Web/API/XMLHttpRequest/error_event
3708
+ const msg = event && event.message ? event.message : 'Network Error';
3709
+ const err = new AxiosError(msg, AxiosError.ERR_NETWORK, config, request);
3710
+ // attach the underlying event for consumers who want details
3711
+ err.event = event || null;
3712
+ reject(err);
3713
+ request = null;
3566
3714
  };
3567
-
3715
+
3568
3716
  // Handle timeout
3569
3717
  request.ontimeout = function handleTimeout() {
3570
3718
  let timeoutErrorMessage = _config.timeout ? 'timeout of ' + _config.timeout + 'ms exceeded' : 'timeout exceeded';
@@ -3780,14 +3928,18 @@ const trackStream = (stream, chunkSize, onProgress, onFinish) => {
3780
3928
  })
3781
3929
  };
3782
3930
 
3783
- const isFetchSupported = typeof fetch === 'function' && typeof Request === 'function' && typeof Response === 'function';
3784
- const isReadableStreamSupported = isFetchSupported && typeof ReadableStream === 'function';
3931
+ const DEFAULT_CHUNK_SIZE = 64 * 1024;
3932
+
3933
+ const {isFunction} = utils$1;
3934
+
3935
+ const globalFetchAPI = (({fetch, Request, Response}) => ({
3936
+ fetch, Request, Response
3937
+ }))(utils$1.global);
3938
+
3939
+ const {
3940
+ ReadableStream: ReadableStream$1, TextEncoder: TextEncoder$1
3941
+ } = utils$1.global;
3785
3942
 
3786
- // used only inside the fetch adapter
3787
- const encodeText = isFetchSupported && (typeof TextEncoder === 'function' ?
3788
- ((encoder) => (str) => encoder.encode(str))(new TextEncoder()) :
3789
- async (str) => new Uint8Array(await new Response(str).arrayBuffer())
3790
- );
3791
3943
 
3792
3944
  const test = (fn, ...args) => {
3793
3945
  try {
@@ -3797,211 +3949,266 @@ const test = (fn, ...args) => {
3797
3949
  }
3798
3950
  };
3799
3951
 
3800
- const supportsRequestStream = isReadableStreamSupported && test(() => {
3801
- let duplexAccessed = false;
3952
+ const factory = (env) => {
3953
+ const {fetch, Request, Response} = Object.assign({}, globalFetchAPI, env);
3954
+ const isFetchSupported = isFunction(fetch);
3955
+ const isRequestSupported = isFunction(Request);
3956
+ const isResponseSupported = isFunction(Response);
3802
3957
 
3803
- const hasContentType = new Request(platform.origin, {
3804
- body: new ReadableStream(),
3805
- method: 'POST',
3806
- get duplex() {
3807
- duplexAccessed = true;
3808
- return 'half';
3809
- },
3810
- }).headers.has('Content-Type');
3958
+ if (!isFetchSupported) {
3959
+ return false;
3960
+ }
3811
3961
 
3812
- return duplexAccessed && !hasContentType;
3813
- });
3962
+ const isReadableStreamSupported = isFetchSupported && isFunction(ReadableStream$1);
3814
3963
 
3815
- const DEFAULT_CHUNK_SIZE = 64 * 1024;
3964
+ const encodeText = isFetchSupported && (typeof TextEncoder$1 === 'function' ?
3965
+ ((encoder) => (str) => encoder.encode(str))(new TextEncoder$1()) :
3966
+ async (str) => new Uint8Array(await new Request(str).arrayBuffer())
3967
+ );
3816
3968
 
3817
- const supportsResponseStream = isReadableStreamSupported &&
3818
- test(() => utils$1.isReadableStream(new Response('').body));
3969
+ const supportsRequestStream = isRequestSupported && isReadableStreamSupported && test(() => {
3970
+ let duplexAccessed = false;
3819
3971
 
3972
+ const hasContentType = new Request(platform.origin, {
3973
+ body: new ReadableStream$1(),
3974
+ method: 'POST',
3975
+ get duplex() {
3976
+ duplexAccessed = true;
3977
+ return 'half';
3978
+ },
3979
+ }).headers.has('Content-Type');
3820
3980
 
3821
- const resolvers = {
3822
- stream: supportsResponseStream && ((res) => res.body)
3823
- };
3981
+ return duplexAccessed && !hasContentType;
3982
+ });
3983
+
3984
+ const supportsResponseStream = isResponseSupported && isReadableStreamSupported &&
3985
+ test(() => utils$1.isReadableStream(new Response('').body));
3986
+
3987
+ const resolvers = {
3988
+ stream: supportsResponseStream && ((res) => res.body)
3989
+ };
3990
+
3991
+ isFetchSupported && ((() => {
3992
+ ['text', 'arrayBuffer', 'blob', 'formData', 'stream'].forEach(type => {
3993
+ !resolvers[type] && (resolvers[type] = (res, config) => {
3994
+ let method = res && res[type];
3995
+
3996
+ if (method) {
3997
+ return method.call(res);
3998
+ }
3824
3999
 
3825
- isFetchSupported && (((res) => {
3826
- ['text', 'arrayBuffer', 'blob', 'formData', 'stream'].forEach(type => {
3827
- !resolvers[type] && (resolvers[type] = utils$1.isFunction(res[type]) ? (res) => res[type]() :
3828
- (_, config) => {
3829
4000
  throw new AxiosError(`Response type '${type}' is not supported`, AxiosError.ERR_NOT_SUPPORT, config);
3830
4001
  });
3831
- });
3832
- })(new Response));
4002
+ });
4003
+ })());
3833
4004
 
3834
- const getBodyLength = async (body) => {
3835
- if (body == null) {
3836
- return 0;
3837
- }
4005
+ const getBodyLength = async (body) => {
4006
+ if (body == null) {
4007
+ return 0;
4008
+ }
3838
4009
 
3839
- if(utils$1.isBlob(body)) {
3840
- return body.size;
3841
- }
4010
+ if (utils$1.isBlob(body)) {
4011
+ return body.size;
4012
+ }
3842
4013
 
3843
- if(utils$1.isSpecCompliantForm(body)) {
3844
- const _request = new Request(platform.origin, {
3845
- method: 'POST',
3846
- body,
3847
- });
3848
- return (await _request.arrayBuffer()).byteLength;
3849
- }
4014
+ if (utils$1.isSpecCompliantForm(body)) {
4015
+ const _request = new Request(platform.origin, {
4016
+ method: 'POST',
4017
+ body,
4018
+ });
4019
+ return (await _request.arrayBuffer()).byteLength;
4020
+ }
3850
4021
 
3851
- if(utils$1.isArrayBufferView(body) || utils$1.isArrayBuffer(body)) {
3852
- return body.byteLength;
3853
- }
4022
+ if (utils$1.isArrayBufferView(body) || utils$1.isArrayBuffer(body)) {
4023
+ return body.byteLength;
4024
+ }
3854
4025
 
3855
- if(utils$1.isURLSearchParams(body)) {
3856
- body = body + '';
3857
- }
4026
+ if (utils$1.isURLSearchParams(body)) {
4027
+ body = body + '';
4028
+ }
3858
4029
 
3859
- if(utils$1.isString(body)) {
3860
- return (await encodeText(body)).byteLength;
3861
- }
3862
- };
4030
+ if (utils$1.isString(body)) {
4031
+ return (await encodeText(body)).byteLength;
4032
+ }
4033
+ };
3863
4034
 
3864
- const resolveBodyLength = async (headers, body) => {
3865
- const length = utils$1.toFiniteNumber(headers.getContentLength());
4035
+ const resolveBodyLength = async (headers, body) => {
4036
+ const length = utils$1.toFiniteNumber(headers.getContentLength());
3866
4037
 
3867
- return length == null ? getBodyLength(body) : length;
3868
- };
4038
+ return length == null ? getBodyLength(body) : length;
4039
+ };
4040
+
4041
+ return async (config) => {
4042
+ let {
4043
+ url,
4044
+ method,
4045
+ data,
4046
+ signal,
4047
+ cancelToken,
4048
+ timeout,
4049
+ onDownloadProgress,
4050
+ onUploadProgress,
4051
+ responseType,
4052
+ headers,
4053
+ withCredentials = 'same-origin',
4054
+ fetchOptions
4055
+ } = resolveConfig(config);
4056
+
4057
+ responseType = responseType ? (responseType + '').toLowerCase() : 'text';
4058
+
4059
+ let composedSignal = composeSignals$1([signal, cancelToken && cancelToken.toAbortSignal()], timeout);
3869
4060
 
3870
- const fetchAdapter = isFetchSupported && (async (config) => {
3871
- let {
3872
- url,
3873
- method,
3874
- data,
3875
- signal,
3876
- cancelToken,
3877
- timeout,
3878
- onDownloadProgress,
3879
- onUploadProgress,
3880
- responseType,
3881
- headers,
3882
- withCredentials = 'same-origin',
3883
- fetchOptions
3884
- } = resolveConfig(config);
3885
-
3886
- responseType = responseType ? (responseType + '').toLowerCase() : 'text';
3887
-
3888
- let composedSignal = composeSignals$1([signal, cancelToken && cancelToken.toAbortSignal()], timeout);
3889
-
3890
- let request;
3891
-
3892
- const unsubscribe = composedSignal && composedSignal.unsubscribe && (() => {
4061
+ let request = null;
4062
+
4063
+ const unsubscribe = composedSignal && composedSignal.unsubscribe && (() => {
3893
4064
  composedSignal.unsubscribe();
3894
- });
4065
+ });
3895
4066
 
3896
- let requestContentLength;
4067
+ let requestContentLength;
3897
4068
 
3898
- try {
3899
- if (
3900
- onUploadProgress && supportsRequestStream && method !== 'get' && method !== 'head' &&
3901
- (requestContentLength = await resolveBodyLength(headers, data)) !== 0
3902
- ) {
3903
- let _request = new Request(url, {
3904
- method: 'POST',
3905
- body: data,
3906
- duplex: "half"
3907
- });
4069
+ try {
4070
+ if (
4071
+ onUploadProgress && supportsRequestStream && method !== 'get' && method !== 'head' &&
4072
+ (requestContentLength = await resolveBodyLength(headers, data)) !== 0
4073
+ ) {
4074
+ let _request = new Request(url, {
4075
+ method: 'POST',
4076
+ body: data,
4077
+ duplex: "half"
4078
+ });
3908
4079
 
3909
- let contentTypeHeader;
4080
+ let contentTypeHeader;
3910
4081
 
3911
- if (utils$1.isFormData(data) && (contentTypeHeader = _request.headers.get('content-type'))) {
3912
- headers.setContentType(contentTypeHeader);
3913
- }
4082
+ if (utils$1.isFormData(data) && (contentTypeHeader = _request.headers.get('content-type'))) {
4083
+ headers.setContentType(contentTypeHeader);
4084
+ }
3914
4085
 
3915
- if (_request.body) {
3916
- const [onProgress, flush] = progressEventDecorator(
3917
- requestContentLength,
3918
- progressEventReducer(asyncDecorator(onUploadProgress))
3919
- );
4086
+ if (_request.body) {
4087
+ const [onProgress, flush] = progressEventDecorator(
4088
+ requestContentLength,
4089
+ progressEventReducer(asyncDecorator(onUploadProgress))
4090
+ );
3920
4091
 
3921
- data = trackStream(_request.body, DEFAULT_CHUNK_SIZE, onProgress, flush);
4092
+ data = trackStream(_request.body, DEFAULT_CHUNK_SIZE, onProgress, flush);
4093
+ }
3922
4094
  }
3923
- }
3924
4095
 
3925
- if (!utils$1.isString(withCredentials)) {
3926
- withCredentials = withCredentials ? 'include' : 'omit';
3927
- }
4096
+ if (!utils$1.isString(withCredentials)) {
4097
+ withCredentials = withCredentials ? 'include' : 'omit';
4098
+ }
3928
4099
 
3929
- // Cloudflare Workers throws when credentials are defined
3930
- // see https://github.com/cloudflare/workerd/issues/902
3931
- const isCredentialsSupported = "credentials" in Request.prototype;
3932
- request = new Request(url, {
3933
- ...fetchOptions,
3934
- signal: composedSignal,
3935
- method: method.toUpperCase(),
3936
- headers: headers.normalize().toJSON(),
3937
- body: data,
3938
- duplex: "half",
3939
- credentials: isCredentialsSupported ? withCredentials : undefined
3940
- });
4100
+ // Cloudflare Workers throws when credentials are defined
4101
+ // see https://github.com/cloudflare/workerd/issues/902
4102
+ const isCredentialsSupported = isRequestSupported && "credentials" in Request.prototype;
3941
4103
 
3942
- let response = await fetch(request);
4104
+ const resolvedOptions = {
4105
+ ...fetchOptions,
4106
+ signal: composedSignal,
4107
+ method: method.toUpperCase(),
4108
+ headers: headers.normalize().toJSON(),
4109
+ body: data,
4110
+ duplex: "half",
4111
+ credentials: isCredentialsSupported ? withCredentials : undefined
4112
+ };
3943
4113
 
3944
- const isStreamResponse = supportsResponseStream && (responseType === 'stream' || responseType === 'response');
4114
+ request = isRequestSupported && new Request(url, resolvedOptions);
3945
4115
 
3946
- if (supportsResponseStream && (onDownloadProgress || (isStreamResponse && unsubscribe))) {
3947
- const options = {};
4116
+ let response = await (isRequestSupported ? fetch(request, fetchOptions) : fetch(url, resolvedOptions));
3948
4117
 
3949
- ['status', 'statusText', 'headers'].forEach(prop => {
3950
- options[prop] = response[prop];
3951
- });
4118
+ const isStreamResponse = supportsResponseStream && (responseType === 'stream' || responseType === 'response');
3952
4119
 
3953
- const responseContentLength = utils$1.toFiniteNumber(response.headers.get('content-length'));
4120
+ if (supportsResponseStream && (onDownloadProgress || (isStreamResponse && unsubscribe))) {
4121
+ const options = {};
3954
4122
 
3955
- const [onProgress, flush] = onDownloadProgress && progressEventDecorator(
3956
- responseContentLength,
3957
- progressEventReducer(asyncDecorator(onDownloadProgress), true)
3958
- ) || [];
4123
+ ['status', 'statusText', 'headers'].forEach(prop => {
4124
+ options[prop] = response[prop];
4125
+ });
3959
4126
 
3960
- response = new Response(
3961
- trackStream(response.body, DEFAULT_CHUNK_SIZE, onProgress, () => {
3962
- flush && flush();
3963
- unsubscribe && unsubscribe();
3964
- }),
3965
- options
3966
- );
3967
- }
4127
+ const responseContentLength = utils$1.toFiniteNumber(response.headers.get('content-length'));
3968
4128
 
3969
- responseType = responseType || 'text';
4129
+ const [onProgress, flush] = onDownloadProgress && progressEventDecorator(
4130
+ responseContentLength,
4131
+ progressEventReducer(asyncDecorator(onDownloadProgress), true)
4132
+ ) || [];
3970
4133
 
3971
- let responseData = await resolvers[utils$1.findKey(resolvers, responseType) || 'text'](response, config);
4134
+ response = new Response(
4135
+ trackStream(response.body, DEFAULT_CHUNK_SIZE, onProgress, () => {
4136
+ flush && flush();
4137
+ unsubscribe && unsubscribe();
4138
+ }),
4139
+ options
4140
+ );
4141
+ }
3972
4142
 
3973
- !isStreamResponse && unsubscribe && unsubscribe();
4143
+ responseType = responseType || 'text';
3974
4144
 
3975
- return await new Promise((resolve, reject) => {
3976
- settle(resolve, reject, {
3977
- data: responseData,
3978
- headers: AxiosHeaders$1.from(response.headers),
3979
- status: response.status,
3980
- statusText: response.statusText,
3981
- config,
3982
- request
3983
- });
3984
- })
3985
- } catch (err) {
3986
- unsubscribe && unsubscribe();
3987
-
3988
- if (err && err.name === 'TypeError' && /Load failed|fetch/i.test(err.message)) {
3989
- throw Object.assign(
3990
- new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request),
3991
- {
3992
- cause: err.cause || err
3993
- }
3994
- )
4145
+ let responseData = await resolvers[utils$1.findKey(resolvers, responseType) || 'text'](response, config);
4146
+
4147
+ !isStreamResponse && unsubscribe && unsubscribe();
4148
+
4149
+ return await new Promise((resolve, reject) => {
4150
+ settle(resolve, reject, {
4151
+ data: responseData,
4152
+ headers: AxiosHeaders$1.from(response.headers),
4153
+ status: response.status,
4154
+ statusText: response.statusText,
4155
+ config,
4156
+ request
4157
+ });
4158
+ })
4159
+ } catch (err) {
4160
+ unsubscribe && unsubscribe();
4161
+
4162
+ if (err && err.name === 'TypeError' && /Load failed|fetch/i.test(err.message)) {
4163
+ throw Object.assign(
4164
+ new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request),
4165
+ {
4166
+ cause: err.cause || err
4167
+ }
4168
+ )
4169
+ }
4170
+
4171
+ throw AxiosError.from(err, err && err.code, config, request);
3995
4172
  }
4173
+ }
4174
+ };
4175
+
4176
+ const seedCache = new Map();
4177
+
4178
+ const getFetch = (config) => {
4179
+ let env = utils$1.merge.call({
4180
+ skipUndefined: true
4181
+ }, globalFetchAPI, config ? config.env : null);
3996
4182
 
3997
- throw AxiosError.from(err, err && err.code, config, request);
4183
+ const {fetch, Request, Response} = env;
4184
+
4185
+ const seeds = [
4186
+ Request, Response, fetch
4187
+ ];
4188
+
4189
+ let len = seeds.length, i = len,
4190
+ seed, target, map = seedCache;
4191
+
4192
+ while (i--) {
4193
+ seed = seeds[i];
4194
+ target = map.get(seed);
4195
+
4196
+ target === undefined && map.set(seed, target = (i ? new Map() : factory(env)));
4197
+
4198
+ map = target;
3998
4199
  }
3999
- });
4200
+
4201
+ return target;
4202
+ };
4203
+
4204
+ getFetch();
4000
4205
 
4001
4206
  const knownAdapters = {
4002
4207
  http: httpAdapter,
4003
4208
  xhr: xhrAdapter,
4004
- fetch: fetchAdapter
4209
+ fetch: {
4210
+ get: getFetch,
4211
+ }
4005
4212
  };
4006
4213
 
4007
4214
  utils$1.forEach(knownAdapters, (fn, value) => {
@@ -4020,7 +4227,7 @@ const renderReason = (reason) => `- ${reason}`;
4020
4227
  const isResolvedHandle = (adapter) => utils$1.isFunction(adapter) || adapter === null || adapter === false;
4021
4228
 
4022
4229
  const adapters = {
4023
- getAdapter: (adapters) => {
4230
+ getAdapter: (adapters, config) => {
4024
4231
  adapters = utils$1.isArray(adapters) ? adapters : [adapters];
4025
4232
 
4026
4233
  const {length} = adapters;
@@ -4043,7 +4250,7 @@ const adapters = {
4043
4250
  }
4044
4251
  }
4045
4252
 
4046
- if (adapter) {
4253
+ if (adapter && (utils$1.isFunction(adapter) || (adapter = adapter.get(config)))) {
4047
4254
  break;
4048
4255
  }
4049
4256
 
@@ -4111,7 +4318,7 @@ function dispatchRequest(config) {
4111
4318
  config.headers.setContentType('application/x-www-form-urlencoded', false);
4112
4319
  }
4113
4320
 
4114
- const adapter = adapters.getAdapter(config.adapter || defaults$1.adapter);
4321
+ const adapter = adapters.getAdapter(config.adapter || defaults$1.adapter, config);
4115
4322
 
4116
4323
  return adapter(config).then(function onAdapterResolution(response) {
4117
4324
  throwIfCancellationRequested(config);
@@ -4382,8 +4589,8 @@ class Axios {
4382
4589
 
4383
4590
  if (!synchronousRequestInterceptors) {
4384
4591
  const chain = [dispatchRequest.bind(this), undefined];
4385
- chain.unshift.apply(chain, requestInterceptorChain);
4386
- chain.push.apply(chain, responseInterceptorChain);
4592
+ chain.unshift(...requestInterceptorChain);
4593
+ chain.push(...responseInterceptorChain);
4387
4594
  len = chain.length;
4388
4595
 
4389
4596
  promise = Promise.resolve(config);