axios 1.7.2 → 1.7.4

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

Potentially problematic release.


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

@@ -1,4 +1,4 @@
1
- // Axios v1.7.2 Copyright (c) 2024 Matt Zabriskie and contributors
1
+ // Axios v1.7.4 Copyright (c) 2024 Matt Zabriskie and contributors
2
2
  'use strict';
3
3
 
4
4
  const FormData$1 = require('form-data');
@@ -696,6 +696,36 @@ const isAsyncFn = kindOfTest('AsyncFunction');
696
696
  const isThenable = (thing) =>
697
697
  thing && (isObject(thing) || isFunction(thing)) && isFunction(thing.then) && isFunction(thing.catch);
698
698
 
699
+ // original code
700
+ // https://github.com/DigitalBrainJS/AxiosPromise/blob/16deab13710ec09779922131f3fa5954320f83ab/lib/utils.js#L11-L34
701
+
702
+ const _setImmediate = ((setImmediateSupported, postMessageSupported) => {
703
+ if (setImmediateSupported) {
704
+ return setImmediate;
705
+ }
706
+
707
+ return postMessageSupported ? ((token, callbacks) => {
708
+ _global.addEventListener("message", ({source, data}) => {
709
+ if (source === _global && data === token) {
710
+ callbacks.length && callbacks.shift()();
711
+ }
712
+ }, false);
713
+
714
+ return (cb) => {
715
+ callbacks.push(cb);
716
+ _global.postMessage(token, "*");
717
+ }
718
+ })(`axios@${Math.random()}`, []) : (cb) => setTimeout(cb);
719
+ })(
720
+ typeof setImmediate === 'function',
721
+ isFunction(_global.postMessage)
722
+ );
723
+
724
+ const asap = typeof queueMicrotask !== 'undefined' ?
725
+ queueMicrotask.bind(_global) : ( typeof process !== 'undefined' && process.nextTick || _setImmediate);
726
+
727
+ // *********************
728
+
699
729
  const utils$1 = {
700
730
  isArray,
701
731
  isArrayBuffer,
@@ -751,7 +781,9 @@ const utils$1 = {
751
781
  isSpecCompliantForm,
752
782
  toJSONObject,
753
783
  isAsyncFn,
754
- isThenable
784
+ isThenable,
785
+ setImmediate: _setImmediate,
786
+ asap
755
787
  };
756
788
 
757
789
  /**
@@ -2035,7 +2067,7 @@ function buildFullPath(baseURL, requestedURL) {
2035
2067
  return requestedURL;
2036
2068
  }
2037
2069
 
2038
- const VERSION = "1.7.2";
2070
+ const VERSION = "1.7.4";
2039
2071
 
2040
2072
  function parseProtocol(url) {
2041
2073
  const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url);
@@ -2090,90 +2122,6 @@ function fromDataURI(uri, asBlob, options) {
2090
2122
  throw new AxiosError('Unsupported protocol ' + protocol, AxiosError.ERR_NOT_SUPPORT);
2091
2123
  }
2092
2124
 
2093
- /**
2094
- * Throttle decorator
2095
- * @param {Function} fn
2096
- * @param {Number} freq
2097
- * @return {Function}
2098
- */
2099
- function throttle(fn, freq) {
2100
- let timestamp = 0;
2101
- const threshold = 1000 / freq;
2102
- let timer = null;
2103
- return function throttled() {
2104
- const force = this === true;
2105
-
2106
- const now = Date.now();
2107
- if (force || now - timestamp > threshold) {
2108
- if (timer) {
2109
- clearTimeout(timer);
2110
- timer = null;
2111
- }
2112
- timestamp = now;
2113
- return fn.apply(null, arguments);
2114
- }
2115
- if (!timer) {
2116
- timer = setTimeout(() => {
2117
- timer = null;
2118
- timestamp = Date.now();
2119
- return fn.apply(null, arguments);
2120
- }, threshold - (now - timestamp));
2121
- }
2122
- };
2123
- }
2124
-
2125
- /**
2126
- * Calculate data maxRate
2127
- * @param {Number} [samplesCount= 10]
2128
- * @param {Number} [min= 1000]
2129
- * @returns {Function}
2130
- */
2131
- function speedometer(samplesCount, min) {
2132
- samplesCount = samplesCount || 10;
2133
- const bytes = new Array(samplesCount);
2134
- const timestamps = new Array(samplesCount);
2135
- let head = 0;
2136
- let tail = 0;
2137
- let firstSampleTS;
2138
-
2139
- min = min !== undefined ? min : 1000;
2140
-
2141
- return function push(chunkLength) {
2142
- const now = Date.now();
2143
-
2144
- const startedAt = timestamps[tail];
2145
-
2146
- if (!firstSampleTS) {
2147
- firstSampleTS = now;
2148
- }
2149
-
2150
- bytes[head] = chunkLength;
2151
- timestamps[head] = now;
2152
-
2153
- let i = tail;
2154
- let bytesCount = 0;
2155
-
2156
- while (i !== head) {
2157
- bytesCount += bytes[i++];
2158
- i = i % samplesCount;
2159
- }
2160
-
2161
- head = (head + 1) % samplesCount;
2162
-
2163
- if (head === tail) {
2164
- tail = (tail + 1) % samplesCount;
2165
- }
2166
-
2167
- if (now - firstSampleTS < min) {
2168
- return;
2169
- }
2170
-
2171
- const passed = startedAt && now - startedAt;
2172
-
2173
- return passed ? Math.round(bytesCount * 1000 / passed) : undefined;
2174
- };
2175
- }
2176
-
2177
2125
  const kInternals = Symbol('internals');
2178
2126
 
2179
2127
  class AxiosTransformStream extends stream__default["default"].Transform{
@@ -2193,12 +2141,8 @@ class AxiosTransformStream extends stream__default["default"].Transform{
2193
2141
  readableHighWaterMark: options.chunkSize
2194
2142
  });
2195
2143
 
2196
- const self = this;
2197
-
2198
2144
  const internals = this[kInternals] = {
2199
- length: options.length,
2200
2145
  timeWindow: options.timeWindow,
2201
- ticksRate: options.ticksRate,
2202
2146
  chunkSize: options.chunkSize,
2203
2147
  maxRate: options.maxRate,
2204
2148
  minChunkSize: options.minChunkSize,
@@ -2210,8 +2154,6 @@ class AxiosTransformStream extends stream__default["default"].Transform{
2210
2154
  onReadCallback: null
2211
2155
  };
2212
2156
 
2213
- const _speedometer = speedometer(internals.ticksRate * options.samplesCount, internals.timeWindow);
2214
-
2215
2157
  this.on('newListener', event => {
2216
2158
  if (event === 'progress') {
2217
2159
  if (!internals.isCaptured) {
@@ -2219,39 +2161,6 @@ class AxiosTransformStream extends stream__default["default"].Transform{
2219
2161
  }
2220
2162
  }
2221
2163
  });
2222
-
2223
- let bytesNotified = 0;
2224
-
2225
- internals.updateProgress = throttle(function throttledHandler() {
2226
- const totalBytes = internals.length;
2227
- const bytesTransferred = internals.bytesSeen;
2228
- const progressBytes = bytesTransferred - bytesNotified;
2229
- if (!progressBytes || self.destroyed) return;
2230
-
2231
- const rate = _speedometer(progressBytes);
2232
-
2233
- bytesNotified = bytesTransferred;
2234
-
2235
- process.nextTick(() => {
2236
- self.emit('progress', {
2237
- loaded: bytesTransferred,
2238
- total: totalBytes,
2239
- progress: totalBytes ? (bytesTransferred / totalBytes) : undefined,
2240
- bytes: progressBytes,
2241
- rate: rate ? rate : undefined,
2242
- estimated: rate && totalBytes && bytesTransferred <= totalBytes ?
2243
- (totalBytes - bytesTransferred) / rate : undefined,
2244
- lengthComputable: totalBytes != null
2245
- });
2246
- });
2247
- }, internals.ticksRate);
2248
-
2249
- const onFinish = () => {
2250
- internals.updateProgress.call(true);
2251
- };
2252
-
2253
- this.once('end', onFinish);
2254
- this.once('error', onFinish);
2255
2164
  }
2256
2165
 
2257
2166
  _read(size) {
@@ -2265,7 +2174,6 @@ class AxiosTransformStream extends stream__default["default"].Transform{
2265
2174
  }
2266
2175
 
2267
2176
  _transform(chunk, encoding, callback) {
2268
- const self = this;
2269
2177
  const internals = this[kInternals];
2270
2178
  const maxRate = internals.maxRate;
2271
2179
 
@@ -2277,16 +2185,14 @@ class AxiosTransformStream extends stream__default["default"].Transform{
2277
2185
  const bytesThreshold = (maxRate / divider);
2278
2186
  const minChunkSize = internals.minChunkSize !== false ? Math.max(internals.minChunkSize, bytesThreshold * 0.01) : 0;
2279
2187
 
2280
- function pushChunk(_chunk, _callback) {
2188
+ const pushChunk = (_chunk, _callback) => {
2281
2189
  const bytes = Buffer.byteLength(_chunk);
2282
2190
  internals.bytesSeen += bytes;
2283
2191
  internals.bytes += bytes;
2284
2192
 
2285
- if (internals.isCaptured) {
2286
- internals.updateProgress();
2287
- }
2193
+ internals.isCaptured && this.emit('progress', internals.bytesSeen);
2288
2194
 
2289
- if (self.push(_chunk)) {
2195
+ if (this.push(_chunk)) {
2290
2196
  process.nextTick(_callback);
2291
2197
  } else {
2292
2198
  internals.onReadCallback = () => {
@@ -2294,7 +2200,7 @@ class AxiosTransformStream extends stream__default["default"].Transform{
2294
2200
  process.nextTick(_callback);
2295
2201
  };
2296
2202
  }
2297
- }
2203
+ };
2298
2204
 
2299
2205
  const transformChunk = (_chunk, _callback) => {
2300
2206
  const chunkSize = Buffer.byteLength(_chunk);
@@ -2351,11 +2257,6 @@ class AxiosTransformStream extends stream__default["default"].Transform{
2351
2257
  }
2352
2258
  });
2353
2259
  }
2354
-
2355
- setLength(length) {
2356
- this[kInternals].length = +length;
2357
- return this;
2358
- }
2359
2260
  }
2360
2261
 
2361
2262
  const AxiosTransformStream$1 = AxiosTransformStream;
@@ -2523,6 +2424,142 @@ const callbackify = (fn, reducer) => {
2523
2424
 
2524
2425
  const callbackify$1 = callbackify;
2525
2426
 
2427
+ /**
2428
+ * Calculate data maxRate
2429
+ * @param {Number} [samplesCount= 10]
2430
+ * @param {Number} [min= 1000]
2431
+ * @returns {Function}
2432
+ */
2433
+ function speedometer(samplesCount, min) {
2434
+ samplesCount = samplesCount || 10;
2435
+ const bytes = new Array(samplesCount);
2436
+ const timestamps = new Array(samplesCount);
2437
+ let head = 0;
2438
+ let tail = 0;
2439
+ let firstSampleTS;
2440
+
2441
+ min = min !== undefined ? min : 1000;
2442
+
2443
+ return function push(chunkLength) {
2444
+ const now = Date.now();
2445
+
2446
+ const startedAt = timestamps[tail];
2447
+
2448
+ if (!firstSampleTS) {
2449
+ firstSampleTS = now;
2450
+ }
2451
+
2452
+ bytes[head] = chunkLength;
2453
+ timestamps[head] = now;
2454
+
2455
+ let i = tail;
2456
+ let bytesCount = 0;
2457
+
2458
+ while (i !== head) {
2459
+ bytesCount += bytes[i++];
2460
+ i = i % samplesCount;
2461
+ }
2462
+
2463
+ head = (head + 1) % samplesCount;
2464
+
2465
+ if (head === tail) {
2466
+ tail = (tail + 1) % samplesCount;
2467
+ }
2468
+
2469
+ if (now - firstSampleTS < min) {
2470
+ return;
2471
+ }
2472
+
2473
+ const passed = startedAt && now - startedAt;
2474
+
2475
+ return passed ? Math.round(bytesCount * 1000 / passed) : undefined;
2476
+ };
2477
+ }
2478
+
2479
+ /**
2480
+ * Throttle decorator
2481
+ * @param {Function} fn
2482
+ * @param {Number} freq
2483
+ * @return {Function}
2484
+ */
2485
+ function throttle(fn, freq) {
2486
+ let timestamp = 0;
2487
+ let threshold = 1000 / freq;
2488
+ let lastArgs;
2489
+ let timer;
2490
+
2491
+ const invoke = (args, now = Date.now()) => {
2492
+ timestamp = now;
2493
+ lastArgs = null;
2494
+ if (timer) {
2495
+ clearTimeout(timer);
2496
+ timer = null;
2497
+ }
2498
+ fn.apply(null, args);
2499
+ };
2500
+
2501
+ const throttled = (...args) => {
2502
+ const now = Date.now();
2503
+ const passed = now - timestamp;
2504
+ if ( passed >= threshold) {
2505
+ invoke(args, now);
2506
+ } else {
2507
+ lastArgs = args;
2508
+ if (!timer) {
2509
+ timer = setTimeout(() => {
2510
+ timer = null;
2511
+ invoke(lastArgs);
2512
+ }, threshold - passed);
2513
+ }
2514
+ }
2515
+ };
2516
+
2517
+ const flush = () => lastArgs && invoke(lastArgs);
2518
+
2519
+ return [throttled, flush];
2520
+ }
2521
+
2522
+ const progressEventReducer = (listener, isDownloadStream, freq = 3) => {
2523
+ let bytesNotified = 0;
2524
+ const _speedometer = speedometer(50, 250);
2525
+
2526
+ return throttle(e => {
2527
+ const loaded = e.loaded;
2528
+ const total = e.lengthComputable ? e.total : undefined;
2529
+ const progressBytes = loaded - bytesNotified;
2530
+ const rate = _speedometer(progressBytes);
2531
+ const inRange = loaded <= total;
2532
+
2533
+ bytesNotified = loaded;
2534
+
2535
+ const data = {
2536
+ loaded,
2537
+ total,
2538
+ progress: total ? (loaded / total) : undefined,
2539
+ bytes: progressBytes,
2540
+ rate: rate ? rate : undefined,
2541
+ estimated: rate && total && inRange ? (total - loaded) / rate : undefined,
2542
+ event: e,
2543
+ lengthComputable: total != null,
2544
+ [isDownloadStream ? 'download' : 'upload']: true
2545
+ };
2546
+
2547
+ listener(data);
2548
+ }, freq);
2549
+ };
2550
+
2551
+ const progressEventDecorator = (total, throttled) => {
2552
+ const lengthComputable = total != null;
2553
+
2554
+ return [(loaded) => throttled[0]({
2555
+ lengthComputable,
2556
+ total,
2557
+ loaded
2558
+ }), throttled[1]];
2559
+ };
2560
+
2561
+ const asyncDecorator = (fn) => (...args) => utils$1.asap(() => fn(...args));
2562
+
2526
2563
  const zlibOptions = {
2527
2564
  flush: zlib__default["default"].constants.Z_SYNC_FLUSH,
2528
2565
  finishFlush: zlib__default["default"].constants.Z_SYNC_FLUSH
@@ -2543,6 +2580,14 @@ const supportedProtocols = platform.protocols.map(protocol => {
2543
2580
  return protocol + ':';
2544
2581
  });
2545
2582
 
2583
+ const flushOnFinish = (stream, [throttled, flush]) => {
2584
+ stream
2585
+ .on('end', flush)
2586
+ .on('error', flush);
2587
+
2588
+ return throttled;
2589
+ };
2590
+
2546
2591
  /**
2547
2592
  * If the proxy or config beforeRedirects functions are defined, call them with the options
2548
2593
  * object.
@@ -2718,7 +2763,7 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) {
2718
2763
 
2719
2764
  // Parse url
2720
2765
  const fullPath = buildFullPath(config.baseURL, config.url);
2721
- const parsed = new URL(fullPath, 'http://localhost');
2766
+ const parsed = new URL(fullPath, utils$1.hasBrowserEnv ? platform.origin : undefined);
2722
2767
  const protocol = parsed.protocol || supportedProtocols[0];
2723
2768
 
2724
2769
  if (protocol === 'data:') {
@@ -2776,8 +2821,7 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) {
2776
2821
  // Only set header if it hasn't been set in config
2777
2822
  headers.set('User-Agent', 'axios/' + VERSION, false);
2778
2823
 
2779
- const onDownloadProgress = config.onDownloadProgress;
2780
- const onUploadProgress = config.onUploadProgress;
2824
+ const {onUploadProgress, onDownloadProgress} = config;
2781
2825
  const maxRate = config.maxRate;
2782
2826
  let maxUploadRate = undefined;
2783
2827
  let maxDownloadRate = undefined;
@@ -2848,15 +2892,16 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) {
2848
2892
  }
2849
2893
 
2850
2894
  data = stream__default["default"].pipeline([data, new AxiosTransformStream$1({
2851
- length: contentLength,
2852
2895
  maxRate: utils$1.toFiniteNumber(maxUploadRate)
2853
2896
  })], utils$1.noop);
2854
2897
 
2855
- onUploadProgress && data.on('progress', progress => {
2856
- onUploadProgress(Object.assign(progress, {
2857
- upload: true
2858
- }));
2859
- });
2898
+ onUploadProgress && data.on('progress', flushOnFinish(
2899
+ data,
2900
+ progressEventDecorator(
2901
+ contentLength,
2902
+ progressEventReducer(asyncDecorator(onUploadProgress), false, 3)
2903
+ )
2904
+ ));
2860
2905
  }
2861
2906
 
2862
2907
  // HTTP basic authentication
@@ -2955,17 +3000,18 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) {
2955
3000
 
2956
3001
  const responseLength = +res.headers['content-length'];
2957
3002
 
2958
- if (onDownloadProgress) {
3003
+ if (onDownloadProgress || maxDownloadRate) {
2959
3004
  const transformStream = new AxiosTransformStream$1({
2960
- length: utils$1.toFiniteNumber(responseLength),
2961
3005
  maxRate: utils$1.toFiniteNumber(maxDownloadRate)
2962
3006
  });
2963
3007
 
2964
- onDownloadProgress && transformStream.on('progress', progress => {
2965
- onDownloadProgress(Object.assign(progress, {
2966
- download: true
2967
- }));
2968
- });
3008
+ onDownloadProgress && transformStream.on('progress', flushOnFinish(
3009
+ transformStream,
3010
+ progressEventDecorator(
3011
+ responseLength,
3012
+ progressEventReducer(asyncDecorator(onDownloadProgress), true, 3)
3013
+ )
3014
+ ));
2969
3015
 
2970
3016
  streams.push(transformStream);
2971
3017
  }
@@ -3178,36 +3224,6 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) {
3178
3224
  });
3179
3225
  };
3180
3226
 
3181
- const progressEventReducer = (listener, isDownloadStream, freq = 3) => {
3182
- let bytesNotified = 0;
3183
- const _speedometer = speedometer(50, 250);
3184
-
3185
- return throttle(e => {
3186
- const loaded = e.loaded;
3187
- const total = e.lengthComputable ? e.total : undefined;
3188
- const progressBytes = loaded - bytesNotified;
3189
- const rate = _speedometer(progressBytes);
3190
- const inRange = loaded <= total;
3191
-
3192
- bytesNotified = loaded;
3193
-
3194
- const data = {
3195
- loaded,
3196
- total,
3197
- progress: total ? (loaded / total) : undefined,
3198
- bytes: progressBytes,
3199
- rate: rate ? rate : undefined,
3200
- estimated: rate && total && inRange ? (total - loaded) / rate : undefined,
3201
- event: e,
3202
- lengthComputable: total != null
3203
- };
3204
-
3205
- data[isDownloadStream ? 'download' : 'upload'] = true;
3206
-
3207
- listener(data);
3208
- }, freq);
3209
- };
3210
-
3211
3227
  const isURLSameOrigin = platform.hasStandardBrowserEnv ?
3212
3228
 
3213
3229
  // Standard browser envs have full support of the APIs needed to test
@@ -3467,16 +3483,18 @@ const xhrAdapter = isXHRAdapterSupported && function (config) {
3467
3483
  const _config = resolveConfig(config);
3468
3484
  let requestData = _config.data;
3469
3485
  const requestHeaders = AxiosHeaders$1.from(_config.headers).normalize();
3470
- let {responseType} = _config;
3486
+ let {responseType, onUploadProgress, onDownloadProgress} = _config;
3471
3487
  let onCanceled;
3488
+ let uploadThrottled, downloadThrottled;
3489
+ let flushUpload, flushDownload;
3490
+
3472
3491
  function done() {
3473
- if (_config.cancelToken) {
3474
- _config.cancelToken.unsubscribe(onCanceled);
3475
- }
3492
+ flushUpload && flushUpload(); // flush events
3493
+ flushDownload && flushDownload(); // flush events
3476
3494
 
3477
- if (_config.signal) {
3478
- _config.signal.removeEventListener('abort', onCanceled);
3479
- }
3495
+ _config.cancelToken && _config.cancelToken.unsubscribe(onCanceled);
3496
+
3497
+ _config.signal && _config.signal.removeEventListener('abort', onCanceled);
3480
3498
  }
3481
3499
 
3482
3500
  let request = new XMLHttpRequest();
@@ -3546,7 +3564,7 @@ const xhrAdapter = isXHRAdapterSupported && function (config) {
3546
3564
  return;
3547
3565
  }
3548
3566
 
3549
- reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, _config, request));
3567
+ reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request));
3550
3568
 
3551
3569
  // Clean up request
3552
3570
  request = null;
@@ -3556,7 +3574,7 @@ const xhrAdapter = isXHRAdapterSupported && function (config) {
3556
3574
  request.onerror = function handleError() {
3557
3575
  // Real errors are hidden from us by the browser
3558
3576
  // onerror should only fire if it's a network error
3559
- reject(new AxiosError('Network Error', AxiosError.ERR_NETWORK, _config, request));
3577
+ reject(new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request));
3560
3578
 
3561
3579
  // Clean up request
3562
3580
  request = null;
@@ -3572,7 +3590,7 @@ const xhrAdapter = isXHRAdapterSupported && function (config) {
3572
3590
  reject(new AxiosError(
3573
3591
  timeoutErrorMessage,
3574
3592
  transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED,
3575
- _config,
3593
+ config,
3576
3594
  request));
3577
3595
 
3578
3596
  // Clean up request
@@ -3600,13 +3618,18 @@ const xhrAdapter = isXHRAdapterSupported && function (config) {
3600
3618
  }
3601
3619
 
3602
3620
  // Handle progress if needed
3603
- if (typeof _config.onDownloadProgress === 'function') {
3604
- request.addEventListener('progress', progressEventReducer(_config.onDownloadProgress, true));
3621
+ if (onDownloadProgress) {
3622
+ ([downloadThrottled, flushDownload] = progressEventReducer(onDownloadProgress, true));
3623
+ request.addEventListener('progress', downloadThrottled);
3605
3624
  }
3606
3625
 
3607
3626
  // Not all browsers support upload events
3608
- if (typeof _config.onUploadProgress === 'function' && request.upload) {
3609
- request.upload.addEventListener('progress', progressEventReducer(_config.onUploadProgress));
3627
+ if (onUploadProgress && request.upload) {
3628
+ ([uploadThrottled, flushUpload] = progressEventReducer(onUploadProgress));
3629
+
3630
+ request.upload.addEventListener('progress', uploadThrottled);
3631
+
3632
+ request.upload.addEventListener('loadend', flushUpload);
3610
3633
  }
3611
3634
 
3612
3635
  if (_config.cancelToken || _config.signal) {
@@ -3712,25 +3735,38 @@ const trackStream = (stream, chunkSize, onProgress, onFinish, encode) => {
3712
3735
  const iterator = readBytes(stream, chunkSize, encode);
3713
3736
 
3714
3737
  let bytes = 0;
3738
+ let done;
3739
+ let _onFinish = (e) => {
3740
+ if (!done) {
3741
+ done = true;
3742
+ onFinish && onFinish(e);
3743
+ }
3744
+ };
3715
3745
 
3716
3746
  return new ReadableStream({
3717
- type: 'bytes',
3718
-
3719
3747
  async pull(controller) {
3720
- const {done, value} = await iterator.next();
3748
+ try {
3749
+ const {done, value} = await iterator.next();
3721
3750
 
3722
- if (done) {
3723
- controller.close();
3724
- onFinish();
3725
- return;
3726
- }
3751
+ if (done) {
3752
+ _onFinish();
3753
+ controller.close();
3754
+ return;
3755
+ }
3727
3756
 
3728
- let len = value.byteLength;
3729
- onProgress && onProgress(bytes += len);
3730
- controller.enqueue(new Uint8Array(value));
3757
+ let len = value.byteLength;
3758
+ if (onProgress) {
3759
+ let loadedBytes = bytes += len;
3760
+ onProgress(loadedBytes);
3761
+ }
3762
+ controller.enqueue(new Uint8Array(value));
3763
+ } catch (err) {
3764
+ _onFinish(err);
3765
+ throw err;
3766
+ }
3731
3767
  },
3732
3768
  cancel(reason) {
3733
- onFinish(reason);
3769
+ _onFinish(reason);
3734
3770
  return iterator.return();
3735
3771
  }
3736
3772
  }, {
@@ -3738,15 +3774,6 @@ const trackStream = (stream, chunkSize, onProgress, onFinish, encode) => {
3738
3774
  })
3739
3775
  };
3740
3776
 
3741
- const fetchProgressDecorator = (total, fn) => {
3742
- const lengthComputable = total != null;
3743
- return (loaded) => setTimeout(() => fn({
3744
- lengthComputable,
3745
- total,
3746
- loaded
3747
- }));
3748
- };
3749
-
3750
3777
  const isFetchSupported = typeof fetch === 'function' && typeof Request === 'function' && typeof Response === 'function';
3751
3778
  const isReadableStreamSupported = isFetchSupported && typeof ReadableStream === 'function';
3752
3779
 
@@ -3756,7 +3783,15 @@ const encodeText = isFetchSupported && (typeof TextEncoder === 'function' ?
3756
3783
  async (str) => new Uint8Array(await new Response(str).arrayBuffer())
3757
3784
  );
3758
3785
 
3759
- const supportsRequestStream = isReadableStreamSupported && (() => {
3786
+ const test = (fn, ...args) => {
3787
+ try {
3788
+ return !!fn(...args);
3789
+ } catch (e) {
3790
+ return false
3791
+ }
3792
+ };
3793
+
3794
+ const supportsRequestStream = isReadableStreamSupported && test(() => {
3760
3795
  let duplexAccessed = false;
3761
3796
 
3762
3797
  const hasContentType = new Request(platform.origin, {
@@ -3769,17 +3804,13 @@ const supportsRequestStream = isReadableStreamSupported && (() => {
3769
3804
  }).headers.has('Content-Type');
3770
3805
 
3771
3806
  return duplexAccessed && !hasContentType;
3772
- })();
3807
+ });
3773
3808
 
3774
3809
  const DEFAULT_CHUNK_SIZE = 64 * 1024;
3775
3810
 
3776
- const supportsResponseStream = isReadableStreamSupported && !!(()=> {
3777
- try {
3778
- return utils$1.isReadableStream(new Response('').body);
3779
- } catch(err) {
3780
- // return undefined
3781
- }
3782
- })();
3811
+ const supportsResponseStream = isReadableStreamSupported &&
3812
+ test(() => utils$1.isReadableStream(new Response('').body));
3813
+
3783
3814
 
3784
3815
  const resolvers = {
3785
3816
  stream: supportsResponseStream && ((res) => res.body)
@@ -3807,7 +3838,7 @@ const getBodyLength = async (body) => {
3807
3838
  return (await new Request(body).arrayBuffer()).byteLength;
3808
3839
  }
3809
3840
 
3810
- if(utils$1.isArrayBufferView(body)) {
3841
+ if(utils$1.isArrayBufferView(body) || utils$1.isArrayBuffer(body)) {
3811
3842
  return body.byteLength;
3812
3843
  }
3813
3844
 
@@ -3877,15 +3908,17 @@ const fetchAdapter = isFetchSupported && (async (config) => {
3877
3908
  }
3878
3909
 
3879
3910
  if (_request.body) {
3880
- data = trackStream(_request.body, DEFAULT_CHUNK_SIZE, fetchProgressDecorator(
3911
+ const [onProgress, flush] = progressEventDecorator(
3881
3912
  requestContentLength,
3882
- progressEventReducer(onUploadProgress)
3883
- ), null, encodeText);
3913
+ progressEventReducer(asyncDecorator(onUploadProgress))
3914
+ );
3915
+
3916
+ data = trackStream(_request.body, DEFAULT_CHUNK_SIZE, onProgress, flush, encodeText);
3884
3917
  }
3885
3918
  }
3886
3919
 
3887
3920
  if (!utils$1.isString(withCredentials)) {
3888
- withCredentials = withCredentials ? 'cors' : 'omit';
3921
+ withCredentials = withCredentials ? 'include' : 'omit';
3889
3922
  }
3890
3923
 
3891
3924
  request = new Request(url, {
@@ -3895,7 +3928,7 @@ const fetchAdapter = isFetchSupported && (async (config) => {
3895
3928
  headers: headers.normalize().toJSON(),
3896
3929
  body: data,
3897
3930
  duplex: "half",
3898
- withCredentials
3931
+ credentials: withCredentials
3899
3932
  });
3900
3933
 
3901
3934
  let response = await fetch(request);
@@ -3911,11 +3944,16 @@ const fetchAdapter = isFetchSupported && (async (config) => {
3911
3944
 
3912
3945
  const responseContentLength = utils$1.toFiniteNumber(response.headers.get('content-length'));
3913
3946
 
3947
+ const [onProgress, flush] = onDownloadProgress && progressEventDecorator(
3948
+ responseContentLength,
3949
+ progressEventReducer(asyncDecorator(onDownloadProgress), true)
3950
+ ) || [];
3951
+
3914
3952
  response = new Response(
3915
- trackStream(response.body, DEFAULT_CHUNK_SIZE, onDownloadProgress && fetchProgressDecorator(
3916
- responseContentLength,
3917
- progressEventReducer(onDownloadProgress, true)
3918
- ), isStreamResponse && onFinish, encodeText),
3953
+ trackStream(response.body, DEFAULT_CHUNK_SIZE, onProgress, () => {
3954
+ flush && flush();
3955
+ isStreamResponse && onFinish();
3956
+ }, encodeText),
3919
3957
  options
3920
3958
  );
3921
3959
  }