@openfn/language-dhis2 2.0.10 → 3.0.0-3

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.
Files changed (44) hide show
  1. package/README.md +39 -4
  2. package/ast.json +189 -2491
  3. package/lib/Adaptor.js +542 -1588
  4. package/lib/Client.js +48 -0
  5. package/lib/Utils.js +58 -179
  6. package/lib/index.js +4 -6
  7. package/node_modules/@openfn/language-common/node_modules/axios/package.json +20 -0
  8. package/node_modules/@openfn/language-common/node_modules/follow-redirects/package.json +20 -0
  9. package/node_modules/@openfn/language-common/node_modules/jsonpath-plus/package.json +20 -0
  10. package/node_modules/@openfn/language-common/node_modules/lodash/package.json +20 -0
  11. package/node_modules/@openfn/language-common/package.json +8 -4
  12. package/node_modules/axios/CHANGELOG.md +159 -8
  13. package/node_modules/axios/README.md +98 -6
  14. package/node_modules/axios/SECURITY.md +5 -0
  15. package/node_modules/axios/dist/axios.js +2101 -1582
  16. package/node_modules/axios/dist/axios.map +1 -1
  17. package/node_modules/axios/dist/axios.min.js +1 -2
  18. package/node_modules/axios/dist/axios.min.map +1 -1
  19. package/node_modules/axios/index.d.ts +76 -31
  20. package/node_modules/axios/lib/adapters/http.js +74 -14
  21. package/node_modules/axios/lib/adapters/xhr.js +66 -33
  22. package/node_modules/axios/lib/axios.js +6 -5
  23. package/node_modules/axios/lib/cancel/CancelToken.js +62 -0
  24. package/node_modules/axios/lib/core/Axios.js +60 -7
  25. package/node_modules/axios/lib/core/InterceptorManager.js +4 -2
  26. package/node_modules/axios/lib/core/README.md +1 -0
  27. package/node_modules/axios/lib/core/dispatchRequest.js +11 -3
  28. package/node_modules/axios/lib/core/enhanceError.js +2 -1
  29. package/node_modules/axios/lib/core/mergeConfig.js +50 -38
  30. package/node_modules/axios/lib/core/transformData.js +3 -1
  31. package/node_modules/axios/lib/defaults.js +48 -12
  32. package/node_modules/axios/lib/env/README.md +3 -0
  33. package/node_modules/axios/lib/env/data.js +3 -0
  34. package/node_modules/axios/lib/helpers/validator.js +82 -0
  35. package/node_modules/axios/lib/utils.js +1 -3
  36. package/node_modules/axios/package.json +37 -40
  37. package/node_modules/axios/tsconfig.json +14 -0
  38. package/node_modules/axios/tslint.json +6 -0
  39. package/node_modules/follow-redirects/README.md +1 -1
  40. package/node_modules/follow-redirects/debug.js +14 -8
  41. package/node_modules/follow-redirects/index.js +106 -41
  42. package/node_modules/follow-redirects/package.json +14 -17
  43. package/node_modules/lodash/package.json +2 -2
  44. package/package.json +5 -4
