axios 1.21.0 → 1.22.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.
package/index.d.cts CHANGED
@@ -112,10 +112,20 @@ declare class AxiosHeaders {
112
112
  value: axios.AxiosHeaderValue,
113
113
  rewrite?: boolean | AxiosHeaderMatcher
114
114
  ): AxiosHeaders;
115
- getContentEncoding(parser?: RegExp): RegExpExecArray | null;
116
- getContentEncoding(matcher?: AxiosHeaderMatcher): axios.AxiosHeaderValue;
115
+ getContentEncoding(parser: typeof AxiosHeaders.parseParameters): axios.AxiosHeaderParameters;
116
+ getContentEncoding(parser: RegExp): RegExpExecArray | null;
117
+ getContentEncoding(matcher?: true | AxiosHeaderParser): axios.AxiosHeaderValue;
117
118
  hasContentEncoding(matcher?: AxiosHeaderMatcher): boolean;
118
119
 
120
+ setAcceptEncoding(
121
+ value: axios.AxiosHeaderValue,
122
+ rewrite?: boolean | AxiosHeaderMatcher
123
+ ): AxiosHeaders;
124
+ getAcceptEncoding(parser: typeof AxiosHeaders.parseParameters): axios.AxiosHeaderParameters;
125
+ getAcceptEncoding(parser: RegExp): RegExpExecArray | null;
126
+ getAcceptEncoding(matcher?: true | AxiosHeaderParser): axios.AxiosHeaderValue;
127
+ hasAcceptEncoding(matcher?: AxiosHeaderMatcher): boolean;
128
+
119
129
  setAuthorization(
120
130
  value: axios.AxiosHeaderValue,
121
131
  rewrite?: boolean | AxiosHeaderMatcher
@@ -651,7 +661,8 @@ declare namespace axios {
651
661
  status: number;
652
662
  statusText: string;
653
663
  /**
654
- * Wall-clock milliseconds from adapter invocation to settlement, clamped at zero.
664
+ * Whole milliseconds from adapter invocation to settlement, clamped at zero. Measured with
665
+ * `performance.now()` when available, otherwise `Date.now()`.
655
666
  * Excludes interceptors and request/response transforms. Stream consumption is not included.
656
667
  */
657
668
  duration?: number;
@@ -771,7 +782,16 @@ declare namespace axios {
771
782
  options?: FormSerializerOptions
772
783
  ): GenericFormData;
773
784
  formToJSON(form: GenericFormData | GenericHTMLFormElement): object;
774
- getAdapter(adapters: AxiosAdapterConfig | AxiosAdapterConfig[] | undefined): AxiosAdapter;
785
+ /**
786
+ * Resolves an adapter by name, adapter function, or priority list.
787
+ * @param config Request config forwarded to adapter getters. The built-in `fetch`
788
+ * adapter reads `env.fetch`, `env.Request`, and `env.Response` from it and falls
789
+ * back to the globals when it is omitted. Other fields are not applied here.
790
+ */
791
+ getAdapter(
792
+ adapters: AxiosAdapterConfig | AxiosAdapterConfig[] | undefined,
793
+ config?: AxiosRequestConfig
794
+ ): AxiosAdapter;
775
795
  AxiosHeaders: typeof AxiosHeaders;
776
796
  mergeConfig<D = any, P = any>(
777
797
  config1: AxiosRequestConfig<D, P>,
package/index.d.ts CHANGED
@@ -86,10 +86,17 @@ export class AxiosHeaders {
86
86
  hasUserAgent(matcher?: AxiosHeaderMatcher): boolean;
87
87
 
88
88
  setContentEncoding(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
89
- getContentEncoding(parser?: RegExp): RegExpExecArray | null;
90
- getContentEncoding(matcher?: AxiosHeaderMatcher): AxiosHeaderValue;
89
+ getContentEncoding(parser: typeof AxiosHeaders.parseParameters): AxiosHeaderParameters;
90
+ getContentEncoding(parser: RegExp): RegExpExecArray | null;
91
+ getContentEncoding(matcher?: true | AxiosHeaderParser): AxiosHeaderValue;
91
92
  hasContentEncoding(matcher?: AxiosHeaderMatcher): boolean;
92
93
 
94
+ setAcceptEncoding(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
95
+ getAcceptEncoding(parser: typeof AxiosHeaders.parseParameters): AxiosHeaderParameters;
96
+ getAcceptEncoding(parser: RegExp): RegExpExecArray | null;
97
+ getAcceptEncoding(matcher?: true | AxiosHeaderParser): AxiosHeaderValue;
98
+ hasAcceptEncoding(matcher?: AxiosHeaderMatcher): boolean;
99
+
93
100
  setAuthorization(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
94
101
  getAuthorization(parser?: RegExp): RegExpExecArray | null;
95
102
  getAuthorization(matcher?: AxiosHeaderMatcher): AxiosHeaderValue;
@@ -527,7 +534,8 @@ export interface AxiosResponse<T = any, D = any, H = {}, P = any> {
527
534
  status: number;
528
535
  statusText: string;
529
536
  /**
530
- * Wall-clock milliseconds from adapter invocation to settlement, clamped at zero.
537
+ * Whole milliseconds from adapter invocation to settlement, clamped at zero. Measured with
538
+ * `performance.now()` when available, otherwise `Date.now()`.
531
539
  * Excludes interceptors and request/response transforms. Stream consumption is not included.
532
540
  */
533
541
  duration?: number;
@@ -751,8 +759,15 @@ export interface GenericHTMLFormElement {
751
759
  submit(): void;
752
760
  }
753
761
 
762
+ /**
763
+ * Resolves an adapter by name, adapter function, or priority list.
764
+ * @param config Request config forwarded to adapter getters. The built-in `fetch`
765
+ * adapter reads `env.fetch`, `env.Request`, and `env.Response` from it and falls
766
+ * back to the globals when it is omitted. Other fields are not applied here.
767
+ */
754
768
  export function getAdapter(
755
- adapters: AxiosAdapterConfig | AxiosAdapterConfig[] | undefined
769
+ adapters: AxiosAdapterConfig | AxiosAdapterConfig[] | undefined,
770
+ config?: AxiosRequestConfig
756
771
  ): AxiosAdapter;
757
772
 
758
773
  export function toFormData(
@@ -114,6 +114,21 @@ function getAdapter(adapters, config) {
114
114
  return adapter;
115
115
  }
116
116
 
117
+ /**
118
+ * Check whether a resolved adapter function is one of the built-in adapters.
119
+ *
120
+ * @param {Function} adapter The adapter resolved by `getAdapter`
121
+ * @returns {boolean} `true` for the built-in `xhr`, `http` or `fetch` adapter
122
+ */
123
+ function isBuiltinAdapter(adapter) {
124
+ return (
125
+ !!adapter &&
126
+ (adapter === knownAdapters.xhr ||
127
+ adapter === knownAdapters.http ||
128
+ fetchAdapter.isFetchAdapter(adapter))
129
+ );
130
+ }
131
+
117
132
  /**
118
133
  * Exports Axios adapters and utility to resolve an adapter
119
134
  */
@@ -124,6 +139,12 @@ export default {
124
139
  */
125
140
  getAdapter,
126
141
 
142
+ /**
143
+ * Check whether a resolved adapter is a built-in one.
144
+ * @type {Function}
145
+ */
146
+ isBuiltinAdapter,
147
+
127
148
  /**
128
149
  * Exposes all known adapters
129
150
  * @type {Object<string, Function|Object>}
@@ -69,6 +69,45 @@ const test = (fn, ...args) => {
69
69
  }
70
70
  };
71
71
 
72
+ // Marks a probe body's cancellation result as handled. Reads `then` once and
73
+ // does not go through the global Promise or `Promise.prototype.catch`, so a
74
+ // rejected cancellation from a custom body cannot surface as an unhandled
75
+ // rejection.
76
+ const ignoreRejection = (result) => {
77
+ try {
78
+ if (result !== null && (typeof result === 'object' || typeof result === 'function')) {
79
+ const then = result.then;
80
+
81
+ if (isFunction(then)) {
82
+ then.call(result, undefined, utils.noop);
83
+ }
84
+ }
85
+ } catch (e) {
86
+ // Ignored: the cancellation has already been requested.
87
+ }
88
+ };
89
+
90
+ // On Node.js 22 and older, the body of the throwaway `new Response('')` used by
91
+ // the response-stream probe leaves its stream's internal closed promise pending
92
+ // until the stream is cancelled, which async-leak detectors report for every
93
+ // realm that loads axios. This cleanup runs in `finally`, whether the check
94
+ // returned or threw, and is best-effort so it never affects the probe result.
95
+ const cancelProbeBody = (body) => {
96
+ if (body == null) {
97
+ return;
98
+ }
99
+
100
+ try {
101
+ const cancel = body.cancel;
102
+
103
+ if (isFunction(cancel)) {
104
+ ignoreRejection(cancel.call(body));
105
+ }
106
+ } catch (e) {
107
+ // Ignored: an uncancellable probe body is still a valid probe result.
108
+ }
109
+ };
110
+
72
111
  const maybeWithAuthCredentials = (url) => {
73
112
  const protocolIndex = url.indexOf('://');
74
113
  let urlToCheck = url;
@@ -134,7 +173,7 @@ const factory = (env) => {
134
173
  const hasContentType = request.headers.has('Content-Type');
135
174
 
136
175
  if (request.body != null) {
137
- request.body.cancel();
176
+ ignoreRejection(request.body.cancel());
138
177
  }
139
178
 
140
179
  return duplexAccessed && !hasContentType;
@@ -143,7 +182,15 @@ const factory = (env) => {
143
182
  const supportsResponseStream =
144
183
  isResponseSupported &&
145
184
  isReadableStreamSupported &&
146
- test(() => utils.isReadableStream(new Response('').body));
185
+ test(() => {
186
+ const probeBody = new Response('').body;
187
+
188
+ try {
189
+ return utils.isReadableStream(probeBody);
190
+ } finally {
191
+ cancelProbeBody(probeBody);
192
+ }
193
+ });
147
194
 
148
195
  // Some runtimes reject every explicit cache mode. Use own defaults for both
149
196
  // probes so unrelated polluted options cannot affect cache-mode detection.
@@ -715,6 +762,28 @@ const factory = (env) => {
715
762
 
716
763
  const seedCache = new Map();
717
764
 
765
+ // Every adapter the factory has created. The adapter is cached per
766
+ // environment, so one created for another environment, such as by
767
+ // `axios.getAdapter('fetch')` without a config, is still recognized.
768
+ const createdAdapters = new WeakSet();
769
+
770
+ const createAdapter = (env) => {
771
+ const adapter = factory(env);
772
+
773
+ adapter && createdAdapters.add(adapter);
774
+
775
+ return adapter;
776
+ };
777
+
778
+ /**
779
+ * Check whether a function was created by the fetch adapter factory.
780
+ *
781
+ * @param {*} adapter The value to check
782
+ *
783
+ * @returns {boolean} `true` for a built-in fetch adapter
784
+ */
785
+ export const isFetchAdapter = (adapter) => createdAdapters.has(adapter);
786
+
718
787
  export const getFetch = (config) => {
719
788
  const env = Object.create(null);
720
789
  const configuredEnv = config && utils.hasOwnProp(config, 'env') && config.env;
@@ -736,7 +805,7 @@ export const getFetch = (config) => {
736
805
  seed = seeds[i];
737
806
  target = map.get(seed);
738
807
 
739
- target === undefined && map.set(seed, (target = i ? new Map() : factory(env)));
808
+ target === undefined && map.set(seed, (target = i ? new Map() : createAdapter(env)));
740
809
 
741
810
  map = target;
742
811
  }
@@ -2,13 +2,17 @@ import utils from '../utils.js';
2
2
  import settle from '../core/settle.js';
3
3
  import buildFullPath from '../core/buildFullPath.js';
4
4
  import buildURL from '../helpers/buildURL.js';
5
- import { getProxyForUrl } from 'proxy-from-env';
5
+ import { getProxyForUrl } from '../helpers/proxyFromEnv.js';
6
6
  import HttpsProxyAgent from 'https-proxy-agent';
7
7
  import http from 'http';
8
8
  import https from 'https';
9
9
  import http2 from 'http2';
10
10
  import util from 'util';
11
- import { resolve as resolvePath } from 'path';
11
+ import {
12
+ isAbsolute as isAbsolutePath,
13
+ relative as relativePath,
14
+ resolve as resolvePath,
15
+ } from 'path';
12
16
  import followRedirects from 'follow-redirects';
13
17
  import zlib from 'zlib';
14
18
  import { VERSION } from '../env/data.js';
@@ -214,6 +218,46 @@ function getDirectAgent(configuredAgent, transport) {
214
218
  return direct;
215
219
  }
216
220
 
221
+ // Windows named pipes and Linux abstract sockets (leading NUL byte) are not
222
+ // filesystem paths, so they are compared and connected to as given.
223
+ function isNonFileSocketPath(socketPath) {
224
+ return /^\\\\[.?]\\pipe\\/i.test(socketPath) || socketPath.charAt(0) === '\0';
225
+ }
226
+
227
+ function normalizeSocketPath(socketPath) {
228
+ return isNonFileSocketPath(socketPath) ? socketPath : resolvePath(socketPath);
229
+ }
230
+
231
+ // The longest socket path every supported platform accepts: sun_path is 104
232
+ // bytes on macOS and the BSDs and 108 on Linux, including the trailing NUL.
233
+ const MAX_SOCKET_PATH_BYTES = 103;
234
+
235
+ // The path to connect to when an allowlist is in use. `..` is collapsed
236
+ // lexically, as the allowlist check does, so the path that is connected is the
237
+ // path that was checked.
238
+ //
239
+ // The absolute path is used whenever it fits, so the target does not depend on
240
+ // the working directory when the connection opens (an Agent can open it later,
241
+ // after a process.chdir()). Only when the absolute path is too long is the
242
+ // shorter path relative to the working directory used. Either way the result
243
+ // is never longer than the absolute path, because some Node versions silently
244
+ // truncate a socket path that is too long and would connect to a prefix of it.
245
+ function getConnectSocketPath(socketPath) {
246
+ if (isNonFileSocketPath(socketPath)) {
247
+ return socketPath;
248
+ }
249
+
250
+ const resolved = resolvePath(socketPath);
251
+
252
+ if (isAbsolutePath(socketPath) || Buffer.byteLength(resolved) <= MAX_SOCKET_PATH_BYTES) {
253
+ return resolved;
254
+ }
255
+
256
+ const relative = relativePath(process.cwd(), resolved) || '.';
257
+
258
+ return Buffer.byteLength(relative) < Buffer.byteLength(resolved) ? relative : resolved;
259
+ }
260
+
217
261
  function setDirectAgent(options, configHttpAgent, configHttpsAgent) {
218
262
  const secure = isHttps.test(options.protocol);
219
263
  const agent = getDirectAgent(secure ? configHttpsAgent : configHttpAgent, secure ? https : http);
@@ -289,6 +333,53 @@ const flushOnFinish = (stream, [throttled, flush]) => {
289
333
 
290
334
  const http2Sessions = new Http2Sessions();
291
335
 
336
+ // Options that follow-redirects reads but axios does not always set.
337
+ // follow-redirects copies the request options into a plain object, so any of
338
+ // these left unset would be read from Object.prototype. hostname and port are
339
+ // only unset for socketPath requests, and sensitiveHeaders only with a custom
340
+ // transport. Checked against follow-redirects 1.16.3; a later release that
341
+ // reads more options needs them added here.
342
+ const REDIRECT_OPTION_KEYS = [
343
+ 'host',
344
+ 'hostname',
345
+ 'port',
346
+ 'pathname',
347
+ 'search',
348
+ 'hash',
349
+ 'query',
350
+ 'slashes',
351
+ 'followRedirects',
352
+ 'trackRedirects',
353
+ 'sensitiveHeaders',
354
+ ];
355
+
356
+ // follow-redirects reads these when a response arrives rather than when the
357
+ // request starts, so they are pinned even when nothing is inherited yet.
358
+ const RESPONSE_OPTION_KEYS = new Set(['followRedirects', 'trackRedirects']);
359
+
360
+ /**
361
+ * Give the options follow-redirects reads an own value whenever one would
362
+ * otherwise be inherited. dispatchBeforeRedirect also resets host, auth and
363
+ * query on each redirect hop. Other keys that are not inherited are left
364
+ * unset, so the options passed to the transport do not change otherwise.
365
+ *
366
+ * The check is against Object.prototype rather than `key in options`: the
367
+ * initial options object has a null prototype, and follow-redirects copies it
368
+ * into a plain object that inherits from Object.prototype.
369
+ *
370
+ * @param {Object<string, any>} options
371
+ */
372
+ function setRedirectDefaults(options) {
373
+ REDIRECT_OPTION_KEYS.forEach((key) => {
374
+ if (utils.hasOwnProp(options, key)) {
375
+ return;
376
+ }
377
+ if (key in Object.prototype || RESPONSE_OPTION_KEYS.has(key)) {
378
+ options[key] = undefined;
379
+ }
380
+ });
381
+ }
382
+
292
383
  /**
293
384
  * If the proxy, auth, sensitive header, or config beforeRedirects functions are defined,
294
385
  * call them with the options object.
@@ -298,9 +389,13 @@ const http2Sessions = new Http2Sessions();
298
389
  * @returns {Object<string, any>}
299
390
  */
300
391
  function dispatchBeforeRedirect(options, responseDetails, requestDetails) {
392
+ // follow-redirects copies auth and query from a WHATWG URL, which has
393
+ // neither, so both would otherwise be read from Object.prototype. Own Basic
394
+ // credentials are restored on same-origin hops by beforeRedirects.auth.
395
+ options.auth = undefined;
396
+ options.query = undefined;
301
397
  if (!isSameOriginRedirect(options, requestDetails)) {
302
398
  stripMatchingHeaders(options.headers, new Set(['authorization', 'cookie']));
303
- delete options.auth;
304
399
  }
305
400
  if (options.beforeRedirects.proxy) {
306
401
  options.beforeRedirects.proxy(options);
@@ -317,6 +412,14 @@ function dispatchBeforeRedirect(options, responseDetails, requestDetails) {
317
412
  if (options.beforeRedirects.config) {
318
413
  options.beforeRedirects.config(options, responseDetails, requestDetails);
319
414
  }
415
+ // follow-redirects deletes a truthy host after this hook returns, which
416
+ // would let the next hop read host from Object.prototype. Fold it into
417
+ // hostname the same way follow-redirects does, but keep an own value.
418
+ if (options.host && !options.hostname) {
419
+ options.hostname = options.host;
420
+ }
421
+ options.host = undefined;
422
+ setRedirectDefaults(options);
320
423
  }
321
424
 
322
425
  function stripMatchingHeaders(headers, sensitiveSet) {
@@ -754,8 +857,7 @@ export default isHttpAdapterSupported &&
754
857
  }
755
858
  }
756
859
 
757
- function createTimeoutError() {
758
- const configTimeout = own('timeout');
860
+ function createTimeoutError(configTimeout = own('timeout')) {
759
861
  let timeoutErrorMessage = configTimeout
760
862
  ? 'timeout of ' + configTimeout + 'ms exceeded'
761
863
  : 'timeout exceeded';
@@ -994,34 +1096,6 @@ export default isHttpAdapterSupported &&
994
1096
  maxUploadRate = maxDownloadRate = maxRate;
995
1097
  }
996
1098
 
997
- if (data && (onUploadProgress || maxUploadRate)) {
998
- if (!utils.isStream(data)) {
999
- data = stream.Readable.from(data, { objectMode: false });
1000
- }
1001
-
1002
- data = stream.pipeline(
1003
- [
1004
- data,
1005
- new AxiosTransformStream({
1006
- maxRate: utils.toFiniteNumber(maxUploadRate),
1007
- }),
1008
- ],
1009
- utils.noop
1010
- );
1011
-
1012
- onUploadProgress &&
1013
- data.on(
1014
- 'progress',
1015
- flushOnFinish(
1016
- data,
1017
- progressEventDecorator(
1018
- contentLength,
1019
- progressEventReducer(asyncDecorator(onUploadProgress, scheduleProgress), false, 3)
1020
- )
1021
- )
1022
- );
1023
- }
1024
-
1025
1099
  // HTTP basic authentication
1026
1100
  let auth = undefined;
1027
1101
  const configAuth = own('auth');
@@ -1097,15 +1171,18 @@ export default isHttpAdapterSupported &&
1097
1171
  );
1098
1172
  }
1099
1173
 
1174
+ let connectSocketPath = socketPath;
1100
1175
  const allowedSocketPaths = own('allowedSocketPaths');
1101
1176
  if (allowedSocketPaths != null) {
1102
1177
  const allowed = Array.isArray(allowedSocketPaths)
1103
1178
  ? allowedSocketPaths
1104
1179
  : [allowedSocketPaths];
1105
1180
 
1106
- const resolvedSocket = resolvePath(socketPath);
1181
+ // Check the path that will be connected, so the two cannot disagree.
1182
+ connectSocketPath = getConnectSocketPath(socketPath);
1183
+ const normalizedSocket = normalizeSocketPath(connectSocketPath);
1107
1184
  const isAllowed = allowed.some(
1108
- (entry) => typeof entry === 'string' && resolvePath(entry) === resolvedSocket
1185
+ (entry) => typeof entry === 'string' && normalizeSocketPath(entry) === normalizedSocket
1109
1186
  );
1110
1187
 
1111
1188
  if (!isAllowed) {
@@ -1119,8 +1196,15 @@ export default isHttpAdapterSupported &&
1119
1196
  }
1120
1197
  }
1121
1198
 
1122
- options.socketPath = socketPath;
1199
+ options.socketPath = connectSocketPath;
1123
1200
  } else {
1201
+ // Node 14 and older copy the request options into a plain object in
1202
+ // Agent#addRequest and read socketPath from that copy, so an inherited
1203
+ // value would turn this into a socket request. Only set when one is
1204
+ // inherited, so the options passed on do not change otherwise.
1205
+ if ('socketPath' in Object.prototype) {
1206
+ options.socketPath = undefined;
1207
+ }
1124
1208
  options.hostname = parsed.hostname.startsWith('[')
1125
1209
  ? parsed.hostname.slice(1, -1)
1126
1210
  : parsed.hostname;
@@ -1167,6 +1251,8 @@ export default isHttpAdapterSupported &&
1167
1251
  } else {
1168
1252
  const configTransport = own('transport');
1169
1253
  if (configTransport) {
1254
+ // A custom transport may be follow-redirects itself.
1255
+ setRedirectDefaults(options);
1170
1256
  transport = configTransport;
1171
1257
  } else if (maxRedirects === 0) {
1172
1258
  transport = isHttpsRequest ? https : http;
@@ -1236,6 +1322,7 @@ export default isHttpAdapterSupported &&
1236
1322
  };
1237
1323
  }
1238
1324
  }
1325
+ setRedirectDefaults(options);
1239
1326
  transport = isHttpsRequest ? httpsFollow : httpFollow;
1240
1327
  }
1241
1328
  }
@@ -1254,6 +1341,57 @@ export default isHttpAdapterSupported &&
1254
1341
  // through Node's internal options copy
1255
1342
  options.insecureHTTPParser = Boolean(own('insecureHTTPParser'));
1256
1343
 
1344
+ // Read and convert the timeout once, so the value checked here is the value applied and
1345
+ // reported below, and fail a negative timeout (for example from a deadline that has
1346
+ // already passed) as an elapsed timeout before connecting. Passed through, Node would
1347
+ // throw a RangeError that follow-redirects raises outside this promise. It runs after the
1348
+ // other config checks so their errors win, and data: URLs above never apply a timeout.
1349
+ // parseFloat also treats fractions such as -0.5 as elapsed (parseInt yields -0, which
1350
+ // disables the timeout on the native transport), and parseInt catches strings such as
1351
+ // '-1e-324' that parseFloat reads as -0.
1352
+ const rawTimeout = own('timeout');
1353
+ let timeoutString;
1354
+ let parsedTimeout;
1355
+
1356
+ if (rawTimeout) {
1357
+ timeoutString = `${rawTimeout}`;
1358
+ parsedTimeout = parseInt(timeoutString, 10);
1359
+
1360
+ if (parseFloat(timeoutString) < 0 || parsedTimeout < 0) {
1361
+ return reject(createTimeoutError(timeoutString));
1362
+ }
1363
+ }
1364
+
1365
+ // Start the upload pipeline only once the request goes ahead, so a config rejected above
1366
+ // never starts reading the body.
1367
+ if (data && (onUploadProgress || maxUploadRate)) {
1368
+ if (!utils.isStream(data)) {
1369
+ data = stream.Readable.from(data, { objectMode: false });
1370
+ }
1371
+
1372
+ data = stream.pipeline(
1373
+ [
1374
+ data,
1375
+ new AxiosTransformStream({
1376
+ maxRate: utils.toFiniteNumber(maxUploadRate),
1377
+ }),
1378
+ ],
1379
+ utils.noop
1380
+ );
1381
+
1382
+ onUploadProgress &&
1383
+ data.on(
1384
+ 'progress',
1385
+ flushOnFinish(
1386
+ data,
1387
+ progressEventDecorator(
1388
+ contentLength,
1389
+ progressEventReducer(asyncDecorator(onUploadProgress, scheduleProgress), false, 3)
1390
+ )
1391
+ )
1392
+ );
1393
+ }
1394
+
1257
1395
  // Create the request
1258
1396
  req = transport.request(options, function handleResponse(res) {
1259
1397
  clearConnectPhaseTimer();
@@ -1501,11 +1639,13 @@ export default isHttpAdapterSupported &&
1501
1639
  });
1502
1640
 
1503
1641
  // Handle request timeout
1504
- if (own('timeout')) {
1505
- // This is forcing a int timeout to avoid problems if the `req` interface doesn't handle other types.
1506
- const timeout = parseInt(own('timeout'), 10);
1642
+ if (rawTimeout) {
1643
+ // An int timeout, converted once above, avoids problems if the `req` interface doesn't
1644
+ // handle other types. Node also rejects non-finite values, such as the Infinity that
1645
+ // parseInt returns for a very long digit string, so treat those as unparsable too.
1646
+ const timeout = parsedTimeout;
1507
1647
 
1508
- if (Number.isNaN(timeout)) {
1648
+ if (!Number.isFinite(timeout)) {
1509
1649
  abort(
1510
1650
  new AxiosError(
1511
1651
  'error trying to parse `config.timeout` to int',
@@ -1520,7 +1660,7 @@ export default isHttpAdapterSupported &&
1520
1660
 
1521
1661
  const handleTimeout = function handleTimeout() {
1522
1662
  if (isDone) return;
1523
- abort(createTimeoutError());
1663
+ abort(createTimeoutError(timeoutString));
1524
1664
  };
1525
1665
 
1526
1666
  if (isNativeTransport && timeout > 0) {
package/lib/core/Axios.js CHANGED
@@ -4,6 +4,9 @@ import utils from '../utils.js';
4
4
  import buildURL from '../helpers/buildURL.js';
5
5
  import InterceptorManager from './InterceptorManager.js';
6
6
  import dispatchRequest from './dispatchRequest.js';
7
+ import assertValidRequestUrl from './assertValidRequestUrl.js';
8
+ import adapters from '../adapters/adapters.js';
9
+ import defaults from '../defaults/index.js';
7
10
  import mergeConfig from './mergeConfig.js';
8
11
  import buildFullPath from './buildFullPath.js';
9
12
  import methodList from './methodList.js';
@@ -312,6 +315,9 @@ class Axios {
312
315
 
313
316
  getUri(config) {
314
317
  config = mergeConfig(this.defaults, config);
318
+ assertValidRequestUrl(config, () =>
319
+ adapters.getAdapter(config.adapter || defaults.adapter, config)
320
+ );
315
321
  const fullPath = buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls, config);
316
322
  return buildURL(fullPath, config.params, config.paramsSerializer);
317
323
  }
@@ -465,6 +465,7 @@ class AxiosHeaders {
465
465
  AxiosHeaders.accessor([
466
466
  'Content-Type',
467
467
  'Content-Length',
468
+ 'Content-Encoding',
468
469
  'Accept',
469
470
  'Accept-Encoding',
470
471
  'User-Agent',
@@ -78,8 +78,13 @@ class InterceptorManager {
78
78
  const handler = {
79
79
  fulfilled,
80
80
  rejected,
81
- synchronous: options ? options.synchronous : false,
82
- runWhen: options ? options.runWhen : null,
81
+ // Options from a class or template object are read as usual; a value
82
+ // only inherited from Object.prototype is ignored.
83
+ synchronous:
84
+ options && utils.hasOwnInPrototypeChain(options, 'synchronous')
85
+ ? options.synchronous
86
+ : false,
87
+ runWhen: options && utils.hasOwnInPrototypeChain(options, 'runWhen') ? options.runWhen : null,
83
88
  };
84
89
  const internals = this[$internals];
85
90
 
@@ -0,0 +1,62 @@
1
+ 'use strict';
2
+
3
+ import AxiosError from './AxiosError.js';
4
+ import adapters from '../adapters/adapters.js';
5
+ import utils from '../utils.js';
6
+
7
+ /**
8
+ * Reject a `null` or `undefined` url that a built-in adapter would send
9
+ * somewhere the caller did not choose.
10
+ *
11
+ * With params, the nullish url becomes a query-only url such as `?foo=bar`,
12
+ * which a browser resolves against the current page. Without params, XHR
13
+ * requests `./null` or `./undefined` and the Node adapter throws a native
14
+ * `TypeError`.
15
+ *
16
+ * The request still has a destination when `baseURL` is set, or when the Node
17
+ * HTTP adapter is given a `socketPath`. A caller-supplied adapter handles its
18
+ * own destination and is not checked.
19
+ *
20
+ * `dispatchRequest` and `Axios#getUri` both call this, so `getUri` rejects
21
+ * exactly the configs that a request would reject. Request interceptors are
22
+ * not run by `getUri`, so a url that an interceptor would supply is still
23
+ * missing there. Keep this out of `buildURL` and `buildFullPath`: they only
24
+ * format urls and have other callers.
25
+ *
26
+ * @param {Object} config The merged request config
27
+ * @param {Function} resolveAdapter Returns the adapter that handles the
28
+ * request. Called only for a nullish url without `baseURL`, so a usable url
29
+ * never depends on adapter resolution.
30
+ *
31
+ * @returns {void}
32
+ */
33
+ export default function assertValidRequestUrl(config, resolveAdapter) {
34
+ const url = utils.getSafeProp(config, 'url');
35
+
36
+ if (url !== null && url !== undefined) {
37
+ return;
38
+ }
39
+
40
+ if (utils.getSafeProp(config, 'baseURL')) {
41
+ return;
42
+ }
43
+
44
+ const adapter = resolveAdapter();
45
+
46
+ // Only the Node HTTP adapter reads socketPath; XHR and fetch ignore it.
47
+ const httpAdapter = adapters.adapters.http;
48
+
49
+ if (httpAdapter && adapter === httpAdapter && utils.getSafeProp(config, 'socketPath')) {
50
+ return;
51
+ }
52
+
53
+ if (!adapters.isBuiltinAdapter(adapter)) {
54
+ return;
55
+ }
56
+
57
+ throw new AxiosError(
58
+ `Invalid URL: url cannot be ${url === null ? 'null' : 'undefined'} when baseURL is not set`,
59
+ AxiosError.ERR_INVALID_URL,
60
+ config
61
+ );
62
+ }