2
0
mirror of https://github.com/tenrok/axios.git synced 2026-06-14 18:42:33 +03:00

Axios ES2017 (#4787)

* Added AxiosHeaders class;

* Fixed README.md href;

* Fixed a potential bug with headers normalization;

* Fixed a potential bug with headers normalization;
Refactored accessor building routine;
Refactored default transforms;
Removed `normalizeHeaderName` helper;

* Added `Content-Length` accessor;
Added missed `has` accessor to TS types;

* Added `AxiosTransformStream` class;
Added progress capturing ability for node.js environment;
Added `maxRate` option to limit the data rate in node.js environment;
Refactored event handled by `onUploadProgress` && `onDownloadProgress` listeners in browser environment;
Added progress & data rate tests for the http adapter;
Added response stream aborting test;
Added a manual progress capture test for the browser;
Updated TS types;
Added TS tests;
Refactored request abort logic for the http adapter;
Added ability to abort the response stream;

* Remove `stream/promises` & `timers/promises` modules usage in tests;

* Use `abortcontroller-polyfill`;

* Fixed AxiosTransformStream dead-lock in legacy node versions;
Fixed CancelError emitting in streams;

* Reworked AxiosTransformStream internal logic to optimize memory consumption;
Added throwing an error if the request stream was silently destroying (without error) Refers to #3966;

* Treat the destruction of the request stream as a cancellation of the request;
Fixed tests;

* Emit `progress` event in the next tick;

* Initial refactoring;

* Refactored Mocha tests to use ESM;

* Refactored Karma tests to use rollup preprocessor & ESM;
Replaced grunt with gulp;
Improved dev scripts;
Added Babel for rollup build;

* Added default commonjs package export for Node build;
Added automatic contributors list generator for package.json;

Co-authored-by: Jay <jasonsaayman@gmail.com>
This commit is contained in:
Dmitriy Mozgovoy
2022-06-18 12:19:27 +03:00
committed by GitHub
parent 1db715dd3b
commit bdf493cf8b
125 changed files with 10462 additions and 7291 deletions
+229 -121
View File
@@ -1,27 +1,33 @@
'use strict';
var utils = require('./../utils');
var settle = require('./../core/settle');
var buildFullPath = require('../core/buildFullPath');
var buildURL = require('./../helpers/buildURL');
var getProxyForUrl = require('proxy-from-env').getProxyForUrl;
var http = require('http');
var https = require('https');
var httpFollow = require('follow-redirects/http');
var httpsFollow = require('follow-redirects/https');
var url = require('url');
var zlib = require('zlib');
var VERSION = require('./../env/data').version;
var transitionalDefaults = require('../defaults/transitional');
var AxiosError = require('../core/AxiosError');
var CanceledError = require('../cancel/CanceledError');
var platform = require('../platform');
var fromDataURI = require('../helpers/fromDataURI');
var stream = require('stream');
import utils from './../utils.js';
import settle from './../core/settle.js';
import buildFullPath from '../core/buildFullPath.js';
import buildURL from './../helpers/buildURL.js';
import {getProxyForUrl} from 'proxy-from-env';
import http from 'http';
import https from 'https';
import followRedirects from 'follow-redirects';
import url from 'url';
import zlib from 'zlib';
import {VERSION} from '../env/data.js';
import transitionalDefaults from '../defaults/transitional.js';
import AxiosError from '../core/AxiosError.js';
import CanceledError from '../cancel/CanceledError.js';
import platform from '../platform/index.js';
import fromDataURI from '../helpers/fromDataURI.js';
import stream from 'stream';
import AxiosHeaders from '../core/AxiosHeaders.js';
import AxiosTransformStream from '../helpers/AxiosTransformStream.js';
import EventEmitter from 'events';
var isHttps = /https:?/;
const isBrotliSupported = utils.isFunction(zlib.createBrotliDecompress);
var supportedProtocols = platform.protocols.map(function(protocol) {
const {http: httpFollow, https: httpsFollow} = followRedirects;
const isHttps = /https:?/;
const supportedProtocols = platform.protocols.map(protocol => {
return protocol + ':';
});
@@ -52,9 +58,9 @@ function dispatchBeforeRedirect(options) {
* @returns {http.ClientRequestArgs}
*/
function setProxy(options, configProxy, location) {
var proxy = configProxy;
let proxy = configProxy;
if (!proxy && proxy !== false) {
var proxyUrl = getProxyForUrl(location);
const proxyUrl = getProxyForUrl(location);
if (proxyUrl) {
proxy = url.parse(proxyUrl);
// replace 'host' since the proxy object is not a URL object
@@ -68,7 +74,7 @@ function setProxy(options, configProxy, location) {
if (proxy.auth.username || proxy.auth.password) {
proxy.auth = (proxy.auth.username || '') + ':' + (proxy.auth.password || '');
}
var base64 = Buffer
const base64 = Buffer
.from(proxy.auth, 'utf8')
.toString('base64');
options.headers['Proxy-Authorization'] = 'Basic ' + base64;
@@ -92,10 +98,25 @@ function setProxy(options, configProxy, location) {
}
/*eslint consistent-return:0*/
module.exports = function httpAdapter(config) {
export default function httpAdapter(config) {
return new Promise(function dispatchHttpRequest(resolvePromise, rejectPromise) {
var onCanceled;
function done() {
let onCanceled;
let data = config.data;
const responseType = config.responseType;
const responseEncoding = config.responseEncoding;
const method = config.method.toUpperCase();
let isFinished;
let isDone;
let rejected = false;
let req;
// temporary internal emitter until the AxiosRequest class will be implemented
const emitter = new EventEmitter();
function onFinished() {
if (isFinished) return;
isFinished = true;
if (config.cancelToken) {
config.cancelToken.unsubscribe(onCanceled);
}
@@ -103,36 +124,58 @@ module.exports = function httpAdapter(config) {
if (config.signal) {
config.signal.removeEventListener('abort', onCanceled);
}
emitter.removeAllListeners();
}
var resolve = function resolve(value) {
done();
resolvePromise(value);
function done(value, isRejected) {
if (isDone) return;
isDone = true;
if (isRejected) {
rejected = true;
onFinished();
}
isRejected ? rejectPromise(value) : resolvePromise(value);
}
const resolve = function resolve(value) {
done(value);
};
var rejected = false;
var reject = function reject(value) {
done();
rejected = true;
rejectPromise(value);
const reject = function reject(value) {
done(value, true);
};
var data = config.data;
var responseType = config.responseType;
var responseEncoding = config.responseEncoding;
var method = config.method.toUpperCase();
function abort(reason) {
emitter.emit('abort', !reason || reason.type ? new CanceledError(null, config, req) : reason);
}
emitter.once('abort', reject);
if (config.cancelToken || config.signal) {
config.cancelToken && config.cancelToken.subscribe(abort);
if (config.signal) {
config.signal.aborted ? abort() : config.signal.addEventListener('abort', abort);
}
}
// Parse url
var fullPath = buildFullPath(config.baseURL, config.url);
var parsed = url.parse(fullPath);
var protocol = parsed.protocol || supportedProtocols[0];
const fullPath = buildFullPath(config.baseURL, config.url);
const parsed = url.parse(fullPath);
const protocol = parsed.protocol || supportedProtocols[0];
if (protocol === 'data:') {
var convertedData;
let convertedData;
if (method !== 'GET') {
return settle(resolve, reject, {
status: 405,
statusText: 'method not allowed',
headers: {},
config: config
config
});
}
@@ -159,7 +202,7 @@ module.exports = function httpAdapter(config) {
status: 200,
statusText: 'OK',
headers: {},
config: config
config
});
}
@@ -171,29 +214,23 @@ module.exports = function httpAdapter(config) {
));
}
var headers = config.headers;
var headerNames = {};
Object.keys(headers).forEach(function storeLowerName(name) {
headerNames[name.toLowerCase()] = name;
});
const headers = AxiosHeaders.from(config.headers).normalize();
// Set User-Agent (required by some servers)
// See https://github.com/axios/axios/issues/69
if ('user-agent' in headerNames) {
// User-Agent is specified; handle case where no UA header is desired
if (!headers[headerNames['user-agent']]) {
delete headers[headerNames['user-agent']];
}
// Otherwise, use specified value
} else {
// Only set header if it hasn't been set in config
headers['User-Agent'] = 'axios/' + VERSION;
}
// User-Agent is specified; handle case where no UA header is desired
// Only set header if it hasn't been set in config
headers.set('User-Agent', 'axios/' + VERSION, false);
const onDownloadProgress = config.onDownloadProgress;
const onUploadProgress = config.onUploadProgress;
const maxRate = config.maxRate;
let maxUploadRate = undefined;
let maxDownloadRate = undefined;
// support for https://www.npmjs.com/package/form-data api
if (utils.isFormData(data) && utils.isFunction(data.getHeaders)) {
Object.assign(headers, data.getHeaders());
headers.set(data.getHeaders());
} else if (data && !utils.isStream(data)) {
if (Buffer.isBuffer(data)) {
// Nothing to do...
@@ -209,6 +246,9 @@ module.exports = function httpAdapter(config) {
));
}
// Add Content-Length header if data exists
headers.set('Content-Length', data.length, false);
if (config.maxBodyLength > -1 && data.length > config.maxBodyLength) {
return reject(new AxiosError(
'Request body larger than maxBodyLength limit',
@@ -216,49 +256,70 @@ module.exports = function httpAdapter(config) {
config
));
}
}
// Add Content-Length header if data exists
if (!headerNames['content-length']) {
headers['Content-Length'] = data.length;
const contentLength = +headers.getContentLength();
if (utils.isArray(maxRate)) {
maxUploadRate = maxRate[0];
maxDownloadRate = maxRate[1];
} else {
maxUploadRate = maxDownloadRate = maxRate;
}
if (data && (onUploadProgress || maxUploadRate)) {
if (!utils.isStream(data)) {
data = stream.Readable.from(data, {objectMode: false});
}
data = stream.pipeline([data, new AxiosTransformStream({
length: utils.toFiniteNumber(contentLength),
maxRate: utils.toFiniteNumber(maxUploadRate)
})], utils.noop);
onUploadProgress && data.on('progress', progress => {
onUploadProgress(Object.assign(progress, {
upload: true
}));
});
}
// HTTP basic authentication
var auth = undefined;
let auth = undefined;
if (config.auth) {
var username = config.auth.username || '';
var password = config.auth.password || '';
const username = config.auth.username || '';
const password = config.auth.password || '';
auth = username + ':' + password;
}
if (!auth && parsed.auth) {
var urlAuth = parsed.auth.split(':');
var urlUsername = urlAuth[0] || '';
var urlPassword = urlAuth[1] || '';
const urlAuth = parsed.auth.split(':');
const urlUsername = urlAuth[0] || '';
const urlPassword = urlAuth[1] || '';
auth = urlUsername + ':' + urlPassword;
}
if (auth && headerNames.authorization) {
delete headers[headerNames.authorization];
}
auth && headers.delete('authorization');
try {
buildURL(parsed.path, config.params, config.paramsSerializer).replace(/^\?/, '');
} catch (err) {
var customErr = new Error(err.message);
const customErr = new Error(err.message);
customErr.config = config;
customErr.url = config.url;
customErr.exists = true;
reject(customErr);
return reject(customErr);
}
var options = {
headers.set('Accept-Encoding', 'gzip, deflate, gzip, br', false);
const options = {
path: buildURL(parsed.path, config.params, config.paramsSerializer).replace(/^\?/, ''),
method: method,
headers: headers,
method,
headers: headers.toJSON(),
agents: { http: config.httpAgent, https: config.httpsAgent },
auth: auth,
protocol: protocol,
auth,
protocol,
beforeRedirect: dispatchBeforeRedirect,
beforeRedirects: {}
};
@@ -271,8 +332,8 @@ module.exports = function httpAdapter(config) {
setProxy(options, config.proxy, protocol + '//' + parsed.hostname + (parsed.port ? ':' + parsed.port : '') + options.path);
}
var transport;
var isHttpsRequest = isHttps.test(options.protocol);
let transport;
const isHttpsRequest = isHttps.test(options.protocol);
options.agent = isHttpsRequest ? config.httpsAgent : config.httpAgent;
if (config.transport) {
transport = config.transport;
@@ -300,14 +361,16 @@ module.exports = function httpAdapter(config) {
}
// Create the request
var req = transport.request(options, function handleResponse(res) {
if (req.aborted) return;
req = transport.request(options, function handleResponse(res) {
if (req.destroyed) return;
const streams = [res];
// uncompress the response body transparently if required
var responseStream = res;
let responseStream = res;
// return the last request in case of redirects
var lastRequest = res.req || req;
const lastRequest = res.req || req;
// if decompress disabled we should not decompress
if (config.decompress !== false) {
@@ -323,19 +386,48 @@ module.exports = function httpAdapter(config) {
case 'compress':
case 'deflate':
// add the unzipper to the body stream processing pipeline
responseStream = responseStream.pipe(zlib.createUnzip());
streams.push(zlib.createUnzip());
// remove the content-encoding in order to not confuse downstream operations
delete res.headers['content-encoding'];
break;
case 'br':
if (isBrotliSupported) {
streams.push(zlib.createBrotliDecompress());
delete res.headers['content-encoding'];
}
}
}
var response = {
if (onDownloadProgress) {
const responseLength = +res.headers['content-length'];
const transformStream = new AxiosTransformStream({
length: utils.toFiniteNumber(responseLength),
maxRate: utils.toFiniteNumber(maxDownloadRate)
});
onDownloadProgress && transformStream.on('progress', progress => {
onDownloadProgress(Object.assign(progress, {
download: true
}));
});
streams.push(transformStream);
}
responseStream = streams.length > 1 ? stream.pipeline(streams, utils.noop) : streams[0];
const offListeners = stream.finished(responseStream, () => {
offListeners();
onFinished();
});
const response = {
status: res.statusCode,
statusText: res.statusMessage,
headers: res.headers,
config: config,
headers: new AxiosHeaders(res.headers),
config,
request: lastRequest
};
@@ -343,8 +435,9 @@ module.exports = function httpAdapter(config) {
response.data = responseStream;
settle(resolve, reject, response);
} else {
var responseBuffer = [];
var totalResponseBytes = 0;
const responseBuffer = [];
let totalResponseBytes = 0;
responseStream.on('data', function handleStreamData(chunk) {
responseBuffer.push(chunk);
totalResponseBytes += chunk.length;
@@ -363,23 +456,25 @@ module.exports = function httpAdapter(config) {
if (rejected) {
return;
}
responseStream.destroy();
reject(new AxiosError(
const err = new AxiosError(
'maxContentLength size of ' + config.maxContentLength + ' exceeded',
AxiosError.ERR_BAD_RESPONSE,
config,
lastRequest
));
);
responseStream.destroy(err);
reject(err);
});
responseStream.on('error', function handleStreamError(err) {
if (req.aborted) return;
if (req.destroyed) return;
reject(AxiosError.from(err, null, config, lastRequest));
});
responseStream.on('end', function handleStreamEnd() {
try {
var responseData = responseBuffer.length === 1 ? responseBuffer[0] : Buffer.concat(responseBuffer);
let responseData = responseBuffer.length === 1 ? responseBuffer[0] : Buffer.concat(responseBuffer);
if (responseType !== 'arraybuffer') {
responseData = responseData.toString(responseEncoding);
if (!responseEncoding || responseEncoding === 'utf8') {
@@ -393,6 +488,18 @@ module.exports = function httpAdapter(config) {
settle(resolve, reject, response);
});
}
emitter.once('abort', err => {
if (!responseStream.destroyed) {
responseStream.emit('error', err);
responseStream.destroy();
}
});
});
emitter.once('abort', err => {
reject(err);
req.destroy(err);
});
// Handle errors
@@ -411,7 +518,7 @@ module.exports = function httpAdapter(config) {
// Handle request timeout
if (config.timeout) {
// This is forcing a int timeout to avoid problems if the `req` interface doesn't handle other types.
var timeout = parseInt(config.timeout, 10);
const timeout = parseInt(config.timeout, 10);
if (isNaN(timeout)) {
reject(new AxiosError(
@@ -430,9 +537,9 @@ module.exports = function httpAdapter(config) {
// And then these socket which be hang up will devouring CPU little by little.
// ClientRequest.setTimeout will be fired on the specify milliseconds, and can make sure that abort() will be fired after connect.
req.setTimeout(timeout, function handleRequestTimeout() {
req.abort();
var timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded';
var transitional = config.transitional || transitionalDefaults;
if (isDone) return;
let timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded';
const transitional = config.transitional || transitionalDefaults;
if (config.timeoutErrorMessage) {
timeoutErrorMessage = config.timeoutErrorMessage;
}
@@ -442,33 +549,34 @@ module.exports = function httpAdapter(config) {
config,
req
));
abort();
});
}
if (config.cancelToken || config.signal) {
// Handle cancellation
// eslint-disable-next-line func-names
onCanceled = function(cancel) {
if (req.aborted) return;
req.abort();
reject(!cancel || cancel.type ? new CanceledError(null, config, req) : cancel);
};
config.cancelToken && config.cancelToken.subscribe(onCanceled);
if (config.signal) {
config.signal.aborted ? onCanceled() : config.signal.addEventListener('abort', onCanceled);
}
}
// Send the request
if (utils.isStream(data)) {
data.on('error', function handleStreamError(err) {
reject(AxiosError.from(err, config, null, req));
}).pipe(req);
let ended = false;
let errored = false;
data.on('end', () => {
ended = true;
});
data.once('error', err => {
errored = true;
req.destroy(err);
});
data.on('close', () => {
if (!ended && !errored) {
abort(new CanceledError('Request stream has been aborted', config, req));
}
});
data.pipe(req);
} else {
req.end(data);
}
});
};
}
+33
View File
@@ -0,0 +1,33 @@
import utils from '../utils.js';
import httpAdapter from './http.js';
import xhrAdapter from './xhr.js';
const adapters = {
http: httpAdapter,
xhr: xhrAdapter
}
export default {
getAdapter: (nameOrAdapter) => {
if(utils.isString(nameOrAdapter)){
const adapter = adapters[nameOrAdapter];
if (!nameOrAdapter) {
throw Error(
utils.hasOwnProp(nameOrAdapter) ?
`Adapter '${nameOrAdapter}' is not available in the build` :
`Can not resolve adapter '${nameOrAdapter}'`
);
}
return adapter
}
if (!utils.isFunction(nameOrAdapter)) {
throw new TypeError('adapter is not a function');
}
return nameOrAdapter;
},
adapters
}
+75 -48
View File
@@ -1,24 +1,53 @@
'use strict';
var utils = require('./../utils');
var settle = require('./../core/settle');
var cookies = require('./../helpers/cookies');
var buildURL = require('./../helpers/buildURL');
var buildFullPath = require('../core/buildFullPath');
var parseHeaders = require('./../helpers/parseHeaders');
var isURLSameOrigin = require('./../helpers/isURLSameOrigin');
var transitionalDefaults = require('../defaults/transitional');
var AxiosError = require('../core/AxiosError');
var CanceledError = require('../cancel/CanceledError');
var parseProtocol = require('../helpers/parseProtocol');
var platform = require('../platform');
import utils from './../utils.js';
import settle from './../core/settle.js';
import cookies from './../helpers/cookies.js';
import buildURL from './../helpers/buildURL.js';
import buildFullPath from '../core/buildFullPath.js';
import isURLSameOrigin from './../helpers/isURLSameOrigin.js';
import transitionalDefaults from '../defaults/transitional.js';
import AxiosError from '../core/AxiosError.js';
import CanceledError from '../cancel/CanceledError.js';
import parseProtocol from '../helpers/parseProtocol.js';
import platform from '../platform/index.js';
import AxiosHeaders from '../core/AxiosHeaders.js';
import speedometer from '../helpers/speedometer.js';
module.exports = function xhrAdapter(config) {
function progressEventReducer(listener, isDownloadStream) {
let bytesNotified = 0;
const _speedometer = speedometer(50, 250);
return e => {
const loaded = e.loaded;
const total = e.lengthComputable ? e.total : undefined;
const progressBytes = loaded - bytesNotified;
const rate = _speedometer(progressBytes);
const inRange = loaded <= total;
bytesNotified = loaded;
const data = {
loaded,
total,
progress: total ? (loaded / total) : undefined,
bytes: progressBytes,
rate: rate ? rate : undefined,
estimated: rate && total && inRange ? (total - loaded) / rate : undefined
};
data[isDownloadStream ? 'download' : 'upload'] = true;
listener(data);
};
}
export default function xhrAdapter(config) {
return new Promise(function dispatchXhrRequest(resolve, reject) {
var requestData = config.data;
var requestHeaders = config.headers;
var responseType = config.responseType;
var onCanceled;
let requestData = config.data;
const requestHeaders = AxiosHeaders.from(config.headers).normalize();
const responseType = config.responseType;
let onCanceled;
function done() {
if (config.cancelToken) {
config.cancelToken.unsubscribe(onCanceled);
@@ -30,19 +59,19 @@ module.exports = function xhrAdapter(config) {
}
if (utils.isFormData(requestData) && utils.isStandardBrowserEnv()) {
delete requestHeaders['Content-Type']; // Let the browser set it
requestHeaders.setContentType(false); // Let the browser set it
}
var request = new XMLHttpRequest();
let request = new XMLHttpRequest();
// HTTP basic authentication
if (config.auth) {
var username = config.auth.username || '';
var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : '';
requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password);
const username = config.auth.username || '';
const password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : '';
requestHeaders.set('Authorization', 'Basic ' + btoa(username + ':' + password));
}
var fullPath = buildFullPath(config.baseURL, config.url);
const fullPath = buildFullPath(config.baseURL, config.url);
request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true);
@@ -54,16 +83,18 @@ module.exports = function xhrAdapter(config) {
return;
}
// Prepare the response
var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null;
var responseData = !responseType || responseType === 'text' || responseType === 'json' ?
const responseHeaders = AxiosHeaders.from(
'getAllResponseHeaders' in request && request.getAllResponseHeaders()
);
const responseData = !responseType || responseType === 'text' || responseType === 'json' ?
request.responseText : request.response;
var response = {
const response = {
data: responseData,
status: request.status,
statusText: request.statusText,
headers: responseHeaders,
config: config,
request: request
config,
request
};
settle(function _resolve(value) {
@@ -125,8 +156,8 @@ module.exports = function xhrAdapter(config) {
// Handle timeout
request.ontimeout = function handleTimeout() {
var timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded';
var transitional = config.transitional || transitionalDefaults;
let timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded';
const transitional = config.transitional || transitionalDefaults;
if (config.timeoutErrorMessage) {
timeoutErrorMessage = config.timeoutErrorMessage;
}
@@ -145,25 +176,21 @@ module.exports = function xhrAdapter(config) {
// Specifically not if we're in a web worker, or react-native.
if (utils.isStandardBrowserEnv()) {
// Add xsrf header
var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ?
cookies.read(config.xsrfCookieName) :
undefined;
const xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath))
&& config.xsrfCookieName && cookies.read(config.xsrfCookieName);
if (xsrfValue) {
requestHeaders[config.xsrfHeaderName] = xsrfValue;
requestHeaders.set(config.xsrfHeaderName, xsrfValue);
}
}
// Remove Content-Type if data is undefined
requestData === undefined && requestHeaders.setContentType(null);
// Add headers to the request
if ('setRequestHeader' in request) {
utils.forEach(requestHeaders, function setRequestHeader(val, key) {
if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') {
// Remove Content-Type if data is undefined
delete requestHeaders[key];
} else {
// Otherwise add header to the request
request.setRequestHeader(key, val);
}
utils.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) {
request.setRequestHeader(key, val);
});
}
@@ -179,22 +206,22 @@ module.exports = function xhrAdapter(config) {
// Handle progress if needed
if (typeof config.onDownloadProgress === 'function') {
request.addEventListener('progress', config.onDownloadProgress);
request.addEventListener('progress', progressEventReducer(config.onDownloadProgress, true));
}
// Not all browsers support upload events
if (typeof config.onUploadProgress === 'function' && request.upload) {
request.upload.addEventListener('progress', config.onUploadProgress);
request.upload.addEventListener('progress', progressEventReducer(config.onUploadProgress));
}
if (config.cancelToken || config.signal) {
// Handle cancellation
// eslint-disable-next-line func-names
onCanceled = function(cancel) {
onCanceled = cancel => {
if (!request) {
return;
}
reject(!cancel || cancel.type ? new CanceledError(null, config, req) : cancel);
reject(!cancel || cancel.type ? new CanceledError(null, config, request) : cancel);
request.abort();
request = null;
};
@@ -210,7 +237,7 @@ module.exports = function xhrAdapter(config) {
requestData = null;
}
var protocol = parseProtocol(fullPath);
const protocol = parseProtocol(fullPath);
if (protocol && platform.protocols.indexOf(protocol) === -1) {
reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config));
@@ -221,4 +248,4 @@ module.exports = function xhrAdapter(config) {
// Send the request
request.send(requestData);
});
};
}
+31 -24
View File
@@ -1,11 +1,20 @@
'use strict';
var utils = require('./utils');
var bind = require('./helpers/bind');
var Axios = require('./core/Axios');
var mergeConfig = require('./core/mergeConfig');
var defaults = require('./defaults');
var formDataToJSON = require('./helpers/formDataToJSON');
import utils from './utils.js';
import bind from './helpers/bind.js';
import Axios from './core/Axios.js';
import mergeConfig from './core/mergeConfig.js';
import defaults from './defaults/index.js';
import formDataToJSON from './helpers/formDataToJSON.js';
import CanceledError from './cancel/CanceledError.js';
import CancelToken from'./cancel/CancelToken.js';
import isCancel from'./cancel/isCancel.js';
import {VERSION} from './env/data.js';
import toFormData from './helpers/toFormData.js';
import AxiosError from '../lib/core/AxiosError.js';
import spread from './helpers/spread.js';
import isAxiosError from './helpers/isAxiosError.js';
/**
* Create an instance of Axios
*
@@ -14,14 +23,14 @@ var formDataToJSON = require('./helpers/formDataToJSON');
* @returns {Axios} A new instance of Axios
*/
function createInstance(defaultConfig) {
var context = new Axios(defaultConfig);
var instance = bind(Axios.prototype.request, context);
const context = new Axios(defaultConfig);
const instance = bind(Axios.prototype.request, context);
// Copy axios.prototype to instance
utils.extend(instance, Axios.prototype, context);
utils.extend(instance, Axios.prototype, context, {allOwnKeys: true});
// Copy context to instance
utils.extend(instance, context);
utils.extend(instance, context, {allOwnKeys: true});
// Factory for creating new instances
instance.create = function create(instanceConfig) {
@@ -32,20 +41,20 @@ function createInstance(defaultConfig) {
}
// Create the default instance to be exported
var axios = createInstance(defaults);
const axios = createInstance(defaults);
// Expose Axios class to allow class inheritance
axios.Axios = Axios;
// Expose Cancel & CancelToken
axios.CanceledError = require('./cancel/CanceledError');
axios.CancelToken = require('./cancel/CancelToken');
axios.isCancel = require('./cancel/isCancel');
axios.VERSION = require('./env/data').version;
axios.toFormData = require('./helpers/toFormData');
axios.CanceledError = CanceledError;
axios.CancelToken = CancelToken;
axios.isCancel = isCancel;
axios.VERSION = VERSION;
axios.toFormData = toFormData;
// Expose AxiosError class
axios.AxiosError = require('../lib/core/AxiosError');
axios.AxiosError = AxiosError;
// alias for CanceledError for backward compatibility
axios.Cancel = axios.CanceledError;
@@ -54,16 +63,14 @@ axios.Cancel = axios.CanceledError;
axios.all = function all(promises) {
return Promise.all(promises);
};
axios.spread = require('./helpers/spread');
axios.spread = spread;
// Expose isAxiosError
axios.isAxiosError = require('./helpers/isAxiosError');
axios.isAxiosError = isAxiosError;
axios.formToJSON = function(thing) {
axios.formToJSON = thing => {
return formDataToJSON(utils.isHTMLForm(thing) ? new FormData(thing) : thing);
};
module.exports = axios;
// Allow use of default import syntax in TypeScript
module.exports.default = axios;
export default axios;
+99 -97
View File
@@ -1,6 +1,6 @@
'use strict';
var CanceledError = require('./CanceledError');
import CanceledError from './CanceledError.js';
/**
* A `CancelToken` is an object that can be used to request cancellation of an operation.
@@ -9,111 +9,113 @@ var CanceledError = require('./CanceledError');
*
* @returns {CancelToken}
*/
function CancelToken(executor) {
if (typeof executor !== 'function') {
throw new TypeError('executor must be a function.');
}
var resolvePromise;
this.promise = new Promise(function promiseExecutor(resolve) {
resolvePromise = resolve;
});
var token = this;
// eslint-disable-next-line func-names
this.promise.then(function(cancel) {
if (!token._listeners) return;
var i = token._listeners.length;
while (i-- > 0) {
token._listeners[i](cancel);
class CancelToken {
constructor(executor) {
if (typeof executor !== 'function') {
throw new TypeError('executor must be a function.');
}
token._listeners = null;
});
// eslint-disable-next-line func-names
this.promise.then = function(onfulfilled) {
var _resolve;
let resolvePromise;
this.promise = new Promise(function promiseExecutor(resolve) {
resolvePromise = resolve;
});
const token = this;
// eslint-disable-next-line func-names
var promise = new Promise(function(resolve) {
token.subscribe(resolve);
_resolve = resolve;
}).then(onfulfilled);
this.promise.then(cancel => {
if (!token._listeners) return;
promise.cancel = function reject() {
token.unsubscribe(_resolve);
let i = token._listeners.length;
while (i-- > 0) {
token._listeners[i](cancel);
}
token._listeners = null;
});
// eslint-disable-next-line func-names
this.promise.then = onfulfilled => {
let _resolve;
// eslint-disable-next-line func-names
const promise = new Promise(resolve => {
token.subscribe(resolve);
_resolve = resolve;
}).then(onfulfilled);
promise.cancel = function reject() {
token.unsubscribe(_resolve);
};
return promise;
};
return promise;
};
executor(function cancel(message, config, request) {
if (token.reason) {
// Cancellation has already been requested
return;
}
executor(function cancel(message, config, request) {
if (token.reason) {
// Cancellation has already been requested
token.reason = new CanceledError(message, config, request);
resolvePromise(token.reason);
});
}
/**
* Throws a `CanceledError` if cancellation has been requested.
*/
throwIfRequested() {
if (this.reason) {
throw this.reason;
}
}
/**
* Subscribe to the cancel signal
*/
subscribe(listener) {
if (this.reason) {
listener(this.reason);
return;
}
token.reason = new CanceledError(message, config, request);
resolvePromise(token.reason);
});
if (this._listeners) {
this._listeners.push(listener);
} else {
this._listeners = [listener];
}
}
/**
* Unsubscribe from the cancel signal
*/
unsubscribe(listener) {
if (!this._listeners) {
return;
}
const index = this._listeners.indexOf(listener);
if (index !== -1) {
this._listeners.splice(index, 1);
}
}
/**
* Returns an object that contains a new `CancelToken` and a function that, when called,
* cancels the `CancelToken`.
*/
static source() {
let cancel;
const token = new CancelToken(function executor(c) {
cancel = c;
});
return {
token,
cancel
};
}
}
/**
* Throws a `CanceledError` if cancellation has been requested.
*/
CancelToken.prototype.throwIfRequested = function throwIfRequested() {
if (this.reason) {
throw this.reason;
}
};
/**
* Subscribe to the cancel signal
*/
CancelToken.prototype.subscribe = function subscribe(listener) {
if (this.reason) {
listener(this.reason);
return;
}
if (this._listeners) {
this._listeners.push(listener);
} else {
this._listeners = [listener];
}
};
/**
* Unsubscribe from the cancel signal
*/
CancelToken.prototype.unsubscribe = function unsubscribe(listener) {
if (!this._listeners) {
return;
}
var index = this._listeners.indexOf(listener);
if (index !== -1) {
this._listeners.splice(index, 1);
}
};
/**
* Returns an object that contains a new `CancelToken` and a function that, when called,
* cancels the `CancelToken`.
*/
CancelToken.source = function source() {
var cancel;
var token = new CancelToken(function executor(c) {
cancel = c;
});
return {
token: token,
cancel: cancel
};
};
module.exports = CancelToken;
export default CancelToken;
+3 -3
View File
@@ -1,7 +1,7 @@
'use strict';
var AxiosError = require('../core/AxiosError');
var utils = require('../utils');
import AxiosError from '../core/AxiosError.js';
import utils from '../utils.js';
/**
* A `CanceledError` is an object that is thrown when an operation is canceled.
@@ -22,4 +22,4 @@ utils.inherits(CanceledError, AxiosError, {
__CANCEL__: true
});
module.exports = CanceledError;
export default CanceledError;
+2 -2
View File
@@ -1,5 +1,5 @@
'use strict';
module.exports = function isCancel(value) {
export default function isCancel(value) {
return !!(value && value.__CANCEL__);
};
}
+133 -110
View File
@@ -1,14 +1,16 @@
'use strict';
var utils = require('./../utils');
var buildURL = require('../helpers/buildURL');
var InterceptorManager = require('./InterceptorManager');
var dispatchRequest = require('./dispatchRequest');
var mergeConfig = require('./mergeConfig');
var buildFullPath = require('./buildFullPath');
var validator = require('../helpers/validator');
import utils from './../utils.js';
import buildURL from '../helpers/buildURL.js';
import InterceptorManager from './InterceptorManager.js';
import dispatchRequest from './dispatchRequest.js';
import mergeConfig from './mergeConfig.js';
import buildFullPath from './buildFullPath.js';
import validator from '../helpers/validator.js';
import AxiosHeaders from './AxiosHeaders.js';
const validators = validator.validators;
var validators = validator.validators;
/**
* Create a new instance of Axios
*
@@ -16,126 +18,147 @@ var validators = validator.validators;
*
* @return {Axios} A new instance of Axios
*/
function Axios(instanceConfig) {
this.defaults = instanceConfig;
this.interceptors = {
request: new InterceptorManager(),
response: new InterceptorManager()
};
}
/**
* Dispatch a request
*
* @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults)
* @param {?Object} config
*
* @returns {Promise} The Promise to be fulfilled
*/
Axios.prototype.request = function request(configOrUrl, config) {
/*eslint no-param-reassign:0*/
// Allow for axios('example/url'[, config]) a la fetch API
if (typeof configOrUrl === 'string') {
config = config || {};
config.url = configOrUrl;
} else {
config = configOrUrl || {};
class Axios {
constructor(instanceConfig) {
this.defaults = instanceConfig;
this.interceptors = {
request: new InterceptorManager(),
response: new InterceptorManager()
};
}
config = mergeConfig(this.defaults, config);
// Set config.method
if (config.method) {
config.method = config.method.toLowerCase();
} else if (this.defaults.method) {
config.method = this.defaults.method.toLowerCase();
} else {
config.method = 'get';
}
var transitional = config.transitional;
if (transitional !== undefined) {
validator.assertOptions(transitional, {
silentJSONParsing: validators.transitional(validators.boolean),
forcedJSONParsing: validators.transitional(validators.boolean),
clarifyTimeoutError: validators.transitional(validators.boolean)
}, false);
}
// filter out skipped interceptors
var requestInterceptorChain = [];
var synchronousRequestInterceptors = true;
this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {
return;
/**
* Dispatch a request
*
* @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults)
* @param {?Object} config
*
* @returns {Promise} The Promise to be fulfilled
*/
request(configOrUrl, config) {
/*eslint no-param-reassign:0*/
// Allow for axios('example/url'[, config]) a la fetch API
if (typeof configOrUrl === 'string') {
config = config || {};
config.url = configOrUrl;
} else {
config = configOrUrl || {};
}
synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
config = mergeConfig(this.defaults, config);
requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
});
const transitional = config.transitional;
var responseInterceptorChain = [];
this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
});
if (transitional !== undefined) {
validator.assertOptions(transitional, {
silentJSONParsing: validators.transitional(validators.boolean),
forcedJSONParsing: validators.transitional(validators.boolean),
clarifyTimeoutError: validators.transitional(validators.boolean)
}, false);
}
var promise;
// Set config.method
config.method = (config.method || this.defaults.method || 'get').toLowerCase();
if (!synchronousRequestInterceptors) {
var chain = [dispatchRequest, undefined];
// Flatten headers
const defaultHeaders = config.headers && utils.merge(
config.headers.common,
config.headers[config.method]
);
Array.prototype.unshift.apply(chain, requestInterceptorChain);
chain = chain.concat(responseInterceptorChain);
defaultHeaders && utils.forEach(
['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
function cleanHeaderConfig(method) {
delete config.headers[method];
}
);
promise = Promise.resolve(config);
while (chain.length) {
promise = promise.then(chain.shift(), chain.shift());
config.headers = new AxiosHeaders(config.headers, defaultHeaders);
// filter out skipped interceptors
const requestInterceptorChain = [];
let synchronousRequestInterceptors = true;
this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {
return;
}
synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
});
const responseInterceptorChain = [];
this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
});
let promise;
let i = 0;
let len;
if (!synchronousRequestInterceptors) {
const chain = [dispatchRequest.bind(this), undefined];
chain.unshift.apply(chain, requestInterceptorChain);
chain.push.apply(chain, responseInterceptorChain);
len = chain.length;
promise = Promise.resolve(config);
while (i < len) {
promise = promise.then(chain[i++], chain[i++]);
}
return promise;
}
len = requestInterceptorChain.length;
let newConfig = config;
i = 0;
while (i < len) {
const onFulfilled = requestInterceptorChain[i++];
const onRejected = requestInterceptorChain[i++];
try {
newConfig = onFulfilled(newConfig);
} catch (error) {
onRejected.call(this, error);
break;
}
}
try {
promise = dispatchRequest.call(this, newConfig);
} catch (error) {
return Promise.reject(error);
}
i = 0;
len = responseInterceptorChain.length;
while (i < len) {
promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);
}
return promise;
}
var newConfig = config;
while (requestInterceptorChain.length) {
var onFulfilled = requestInterceptorChain.shift();
var onRejected = requestInterceptorChain.shift();
try {
newConfig = onFulfilled(newConfig);
} catch (error) {
onRejected(error);
break;
}
getUri(config) {
config = mergeConfig(this.defaults, config);
const fullPath = buildFullPath(config.baseURL, config.url);
return buildURL(fullPath, config.params, config.paramsSerializer);
}
try {
promise = dispatchRequest(newConfig);
} catch (error) {
return Promise.reject(error);
}
while (responseInterceptorChain.length) {
promise = promise.then(responseInterceptorChain.shift(), responseInterceptorChain.shift());
}
return promise;
};
Axios.prototype.getUri = function getUri(config) {
config = mergeConfig(this.defaults, config);
var fullPath = buildFullPath(config.baseURL, config.url);
return buildURL(fullPath, config.params, config.paramsSerializer);
};
}
// Provide aliases for supported request methods
utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
/*eslint func-names:0*/
Axios.prototype[method] = function(url, config) {
return this.request(mergeConfig(config || {}, {
method: method,
url: url,
method,
url,
data: (config || {}).data
}));
};
@@ -147,12 +170,12 @@ utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
function generateHTTPMethod(isForm) {
return function httpMethod(url, data, config) {
return this.request(mergeConfig(config || {}, {
method: method,
method,
headers: isForm ? {
'Content-Type': 'multipart/form-data'
} : {},
url: url,
data: data
url,
data
}));
};
}
@@ -162,4 +185,4 @@ utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
Axios.prototype[method + 'Form'] = generateHTTPMethod(true);
});
module.exports = Axios;
export default Axios;
+9 -7
View File
@@ -1,6 +1,6 @@
'use strict';
var utils = require('../utils');
import utils from '../utils.js';
/**
* Create an Error with the specified message, config, error code, request and response.
@@ -52,8 +52,8 @@ utils.inherits(AxiosError, Error, {
}
});
var prototype = AxiosError.prototype;
var descriptors = {};
const prototype = AxiosError.prototype;
const descriptors = {};
[
'ERR_BAD_OPTION_VALUE',
@@ -69,7 +69,7 @@ var descriptors = {};
'ERR_NOT_SUPPORT',
'ERR_INVALID_URL'
// eslint-disable-next-line func-names
].forEach(function(code) {
].forEach(code => {
descriptors[code] = {value: code};
});
@@ -77,11 +77,13 @@ Object.defineProperties(AxiosError, descriptors);
Object.defineProperty(prototype, 'isAxiosError', {value: true});
// eslint-disable-next-line func-names
AxiosError.from = function(error, code, config, request, response, customProps) {
var axiosError = Object.create(prototype);
AxiosError.from = (error, code, config, request, response, customProps) => {
const axiosError = Object.create(prototype);
utils.toFlatObject(error, axiosError, function filter(obj) {
return obj !== Error.prototype;
}, prop => {
return prop !== 'isAxiosError';
});
AxiosError.call(axiosError, error.message, code, config, request, response);
@@ -95,4 +97,4 @@ AxiosError.from = function(error, code, config, request, response, customProps)
return axiosError;
};
module.exports = AxiosError;
export default AxiosError;
+274
View File
@@ -0,0 +1,274 @@
'use strict';
import utils from '../utils.js';
import parseHeaders from '../helpers/parseHeaders.js';
const $internals = Symbol('internals');
const $defaults = Symbol('defaults');
function normalizeHeader(header) {
return header && String(header).trim().toLowerCase();
}
function normalizeValue(value) {
if (value === false || value == null) {
return value;
}
return String(value);
}
function parseTokens(str) {
const tokens = Object.create(null);
const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;
let match;
while ((match = tokensRE.exec(str))) {
tokens[match[1]] = match[2];
}
return tokens;
}
function matchHeaderValue(context, value, header, filter) {
if (utils.isFunction(filter)) {
return filter.call(this, value, header);
}
if (!utils.isString(value)) return;
if (utils.isString(filter)) {
return value.indexOf(filter) !== -1;
}
if (utils.isRegExp(filter)) {
return filter.test(value);
}
}
function formatHeader(header) {
return header.trim()
.toLowerCase().replace(/([a-z\d])(\w*)/g, (w, char, str) => {
return char.toUpperCase() + str;
});
}
function buildAccessors(obj, header) {
const accessorName = utils.toCamelCase(' ' + header);
['get', 'set', 'has'].forEach(methodName => {
Object.defineProperty(obj, methodName + accessorName, {
value: function(arg1, arg2, arg3) {
return this[methodName].call(this, header, arg1, arg2, arg3);
},
configurable: true
});
});
}
function findKey(obj, key) {
key = key.toLowerCase();
const keys = Object.keys(obj);
let i = keys.length;
let _key;
while (i-- > 0) {
_key = keys[i];
if (key === _key.toLowerCase()) {
return _key;
}
}
return null;
}
function AxiosHeaders(headers, defaults) {
headers && this.set(headers);
this[$defaults] = defaults || null;
}
Object.assign(AxiosHeaders.prototype, {
set: function(header, valueOrRewrite, rewrite) {
const self = this;
function setHeader(_value, _header, _rewrite) {
const lHeader = normalizeHeader(_header);
if (!lHeader) {
throw new Error('header name must be a non-empty string');
}
const key = findKey(self, lHeader);
if (key && _rewrite !== true && (self[key] === false || _rewrite === false)) {
return;
}
if (utils.isArray(_value)) {
_value = _value.map(normalizeValue);
} else {
_value = normalizeValue(_value);
}
self[key || _header] = _value;
}
if (utils.isPlainObject(header)) {
utils.forEach(header, (_value, _header) => {
setHeader(_value, _header, valueOrRewrite);
});
} else {
setHeader(valueOrRewrite, header, rewrite);
}
return this;
},
get: function(header, parser) {
header = normalizeHeader(header);
if (!header) return undefined;
const key = findKey(this, header);
if (key) {
const value = this[key];
if (!parser) {
return value;
}
if (parser === true) {
return parseTokens(value);
}
if (utils.isFunction(parser)) {
return parser.call(this, value, key);
}
if (utils.isRegExp(parser)) {
return parser.exec(value);
}
throw new TypeError('parser must be boolean|regexp|function');
}
},
has: function(header, matcher) {
header = normalizeHeader(header);
if (header) {
const key = findKey(this, header);
return !!(key && (!matcher || matchHeaderValue(this, this[key], key, matcher)));
}
return false;
},
delete: function(header, matcher) {
const self = this;
let deleted = false;
function deleteHeader(_header) {
_header = normalizeHeader(_header);
if (_header) {
const key = findKey(self, _header);
if (key && (!matcher || matchHeaderValue(self, self[key], key, matcher))) {
delete self[key];
deleted = true;
}
}
}
if (utils.isArray(header)) {
header.forEach(deleteHeader);
} else {
deleteHeader(header);
}
return deleted;
},
clear: function() {
return Object.keys(this).forEach(this.delete.bind(this));
},
normalize: function(format) {
const self = this;
const headers = {};
utils.forEach(this, (value, header) => {
const key = findKey(headers, header);
if (key) {
self[key] = normalizeValue(value);
delete self[header];
return;
}
const normalized = format ? formatHeader(header) : String(header).trim();
if (normalized !== header) {
delete self[header];
}
self[normalized] = normalizeValue(value);
headers[normalized] = true;
});
return this;
},
toJSON: function() {
const obj = Object.create(null);
utils.forEach(Object.assign({}, this[$defaults] || null, this),
(value, header) => {
if (value == null || value === false) return;
obj[header] = utils.isArray(value) ? value.join(', ') : value;
});
return obj;
}
});
Object.assign(AxiosHeaders, {
from: function(thing) {
if (utils.isString(thing)) {
return new this(parseHeaders(thing));
}
return thing instanceof this ? thing : new this(thing);
},
accessor: function(header) {
const internals = this[$internals] = (this[$internals] = {
accessors: {}
});
const accessors = internals.accessors;
const prototype = this.prototype;
function defineAccessor(_header) {
const lHeader = normalizeHeader(_header);
if (!accessors[lHeader]) {
buildAccessors(prototype, _header);
accessors[lHeader] = true;
}
}
utils.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header);
return this;
}
});
AxiosHeaders.accessor(['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent']);
utils.freezeMethods(AxiosHeaders.prototype);
utils.freezeMethods(AxiosHeaders);
export default AxiosHeaders;
+63 -61
View File
@@ -1,69 +1,71 @@
'use strict';
var utils = require('./../utils');
import utils from './../utils.js';
function InterceptorManager() {
this.handlers = [];
}
/**
* Add a new interceptor to the stack
*
* @param {Function} fulfilled The function to handle `then` for a `Promise`
* @param {Function} rejected The function to handle `reject` for a `Promise`
*
* @return {Number} An ID used to remove interceptor later
*/
InterceptorManager.prototype.use = function use(fulfilled, rejected, options) {
this.handlers.push({
fulfilled: fulfilled,
rejected: rejected,
synchronous: options ? options.synchronous : false,
runWhen: options ? options.runWhen : null
});
return this.handlers.length - 1;
};
/**
* Remove an interceptor from the stack
*
* @param {Number} id The ID that was returned by `use`
*
* @returns {Boolean} `true` if the interceptor was removed, `false` otherwise
*/
InterceptorManager.prototype.eject = function eject(id) {
if (this.handlers[id]) {
this.handlers[id] = null;
}
};
/**
* Clear all interceptors from the stack
*
* @returns {void}
*/
InterceptorManager.prototype.clear = function clear() {
if (this.handlers) {
class InterceptorManager {
constructor() {
this.handlers = [];
}
};
/**
* Iterate over all the registered interceptors
*
* This method is particularly useful for skipping over any
* interceptors that may have become `null` calling `eject`.
*
* @param {Function} fn The function to call for each interceptor
*
* @returns {void}
*/
InterceptorManager.prototype.forEach = function forEach(fn) {
utils.forEach(this.handlers, function forEachHandler(h) {
if (h !== null) {
fn(h);
/**
* Add a new interceptor to the stack
*
* @param {Function} fulfilled The function to handle `then` for a `Promise`
* @param {Function} rejected The function to handle `reject` for a `Promise`
*
* @return {Number} An ID used to remove interceptor later
*/
use(fulfilled, rejected, options) {
this.handlers.push({
fulfilled,
rejected,
synchronous: options ? options.synchronous : false,
runWhen: options ? options.runWhen : null
});
return this.handlers.length - 1;
}
/**
* Remove an interceptor from the stack
*
* @param {Number} id The ID that was returned by `use`
*
* @returns {Boolean} `true` if the interceptor was removed, `false` otherwise
*/
eject(id) {
if (this.handlers[id]) {
this.handlers[id] = null;
}
});
};
}
module.exports = InterceptorManager;
/**
* Clear all interceptors from the stack
*
* @returns {void}
*/
clear() {
if (this.handlers) {
this.handlers = [];
}
}
/**
* Iterate over all the registered interceptors
*
* This method is particularly useful for skipping over any
* interceptors that may have become `null` calling `eject`.
*
* @param {Function} fn The function to call for each interceptor
*
* @returns {void}
*/
forEach(fn) {
utils.forEach(this.handlers, function forEachHandler(h) {
if (h !== null) {
fn(h);
}
});
}
}
export default InterceptorManager;
+4 -4
View File
@@ -1,7 +1,7 @@
'use strict';
var isAbsoluteURL = require('../helpers/isAbsoluteURL');
var combineURLs = require('../helpers/combineURLs');
import isAbsoluteURL from '../helpers/isAbsoluteURL.js';
import combineURLs from '../helpers/combineURLs.js';
/**
* Creates a new URL by combining the baseURL with the requestedURL,
@@ -13,9 +13,9 @@ var combineURLs = require('../helpers/combineURLs');
*
* @returns {string} The combined full path
*/
module.exports = function buildFullPath(baseURL, requestedURL) {
export default function buildFullPath(baseURL, requestedURL) {
if (baseURL && !isAbsoluteURL(requestedURL)) {
return combineURLs(baseURL, requestedURL);
}
return requestedURL;
};
}
+16 -39
View File
@@ -1,11 +1,10 @@
'use strict';
var utils = require('./../utils');
var transformData = require('./transformData');
var isCancel = require('../cancel/isCancel');
var defaults = require('../defaults');
var CanceledError = require('../cancel/CanceledError');
var normalizeHeaderName = require('../helpers/normalizeHeaderName');
import transformData from './transformData.js';
import isCancel from '../cancel/isCancel.js';
import defaults from '../defaults/index.js';
import CanceledError from '../cancel/CanceledError.js';
import AxiosHeaders from '../core/AxiosHeaders.js';
/**
* Throws a `CanceledError` if cancellation has been requested.
@@ -31,39 +30,18 @@ function throwIfCancellationRequested(config) {
*
* @returns {Promise} The Promise to be fulfilled
*/
module.exports = function dispatchRequest(config) {
export default function dispatchRequest(config) {
throwIfCancellationRequested(config);
// Ensure headers exist
config.headers = config.headers || {};
config.headers = AxiosHeaders.from(config.headers);
// Transform request data
config.data = transformData.call(
config,
config.data,
config.headers,
null,
config.transformRequest
);
normalizeHeaderName(config.headers, 'Accept');
normalizeHeaderName(config.headers, 'Content-Type');
// Flatten headers
config.headers = utils.merge(
config.headers.common || {},
config.headers[config.method] || {},
config.headers
);
utils.forEach(
['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
function cleanHeaderConfig(method) {
delete config.headers[method];
}
);
var adapter = config.adapter || defaults.adapter;
const adapter = config.adapter || defaults.adapter;
return adapter(config).then(function onAdapterResolution(response) {
throwIfCancellationRequested(config);
@@ -71,12 +49,12 @@ module.exports = function dispatchRequest(config) {
// Transform response data
response.data = transformData.call(
config,
response.data,
response.headers,
response.status,
config.transformResponse
config.transformResponse,
response
);
response.headers = AxiosHeaders.from(response.headers);
return response;
}, function onAdapterRejection(reason) {
if (!isCancel(reason)) {
@@ -86,14 +64,13 @@ module.exports = function dispatchRequest(config) {
if (reason && reason.response) {
reason.response.data = transformData.call(
config,
reason.response.data,
reason.response.headers,
reason.response.status,
config.transformResponse
config.transformResponse,
reason.response
);
reason.response.headers = AxiosHeaders.from(reason.response.headers);
}
}
return Promise.reject(reason);
});
};
}
+7 -7
View File
@@ -1,6 +1,6 @@
'use strict';
var utils = require('../utils');
import utils from '../utils.js';
/**
* Config-specific merge-function which creates a new config-object
@@ -11,10 +11,10 @@ var utils = require('../utils');
*
* @returns {Object} New object resulting from merging config2 to config1
*/
module.exports = function mergeConfig(config1, config2) {
export default function mergeConfig(config1, config2) {
// eslint-disable-next-line no-param-reassign
config2 = config2 || {};
var config = {};
const config = {};
function getMergedValue(target, source) {
if (utils.isPlainObject(target) && utils.isPlainObject(source)) {
@@ -61,7 +61,7 @@ module.exports = function mergeConfig(config1, config2) {
}
}
var mergeMap = {
const mergeMap = {
'url': valueFromConfig2,
'method': valueFromConfig2,
'data': valueFromConfig2,
@@ -92,10 +92,10 @@ module.exports = function mergeConfig(config1, config2) {
};
utils.forEach(Object.keys(config1).concat(Object.keys(config2)), function computeConfigValue(prop) {
var merge = mergeMap[prop] || mergeDeepProperties;
var configValue = merge(prop);
const merge = mergeMap[prop] || mergeDeepProperties;
const configValue = merge(prop);
(utils.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue);
});
return config;
};
}
+4 -4
View File
@@ -1,6 +1,6 @@
'use strict';
var AxiosError = require('./AxiosError');
import AxiosError from './AxiosError.js';
/**
* Resolve or reject a Promise based on response status.
@@ -11,8 +11,8 @@ var AxiosError = require('./AxiosError');
*
* @returns {object} The response.
*/
module.exports = function settle(resolve, reject, response) {
var validateStatus = response.config.validateStatus;
export default function settle(resolve, reject, response) {
const validateStatus = response.config.validateStatus;
if (!response.status || !validateStatus || validateStatus(response.status)) {
resolve(response);
} else {
@@ -24,4 +24,4 @@ module.exports = function settle(resolve, reject, response) {
response
));
}
};
}
+14 -10
View File
@@ -1,24 +1,28 @@
'use strict';
var utils = require('./../utils');
var defaults = require('../defaults');
import utils from './../utils.js';
import defaults from '../defaults/index.js';
import AxiosHeaders from '../core/AxiosHeaders.js';
/**
* Transform the data for a request or a response
*
* @param {Object|String} data The data to be transformed
* @param {Array} headers The headers for the request or response
* @param {Number} status HTTP status code
* @param {Array|Function} fns A single function or Array of functions
* @param {?Object} response The response object
*
* @returns {*} The resulting transformed data
*/
module.exports = function transformData(data, headers, status, fns) {
var context = this || defaults;
/*eslint no-param-reassign:0*/
export default function transformData(fns, response) {
const config = this || defaults;
const context = response || config;
const headers = AxiosHeaders.from(context.headers);
let data = context.data;
utils.forEach(fns, function transform(fn) {
data = fn.call(context, data, headers, status);
data = fn.call(config, data, headers.normalize(), response ? response.status : undefined);
});
headers.normalize();
return data;
};
}
+29 -48
View File
@@ -1,34 +1,18 @@
'use strict';
var utils = require('../utils');
var normalizeHeaderName = require('../helpers/normalizeHeaderName');
var AxiosError = require('../core/AxiosError');
var transitionalDefaults = require('./transitional');
var toFormData = require('../helpers/toFormData');
var toURLEncodedForm = require('../helpers/toURLEncodedForm');
var platform = require('../platform');
var formDataToJSON = require('../helpers/formDataToJSON');
import utils from '../utils.js';
import AxiosError from '../core/AxiosError.js';
import transitionalDefaults from './transitional.js';
import toFormData from '../helpers/toFormData.js';
import toURLEncodedForm from '../helpers/toURLEncodedForm.js';
import platform from '../platform/index.js';
import formDataToJSON from '../helpers/formDataToJSON.js';
import adapters from '../adapters/index.js';
var DEFAULT_CONTENT_TYPE = {
const DEFAULT_CONTENT_TYPE = {
'Content-Type': 'application/x-www-form-urlencoded'
};
/**
* If the headers object is not undefined and the Content-Type property of the headers object
* is undefined, then set the Content-Type property of the headers object to the value passed
* in
*
* @param {Object<string, string>} headers - The headers object that will be sent to the server.
* @param {any} value - The value of the Content-Type header.
*
* @returns {void}
*/
function setContentTypeIfUnset(headers, value) {
if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) {
headers['Content-Type'] = value;
}
}
/**
* If the browser has an XMLHttpRequest object, use the XHR adapter, otherwise use the HTTP
* adapter
@@ -36,13 +20,13 @@ function setContentTypeIfUnset(headers, value) {
* @returns {Function}
*/
function getDefaultAdapter() {
var adapter;
let adapter;
if (typeof XMLHttpRequest !== 'undefined') {
// For browsers use XHR adapter
adapter = require('../adapters/xhr');
} else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') {
adapter = adapters.getAdapter('xhr');
} else if (typeof process !== 'undefined' && utils.kindOf(process) === 'process') {
// For node use HTTP adapter
adapter = require('../adapters/http');
adapter = adapters.getAdapter('http');
}
return adapter;
}
@@ -72,25 +56,22 @@ function stringifySafely(rawValue, parser, encoder) {
return (encoder || JSON.stringify)(rawValue);
}
var defaults = {
const defaults = {
transitional: transitionalDefaults,
adapter: getDefaultAdapter(),
transformRequest: [function transformRequest(data, headers) {
normalizeHeaderName(headers, 'Accept');
normalizeHeaderName(headers, 'Content-Type');
var contentType = headers && headers['Content-Type'] || '';
var hasJSONContentType = contentType.indexOf('application/json') > -1;
var isObjectPayload = utils.isObject(data);
const contentType = headers.getContentType() || '';
const hasJSONContentType = contentType.indexOf('application/json') > -1;
const isObjectPayload = utils.isObject(data);
if (isObjectPayload && utils.isHTMLForm(data)) {
data = new FormData(data);
}
var isFormData = utils.isFormData(data);
const isFormData = utils.isFormData(data);
if (isFormData) {
if (!hasJSONContentType) {
@@ -111,19 +92,19 @@ var defaults = {
return data.buffer;
}
if (utils.isURLSearchParams(data)) {
setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8');
headers.setContentType('application/x-www-form-urlencoded;charset=utf-8', false);
return data.toString();
}
var isFileList;
let isFileList;
if (isObjectPayload) {
if (contentType.indexOf('application/x-www-form-urlencoded') !== -1) {
if (contentType.indexOf('application/x-www-form-urlencoded') > -1) {
return toURLEncodedForm(data, this.formSerializer).toString();
}
if ((isFileList = utils.isFileList(data)) || contentType.indexOf('multipart/form-data') > -1) {
var _FormData = this.env && this.env.FormData;
const _FormData = this.env && this.env.FormData;
return toFormData(
isFileList ? {'files[]': data} : data,
@@ -134,7 +115,7 @@ var defaults = {
}
if (isObjectPayload || hasJSONContentType ) {
setContentTypeIfUnset(headers, 'application/json');
headers.setContentType('application/json', false);
return stringifySafely(data);
}
@@ -142,13 +123,13 @@ var defaults = {
}],
transformResponse: [function transformResponse(data) {
var transitional = this.transitional || defaults.transitional;
var forcedJSONParsing = transitional && transitional.forcedJSONParsing;
var JSONRequested = this.responseType === 'json';
const transitional = this.transitional || defaults.transitional;
const forcedJSONParsing = transitional && transitional.forcedJSONParsing;
const JSONRequested = this.responseType === 'json';
if (data && utils.isString(data) && ((forcedJSONParsing && !this.responseType) || JSONRequested)) {
var silentJSONParsing = transitional && transitional.silentJSONParsing;
var strictJSONParsing = !silentJSONParsing && JSONRequested;
const silentJSONParsing = transitional && transitional.silentJSONParsing;
const strictJSONParsing = !silentJSONParsing && JSONRequested;
try {
return JSON.parse(data);
@@ -201,4 +182,4 @@ utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE);
});
module.exports = defaults;
export default defaults;
+1 -1
View File
@@ -1,6 +1,6 @@
'use strict';
module.exports = {
export default {
silentJSONParsing: true,
forcedJSONParsing: true,
clarifyTimeoutError: false
+2 -2
View File
@@ -1,2 +1,2 @@
// eslint-disable-next-line strict
module.exports = require('form-data');
import FormData from 'form-data';
export default FormData;
+1 -3
View File
@@ -1,3 +1 @@
module.exports = {
"version": "1.0.0-alpha.1"
};
export const VERSION = "1.0.0-alpha.1";
+191
View File
@@ -0,0 +1,191 @@
'use strict';
import stream from 'stream';
import utils from '../utils.js';
import throttle from './throttle.js';
import speedometer from './speedometer.js';
const kInternals = Symbol('internals');
class AxiosTransformStream extends stream.Transform{
constructor(options) {
options = utils.toFlatObject(options, {
maxRate: 0,
chunkSize: 64 * 1024,
minChunkSize: 100,
timeWindow: 500,
ticksRate: 2,
samplesCount: 15
}, null, (prop, source) => {
return !utils.isUndefined(source[prop]);
});
super({
readableHighWaterMark: options.chunkSize
});
const self = this;
const internals = this[kInternals] = {
length: options.length,
timeWindow: options.timeWindow,
ticksRate: options.ticksRate,
chunkSize: options.chunkSize,
maxRate: options.maxRate,
minChunkSize: options.minChunkSize,
bytesSeen: 0,
isCaptured: false,
notifiedBytesLoaded: 0,
ts: Date.now(),
bytes: 0,
onReadCallback: null
};
const _speedometer = speedometer(internals.ticksRate * options.samplesCount, internals.timeWindow);
this.on('newListener', event => {
if (event === 'progress') {
if (!internals.isCaptured) {
internals.isCaptured = true;
}
}
});
let bytesNotified = 0;
internals.updateProgress = throttle(function throttledHandler() {
const totalBytes = internals.length;
const bytesTransferred = internals.bytesSeen;
const progressBytes = bytesTransferred - bytesNotified;
if (!progressBytes || self.destroyed) return;
const rate = _speedometer(progressBytes);
bytesNotified = bytesTransferred;
process.nextTick(() => {
self.emit('progress', {
'loaded': bytesTransferred,
'total': totalBytes,
'progress': totalBytes ? (bytesTransferred / totalBytes) : undefined,
'bytes': progressBytes,
'rate': rate ? rate : undefined,
'estimated': rate && totalBytes && bytesTransferred <= totalBytes ?
(totalBytes - bytesTransferred) / rate : undefined
});
});
}, internals.ticksRate);
const onFinish = () => {
internals.updateProgress(true);
};
this.once('end', onFinish);
this.once('error', onFinish);
}
_read(size) {
const internals = this[kInternals];
if (internals.onReadCallback) {
internals.onReadCallback();
}
return super._read(size);
}
_transform(chunk, encoding, callback) {
const self = this;
const internals = this[kInternals];
const maxRate = internals.maxRate;
const readableHighWaterMark = this.readableHighWaterMark;
const timeWindow = internals.timeWindow;
const divider = 1000 / timeWindow;
const bytesThreshold = (maxRate / divider);
const minChunkSize = internals.minChunkSize !== false ? Math.max(internals.minChunkSize, bytesThreshold * 0.01) : 0;
function pushChunk(_chunk, _callback) {
const bytes = Buffer.byteLength(_chunk);
internals.bytesSeen += bytes;
internals.bytes += bytes;
if (internals.isCaptured) {
internals.updateProgress();
}
if (self.push(_chunk)) {
process.nextTick(_callback);
} else {
internals.onReadCallback = () => {
internals.onReadCallback = null;
process.nextTick(_callback);
};
}
}
const transformChunk = (_chunk, _callback) => {
const chunkSize = Buffer.byteLength(_chunk);
let chunkRemainder = null;
let maxChunkSize = readableHighWaterMark;
let bytesLeft;
let passed = 0;
if (maxRate) {
const now = Date.now();
if (!internals.ts || (passed = (now - internals.ts)) >= timeWindow) {
internals.ts = now;
bytesLeft = bytesThreshold - internals.bytes;
internals.bytes = bytesLeft < 0 ? -bytesLeft : 0;
passed = 0;
}
bytesLeft = bytesThreshold - internals.bytes;
}
if (maxRate) {
if (bytesLeft <= 0) {
// next time window
return setTimeout(() => {
_callback(null, _chunk);
}, timeWindow - passed);
}
if (bytesLeft < maxChunkSize) {
maxChunkSize = bytesLeft;
}
}
if (maxChunkSize && chunkSize > maxChunkSize && (chunkSize - maxChunkSize) > minChunkSize) {
chunkRemainder = _chunk.subarray(maxChunkSize);
_chunk = _chunk.subarray(0, maxChunkSize);
}
pushChunk(_chunk, chunkRemainder ? () => {
process.nextTick(_callback, null, chunkRemainder);
} : _callback);
};
transformChunk(chunk, function transformNextChunk(err, _chunk) {
if (err) {
return callback(err);
}
if (_chunk) {
transformChunk(_chunk, transformNextChunk);
} else {
callback(null);
}
});
}
setLength(length) {
this[kInternals].length = +length;
return this;
}
}
export default AxiosTransformStream;
+6 -6
View File
@@ -1,6 +1,6 @@
'use strict';
var toFormData = require('./toFormData');
import toFormData from './toFormData.js';
/**
* It encodes a string by replacing all characters that are not in the unreserved set with
@@ -11,7 +11,7 @@ var toFormData = require('./toFormData');
* @returns {string} The encoded string.
*/
function encode(str) {
var charMap = {
const charMap = {
'!': '%21',
"'": '%27',
'(': '%28',
@@ -20,7 +20,7 @@ function encode(str) {
'%20': '+',
'%00': '\x00'
};
return encodeURIComponent(str).replace(/[!'\(\)~]|%20|%00/g, function replacer(match) {
return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) {
return charMap[match];
});
}
@@ -39,14 +39,14 @@ function AxiosURLSearchParams(params, options) {
params && toFormData(params, this, options);
}
var prototype = AxiosURLSearchParams.prototype;
const prototype = AxiosURLSearchParams.prototype;
prototype.append = function append(name, value) {
this._pairs.push([name, value]);
};
prototype.toString = function toString(encoder) {
var _encode = encoder ? function(value) {
const _encode = encoder ? function(value) {
return encoder.call(this, value, encode);
} : encode;
@@ -55,4 +55,4 @@ prototype.toString = function toString(encoder) {
}, '').join('&');
};
module.exports = AxiosURLSearchParams;
export default AxiosURLSearchParams;
+2 -2
View File
@@ -1,7 +1,7 @@
'use strict';
module.exports = function bind(fn, thisArg) {
export default function bind(fn, thisArg) {
return function wrap() {
return fn.apply(thisArg, arguments);
};
};
}
+7 -7
View File
@@ -1,7 +1,7 @@
'use strict';
var utils = require('../utils');
var AxiosURLSearchParams = require('../helpers/AxiosURLSearchParams');
import utils from '../utils.js';
import AxiosURLSearchParams from '../helpers/AxiosURLSearchParams.js';
/**
* It replaces all instances of the characters `:`, `$`, `,`, `+`, `[`, and `]` with their
@@ -30,21 +30,21 @@ function encode(val) {
*
* @returns {string} The formatted url
*/
module.exports = function buildURL(url, params, options) {
export default function buildURL(url, params, options) {
/*eslint no-param-reassign:0*/
if (!params) {
return url;
}
var hashmarkIndex = url.indexOf('#');
const hashmarkIndex = url.indexOf('#');
if (hashmarkIndex !== -1) {
url = url.slice(0, hashmarkIndex);
}
var _encode = options && options.encode || encode;
const _encode = options && options.encode || encode;
var serializerParams = utils.isURLSearchParams(params) ?
const serializerParams = utils.isURLSearchParams(params) ?
params.toString() :
new AxiosURLSearchParams(params, options).toString(_encode);
@@ -53,4 +53,4 @@ module.exports = function buildURL(url, params, options) {
}
return url;
};
}
+2 -2
View File
@@ -8,8 +8,8 @@
*
* @returns {string} The combined URL
*/
module.exports = function combineURLs(baseURL, relativeURL) {
export default function combineURLs(baseURL, relativeURL) {
return relativeURL
? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '')
: baseURL;
};
}
+44 -46
View File
@@ -1,53 +1,51 @@
'use strict';
var utils = require('./../utils');
import utils from './../utils.js';
module.exports = (
utils.isStandardBrowserEnv() ?
export default utils.isStandardBrowserEnv() ?
// Standard browser envs support document.cookie
(function standardBrowserEnv() {
return {
write: function write(name, value, expires, path, domain, secure) {
var cookie = [];
cookie.push(name + '=' + encodeURIComponent(value));
// Standard browser envs support document.cookie
(function standardBrowserEnv() {
return {
write: function write(name, value, expires, path, domain, secure) {
const cookie = [];
cookie.push(name + '=' + encodeURIComponent(value));
if (utils.isNumber(expires)) {
cookie.push('expires=' + new Date(expires).toGMTString());
}
if (utils.isString(path)) {
cookie.push('path=' + path);
}
if (utils.isString(domain)) {
cookie.push('domain=' + domain);
}
if (secure === true) {
cookie.push('secure');
}
document.cookie = cookie.join('; ');
},
read: function read(name) {
var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
return (match ? decodeURIComponent(match[3]) : null);
},
remove: function remove(name) {
this.write(name, '', Date.now() - 86400000);
if (utils.isNumber(expires)) {
cookie.push('expires=' + new Date(expires).toGMTString());
}
};
})() :
// Non standard browser env (web workers, react-native) lack needed support.
(function nonStandardBrowserEnv() {
return {
write: function write() {},
read: function read() { return null; },
remove: function remove() {}
};
})()
);
if (utils.isString(path)) {
cookie.push('path=' + path);
}
if (utils.isString(domain)) {
cookie.push('domain=' + domain);
}
if (secure === true) {
cookie.push('secure');
}
document.cookie = cookie.join('; ');
},
read: function read(name) {
const match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
return (match ? decodeURIComponent(match[3]) : null);
},
remove: function remove(name) {
this.write(name, '', Date.now() - 86400000);
}
};
})() :
// Non standard browser env (web workers, react-native) lack needed support.
(function nonStandardBrowserEnv() {
return {
write: function write() {},
read: function read() { return null; },
remove: function remove() {}
};
})();
+2 -2
View File
@@ -12,7 +12,7 @@
*
* @returns {void}
*/
module.exports = function deprecatedMethod(method, instead, docs) {
export default function deprecatedMethod(method, instead, docs) {
try {
console.warn(
'DEPRECATED method `' + method + '`.' +
@@ -23,4 +23,4 @@ module.exports = function deprecatedMethod(method, instead, docs) {
console.warn('For more information about usage see ' + docs);
}
} catch (e) { /* Ignore */ }
};
}
+15 -15
View File
@@ -1,6 +1,6 @@
'use strict';
var utils = require('../utils');
import utils from '../utils.js';
/**
* It takes a string like `foo[x][y][z]` and returns an array like `['foo', 'x', 'y', 'z']
@@ -14,7 +14,7 @@ function parsePropPath(name) {
// foo.x.y.z
// foo-x-y-z
// foo x y z
return utils.matchAll(/\w+|\[(\w*)]/g, name).map(function(match) {
return utils.matchAll(/\w+|\[(\w*)]/g, name).map(match => {
return match[0] === '[]' ? '' : match[1] || match[0];
});
}
@@ -27,11 +27,11 @@ function parsePropPath(name) {
* @returns An object with the same keys and values as the array.
*/
function arrayToObject(arr) {
var obj = {};
var keys = Object.keys(arr);
var i;
var len = keys.length;
var key;
const obj = {};
const keys = Object.keys(arr);
let i;
const len = keys.length;
let key;
for (i = 0; i < len; i++) {
key = keys[i];
obj[key] = arr[key];
@@ -48,13 +48,13 @@ function arrayToObject(arr) {
*/
function formDataToJSON(formData) {
function buildPath(path, value, target, index) {
var name = path[index++];
var isNumericKey = Number.isFinite(+name);
var isLast = index >= path.length;
let name = path[index++];
const isNumericKey = Number.isFinite(+name);
const isLast = index >= path.length;
name = !name && utils.isArray(target) ? target.length : name;
if (isLast) {
if (utils.hasOwnProperty(target, name)) {
if (utils.hasOwnProp(target, name)) {
target[name] = [target[name], value];
} else {
target[name] = value;
@@ -67,7 +67,7 @@ function formDataToJSON(formData) {
target[name] = [];
}
var result = buildPath(path, value, target[name], index);
const result = buildPath(path, value, target[name], index);
if (result && utils.isArray(target[name])) {
target[name] = arrayToObject(target[name]);
@@ -77,9 +77,9 @@ function formDataToJSON(formData) {
}
if (utils.isFormData(formData) && utils.isFunction(formData.entries)) {
var obj = {};
const obj = {};
utils.forEachEntry(formData, function(name, value) {
utils.forEachEntry(formData, (name, value) => {
buildPath(parsePropPath(name), value, obj, 0);
});
@@ -89,4 +89,4 @@ function formDataToJSON(formData) {
return null;
}
module.exports = formDataToJSON;
export default formDataToJSON;
+13 -13
View File
@@ -1,10 +1,10 @@
'use strict';
var AxiosError = require('../core/AxiosError');
var parseProtocol = require('./parseProtocol');
var platform = require('../platform');
import AxiosError from '../core/AxiosError.js';
import parseProtocol from './parseProtocol.js';
import platform from '../platform/index.js';
var DATA_URL_PATTERN = /^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;
const DATA_URL_PATTERN = /^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;
/**
* Parse data uri to a Buffer or Blob
@@ -16,9 +16,9 @@ var DATA_URL_PATTERN = /^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;
*
* @returns {Buffer|Blob}
*/
module.exports = function fromDataURI(uri, asBlob, options) {
var _Blob = options && options.Blob || platform.classes.Blob;
var protocol = parseProtocol(uri);
export default function fromDataURI(uri, asBlob, options) {
const _Blob = options && options.Blob || platform.classes.Blob;
const protocol = parseProtocol(uri);
if (asBlob === undefined && _Blob) {
asBlob = true;
@@ -27,16 +27,16 @@ module.exports = function fromDataURI(uri, asBlob, options) {
if (protocol === 'data') {
uri = protocol.length ? uri.slice(protocol.length + 1) : uri;
var match = DATA_URL_PATTERN.exec(uri);
const match = DATA_URL_PATTERN.exec(uri);
if (!match) {
throw new AxiosError('Invalid URL', AxiosError.ERR_INVALID_URL);
}
var mime = match[1];
var isBase64 = match[2];
var body = match[3];
var buffer = Buffer.from(decodeURIComponent(body), isBase64 ? 'base64' : 'utf8');
const mime = match[1];
const isBase64 = match[2];
const body = match[3];
const buffer = Buffer.from(decodeURIComponent(body), isBase64 ? 'base64' : 'utf8');
if (asBlob) {
if (!_Blob) {
@@ -50,4 +50,4 @@ module.exports = function fromDataURI(uri, asBlob, options) {
}
throw new AxiosError('Unsupported protocol ' + protocol, AxiosError.ERR_NOT_SUPPORT);
};
}
+2 -2
View File
@@ -7,9 +7,9 @@
*
* @returns {boolean} True if the specified URL is absolute, otherwise false
*/
module.exports = function isAbsoluteURL(url) {
export default function isAbsoluteURL(url) {
// A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
// RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
// by any combination of letters, digits, plus, period, or hyphen.
return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url);
};
}
+3 -3
View File
@@ -1,6 +1,6 @@
'use strict';
var utils = require('./../utils');
import utils from './../utils.js';
/**
* Determines whether the payload is an error thrown by Axios
@@ -9,6 +9,6 @@ var utils = require('./../utils');
*
* @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
*/
module.exports = function isAxiosError(payload) {
export default function isAxiosError(payload) {
return utils.isObject(payload) && (payload.isAxiosError === true);
};
}
+54 -56
View File
@@ -1,68 +1,66 @@
'use strict';
var utils = require('./../utils');
import utils from './../utils.js';
module.exports = (
utils.isStandardBrowserEnv() ?
export default utils.isStandardBrowserEnv() ?
// Standard browser envs have full support of the APIs needed to test
// whether the request URL is of the same origin as current location.
(function standardBrowserEnv() {
var msie = /(msie|trident)/i.test(navigator.userAgent);
var urlParsingNode = document.createElement('a');
var originURL;
// Standard browser envs have full support of the APIs needed to test
// whether the request URL is of the same origin as current location.
(function standardBrowserEnv() {
const msie = /(msie|trident)/i.test(navigator.userAgent);
const urlParsingNode = document.createElement('a');
let originURL;
/**
* Parse a URL to discover it's components
*
* @param {String} url The URL to be parsed
* @returns {Object}
*/
function resolveURL(url) {
var href = url;
if (msie) {
// IE needs attribute set twice to normalize properties
urlParsingNode.setAttribute('href', href);
href = urlParsingNode.href;
}
/**
* Parse a URL to discover it's components
*
* @param {String} url The URL to be parsed
* @returns {Object}
*/
function resolveURL(url) {
let href = url;
if (msie) {
// IE needs attribute set twice to normalize properties
urlParsingNode.setAttribute('href', href);
// urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
return {
href: urlParsingNode.href,
protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
host: urlParsingNode.host,
search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
hostname: urlParsingNode.hostname,
port: urlParsingNode.port,
pathname: (urlParsingNode.pathname.charAt(0) === '/') ?
urlParsingNode.pathname :
'/' + urlParsingNode.pathname
};
href = urlParsingNode.href;
}
originURL = resolveURL(window.location.href);
urlParsingNode.setAttribute('href', href);
/**
* Determine if a URL shares the same origin as the current location
*
* @param {String} requestURL The URL to test
* @returns {boolean} True if URL shares the same origin, otherwise false
*/
return function isURLSameOrigin(requestURL) {
var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL;
return (parsed.protocol === originURL.protocol &&
parsed.host === originURL.host);
// urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
return {
href: urlParsingNode.href,
protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
host: urlParsingNode.host,
search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
hostname: urlParsingNode.hostname,
port: urlParsingNode.port,
pathname: (urlParsingNode.pathname.charAt(0) === '/') ?
urlParsingNode.pathname :
'/' + urlParsingNode.pathname
};
})() :
}
// Non standard browser envs (web workers, react-native) lack needed support.
(function nonStandardBrowserEnv() {
return function isURLSameOrigin() {
return true;
};
})()
);
originURL = resolveURL(window.location.href);
/**
* Determine if a URL shares the same origin as the current location
*
* @param {String} requestURL The URL to test
* @returns {boolean} True if URL shares the same origin, otherwise false
*/
return function isURLSameOrigin(requestURL) {
const parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL;
return (parsed.protocol === originURL.protocol &&
parsed.host === originURL.host);
};
})() :
// Non standard browser envs (web workers, react-native) lack needed support.
(function nonStandardBrowserEnv() {
return function isURLSameOrigin() {
return true;
};
})();
-12
View File
@@ -1,12 +0,0 @@
'use strict';
var utils = require('../utils');
module.exports = function normalizeHeaderName(headers, normalizedName) {
utils.forEach(headers, function processHeader(value, name) {
if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) {
headers[normalizedName] = value;
delete headers[name];
}
});
};
+1 -1
View File
@@ -1,2 +1,2 @@
// eslint-disable-next-line strict
module.exports = null;
export default null;
+23 -22
View File
@@ -1,15 +1,15 @@
'use strict';
var utils = require('./../utils');
import utils from './../utils.js';
// Headers whose duplicates are ignored by node
// RawAxiosHeaders whose duplicates are ignored by node
// c.f. https://nodejs.org/api/http.html#http_message_headers
var ignoreDuplicateOf = [
const ignoreDuplicateOf = utils.toObjectSet([
'age', 'authorization', 'content-length', 'content-type', 'etag',
'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',
'last-modified', 'location', 'max-forwards', 'proxy-authorization',
'referer', 'retry-after', 'user-agent'
];
]);
/**
* Parse headers into an object
@@ -21,32 +21,33 @@ var ignoreDuplicateOf = [
* Transfer-Encoding: chunked
* ```
*
* @param {String} headers Headers needing to be parsed
* @param {String} rawHeaders Headers needing to be parsed
*
* @returns {Object} Headers parsed into an object
*/
module.exports = function parseHeaders(headers) {
var parsed = {};
var key;
var val;
var i;
export default rawHeaders => {
const parsed = {};
let key;
let val;
let i;
if (!headers) { return parsed; }
utils.forEach(headers.split('\n'), function parser(line) {
rawHeaders && rawHeaders.split('\n').forEach(function parser(line) {
i = line.indexOf(':');
key = utils.trim(line.slice(0, i)).toLowerCase();
val = utils.trim(line.slice(i + 1));
key = line.substring(0, i).trim().toLowerCase();
val = line.substring(i + 1).trim();
if (key) {
if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) {
return;
}
if (key === 'set-cookie') {
parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]);
if (!key || (parsed[key] && ignoreDuplicateOf[key])) {
return;
}
if (key === 'set-cookie') {
if (parsed[key]) {
parsed[key].push(val);
} else {
parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
parsed[key] = [val];
}
} else {
parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
}
});
+3 -3
View File
@@ -1,6 +1,6 @@
'use strict';
module.exports = function parseProtocol(url) {
var match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url);
export default function parseProtocol(url) {
const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url);
return match && match[1] || '';
};
}
+55
View File
@@ -0,0 +1,55 @@
'use strict';
/**
* Calculate data maxRate
* @param {Number} [samplesCount= 10]
* @param {Number} [min= 1000]
* @returns {Function}
*/
function speedometer(samplesCount, min) {
samplesCount = samplesCount || 10;
const bytes = new Array(samplesCount);
const timestamps = new Array(samplesCount);
let head = 0;
let tail = 0;
let firstSampleTS;
min = min !== undefined ? min : 1000;
return function push(chunkLength) {
const now = Date.now();
const startedAt = timestamps[tail];
if (!firstSampleTS) {
firstSampleTS = now;
}
bytes[head] = chunkLength;
timestamps[head] = now;
let i = tail;
let bytesCount = 0;
while (i !== head) {
bytesCount += bytes[i++];
i = i % samplesCount;
}
head = (head + 1) % samplesCount;
if (head === tail) {
tail = (tail + 1) % samplesCount;
}
if (now - firstSampleTS < min) {
return;
}
const passed = startedAt && now - startedAt;
return passed ? Math.round(bytesCount * 1000 / passed) : undefined;
};
}
export default speedometer;
+2 -2
View File
@@ -21,8 +21,8 @@
*
* @returns {Function}
*/
module.exports = function spread(callback) {
export default function spread(callback) {
return function wrap(arr) {
return callback.apply(null, arr);
};
};
}
+33
View File
@@ -0,0 +1,33 @@
'use strict';
/**
* Throttle decorator
* @param {Function} fn
* @param {Number} freq
* @return {Function}
*/
function throttle(fn, freq) {
let timestamp = 0;
const threshold = 1000 / freq;
let timer = null;
return function throttled(force, args) {
const now = Date.now();
if (force || now - timestamp > threshold) {
if (timer) {
clearTimeout(timer);
timer = null;
}
timestamp = now;
return fn.apply(null, args);
}
if (!timer) {
timer = setTimeout(() => {
timer = null;
timestamp = Date.now();
return fn.apply(null, args);
}, threshold - (now - timestamp));
}
};
}
export default throttle;
+18 -18
View File
@@ -1,8 +1,8 @@
'use strict';
var utils = require('../utils');
var AxiosError = require('../core/AxiosError');
var envFormData = require('../env/classes/FormData');
import utils from '../utils.js';
import AxiosError from '../core/AxiosError.js';
import envFormData from '../env/classes/FormData.js';
/**
* Determines if the given thing is a array or js object.
@@ -55,7 +55,7 @@ function isFlatArray(arr) {
return utils.isArray(arr) && !arr.some(isVisitable);
}
var predicates = utils.toFlatObject(utils, {}, null, function filter(prop) {
const predicates = utils.toFlatObject(utils, {}, null, function filter(prop) {
return /^is[A-Z]/.test(prop);
});
@@ -111,13 +111,13 @@ function toFormData(obj, formData, options) {
return !utils.isUndefined(source[option]);
});
var metaTokens = options.metaTokens;
const metaTokens = options.metaTokens;
// eslint-disable-next-line no-use-before-define
var visitor = options.visitor || defaultVisitor;
var dots = options.dots;
var indexes = options.indexes;
var _Blob = options.Blob || typeof Blob !== 'undefined' && Blob;
var useBlob = _Blob && isSpecCompliant(formData);
const visitor = options.visitor || defaultVisitor;
const dots = options.dots;
const indexes = options.indexes;
const _Blob = options.Blob || typeof Blob !== 'undefined' && Blob;
const useBlob = _Blob && isSpecCompliant(formData);
if (!utils.isFunction(visitor)) {
throw new TypeError('visitor must be a function');
@@ -152,7 +152,7 @@ function toFormData(obj, formData, options) {
* @returns {boolean} return true to visit the each prop of the value recursively
*/
function defaultVisitor(value, key, path) {
var arr = value;
let arr = value;
if (value && !path && typeof value === 'object') {
if (utils.endsWith(key, '{}')) {
@@ -187,12 +187,12 @@ function toFormData(obj, formData, options) {
return false;
}
var stack = [];
const stack = [];
var exposedHelpers = Object.assign(predicates, {
defaultVisitor: defaultVisitor,
convertValue: convertValue,
isVisitable: isVisitable
const exposedHelpers = Object.assign(predicates, {
defaultVisitor,
convertValue,
isVisitable
});
function build(value, path) {
@@ -205,7 +205,7 @@ function toFormData(obj, formData, options) {
stack.push(value);
utils.forEach(value, function each(el, key) {
var result = !utils.isUndefined(el) && visitor.call(
const result = !utils.isUndefined(el) && visitor.call(
formData, el, utils.isString(key) ? key.trim() : key, path, exposedHelpers
);
@@ -226,4 +226,4 @@ function toFormData(obj, formData, options) {
return formData;
}
module.exports = toFormData;
export default toFormData;
+5 -5
View File
@@ -1,10 +1,10 @@
'use strict';
var utils = require('../utils');
var toFormData = require('./toFormData');
var platform = require('../platform/');
import utils from '../utils.js';
import toFormData from './toFormData.js';
import platform from '../platform/index.js';
module.exports = function toURLEncodedForm(data, options) {
export default function toURLEncodedForm(data, options) {
return toFormData(data, new platform.classes.URLSearchParams(), Object.assign({
visitor: function(value, key, path, helpers) {
if (platform.isNode && utils.isBuffer(value)) {
@@ -15,4 +15,4 @@ module.exports = function toURLEncodedForm(data, options) {
return helpers.defaultVisitor.apply(this, arguments);
}
}, options));
};
}
+15 -15
View File
@@ -1,18 +1,18 @@
'use strict';
var VERSION = require('../env/data').version;
var AxiosError = require('../core/AxiosError');
import {VERSION} from '../env/data.js';
import AxiosError from '../core/AxiosError.js';
var validators = {};
const validators = {};
// eslint-disable-next-line func-names
['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach(function(type, i) {
['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach((type, i) => {
validators[type] = function validator(thing) {
return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type;
};
});
var deprecatedWarnings = {};
const deprecatedWarnings = {};
/**
* Transitional option validator
@@ -29,7 +29,7 @@ validators.transitional = function transitional(validator, version, message) {
}
// eslint-disable-next-line func-names
return function(value, opt, opts) {
return (value, opt, opts) => {
if (validator === false) {
throw new AxiosError(
formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')),
@@ -66,14 +66,14 @@ function assertOptions(options, schema, allowUnknown) {
if (typeof options !== 'object') {
throw new AxiosError('options must be an object', AxiosError.ERR_BAD_OPTION_VALUE);
}
var keys = Object.keys(options);
var i = keys.length;
const keys = Object.keys(options);
let i = keys.length;
while (i-- > 0) {
var opt = keys[i];
var validator = schema[opt];
const opt = keys[i];
const validator = schema[opt];
if (validator) {
var value = options[opt];
var result = value === undefined || validator(value, opt, options);
const value = options[opt];
const result = value === undefined || validator(value, opt, options);
if (result !== true) {
throw new AxiosError('option ' + opt + ' must be ' + result, AxiosError.ERR_BAD_OPTION_VALUE);
}
@@ -85,7 +85,7 @@ function assertOptions(options, schema, allowUnknown) {
}
}
module.exports = {
assertOptions: assertOptions,
validators: validators
export default {
assertOptions,
validators
};
+1 -1
View File
@@ -1,3 +1,3 @@
'use strict';
module.exports = FormData;
export default FormData;
@@ -1,5 +1,4 @@
'use strict';
var AxiosURLSearchParams = require('../../../helpers/AxiosURLSearchParams');
module.exports = typeof URLSearchParams !== 'undefined' ? URLSearchParams : AxiosURLSearchParams;
import AxiosURLSearchParams from '../../../helpers/AxiosURLSearchParams.js';
export default typeof URLSearchParams !== 'undefined' ? URLSearchParams : AxiosURLSearchParams;
+6 -5
View File
@@ -1,11 +1,12 @@
'use strict';
import URLSearchParams from './classes/URLSearchParams.js'
import FormData from './classes/FormData.js'
module.exports = {
export default {
isBrowser: true,
classes: {
URLSearchParams: require('./classes/URLSearchParams'),
FormData: require('./classes/FormData'),
Blob: Blob
URLSearchParams,
FormData,
Blob
},
protocols: ['http', 'https', 'file', 'blob', 'url']
};
+2 -2
View File
@@ -1,3 +1,3 @@
'use strict';
import platform from './node/index.js';
module.exports = require('./node/');
export {platform as default}
+2 -2
View File
@@ -1,3 +1,3 @@
'use strict';
import FormData from 'form-data';
module.exports = require('form-data');
export default FormData;
+2 -3
View File
@@ -1,5 +1,4 @@
'use strict';
var url = require('url');
module.exports = url.URLSearchParams;
import url from 'url';
export default url.URLSearchParams;
+5 -4
View File
@@ -1,10 +1,11 @@
'use strict';
import URLSearchParams from './classes/URLSearchParams.js'
import FormData from './classes/FormData.js'
module.exports = {
export default {
isNode: true,
classes: {
URLSearchParams: require('./classes/URLSearchParams'),
FormData: require('./classes/FormData'),
URLSearchParams,
FormData,
Blob: typeof Blob !== 'undefined' && Blob || null
},
protocols: [ 'http', 'https', 'file', 'data' ]
+220 -116
View File
@@ -1,16 +1,16 @@
'use strict';
var bind = require('./helpers/bind');
import bind from './helpers/bind.js';
// utils is a library of generic helper functions non-specific to axios
var toString = Object.prototype.toString;
const toString = Object.prototype.toString;
// eslint-disable-next-line func-names
var kindOf = (function(cache) {
const kindOf = (cache => {
// eslint-disable-next-line func-names
return function(thing) {
var str = toString.call(thing);
return thing => {
const str = toString.call(thing);
return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
};
})(Object.create(null));
@@ -22,6 +22,12 @@ function kindOfTest(type) {
};
}
function typeOfTest(type) {
return thing => {
return typeof thing === type;
};
}
/**
* Determine if a value is an Array
*
@@ -36,18 +42,16 @@ function isArray(val) {
/**
* Determine if a value is undefined
*
* @param {Object} val The value to test
* @param {*} val The value to test
*
* @returns {boolean} True if the value is undefined, otherwise false
*/
function isUndefined(val) {
return typeof val === 'undefined';
}
const isUndefined = typeOfTest('undefined');
/**
* Determine if a value is a Buffer
*
* @param {Object} val The value to test
* @param {*} val The value to test
*
* @returns {boolean} True if value is a Buffer, otherwise false
*/
@@ -59,22 +63,22 @@ function isBuffer(val) {
/**
* Determine if a value is an ArrayBuffer
*
* @param {Object} val The value to test
* @param {*} val The value to test
*
* @returns {boolean} True if value is an ArrayBuffer, otherwise false
*/
var isArrayBuffer = kindOfTest('ArrayBuffer');
const isArrayBuffer = kindOfTest('ArrayBuffer');
/**
* Determine if a value is a view on an ArrayBuffer
*
* @param {Object} val The value to test
* @param {*} val The value to test
*
* @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
*/
function isArrayBufferView(val) {
var result;
let result;
if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {
result = ArrayBuffer.isView(val);
} else {
@@ -86,40 +90,54 @@ function isArrayBufferView(val) {
/**
* Determine if a value is a String
*
* @param {Object} val The value to test
* @param {*} val The value to test
*
* @returns {boolean} True if value is a String, otherwise false
*/
function isString(val) {
return typeof val === 'string';
}
const isString = typeOfTest('string');
/**
* Determine if a value is a Function
*
* @param {*} val The value to test
* @returns {boolean} True if value is a Function, otherwise false
*/
const isFunction = typeOfTest('function');
/**
* Determine if a value is a Number
*
* @param {Object} val The value to test
* @param {*} val The value to test
*
* @returns {boolean} True if value is a Number, otherwise false
*/
function isNumber(val) {
return typeof val === 'number';
}
const isNumber = typeOfTest('number');
/**
* Determine if a value is an Object
*
* @param {Object} val The value to test
* @param {*} thing The value to test
*
* @returns {boolean} True if value is an Object, otherwise false
*/
function isObject(val) {
return val !== null && typeof val === 'object';
function isObject(thing) {
return thing !== null && typeof thing === 'object';
}
/**
* Determine if a value is a Boolean
*
* @param {*} thing The value to test
* @returns {boolean} True if value is a Boolean, otherwise false
*/
const isBoolean = thing => {
return thing === true || thing === false;
};
/**
* Determine if a value is a plain Object
*
* @param {Object} val The value to test
* @param {*} val The value to test
*
* @returns {boolean} True if value is a plain Object, otherwise false
*/
@@ -128,61 +146,50 @@ function isPlainObject(val) {
return false;
}
var prototype = Object.getPrototypeOf(val);
const prototype = Object.getPrototypeOf(val);
return prototype === null || prototype === Object.prototype;
}
/**
* Determine if a value is a Date
*
* @param {Object} val The value to test
* @param {*} val The value to test
*
* @returns {boolean} True if value is a Date, otherwise false
*/
var isDate = kindOfTest('Date');
const isDate = kindOfTest('Date');
/**
* Determine if a value is a File
*
* @param {Object} val The value to test
* @param {*} val The value to test
*
* @returns {boolean} True if value is a File, otherwise false
*/
var isFile = kindOfTest('File');
const isFile = kindOfTest('File');
/**
* Determine if a value is a Blob
*
* @param {Object} val The value to test
* @param {*} val The value to test
*
* @returns {boolean} True if value is a Blob, otherwise false
*/
var isBlob = kindOfTest('Blob');
const isBlob = kindOfTest('Blob');
/**
* Determine if a value is a FileList
*
* @param {Object} val The value to test
* @param {*} val The value to test
*
* @returns {boolean} True if value is a File, otherwise false
*/
var isFileList = kindOfTest('FileList');
/**
* Determine if a value is a Function
*
* @param {Object} val The value to test
*
* @returns {boolean} True if value is a Function, otherwise false
*/
function isFunction(val) {
return toString.call(val) === '[object Function]';
}
const isFileList = kindOfTest('FileList');
/**
* Determine if a value is a Stream
*
* @param {Object} val The value to test
* @param {*} val The value to test
*
* @returns {boolean} True if value is a Stream, otherwise false
*/
@@ -193,12 +200,12 @@ function isStream(val) {
/**
* Determine if a value is a FormData
*
* @param {Object} thing The value to test
* @param {*} thing The value to test
*
* @returns {boolean} True if value is an FormData, otherwise false
*/
function isFormData(thing) {
var pattern = '[object FormData]';
const pattern = '[object FormData]';
return thing && (
(typeof FormData === 'function' && thing instanceof FormData) ||
toString.call(thing) === pattern ||
@@ -209,11 +216,11 @@ function isFormData(thing) {
/**
* Determine if a value is a URLSearchParams object
*
* @param {Object} val The value to test
* @param {*} val The value to test
*
* @returns {boolean} True if value is a URLSearchParams object, otherwise false
*/
var isURLSearchParams = kindOfTest('URLSearchParams');
const isURLSearchParams = kindOfTest('URLSearchParams');
/**
* Trim excess whitespace off the beginning and end of a string
@@ -244,7 +251,7 @@ function trim(str) {
* @returns {boolean}
*/
function isStandardBrowserEnv() {
var product;
let product;
if (typeof navigator !== 'undefined' && (
(product = navigator.product) === 'ReactNative' ||
product === 'NativeScript' ||
@@ -268,14 +275,18 @@ function isStandardBrowserEnv() {
* @param {Object|Array} obj The object to iterate
* @param {Function} fn The callback to invoke for each item
*
* @param {Boolean} [allOwnKeys = false]
* @returns {void}
*/
function forEach(obj, fn) {
function forEach(obj, fn, {allOwnKeys = false} = {}) {
// Don't bother if no value provided
if (obj === null || typeof obj === 'undefined') {
return;
}
let i;
let l;
// Force an array if not already something iterable
if (typeof obj !== 'object') {
/*eslint no-param-reassign:0*/
@@ -284,15 +295,18 @@ function forEach(obj, fn) {
if (isArray(obj)) {
// Iterate over array values
for (var i = 0, l = obj.length; i < l; i++) {
for (i = 0, l = obj.length; i < l; i++) {
fn.call(null, obj[i], i, obj);
}
} else {
// Iterate over object keys
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
fn.call(null, obj[key], key, obj);
}
const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);
const len = keys.length;
let key;
for (i = 0; i < len; i++) {
key = keys[i];
fn.call(null, obj[key], key, obj);
}
}
}
@@ -316,7 +330,7 @@ function forEach(obj, fn) {
* @returns {Object} Result of all merge properties
*/
function merge(/* obj1, obj2, obj3, ... */) {
var result = {};
const result = {};
function assignValue(val, key) {
if (isPlainObject(result[key]) && isPlainObject(val)) {
result[key] = merge(result[key], val);
@@ -329,8 +343,8 @@ function merge(/* obj1, obj2, obj3, ... */) {
}
}
for (var i = 0, l = arguments.length; i < l; i++) {
forEach(arguments[i], assignValue);
for (let i = 0, l = arguments.length; i < l; i++) {
arguments[i] && forEach(arguments[i], assignValue);
}
return result;
}
@@ -342,16 +356,17 @@ function merge(/* obj1, obj2, obj3, ... */) {
* @param {Object} b The object to copy properties from
* @param {Object} thisArg The object to bind function to
*
* @param {Boolean} [allOwnKeys]
* @returns {Object} The resulting value of object a
*/
function extend(a, b, thisArg) {
function extend(a, b, thisArg, {allOwnKeys}= {}) {
forEach(b, function assignValue(val, key) {
if (thisArg && typeof val === 'function') {
a[key] = bind(val, thisArg);
} else {
a[key] = val;
}
});
}, {allOwnKeys});
return a;
}
@@ -381,6 +396,9 @@ function stripBOM(content) {
function inherits(constructor, superConstructor, props, descriptors) {
constructor.prototype = Object.create(superConstructor.prototype, descriptors);
constructor.prototype.constructor = constructor;
Object.defineProperty(constructor, 'super', {
value: superConstructor.prototype
});
props && Object.assign(constructor.prototype, props);
}
@@ -394,10 +412,10 @@ function inherits(constructor, superConstructor, props, descriptors) {
* @returns {Object}
*/
function toFlatObject(sourceObj, destObj, filter, propFilter) {
var props;
var i;
var prop;
var merged = {};
let props;
let i;
let prop;
const merged = {};
destObj = destObj || {};
// eslint-disable-next-line no-eq-null,eqeqeq
@@ -434,7 +452,7 @@ function endsWith(str, searchString, position) {
position = str.length;
}
position -= searchString.length;
var lastIndex = str.indexOf(searchString, position);
const lastIndex = str.indexOf(searchString, position);
return lastIndex !== -1 && lastIndex === position;
}
@@ -449,9 +467,9 @@ function endsWith(str, searchString, position) {
function toArray(thing) {
if (!thing) return null;
if (isArray(thing)) return thing;
var i = thing.length;
let i = thing.length;
if (!isNumber(i)) return null;
var arr = new Array(i);
const arr = new Array(i);
while (i-- > 0) {
arr[i] = thing[i];
}
@@ -467,9 +485,9 @@ function toArray(thing) {
* @returns {Array}
*/
// eslint-disable-next-line func-names
var isTypedArray = (function(TypedArray) {
const isTypedArray = (TypedArray => {
// eslint-disable-next-line func-names
return function(thing) {
return thing => {
return TypedArray && thing instanceof TypedArray;
};
})(typeof Uint8Array !== 'undefined' && Object.getPrototypeOf(Uint8Array));
@@ -483,14 +501,14 @@ var isTypedArray = (function(TypedArray) {
* @returns {void}
*/
function forEachEntry(obj, fn) {
var generator = obj && obj[Symbol.iterator];
const generator = obj && obj[Symbol.iterator];
var iterator = generator.call(obj);
const iterator = generator.call(obj);
var result;
let result;
while ((result = iterator.next()) && !result.done) {
var pair = result.value;
const pair = result.value;
fn.call(obj, pair[0], pair[1]);
}
}
@@ -504,8 +522,8 @@ function forEachEntry(obj, fn) {
* @returns {Array<boolean>}
*/
function matchAll(regExp, str) {
var matches;
var arr = [];
let matches;
const arr = [];
while ((matches = regExp.exec(str)) !== null) {
arr.push(matches);
@@ -515,48 +533,134 @@ function matchAll(regExp, str) {
}
/* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */
var isHTMLForm = kindOfTest('HTMLFormElement');
const isHTMLForm = kindOfTest('HTMLFormElement');
const toCamelCase = str => {
return str.toLowerCase().replace(/[_-\s]([a-z\d])(\w*)/g,
function replacer(m, p1, p2) {
return p1.toUpperCase() + p2;
}
);
};
/* Creating a function that will check if an object has a property. */
var hasOwnProperty = (function resolver(_hasOwnProperty) {
return function(obj, prop) {
const hasOwnProperty = (function resolver(_hasOwnProperty) {
return (obj, prop) => {
return _hasOwnProperty.call(obj, prop);
};
})(Object.prototype.hasOwnProperty);
module.exports = {
isArray: isArray,
isArrayBuffer: isArrayBuffer,
isBuffer: isBuffer,
isFormData: isFormData,
isArrayBufferView: isArrayBufferView,
isString: isString,
isNumber: isNumber,
isObject: isObject,
isPlainObject: isPlainObject,
isUndefined: isUndefined,
isDate: isDate,
isFile: isFile,
isBlob: isBlob,
isFunction: isFunction,
isStream: isStream,
isURLSearchParams: isURLSearchParams,
isStandardBrowserEnv: isStandardBrowserEnv,
forEach: forEach,
merge: merge,
extend: extend,
trim: trim,
stripBOM: stripBOM,
inherits: inherits,
toFlatObject: toFlatObject,
kindOf: kindOf,
kindOfTest: kindOfTest,
endsWith: endsWith,
toArray: toArray,
isTypedArray: isTypedArray,
isFileList: isFileList,
forEachEntry: forEachEntry,
matchAll: matchAll,
isHTMLForm: isHTMLForm,
hasOwnProperty: hasOwnProperty
/**
* Determine if a value is a RegExp object
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a RegExp object, otherwise false
*/
const isRegExp = kindOfTest('RegExp');
function reduceDescriptors(obj, reducer) {
const descriptors = Object.getOwnPropertyDescriptors(obj);
const reducedDescriptors = {};
forEach(descriptors, (descriptor, name) => {
if (reducer(descriptor, name, obj) !== false) {
reducedDescriptors[name] = descriptor;
}
});
Object.defineProperties(obj, reducedDescriptors);
}
/**
* Makes all methods read-only
* @param {Object} obj
*/
function freezeMethods(obj) {
reduceDescriptors(obj, (descriptor, name) => {
const value = obj[name];
if (!isFunction(value)) return;
descriptor.enumerable = false;
if ('writable' in descriptor) {
descriptor.writable = false;
return;
}
if (!descriptor.set) {
descriptor.set = () => {
throw Error('Can not read-only method \'' + name + '\'');
};
}
});
}
function toObjectSet(arrayOrString, delimiter) {
const obj = {};
function define(arr) {
arr.forEach(value => {
obj[value] = true;
});
}
isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter));
return obj;
}
function noop() {}
function toFiniteNumber(value, defaultValue) {
value = +value;
return Number.isFinite(value) ? value : defaultValue;
}
export default {
isArray,
isArrayBuffer,
isBuffer,
isFormData,
isArrayBufferView,
isString,
isNumber,
isBoolean,
isObject,
isPlainObject,
isUndefined,
isDate,
isFile,
isBlob,
isRegExp,
isFunction,
isStream,
isURLSearchParams,
isTypedArray,
isFileList,
isStandardBrowserEnv,
forEach,
merge,
extend,
trim,
stripBOM,
inherits,
toFlatObject,
kindOf,
kindOfTest,
endsWith,
toArray,
forEachEntry,
matchAll,
isHTMLForm,
hasOwnProperty,
hasOwnProp: hasOwnProperty, // an alias to avoid ESLint no-prototype-builtins detection
reduceDescriptors,
freezeMethods,
toObjectSet,
toCamelCase,
noop,
toFiniteNumber
};