axios 0.32.0 → 0.34.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.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  // TypeScript Version: 4.1
2
2
  type HeaderValue = string | string[] | number | boolean;
3
3
 
4
- type AxiosHeaders = Record<string, HeaderValue | Record<Method & CommonHeaders, HeaderValue>>;
4
+ type AxiosHeaders = Record<string, HeaderValue | Record<string, HeaderValue>>;
5
5
 
6
6
  type MethodsHeaders = {
7
7
  [Key in Method as Lowercase<Key>]: AxiosHeaders;
@@ -86,6 +86,7 @@ export interface TransitionalOptions {
86
86
 
87
87
  export interface GenericAbortSignal {
88
88
  aborted: boolean;
89
+ readonly reason?: unknown;
89
90
  onabort: ((...args: any) => any) | null;
90
91
  addEventListener: (...args: any) => any;
91
92
  removeEventListener: (...args: any) => any;
@@ -168,6 +169,7 @@ export interface AxiosRequestConfig<D = any> {
168
169
  cancelToken?: CancelToken;
169
170
  decompress?: boolean;
170
171
  transitional?: TransitionalOptions;
172
+ captureCallerStack?: boolean;
171
173
  signal?: GenericAbortSignal;
172
174
  insecureHTTPParser?: boolean;
173
175
  env?: {
@@ -241,6 +243,7 @@ export class AxiosError<T = unknown, D = any> extends Error {
241
243
  }
242
244
 
243
245
  export class CanceledError<T> extends AxiosError<T> {
246
+ reason?: unknown;
244
247
  }
245
248
 
246
249
  export type AxiosPromise<T = any> = Promise<AxiosResponse<T>>;
@@ -251,6 +254,7 @@ export interface CancelStatic {
251
254
 
252
255
  export interface Cancel {
253
256
  message: string | undefined;
257
+ reason?: unknown;
254
258
  }
255
259
 
256
260
  export interface Canceler {
@@ -15,7 +15,7 @@ var zlib = require('zlib');
15
15
  var VERSION = require('./../env/data').version;
16
16
  var transitionalDefaults = require('../defaults/transitional');
17
17
  var AxiosError = require('../core/AxiosError');
18
- var CanceledError = require('../cancel/CanceledError');
18
+ var canceledErrorFromSignal = require('../cancel/fromSignal');
19
19
  var platform = require('../platform');
20
20
  var fromDataURI = require('../helpers/fromDataURI');
21
21
  var stream = require('stream');
@@ -125,6 +125,43 @@ function checkSocketPath(config) {
125
125
  return null;
126
126
  }
127
127
 
128
+ /**
129
+ * Normalize a configured HTTP(S) proxy protocol to the `scheme:` form Node expects.
130
+ *
131
+ * `AxiosProxyConfig.protocol` is documented (and typed) as a bare scheme such
132
+ * as `'http'`, but the value is handed straight to `http.request` as
133
+ * `options.protocol`, where it is compared verbatim against the agent's own
134
+ * `protocol`. A missing colon therefore made every documented proxy config
135
+ * fail with `ERR_ASSERTION: protocol mismatch`. Schemes are case-insensitive,
136
+ * so fold to lower case as well.
137
+ *
138
+ * @param {*} protocol The configured proxy protocol
139
+ * @returns {string|undefined} The normalized protocol, or undefined for non-strings or an empty string
140
+ * @throws {AxiosError} If a non-empty string is not an HTTP(S) protocol
141
+ */
142
+ function normalizeProxyProtocol(protocol) {
143
+ if (typeof protocol !== 'string' || protocol === '') {
144
+ return undefined;
145
+ }
146
+
147
+ var normalized = protocol.trim().toLowerCase();
148
+
149
+ if (normalized === 'http' || normalized === 'https') {
150
+ return normalized + ':';
151
+ }
152
+
153
+ if (normalized === 'http:' || normalized === 'https:') {
154
+ return normalized;
155
+ }
156
+
157
+ // Never infer a transport from an explicitly invalid string: an HTTP target
158
+ // could otherwise send HTTPS proxy credentials over a plaintext connection.
159
+ throw new AxiosError(
160
+ 'proxy.protocol must be http or https',
161
+ AxiosError.ERR_BAD_OPTION_VALUE
162
+ );
163
+ }
164
+
128
165
  /**
129
166
  *
130
167
  * @param {http.ClientRequestArgs} options
@@ -147,6 +184,11 @@ function setProxy(options, configProxy, location) {
147
184
  removeProxyAuthorization(options.headers);
148
185
  }
149
186
  if (proxy) {
187
+ // Validate before adding proxy credentials or configuring a connection.
188
+ var proxyProtocol = normalizeProxyProtocol(
189
+ utils.hasOwnProperty(proxy, 'protocol') ? proxy.protocol : undefined
190
+ );
191
+
150
192
  // Basic proxy authorization
151
193
  var proxyAuth = utils.hasOwnProperty(proxy, 'auth')
152
194
  ? proxy.auth
@@ -178,8 +220,11 @@ function setProxy(options, configProxy, location) {
178
220
  options.host = proxy.host;
179
221
  options.port = proxy.port;
180
222
  options.path = location;
181
- if (proxy.protocol) {
182
- options.protocol = proxy.protocol;
223
+
224
+ // Preserve the target protocol when no normalized proxy protocol is supplied.
225
+ // Defaulting to HTTP here could downgrade an existing HTTPS proxy connection.
226
+ if (proxyProtocol) {
227
+ options.protocol = proxyProtocol;
183
228
  }
184
229
  }
185
230
 
@@ -373,9 +418,10 @@ module.exports = function httpAdapter(config) {
373
418
 
374
419
  // HTTP basic authentication
375
420
  var auth = undefined;
376
- if (config.auth) {
377
- var username = config.auth.username || '';
378
- var password = config.auth.password || '';
421
+ var configAuth = utils.hasOwnProperty(config, 'auth') ? config.auth : undefined;
422
+ if (configAuth) {
423
+ var username = utils.hasOwnProperty(configAuth, 'username') ? configAuth.username || '' : '';
424
+ var password = utils.hasOwnProperty(configAuth, 'password') ? configAuth.password || '' : '';
379
425
  auth = username + ':' + password;
380
426
  }
381
427
 
@@ -390,8 +436,10 @@ module.exports = function httpAdapter(config) {
390
436
  delete headers[headerNames.authorization];
391
437
  }
392
438
 
439
+ var paramsSerializer = utils.hasOwnProperty(config, 'paramsSerializer') ? config.paramsSerializer : undefined;
440
+
393
441
  try {
394
- buildURL(parsed.path, config.params, config.paramsSerializer).replace(
442
+ buildURL(parsed.path, config.params, paramsSerializer).replace(
395
443
  /^\?/,
396
444
  ''
397
445
  );
@@ -407,7 +455,7 @@ module.exports = function httpAdapter(config) {
407
455
  path: buildURL(
408
456
  parsed.path,
409
457
  config.params,
410
- config.paramsSerializer
458
+ paramsSerializer
411
459
  ).replace(/^\?/, ''),
412
460
  method: method,
413
461
  headers: headers,
@@ -415,7 +463,11 @@ module.exports = function httpAdapter(config) {
415
463
  auth: auth,
416
464
  protocol: protocol,
417
465
  beforeRedirect: dispatchBeforeRedirect,
418
- beforeRedirects: {}
466
+ // Null-prototype. dispatchBeforeRedirect calls whatever it finds here, and
467
+ // the `config` hook is only populated when the caller supplies
468
+ // beforeRedirect, so a plain object left an inherited function reachable
469
+ // and able to rewrite the redirect target.
470
+ beforeRedirects: Object.create(null)
419
471
  };
420
472
 
421
473
  var socketPathError = checkSocketPath(config);
@@ -428,9 +480,10 @@ module.exports = function httpAdapter(config) {
428
480
  } else {
429
481
  options.hostname = parsed.hostname;
430
482
  options.port = parsed.port;
483
+ var configProxy = utils.hasOwnProperty(config, 'proxy') ? config.proxy : undefined;
431
484
  setProxy(
432
485
  options,
433
- config.proxy,
486
+ configProxy,
434
487
  protocol + '//' + parsed.host + options.path
435
488
  );
436
489
  }
@@ -697,7 +750,7 @@ module.exports = function httpAdapter(config) {
697
750
  req.abort();
698
751
  reject(
699
752
  !cancel || cancel.type
700
- ? new CanceledError(null, config, req)
753
+ ? canceledErrorFromSignal(config.signal, config, req)
701
754
  : cancel
702
755
  );
703
756
  };
@@ -9,7 +9,7 @@ var parseHeaders = require('./../helpers/parseHeaders');
9
9
  var isURLSameOrigin = require('./../helpers/isURLSameOrigin');
10
10
  var transitionalDefaults = require('../defaults/transitional');
11
11
  var AxiosError = require('../core/AxiosError');
12
- var CanceledError = require('../cancel/CanceledError');
12
+ var canceledErrorFromSignal = require('../cancel/fromSignal');
13
13
  var parseProtocol = require('../helpers/parseProtocol');
14
14
  var platform = require('../platform');
15
15
 
@@ -40,10 +40,11 @@ module.exports = function xhrAdapter(config) {
40
40
  var request = new XMLHttpRequest();
41
41
 
42
42
  // HTTP basic authentication
43
- if (config.auth) {
44
- var username = config.auth.username || '';
45
- var password = config.auth.password
46
- ? unescape(encodeURIComponent(config.auth.password))
43
+ var configAuth = utils.hasOwnProperty(config, 'auth') ? config.auth : undefined;
44
+ if (configAuth) {
45
+ var username = utils.hasOwnProperty(configAuth, 'username') ? configAuth.username || '' : '';
46
+ var password = utils.hasOwnProperty(configAuth, 'password') && configAuth.password
47
+ ? unescape(encodeURIComponent(configAuth.password))
47
48
  : '';
48
49
  requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password);
49
50
  }
@@ -56,7 +57,11 @@ module.exports = function xhrAdapter(config) {
56
57
 
57
58
  request.open(
58
59
  config.method.toUpperCase(),
59
- buildURL(fullPath, config.params, config.paramsSerializer),
60
+ buildURL(
61
+ fullPath,
62
+ config.params,
63
+ utils.hasOwnProperty(config, 'paramsSerializer') ? config.paramsSerializer : undefined
64
+ ),
60
65
  true
61
66
  );
62
67
 
@@ -256,7 +261,7 @@ module.exports = function xhrAdapter(config) {
256
261
  }
257
262
  reject(
258
263
  !cancel || cancel.type
259
- ? new CanceledError(null, config, request)
264
+ ? canceledErrorFromSignal(config.signal, config, request)
260
265
  : cancel
261
266
  );
262
267
  request.abort();
@@ -0,0 +1,20 @@
1
+ 'use strict';
2
+
3
+ var CanceledError = require('./CanceledError');
4
+
5
+ module.exports = function fromSignal(signal, config, request) {
6
+ var error = new CanceledError(null, config, request);
7
+
8
+ if (signal) {
9
+ try {
10
+ var reason = signal.reason;
11
+ if (reason !== undefined) {
12
+ error.reason = reason;
13
+ }
14
+ } catch (e) {
15
+ // A custom signal getter must not prevent cancellation.
16
+ }
17
+ }
18
+
19
+ return error;
20
+ };
package/lib/core/Axios.js CHANGED
@@ -9,6 +9,56 @@ var buildFullPath = require('./buildFullPath');
9
9
  var validator = require('../helpers/validator');
10
10
 
11
11
  var validators = validator.validators;
12
+
13
+ function captureCallerStack(boundary) {
14
+ var caller = {};
15
+ try {
16
+ if (Error.captureStackTrace) {
17
+ Error.captureStackTrace(caller, boundary);
18
+ } else {
19
+ caller = new Error();
20
+ }
21
+ } catch (e) {
22
+ // Stack hooks must not prevent a request from being sent.
23
+ }
24
+ return caller;
25
+ }
26
+
27
+ function attachCallerStack(promise, caller) {
28
+ if (!caller) {
29
+ return promise;
30
+ }
31
+
32
+ return promise.then(null, function onRequestRejected(error) {
33
+ try {
34
+ if (error instanceof Error || Object.prototype.toString.call(error) === '[object Error]') {
35
+ // Capture at dispatch time, but only format the stack on failure.
36
+ // Capturing in this callback would lose callers using .then/.catch.
37
+ var stack = caller.stack;
38
+ if (typeof stack === 'string') {
39
+ var newline = stack.indexOf('\n');
40
+ stack = newline === -1 ? '' : stack.slice(newline + 1);
41
+ var original = error.stack;
42
+ if (stack && (original === undefined || original === null || original === '')) {
43
+ error.stack = stack;
44
+ } else if (stack && typeof original === 'string' && original.indexOf(stack) === -1) {
45
+ error.stack = original + '\n' + stack;
46
+ }
47
+ }
48
+ }
49
+ } catch (e) {
50
+ // Frozen errors and custom stack accessors must retain their rejection.
51
+ }
52
+ return Promise.reject(error);
53
+ });
54
+ }
55
+
56
+ function dispatchAfterRecovery(config) {
57
+ return function dispatchRecoveredRequest() {
58
+ return dispatchRequest(config);
59
+ };
60
+ }
61
+
12
62
  /**
13
63
  * Create a new instance of Axios
14
64
  *
@@ -39,11 +89,14 @@ Axios.prototype.request = function request(configOrUrl, config) {
39
89
  }
40
90
 
41
91
  config = mergeConfig(this.defaults, config);
92
+ var caller = config.captureCallerStack === true ? captureCallerStack(request) : null;
42
93
 
43
- // Set config.method
94
+ // Set config.method. The merged config is null-prototype, but instance
95
+ // defaults may be an ordinary object, so the fallback is read as an own
96
+ // property to keep an inherited value from choosing the request method.
44
97
  if (config.method) {
45
98
  config.method = config.method.toLowerCase();
46
- } else if (this.defaults.method) {
99
+ } else if (utils.hasOwnProperty(this.defaults, 'method') && this.defaults.method) {
47
100
  config.method = this.defaults.method.toLowerCase();
48
101
  } else {
49
102
  config.method = 'get';
@@ -105,7 +158,7 @@ Axios.prototype.request = function request(configOrUrl, config) {
105
158
  promise = promise.then(chain.shift(), chain.shift());
106
159
  }
107
160
 
108
- return promise;
161
+ return attachCallerStack(promise, caller);
109
162
  }
110
163
 
111
164
 
@@ -114,24 +167,39 @@ Axios.prototype.request = function request(configOrUrl, config) {
114
167
  var onFulfilled = requestInterceptorChain.shift();
115
168
  var onRejected = requestInterceptorChain.shift();
116
169
  try {
117
- newConfig = onFulfilled(newConfig);
170
+ newConfig = onFulfilled ? onFulfilled(newConfig) : newConfig;
118
171
  } catch (error) {
119
- onRejected(error);
172
+ if (!onRejected) {
173
+ promise = Promise.reject(error);
174
+ break;
175
+ }
176
+ try {
177
+ var recovery = onRejected(error);
178
+ if (recovery && typeof recovery.then === 'function') {
179
+ promise = Promise.resolve(recovery).then(dispatchAfterRecovery(newConfig));
180
+ }
181
+ } catch (rejectedError) {
182
+ promise = Promise.reject(rejectedError);
183
+ }
120
184
  break;
121
185
  }
122
186
  }
123
187
 
124
- try {
125
- promise = dispatchRequest(newConfig);
126
- } catch (error) {
127
- return Promise.reject(error);
188
+ if (!promise) {
189
+ try {
190
+ promise = dispatchRequest(newConfig);
191
+ } catch (error) {
192
+ // Dispatch errors, including pre-aborted signals, still go through the
193
+ // response interceptors registered below.
194
+ promise = Promise.reject(error);
195
+ }
128
196
  }
129
197
 
130
198
  while (responseInterceptorChain.length) {
131
199
  promise = promise.then(responseInterceptorChain.shift(), responseInterceptorChain.shift());
132
200
  }
133
201
 
134
- return promise;
202
+ return attachCallerStack(promise, caller);
135
203
  };
136
204
 
137
205
  Axios.prototype.getUri = function getUri(config) {
@@ -144,10 +212,12 @@ Axios.prototype.getUri = function getUri(config) {
144
212
  utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
145
213
  /*eslint func-names:0*/
146
214
  Axios.prototype[method] = function(url, config) {
147
- return this.request(mergeConfig(config || {}, {
215
+ var requestConfig = config || {};
216
+
217
+ return this.request(mergeConfig(requestConfig, {
148
218
  method: method,
149
219
  url: url,
150
- data: (config || {}).data
220
+ data: utils.hasOwnProperty(requestConfig, 'data') ? requestConfig.data : undefined
151
221
  }));
152
222
  };
153
223
  });
@@ -4,7 +4,7 @@ var utils = require('./../utils');
4
4
  var transformData = require('./transformData');
5
5
  var isCancel = require('../cancel/isCancel');
6
6
  var defaults = require('../defaults');
7
- var CanceledError = require('../cancel/CanceledError');
7
+ var canceledErrorFromSignal = require('../cancel/fromSignal');
8
8
  var normalizeHeaderName = require('../helpers/normalizeHeaderName');
9
9
  var sanitizeHeaderValue = require('../helpers/sanitizeHeaderValue');
10
10
 
@@ -17,7 +17,7 @@ function throwIfCancellationRequested(config) {
17
17
  }
18
18
 
19
19
  if (config.signal && config.signal.aborted) {
20
- throw new CanceledError();
20
+ throw canceledErrorFromSignal(config.signal, config);
21
21
  }
22
22
  }
23
23
 
@@ -30,8 +30,9 @@ function throwIfCancellationRequested(config) {
30
30
  module.exports = function dispatchRequest(config) {
31
31
  throwIfCancellationRequested(config);
32
32
 
33
- // Ensure headers exist
34
- config.headers = config.headers || {};
33
+ // Ensure headers exist. A request interceptor may return a replacement config
34
+ // that inherits from Object.prototype, so only an own headers value is used.
35
+ config.headers = (utils.hasOwnProperty(config, 'headers') && config.headers) || {};
35
36
 
36
37
  // Transform request data
37
38
  config.data = transformData.call(
@@ -63,6 +63,11 @@ module.exports = function mergeConfig(config1, config2) {
63
63
  }
64
64
  }
65
65
 
66
+ function defaultToConfig2Reference(prop) {
67
+ var value = getOwn(config2, prop);
68
+ return utils.isUndefined(value) ? getOwn(config1, prop) : value;
69
+ }
70
+
66
71
  // eslint-disable-next-line consistent-return
67
72
  function mergeDirectKeys(prop) {
68
73
  if (hasOwn(config2, prop)) {
@@ -98,6 +103,8 @@ module.exports = function mergeConfig(config1, config2) {
98
103
  'httpAgent': defaultToConfig2,
99
104
  'httpsAgent': defaultToConfig2,
100
105
  'cancelToken': defaultToConfig2,
106
+ // Signals are live objects; cloning them snapshots getters and reasons.
107
+ 'signal': defaultToConfig2Reference,
101
108
  'socketPath': defaultToConfig2,
102
109
  'allowedSocketPaths': defaultToConfig2,
103
110
  'responseEncoding': defaultToConfig2,
package/lib/env/data.js CHANGED
@@ -1,3 +1,3 @@
1
1
  module.exports = {
2
- "version": "0.32.0"
2
+ "version": "0.34.0"
3
3
  };
@@ -33,9 +33,17 @@ module.exports = function buildURL(url, params, options) {
33
33
  url = url.slice(0, hashmarkIndex);
34
34
  }
35
35
 
36
- var _encode = options && options.encode || encode;
37
-
38
- var serializeFn = options && options.serialize;
36
+ var _encode = encode;
37
+ var serializeFn;
38
+
39
+ if (options) {
40
+ if (utils.isFunction(options)) {
41
+ serializeFn = options;
42
+ } else {
43
+ _encode = utils.hasOwnProperty(options, 'encode') && options.encode || encode;
44
+ serializeFn = utils.hasOwnProperty(options, 'serialize') ? options.serialize : undefined;
45
+ }
46
+ }
39
47
 
40
48
  var serializedParams;
41
49
 
@@ -1,6 +1,20 @@
1
1
  'use strict';
2
2
 
3
3
  var utils = require('../utils');
4
+ var AxiosError = require('../core/AxiosError');
5
+
6
+ var MAX_FORM_DATA_TO_JSON_DEPTH = 100;
7
+
8
+ function assertPathDepth(path) {
9
+ var depth = path.length - 1;
10
+
11
+ if (depth > MAX_FORM_DATA_TO_JSON_DEPTH) {
12
+ throw new AxiosError(
13
+ 'Maximum object depth of ' + MAX_FORM_DATA_TO_JSON_DEPTH + ' exceeded (got ' + depth + ' levels)',
14
+ AxiosError.ERR_FORM_DATA_DEPTH_EXCEEDED
15
+ );
16
+ }
17
+ }
4
18
 
5
19
  function parsePropPath(name) {
6
20
  // foo[x][y][z]
@@ -62,7 +76,10 @@ function formDataToJSON(formData) {
62
76
  var obj = {};
63
77
 
64
78
  utils.forEachEntry(formData, function(name, value) {
65
- buildPath(parsePropPath(name), value, obj, 0);
79
+ var path = parsePropPath(name);
80
+
81
+ assertPathDepth(path);
82
+ buildPath(path, value, obj, 0);
66
83
  });
67
84
 
68
85
  return obj;