@@ -1,9 +1,21 @@
1
- export interface AxiosTransformer {
2
- (data: any, headers?: any): any;
1
+ // TypeScript Version: 3.0
2
+
3
+ export type AxiosRequestHeaders = Record<string, string>;
4
+
5
+ export type AxiosResponseHeaders = Record<string, string> & {
6
+ "set-cookie"?: string[]
7
+ };
8
+
9
+ export interface AxiosRequestTransformer {
10
+ (data: any, headers?: AxiosRequestHeaders): any;
11
+ }
12
+
13
+ export interface AxiosResponseTransformer {
14
+ (data: any, headers?: AxiosResponseHeaders): any;
3
15
  }
4
16
 
5
17
  export interface AxiosAdapter {
6
- (config: AxiosRequestConfig): AxiosPromise<any>;
18
+ (config: AxiosRequestConfig): AxiosPromise;
7
19
  }
8
20
 
9
21
  export interface AxiosBasicCredentials {
@@ -16,7 +28,7 @@ export interface AxiosProxyConfig {
16
28
  port: number;
17
29
  auth?: {
18
30
  username: string;
19
- password:string;
31
+ password: string;
20
32
  };
21
33
  protocol?: string;
22
34
  }
@@ -31,7 +43,7 @@ export type Method =
31
43
  | 'patch' | 'PATCH'
32
44
  | 'purge' | 'PURGE'
33
45
  | 'link' | 'LINK'
34
- | 'unlink' | 'UNLINK'
46
+ | 'unlink' | 'UNLINK';
35
47
 
36
48
  export type ResponseType =
37
49
  | 'arraybuffer'
@@ -39,18 +51,24 @@ export type ResponseType =
39
51
  | 'document'
40
52
  | 'json'
41
53
  | 'text'
42
- | 'stream'
54
+ | 'stream';
55
+
56
+ export interface TransitionalOptions {
57
+ silentJSONParsing?: boolean;
58
+ forcedJSONParsing?: boolean;
59
+ clarifyTimeoutError?: boolean;
60
+ }
43
61
 
44
- export interface AxiosRequestConfig {
62
+ export interface AxiosRequestConfig<D = any> {
45
63
  url?: string;
46
64
  method?: Method;
47
65
  baseURL?: string;
48
- transformRequest?: AxiosTransformer | AxiosTransformer[];
49
- transformResponse?: AxiosTransformer | AxiosTransformer[];
50
- headers?: any;
66
+ transformRequest?: AxiosRequestTransformer | AxiosRequestTransformer[];
67
+ transformResponse?: AxiosResponseTransformer | AxiosResponseTransformer[];
68
+ headers?: AxiosRequestHeaders;
51
69
  params?: any;
52
70
  paramsSerializer?: (params: any) => string;
53
- data?: any;
71
+ data?: D;
54
72
  timeout?: number;
55
73
  timeoutErrorMessage?: string;
56
74
  withCredentials?: boolean;
@@ -71,22 +89,43 @@ export interface AxiosRequestConfig {
71
89
  proxy?: AxiosProxyConfig | false;
72
90
  cancelToken?: CancelToken;
73
91
  decompress?: boolean;
92
+ transitional?: TransitionalOptions;
93
+ signal?: AbortSignal;
94
+ insecureHTTPParser?: boolean;
95
+ }
96
+
97
+ export interface HeadersDefaults {
98
+ common: AxiosRequestHeaders;
99
+ delete: AxiosRequestHeaders;
100
+ get: AxiosRequestHeaders;
101
+ head: AxiosRequestHeaders;
102
+ post: AxiosRequestHeaders;
103
+ put: AxiosRequestHeaders;
104
+ patch: AxiosRequestHeaders;
105
+ options?: AxiosRequestHeaders;
106
+ purge?: AxiosRequestHeaders;
107
+ link?: AxiosRequestHeaders;
108
+ unlink?: AxiosRequestHeaders;
109
+ }
110
+
111
+ export interface AxiosDefaults<D = any> extends Omit<AxiosRequestConfig<D>, 'headers'> {
112
+ headers: HeadersDefaults;
74
113
  }
75
114
 
76
- export interface AxiosResponse<T = any> {
115
+ export interface AxiosResponse<T = any, D = any> {
77
116
  data: T;
78
117
  status: number;
79
118
  statusText: string;
80
- headers: any;
81
- config: AxiosRequestConfig;
119
+ headers: AxiosResponseHeaders;
120
+ config: AxiosRequestConfig<D>;
82
121
  request?: any;
83
122
  }
84
123
 
85
- export interface AxiosError<T = any> extends Error {
86
- config: AxiosRequestConfig;
124
+ export interface AxiosError<T = any, D = any> extends Error {
125
+ config: AxiosRequestConfig<D>;
87
126
  code?: string;
88
127
  request?: any;
89
- response?: AxiosResponse<T>;
128
+ response?: AxiosResponse<T, D>;
90
129
  isAxiosError: boolean;
91
130
  toJSON: () => object;
92
131
  }
@@ -123,35 +162,41 @@ export interface CancelTokenSource {
123
162
  }
124
163
 
125
164
  export interface AxiosInterceptorManager<V> {
126
- use(onFulfilled?: (value: V) => V | Promise<V>, onRejected?: (error: any) => any): number;
165
+ use<T = V>(onFulfilled?: (value: V) => T | Promise<T>, onRejected?: (error: any) => any): number;
127
166
  eject(id: number): void;
128
167
  }
129
168
 
130
- export interface AxiosInstance {
131
- (config: AxiosRequestConfig): AxiosPromise;
132
- (url: string, config?: AxiosRequestConfig): AxiosPromise;
133
- defaults: AxiosRequestConfig;
169
+ export class Axios {
170
+ constructor(config?: AxiosRequestConfig);
171
+ defaults: AxiosDefaults;
134
172
  interceptors: {
135
173
  request: AxiosInterceptorManager<AxiosRequestConfig>;
136
174
  response: AxiosInterceptorManager<AxiosResponse>;
137
175
  };
138
176
  getUri(config?: AxiosRequestConfig): string;
139
- request<T = any, R = AxiosResponse<T>> (config: AxiosRequestConfig): Promise<R>;
140
- get<T = any, R = AxiosResponse<T>>(url: string, config?: AxiosRequestConfig): Promise<R>;
141
- delete<T = any, R = AxiosResponse<T>>(url: string, config?: AxiosRequestConfig): Promise<R>;
142
- head<T = any, R = AxiosResponse<T>>(url: string, config?: AxiosRequestConfig): Promise<R>;
143
- options<T = any, R = AxiosResponse<T>>(url: string, config?: AxiosRequestConfig): Promise<R>;
144
- post<T = any, R = AxiosResponse<T>>(url: string, data?: any, config?: AxiosRequestConfig): Promise<R>;
145
- put<T = any, R = AxiosResponse<T>>(url: string, data?: any, config?: AxiosRequestConfig): Promise<R>;
146
- patch<T = any, R = AxiosResponse<T>>(url: string, data?: any, config?: AxiosRequestConfig): Promise<R>;
177
+ request<T = any, R = AxiosResponse<T>, D = any>(config: AxiosRequestConfig<D>): Promise<R>;
178
+ get<T = any, R = AxiosResponse<T>, D = any>(url: string, config?: AxiosRequestConfig<D>): Promise<R>;
179
+ delete<T = any, R = AxiosResponse<T>, D = any>(url: string, config?: AxiosRequestConfig<D>): Promise<R>;
180
+ head<T = any, R = AxiosResponse<T>, D = any>(url: string, config?: AxiosRequestConfig<D>): Promise<R>;
181
+ options<T = any, R = AxiosResponse<T>, D = any>(url: string, config?: AxiosRequestConfig<D>): Promise<R>;
182
+ post<T = any, R = AxiosResponse<T>, D = any>(url: string, data?: D, config?: AxiosRequestConfig<D>): Promise<R>;
183
+ put<T = any, R = AxiosResponse<T>, D = any>(url: string, data?: D, config?: AxiosRequestConfig<D>): Promise<R>;
184
+ patch<T = any, R = AxiosResponse<T>, D = any>(url: string, data?: D, config?: AxiosRequestConfig<D>): Promise<R>;
185
+ }
186
+
187
+ export interface AxiosInstance extends Axios {
188
+ (config: AxiosRequestConfig): AxiosPromise;
189
+ (url: string, config?: AxiosRequestConfig): AxiosPromise;
147
190
  }
148
191
 
149
192
  export interface AxiosStatic extends AxiosInstance {
150
193
  create(config?: AxiosRequestConfig): AxiosInstance;
151
194
  Cancel: CancelStatic;
152
195
  CancelToken: CancelTokenStatic;
196
+ Axios: typeof Axios;
197
+ readonly VERSION: string;
153
198
  isCancel(value: any): boolean;
154
- all<T>(values: (T | Promise<T>)[]): Promise<T[]>;
199
+ all<T>(values: Array<T | Promise<T>>): Promise<T[]>;
155
200
  spread<T, R>(callback: (...args: T[]) => R): (array: T[]) => R;
156
201
  isAxiosError(payload: any): payload is AxiosError;
157
202
  }
@@ -10,9 +10,11 @@ var httpFollow = require('follow-redirects').http;
10
10
  var httpsFollow = require('follow-redirects').https;
11
11
  var url = require('url');
12
12
  var zlib = require('zlib');
13
- var pkg = require('./../../package.json');
13
+ var VERSION = require('./../env/data').version;
14
14
  var createError = require('../core/createError');
15
15
  var enhanceError = require('../core/enhanceError');
16
+ var defaults = require('../defaults');
17
+ var Cancel = require('../cancel/Cancel');
16
18
 
17
19
  var isHttps = /https:?/;
18
20
 
@@ -44,20 +46,43 @@ function setProxy(options, proxy, location) {
44
46
  /*eslint consistent-return:0*/
45
47
  module.exports = function httpAdapter(config) {
46
48
  return new Promise(function dispatchHttpRequest(resolvePromise, rejectPromise) {
49
+ var onCanceled;
50
+ function done() {
51
+ if (config.cancelToken) {
52
+ config.cancelToken.unsubscribe(onCanceled);
53
+ }
54
+
55
+ if (config.signal) {
56
+ config.signal.removeEventListener('abort', onCanceled);
57
+ }
58
+ }
47
59
  var resolve = function resolve(value) {
60
+ done();
48
61
  resolvePromise(value);
49
62
  };
50
63
  var reject = function reject(value) {
64
+ done();
51
65
  rejectPromise(value);
52
66
  };
53
67
  var data = config.data;
54
68
  var headers = config.headers;
69
+ var headerNames = {};
70
+
71
+ Object.keys(headers).forEach(function storeLowerName(name) {
72
+ headerNames[name.toLowerCase()] = name;
73
+ });
55
74
 
56
75
  // Set User-Agent (required by some servers)
57
- // Only set header if it hasn't been set in config
58
76
  // See https://github.com/axios/axios/issues/69
59
- if (!headers['User-Agent'] && !headers['user-agent']) {
60
- headers['User-Agent'] = 'axios/' + pkg.version;
77
+ if ('user-agent' in headerNames) {
78
+ // User-Agent is specified; handle case where no UA header is desired
79
+ if (!headers[headerNames['user-agent']]) {
80
+ delete headers[headerNames['user-agent']];
81
+ }
82
+ // Otherwise, use specified value
83
+ } else {
84
+ // Only set header if it hasn't been set in config
85
+ headers['User-Agent'] = 'axios/' + VERSION;
61
86
  }
62
87
 
63
88
  if (data && !utils.isStream(data)) {
@@ -75,7 +100,9 @@ module.exports = function httpAdapter(config) {
75
100
  }
76
101
 
77
102
  // Add Content-Length header if data exists
78
- headers['Content-Length'] = data.length;
103
+ if (!headerNames['content-length']) {
104
+ headers['Content-Length'] = data.length;
105
+ }
79
106
  }
80
107
 
81
108
  // HTTP basic authentication
@@ -98,8 +125,8 @@ module.exports = function httpAdapter(config) {
98
125
  auth = urlUsername + ':' + urlPassword;
99
126
  }
100
127
 
101
- if (auth) {
102
- delete headers.Authorization;
128
+ if (auth && headerNames.authorization) {
129
+ delete headers[headerNames.authorization];
103
130
  }
104
131
 
105
132
  var isHttpsRequest = isHttps.test(protocol);
@@ -191,6 +218,10 @@ module.exports = function httpAdapter(config) {
191
218
  options.maxBodyLength = config.maxBodyLength;
192
219
  }
193
220
 
221
+ if (config.insecureHTTPParser) {
222
+ options.insecureHTTPParser = config.insecureHTTPParser;
223
+ }
224
+
194
225
  // Create the request
195
226
  var req = transport.request(options, function handleResponse(res) {
196
227
  if (req.aborted) return;
@@ -231,11 +262,13 @@ module.exports = function httpAdapter(config) {
231
262
  settle(resolve, reject, response);
232
263
  } else {
233
264
  var responseBuffer = [];
265
+ var totalResponseBytes = 0;
234
266
  stream.on('data', function handleStreamData(chunk) {
235
267
  responseBuffer.push(chunk);
268
+ totalResponseBytes += chunk.length;
236
269
 
237
270
  // make sure the content length is not over the maxContentLength if specified
238
- if (config.maxContentLength > -1 && Buffer.concat(responseBuffer).length > config.maxContentLength) {
271
+ if (config.maxContentLength > -1 && totalResponseBytes > config.maxContentLength) {
239
272
  stream.destroy();
240
273
  reject(createError('maxContentLength size of ' + config.maxContentLength + ' exceeded',
241
274
  config, null, lastRequest));
@@ -270,27 +303,54 @@ module.exports = function httpAdapter(config) {
270
303
 
271
304
  // Handle request timeout
272
305
  if (config.timeout) {
306
+ // This is forcing a int timeout to avoid problems if the `req` interface doesn't handle other types.
307
+ var timeout = parseInt(config.timeout, 10);
308
+
309
+ if (isNaN(timeout)) {
310
+ reject(createError(
311
+ 'error trying to parse `config.timeout` to int',
312
+ config,
313
+ 'ERR_PARSE_TIMEOUT',
314
+ req
315
+ ));
316
+
317
+ return;
318
+ }
319
+
273
320
  // Sometime, the response will be very slow, and does not respond, the connect event will be block by event loop system.
274
321
  // And timer callback will be fired, and abort() will be invoked before connection, then get "socket hang up" and code ECONNRESET.
275
322
  // At this time, if we have a large number of request, nodejs will hang up some socket on background. and the number will up and up.
276
323
  // And then these socket which be hang up will devoring CPU little by little.
277
324
  // ClientRequest.setTimeout will be fired on the specify milliseconds, and can make sure that abort() will be fired after connect.
278
- req.setTimeout(config.timeout, function handleRequestTimeout() {
325
+ req.setTimeout(timeout, function handleRequestTimeout() {
279
326
  req.abort();
280
- reject(createError('timeout of ' + config.timeout + 'ms exceeded', config, 'ECONNABORTED', req));
327
+ var transitional = config.transitional || defaults.transitional;
328
+ reject(createError(
329
+ 'timeout of ' + timeout + 'ms exceeded',
330
+ config,
331
+ transitional.clarifyTimeoutError ? 'ETIMEDOUT' : 'ECONNABORTED',
332
+ req
333
+ ));
281
334
  });
282
335
  }
283
336
 
284
- if (config.cancelToken) {
337
+ if (config.cancelToken || config.signal) {
285
338
  // Handle cancellation
286
- config.cancelToken.promise.then(function onCanceled(cancel) {
339
+ // eslint-disable-next-line func-names
340
+ onCanceled = function(cancel) {
287
341
  if (req.aborted) return;
288
342
 
289
343
  req.abort();
290
- reject(cancel);
291
- });
344
+ reject(!cancel || (cancel && cancel.type) ? new Cancel('canceled') : cancel);
345
+ };
346
+
347
+ config.cancelToken && config.cancelToken.subscribe(onCanceled);
348
+ if (config.signal) {
349
+ config.signal.aborted ? onCanceled() : config.signal.addEventListener('abort', onCanceled);
350
+ }
292
351
  }
293
352
 
353
+
294
354
  // Send the request
295
355
  if (utils.isStream(data)) {
296
356
  data.on('error', function handleStreamError(err) {
@@ -8,11 +8,24 @@ var buildFullPath = require('../core/buildFullPath');
8
8
  var parseHeaders = require('./../helpers/parseHeaders');
9
9
  var isURLSameOrigin = require('./../helpers/isURLSameOrigin');
10
10
  var createError = require('../core/createError');
11
+ var defaults = require('../defaults');
12
+ var Cancel = require('../cancel/Cancel');
11
13
 
12
14
  module.exports = function xhrAdapter(config) {
13
15
  return new Promise(function dispatchXhrRequest(resolve, reject) {
14
16
  var requestData = config.data;
15
17
  var requestHeaders = config.headers;
18
+ var responseType = config.responseType;
19
+ var onCanceled;
20
+ function done() {
21
+ if (config.cancelToken) {
22
+ config.cancelToken.unsubscribe(onCanceled);
23
+ }
24
+
25
+ if (config.signal) {
26
+ config.signal.removeEventListener('abort', onCanceled);
27
+ }
28
+ }
16
29
 
17
30
  if (utils.isFormData(requestData)) {
18
31
  delete requestHeaders['Content-Type']; // Let the browser set it
@@ -33,23 +46,14 @@ module.exports = function xhrAdapter(config) {
33
46
  // Set the request timeout in MS
34
47
  request.timeout = config.timeout;
35
48
 
36
- // Listen for ready state
37
- request.onreadystatechange = function handleLoad() {
38
- if (!request || request.readyState !== 4) {
39
- return;
40
- }
41
-
42
- // The request errored out and we didn't get a response, this will be
43
- // handled by onerror instead
44
- // With one exception: request that using file: protocol, most browsers
45
- // will return status as 0 even though it's a successful request
46
- if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {
49
+ function onloadend() {
50
+ if (!request) {
47
51
  return;
48
52
  }
49
-
50
53
  // Prepare the response
51
54
  var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null;
52
- var responseData = !config.responseType || config.responseType === 'text' ? request.responseText : request.response;
55
+ var responseData = !responseType || responseType === 'text' || responseType === 'json' ?
56
+ request.responseText : request.response;
53
57
  var response = {
54
58
  data: responseData,
55
59
  status: request.status,
@@ -59,11 +63,40 @@ module.exports = function xhrAdapter(config) {
59
63
  request: request
60
64
  };
61
65
 
62
- settle(resolve, reject, response);
66
+ settle(function _resolve(value) {
67
+ resolve(value);
68
+ done();
69
+ }, function _reject(err) {
70
+ reject(err);
71
+ done();
72
+ }, response);
63
73
 
64
74
  // Clean up request
65
75
  request = null;
66
- };
76
+ }
77
+
78
+ if ('onloadend' in request) {
79
+ // Use onloadend if available
80
+ request.onloadend = onloadend;
81
+ } else {
82
+ // Listen for ready state to emulate onloadend
83
+ request.onreadystatechange = function handleLoad() {
84
+ if (!request || request.readyState !== 4) {
85
+ return;
86
+ }
87
+
88
+ // The request errored out and we didn't get a response, this will be
89
+ // handled by onerror instead
90
+ // With one exception: request that using file: protocol, most browsers
91
+ // will return status as 0 even though it's a successful request
92
+ if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {
93
+ return;
94
+ }
95
+ // readystate handler is calling before onerror or ontimeout handlers,
96
+ // so we should call onloadend on the next 'tick'
97
+ setTimeout(onloadend);
98
+ };
99
+ }
67
100
 
68
101
  // Handle browser request cancellation (as opposed to a manual cancellation)
69
102
  request.onabort = function handleAbort() {
@@ -89,11 +122,15 @@ module.exports = function xhrAdapter(config) {
89
122
 
90
123
  // Handle timeout
91
124
  request.ontimeout = function handleTimeout() {
92
- var timeoutErrorMessage = 'timeout of ' + config.timeout + 'ms exceeded';
125
+ var timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded';
126
+ var transitional = config.transitional || defaults.transitional;
93
127
  if (config.timeoutErrorMessage) {
94
128
  timeoutErrorMessage = config.timeoutErrorMessage;
95
129
  }
96
- reject(createError(timeoutErrorMessage, config, 'ECONNABORTED',
130
+ reject(createError(
131
+ timeoutErrorMessage,
132
+ config,
133
+ transitional.clarifyTimeoutError ? 'ETIMEDOUT' : 'ECONNABORTED',
97
134
  request));
98
135
 
99
136
  // Clean up request
@@ -133,16 +170,8 @@ module.exports = function xhrAdapter(config) {
133
170
  }
134
171
 
135
172
  // Add responseType to request if needed
136
- if (config.responseType) {
137
- try {
138
- request.responseType = config.responseType;
139
- } catch (e) {
140
- // Expected DOMException thrown by browsers not compatible XMLHttpRequest Level 2.
141
- // But, this can be suppressed for 'json' type as it can be parsed by default 'transformResponse' function.
142
- if (config.responseType !== 'json') {
143
- throw e;
144
- }
145
- }
173
+ if (responseType && responseType !== 'json') {
174
+ request.responseType = config.responseType;
146
175
  }
147
176
 
148
177
  // Handle progress if needed
@@ -155,18 +184,22 @@ module.exports = function xhrAdapter(config) {
155
184
  request.upload.addEventListener('progress', config.onUploadProgress);
156
185
  }
157
186
 
158
- if (config.cancelToken) {
187
+ if (config.cancelToken || config.signal) {
159
188
  // Handle cancellation
160
- config.cancelToken.promise.then(function onCanceled(cancel) {
189
+ // eslint-disable-next-line func-names
190
+ onCanceled = function(cancel) {
161
191
  if (!request) {
162
192
  return;
163
193
  }
164
-
194
+ reject(!cancel || (cancel && cancel.type) ? new Cancel('canceled') : cancel);
165
195
  request.abort();
166
- reject(cancel);
167
- // Clean up request
168
196
  request = null;
169
- });
197
+ };
198
+
199
+ config.cancelToken && config.cancelToken.subscribe(onCanceled);
200
+ if (config.signal) {
201
+ config.signal.aborted ? onCanceled() : config.signal.addEventListener('abort', onCanceled);
202
+ }
170
203
  }
171
204
 
172
205
  if (!requestData) {
@@ -22,6 +22,11 @@ function createInstance(defaultConfig) {
22
22
  // Copy context to instance
23
23
  utils.extend(instance, context);
24
24
 
25
+ // Factory for creating new instances
26
+ instance.create = function create(instanceConfig) {
27
+ return createInstance(mergeConfig(defaultConfig, instanceConfig));
28
+ };
29
+
25
30
  return instance;
26
31
  }
27
32
 
@@ -31,15 +36,11 @@ var axios = createInstance(defaults);
31
36
  // Expose Axios class to allow class inheritance
32
37
  axios.Axios = Axios;
33
38
 
34
- // Factory for creating new instances
35
- axios.create = function create(instanceConfig) {
36
- return createInstance(mergeConfig(axios.defaults, instanceConfig));
37
- };
38
-
39
39
  // Expose Cancel & CancelToken
40
40
  axios.Cancel = require('./cancel/Cancel');
41
41
  axios.CancelToken = require('./cancel/CancelToken');
42
42
  axios.isCancel = require('./cancel/isCancel');
43
+ axios.VERSION = require('./env/data').version;
43
44
 
44
45
  // Expose all/spread
45
46
  axios.all = function all(promises) {
@@ -14,11 +14,42 @@ function CancelToken(executor) {
14
14
  }
15
15
 
16
16
  var resolvePromise;
17
+
17
18
  this.promise = new Promise(function promiseExecutor(resolve) {
18
19
  resolvePromise = resolve;
19
20
  });
20
21
 
21
22
  var token = this;
23
+
24
+ // eslint-disable-next-line func-names
25
+ this.promise.then(function(cancel) {
26
+ if (!token._listeners) return;
27
+
28
+ var i;
29
+ var l = token._listeners.length;
30
+
31
+ for (i = 0; i < l; i++) {
32
+ token._listeners[i](cancel);
33
+ }
34
+ token._listeners = null;
35
+ });
36
+
37
+ // eslint-disable-next-line func-names
38
+ this.promise.then = function(onfulfilled) {
39
+ var _resolve;
40
+ // eslint-disable-next-line func-names
41
+ var promise = new Promise(function(resolve) {
42
+ token.subscribe(resolve);
43
+ _resolve = resolve;
44
+ }).then(onfulfilled);
45
+
46
+ promise.cancel = function reject() {
47
+ token.unsubscribe(_resolve);
48
+ };
49
+
50
+ return promise;
51
+ };
52
+
22
53
  executor(function cancel(message) {
23
54
  if (token.reason) {
24
55
  // Cancellation has already been requested
@@ -39,6 +70,37 @@ CancelToken.prototype.throwIfRequested = function throwIfRequested() {
39
70
  }
40
71
  };
41
72
 
73
+ /**
74
+ * Subscribe to the cancel signal
75
+ */
76
+
77
+ CancelToken.prototype.subscribe = function subscribe(listener) {
78
+ if (this.reason) {
79
+ listener(this.reason);
80
+ return;
81
+ }
82
+
83
+ if (this._listeners) {
84
+ this._listeners.push(listener);
85
+ } else {
86
+ this._listeners = [listener];
87
+ }
88
+ };
89
+
90
+ /**
91
+ * Unsubscribe from the cancel signal
92
+ */
93
+
94
+ CancelToken.prototype.unsubscribe = function unsubscribe(listener) {
95
+ if (!this._listeners) {
96
+ return;
97
+ }
98
+ var index = this._listeners.indexOf(listener);
99
+ if (index !== -1) {
100
+ this._listeners.splice(index, 1);
101
+ }
102
+ };
103
+
42
104
  /**
43
105
  * Returns an object that contains a new `CancelToken` and a function that, when called,
44
106
  * cancels the `CancelToken`.