2
0
mirror of https://github.com/tenrok/axios.git synced 2026-06-11 18:02:32 +03:00

chore(release): v1.7.0-beta.0 (#6373)

Co-authored-by: DigitalBrainJS <DigitalBrainJS@users.noreply.github.com>
This commit is contained in:
github-actions[bot]
2024-04-28 22:50:08 +03:00
committed by GitHub
parent a3ff99b59d
commit 8e4314bfd6
17 changed files with 2844 additions and 1149 deletions
+560 -240
View File
@@ -1,4 +1,4 @@
// Axios v1.6.8 Copyright (c) 2024 Matt Zabriskie and contributors
// Axios v1.7.0-beta.0 Copyright (c) 2024 Matt Zabriskie and contributors
'use strict';
const FormData$1 = require('form-data');
@@ -236,6 +236,8 @@ const isFormData = (thing) => {
*/
const isURLSearchParams = kindOfTest('URLSearchParams');
const [isReadableStream, isRequest, isResponse, isHeaders] = ['ReadableStream', 'Request', 'Response', 'Headers'].map(kindOfTest);
/**
* Trim excess whitespace off the beginning and end of a string
*
@@ -624,8 +626,7 @@ const toObjectSet = (arrayOrString, delimiter) => {
const noop = () => {};
const toFiniteNumber = (value, defaultValue) => {
value = +value;
return Number.isFinite(value) ? value : defaultValue;
return value != null && Number.isFinite(value = +value) ? value : defaultValue;
};
const ALPHA = 'abcdefghijklmnopqrstuvwxyz';
@@ -706,6 +707,10 @@ const utils$1 = {
isBoolean,
isObject,
isPlainObject,
isReadableStream,
isRequest,
isResponse,
isHeaders,
isUndefined,
isDate,
isFile,
@@ -1295,11 +1300,14 @@ const hasStandardBrowserWebWorkerEnv = (() => {
);
})();
const origin = hasBrowserEnv && window.location.href || 'http://localhost';
const utils = /*#__PURE__*/Object.freeze({
__proto__: null,
hasBrowserEnv: hasBrowserEnv,
hasStandardBrowserWebWorkerEnv: hasStandardBrowserWebWorkerEnv,
hasStandardBrowserEnv: hasStandardBrowserEnv
hasStandardBrowserEnv: hasStandardBrowserEnv,
origin: origin
});
const platform = {
@@ -1439,7 +1447,7 @@ const defaults = {
transitional: transitionalDefaults,
adapter: ['xhr', 'http'],
adapter: ['xhr', 'http', 'fetch'],
transformRequest: [function transformRequest(data, headers) {
const contentType = headers.getContentType() || '';
@@ -1460,7 +1468,8 @@ const defaults = {
utils$1.isBuffer(data) ||
utils$1.isStream(data) ||
utils$1.isFile(data) ||
utils$1.isBlob(data)
utils$1.isBlob(data) ||
utils$1.isReadableStream(data)
) {
return data;
}
@@ -1503,6 +1512,10 @@ const defaults = {
const forcedJSONParsing = transitional && transitional.forcedJSONParsing;
const JSONRequested = this.responseType === 'json';
if (utils$1.isResponse(data) || utils$1.isReadableStream(data)) {
return data;
}
if (data && utils$1.isString(data) && ((forcedJSONParsing && !this.responseType) || JSONRequested)) {
const silentJSONParsing = transitional && transitional.silentJSONParsing;
const strictJSONParsing = !silentJSONParsing && JSONRequested;
@@ -1706,6 +1719,10 @@ class AxiosHeaders {
setHeaders(header, valueOrRewrite);
} else if(utils$1.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) {
setHeaders(parseHeaders(header), valueOrRewrite);
} else if (utils$1.isHeaders(header)) {
for (const [key, value] of header.entries()) {
setHeader(value, key, rewrite);
}
} else {
header != null && setHeader(valueOrRewrite, header, rewrite);
}
@@ -2018,7 +2035,7 @@ function buildFullPath(baseURL, requestedURL) {
return requestedURL;
}
const VERSION = "1.6.8";
const VERSION = "1.7.0-beta.0";
function parseProtocol(url) {
const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url);
@@ -2083,7 +2100,9 @@ function throttle(fn, freq) {
let timestamp = 0;
const threshold = 1000 / freq;
let timer = null;
return function throttled(force, args) {
return function throttled() {
const force = this === true;
const now = Date.now();
if (force || now - timestamp > threshold) {
if (timer) {
@@ -2091,13 +2110,13 @@ function throttle(fn, freq) {
timer = null;
}
timestamp = now;
return fn.apply(null, args);
return fn.apply(null, arguments);
}
if (!timer) {
timer = setTimeout(() => {
timer = null;
timestamp = Date.now();
return fn.apply(null, args);
return fn.apply(null, arguments);
}, threshold - (now - timestamp));
}
};
@@ -2215,19 +2234,20 @@ class AxiosTransformStream extends stream__default["default"].Transform{
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
loaded: bytesTransferred,
total: totalBytes,
progress: totalBytes ? (bytesTransferred / totalBytes) : undefined,
bytes: progressBytes,
rate: rate ? rate : undefined,
estimated: rate && totalBytes && bytesTransferred <= totalBytes ?
(totalBytes - bytesTransferred) / rate : undefined,
lengthComputable: totalBytes != null
});
});
}, internals.ticksRate);
const onFinish = () => {
internals.updateProgress(true);
internals.updateProgress.call(true);
};
this.once('end', onFinish);
@@ -3158,44 +3178,35 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) {
});
};
const cookies = platform.hasStandardBrowserEnv ?
const progressEventReducer = (listener, isDownloadStream, freq = 3) => {
let bytesNotified = 0;
const _speedometer = speedometer(50, 250);
// Standard browser envs support document.cookie
{
write(name, value, expires, path, domain, secure) {
const cookie = [name + '=' + encodeURIComponent(value)];
return throttle(e => {
const loaded = e.loaded;
const total = e.lengthComputable ? e.total : undefined;
const progressBytes = loaded - bytesNotified;
const rate = _speedometer(progressBytes);
const inRange = loaded <= total;
utils$1.isNumber(expires) && cookie.push('expires=' + new Date(expires).toGMTString());
bytesNotified = loaded;
utils$1.isString(path) && cookie.push('path=' + path);
const data = {
loaded,
total,
progress: total ? (loaded / total) : undefined,
bytes: progressBytes,
rate: rate ? rate : undefined,
estimated: rate && total && inRange ? (total - loaded) / rate : undefined,
event: e,
lengthComputable: total != null
};
utils$1.isString(domain) && cookie.push('domain=' + domain);
data[isDownloadStream ? 'download' : 'upload'] = true;
secure === true && cookie.push('secure');
document.cookie = cookie.join('; ');
},
read(name) {
const match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
return (match ? decodeURIComponent(match[3]) : null);
},
remove(name) {
this.write(name, '', Date.now() - 86400000);
}
}
:
// Non-standard browser env (web workers, react-native) lack needed support.
{
write() {},
read() {
return null;
},
remove() {}
};
listener(data);
}, freq);
};
const isURLSameOrigin = platform.hasStandardBrowserEnv ?
@@ -3260,80 +3271,220 @@ const isURLSameOrigin = platform.hasStandardBrowserEnv ?
};
})();
function progressEventReducer(listener, isDownloadStream) {
let bytesNotified = 0;
const _speedometer = speedometer(50, 250);
const cookies = platform.hasStandardBrowserEnv ?
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;
// Standard browser envs support document.cookie
{
write(name, value, expires, path, domain, secure) {
const cookie = [name + '=' + encodeURIComponent(value)];
bytesNotified = loaded;
utils$1.isNumber(expires) && cookie.push('expires=' + new Date(expires).toGMTString());
const data = {
loaded,
total,
progress: total ? (loaded / total) : undefined,
bytes: progressBytes,
rate: rate ? rate : undefined,
estimated: rate && total && inRange ? (total - loaded) / rate : undefined,
event: e
};
utils$1.isString(path) && cookie.push('path=' + path);
data[isDownloadStream ? 'download' : 'upload'] = true;
utils$1.isString(domain) && cookie.push('domain=' + domain);
listener(data);
secure === true && cookie.push('secure');
document.cookie = cookie.join('; ');
},
read(name) {
const match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
return (match ? decodeURIComponent(match[3]) : null);
},
remove(name) {
this.write(name, '', Date.now() - 86400000);
}
}
:
// Non-standard browser env (web workers, react-native) lack needed support.
{
write() {},
read() {
return null;
},
remove() {}
};
const headersToObject = (thing) => thing instanceof AxiosHeaders$1 ? { ...thing } : thing;
/**
* Config-specific merge-function which creates a new config-object
* by merging two configuration objects together.
*
* @param {Object} config1
* @param {Object} config2
*
* @returns {Object} New object resulting from merging config2 to config1
*/
function mergeConfig(config1, config2) {
// eslint-disable-next-line no-param-reassign
config2 = config2 || {};
const config = {};
function getMergedValue(target, source, caseless) {
if (utils$1.isPlainObject(target) && utils$1.isPlainObject(source)) {
return utils$1.merge.call({caseless}, target, source);
} else if (utils$1.isPlainObject(source)) {
return utils$1.merge({}, source);
} else if (utils$1.isArray(source)) {
return source.slice();
}
return source;
}
// eslint-disable-next-line consistent-return
function mergeDeepProperties(a, b, caseless) {
if (!utils$1.isUndefined(b)) {
return getMergedValue(a, b, caseless);
} else if (!utils$1.isUndefined(a)) {
return getMergedValue(undefined, a, caseless);
}
}
// eslint-disable-next-line consistent-return
function valueFromConfig2(a, b) {
if (!utils$1.isUndefined(b)) {
return getMergedValue(undefined, b);
}
}
// eslint-disable-next-line consistent-return
function defaultToConfig2(a, b) {
if (!utils$1.isUndefined(b)) {
return getMergedValue(undefined, b);
} else if (!utils$1.isUndefined(a)) {
return getMergedValue(undefined, a);
}
}
// eslint-disable-next-line consistent-return
function mergeDirectKeys(a, b, prop) {
if (prop in config2) {
return getMergedValue(a, b);
} else if (prop in config1) {
return getMergedValue(undefined, a);
}
}
const mergeMap = {
url: valueFromConfig2,
method: valueFromConfig2,
data: valueFromConfig2,
baseURL: defaultToConfig2,
transformRequest: defaultToConfig2,
transformResponse: defaultToConfig2,
paramsSerializer: defaultToConfig2,
timeout: defaultToConfig2,
timeoutMessage: defaultToConfig2,
withCredentials: defaultToConfig2,
withXSRFToken: defaultToConfig2,
adapter: defaultToConfig2,
responseType: defaultToConfig2,
xsrfCookieName: defaultToConfig2,
xsrfHeaderName: defaultToConfig2,
onUploadProgress: defaultToConfig2,
onDownloadProgress: defaultToConfig2,
decompress: defaultToConfig2,
maxContentLength: defaultToConfig2,
maxBodyLength: defaultToConfig2,
beforeRedirect: defaultToConfig2,
transport: defaultToConfig2,
httpAgent: defaultToConfig2,
httpsAgent: defaultToConfig2,
cancelToken: defaultToConfig2,
socketPath: defaultToConfig2,
responseEncoding: defaultToConfig2,
validateStatus: mergeDirectKeys,
headers: (a, b) => mergeDeepProperties(headersToObject(a), headersToObject(b), true)
};
utils$1.forEach(Object.keys(Object.assign({}, config1, config2)), function computeConfigValue(prop) {
const merge = mergeMap[prop] || mergeDeepProperties;
const configValue = merge(config1[prop], config2[prop], prop);
(utils$1.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue);
});
return config;
}
const resolveConfig = (config) => {
const newConfig = mergeConfig({}, config);
let {data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth} = newConfig;
newConfig.headers = headers = AxiosHeaders$1.from(headers);
newConfig.url = buildURL(buildFullPath(newConfig.baseURL, newConfig.url), config.params, config.paramsSerializer);
// HTTP basic authentication
if (auth) {
headers.set('Authorization', 'Basic ' +
btoa((auth.username || '') + ':' + (auth.password ? unescape(encodeURIComponent(auth.password)) : ''))
);
}
let contentType;
if (utils$1.isFormData(data)) {
if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv) {
headers.setContentType(undefined); // Let the browser set it
} else if ((contentType = headers.getContentType()) !== false) {
// fix semicolon duplication issue for ReactNative FormData implementation
const [type, ...tokens] = contentType ? contentType.split(';').map(token => token.trim()).filter(Boolean) : [];
headers.setContentType([type || 'multipart/form-data', ...tokens].join('; '));
}
}
// Add xsrf header
// This is only done if running in a standard browser environment.
// Specifically not if we're in a web worker, or react-native.
if (platform.hasStandardBrowserEnv) {
withXSRFToken && utils$1.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(newConfig));
if (withXSRFToken || (withXSRFToken !== false && isURLSameOrigin(newConfig.url))) {
// Add xsrf header
const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName);
if (xsrfValue) {
headers.set(xsrfHeaderName, xsrfValue);
}
}
}
return newConfig;
};
const isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined';
const xhrAdapter = isXHRAdapterSupported && function (config) {
return new Promise(function dispatchXhrRequest(resolve, reject) {
let requestData = config.data;
const requestHeaders = AxiosHeaders$1.from(config.headers).normalize();
let {responseType, withXSRFToken} = config;
const _config = resolveConfig(config);
let requestData = _config.data;
const requestHeaders = AxiosHeaders$1.from(_config.headers).normalize();
let {responseType} = _config;
let onCanceled;
function done() {
if (config.cancelToken) {
config.cancelToken.unsubscribe(onCanceled);
if (_config.cancelToken) {
_config.cancelToken.unsubscribe(onCanceled);
}
if (config.signal) {
config.signal.removeEventListener('abort', onCanceled);
}
}
let contentType;
if (utils$1.isFormData(requestData)) {
if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv) {
requestHeaders.setContentType(false); // Let the browser set it
} else if ((contentType = requestHeaders.getContentType()) !== false) {
// fix semicolon duplication issue for ReactNative FormData implementation
const [type, ...tokens] = contentType ? contentType.split(';').map(token => token.trim()).filter(Boolean) : [];
requestHeaders.setContentType([type || 'multipart/form-data', ...tokens].join('; '));
if (_config.signal) {
_config.signal.removeEventListener('abort', onCanceled);
}
}
let request = new XMLHttpRequest();
// HTTP basic authentication
if (config.auth) {
const username = config.auth.username || '';
const password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : '';
requestHeaders.set('Authorization', 'Basic ' + btoa(username + ':' + password));
}
const fullPath = buildFullPath(config.baseURL, config.url);
request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true);
request.open(_config.method.toUpperCase(), _config.url, true);
// Set the request timeout in MS
request.timeout = config.timeout;
request.timeout = _config.timeout;
function onloadend() {
if (!request) {
@@ -3395,7 +3546,7 @@ const xhrAdapter = isXHRAdapterSupported && function (config) {
return;
}
reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request));
reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, _config, request));
// Clean up request
request = null;
@@ -3405,7 +3556,7 @@ const xhrAdapter = isXHRAdapterSupported && function (config) {
request.onerror = function handleError() {
// Real errors are hidden from us by the browser
// onerror should only fire if it's a network error
reject(new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request));
reject(new AxiosError('Network Error', AxiosError.ERR_NETWORK, _config, request));
// Clean up request
request = null;
@@ -3413,37 +3564,21 @@ const xhrAdapter = isXHRAdapterSupported && function (config) {
// Handle timeout
request.ontimeout = function handleTimeout() {
let timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded';
const transitional = config.transitional || transitionalDefaults;
if (config.timeoutErrorMessage) {
timeoutErrorMessage = config.timeoutErrorMessage;
let timeoutErrorMessage = _config.timeout ? 'timeout of ' + _config.timeout + 'ms exceeded' : 'timeout exceeded';
const transitional = _config.transitional || transitionalDefaults;
if (_config.timeoutErrorMessage) {
timeoutErrorMessage = _config.timeoutErrorMessage;
}
reject(new AxiosError(
timeoutErrorMessage,
transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED,
config,
_config,
request));
// Clean up request
request = null;
};
// Add xsrf header
// This is only done if running in a standard browser environment.
// Specifically not if we're in a web worker, or react-native.
if(platform.hasStandardBrowserEnv) {
withXSRFToken && utils$1.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(config));
if (withXSRFToken || (withXSRFToken !== false && isURLSameOrigin(fullPath))) {
// Add xsrf header
const xsrfValue = config.xsrfHeaderName && config.xsrfCookieName && cookies.read(config.xsrfCookieName);
if (xsrfValue) {
requestHeaders.set(config.xsrfHeaderName, xsrfValue);
}
}
}
// Remove Content-Type if data is undefined
requestData === undefined && requestHeaders.setContentType(null);
@@ -3455,26 +3590,26 @@ const xhrAdapter = isXHRAdapterSupported && function (config) {
}
// Add withCredentials to request if needed
if (!utils$1.isUndefined(config.withCredentials)) {
request.withCredentials = !!config.withCredentials;
if (!utils$1.isUndefined(_config.withCredentials)) {
request.withCredentials = !!_config.withCredentials;
}
// Add responseType to request if needed
if (responseType && responseType !== 'json') {
request.responseType = config.responseType;
request.responseType = _config.responseType;
}
// Handle progress if needed
if (typeof config.onDownloadProgress === 'function') {
request.addEventListener('progress', progressEventReducer(config.onDownloadProgress, true));
if (typeof _config.onDownloadProgress === 'function') {
request.addEventListener('progress', progressEventReducer(_config.onDownloadProgress, true));
}
// Not all browsers support upload events
if (typeof config.onUploadProgress === 'function' && request.upload) {
request.upload.addEventListener('progress', progressEventReducer(config.onUploadProgress));
if (typeof _config.onUploadProgress === 'function' && request.upload) {
request.upload.addEventListener('progress', progressEventReducer(_config.onUploadProgress));
}
if (config.cancelToken || config.signal) {
if (_config.cancelToken || _config.signal) {
// Handle cancellation
// eslint-disable-next-line func-names
onCanceled = cancel => {
@@ -3486,13 +3621,13 @@ const xhrAdapter = isXHRAdapterSupported && function (config) {
request = null;
};
config.cancelToken && config.cancelToken.subscribe(onCanceled);
if (config.signal) {
config.signal.aborted ? onCanceled() : config.signal.addEventListener('abort', onCanceled);
_config.cancelToken && _config.cancelToken.subscribe(onCanceled);
if (_config.signal) {
_config.signal.aborted ? onCanceled() : _config.signal.addEventListener('abort', onCanceled);
}
}
const protocol = parseProtocol(fullPath);
const protocol = parseProtocol(_config.url);
if (protocol && platform.protocols.indexOf(protocol) === -1) {
reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config));
@@ -3505,9 +3640,296 @@ const xhrAdapter = isXHRAdapterSupported && function (config) {
});
};
const composeSignals = (signals, timeout) => {
let controller = new AbortController();
let aborted;
const onabort = function (cancel) {
if (!aborted) {
aborted = true;
unsubscribe();
const err = cancel instanceof Error ? cancel : this.reason;
controller.abort(err instanceof AxiosError ? err : new CanceledError(err instanceof Error ? err.message : err));
}
};
let timer = timeout && setTimeout(() => {
onabort(new AxiosError(`timeout ${timeout} of ms exceeded`, AxiosError.ETIMEDOUT));
}, timeout);
const unsubscribe = () => {
if (signals) {
timer && clearTimeout(timer);
timer = null;
signals.forEach(signal => {
signal &&
(signal.removeEventListener ? signal.removeEventListener('abort', onabort) : signal.unsubscribe(onabort));
});
signals = null;
}
};
signals.forEach((signal) => signal && signal.addEventListener && signal.addEventListener('abort', onabort));
const {signal} = controller;
signal.unsubscribe = unsubscribe;
return [signal, () => {
timer && clearTimeout(timer);
timer = null;
}];
};
const composeSignals$1 = composeSignals;
const streamChunk = function* (chunk, chunkSize) {
let len = chunk.byteLength;
if (!chunkSize || len < chunkSize) {
yield chunk;
return;
}
let pos = 0;
let end;
while (pos < len) {
end = pos + chunkSize;
yield chunk.slice(pos, end);
pos = end;
}
};
const encoder = new TextEncoder();
const readBytes = async function* (iterable, chunkSize) {
for await (const chunk of iterable) {
yield* streamChunk(ArrayBuffer.isView(chunk) ? chunk : (await encoder.encode(String(chunk))), chunkSize);
}
};
const trackStream = (stream, chunkSize, onProgress, onFinish) => {
const iterator = readBytes(stream, chunkSize);
let bytes = 0;
return new ReadableStream({
type: 'bytes',
async pull(controller) {
const {done, value} = await iterator.next();
if (done) {
controller.close();
onFinish();
return;
}
let len = value.byteLength;
onProgress && onProgress(bytes += len);
controller.enqueue(new Uint8Array(value));
},
cancel(reason) {
onFinish(reason);
return iterator.return();
}
}, {
highWaterMark: 2
})
};
const fetchProgressDecorator = (total, fn) => {
const lengthComputable = total != null;
return (loaded) => setTimeout(() => fn({
lengthComputable,
total,
loaded
}));
};
const isFetchSupported = typeof fetch !== 'undefined';
const supportsRequestStreams = isFetchSupported && (() => {
let duplexAccessed = false;
const hasContentType = new Request(platform.origin, {
body: new ReadableStream(),
method: 'POST',
get duplex() {
duplexAccessed = true;
return 'half';
},
}).headers.has('Content-Type');
return duplexAccessed && !hasContentType;
})();
const DEFAULT_CHUNK_SIZE = 64 * 1024;
const resolvers = {
stream: (res) => res.body
};
isFetchSupported && ['text', 'arrayBuffer', 'blob', 'formData'].forEach(type => [
resolvers[type] = utils$1.isFunction(Response.prototype[type]) ? (res) => res[type]() : (_, config) => {
throw new AxiosError(`Response type ${type} is not supported`, AxiosError.ERR_NOT_SUPPORT, config);
}
]);
const getBodyLength = async (body) => {
if(utils$1.isBlob(body)) {
return body.size;
}
if(utils$1.isSpecCompliantForm(body)) {
return (await new Request(body).arrayBuffer()).byteLength;
}
if(utils$1.isArrayBufferView(body)) {
return body.byteLength;
}
if(utils$1.isURLSearchParams(body)) {
body = body + '';
}
if(utils$1.isString(body)) {
return (await new TextEncoder().encode(body)).byteLength;
}
};
const resolveBodyLength = async (headers, body) => {
const length = utils$1.toFiniteNumber(headers.getContentLength());
return length == null ? getBodyLength(body) : length;
};
const fetchAdapter = async (config) => {
let {
url,
method,
data,
signal,
cancelToken,
timeout,
onDownloadProgress,
onUploadProgress,
responseType,
headers,
withCredentials = 'same-origin',
fetchOptions
} = resolveConfig(config);
responseType = responseType ? (responseType + '').toLowerCase() : 'text';
let [composedSignal, stopTimeout] = (signal || cancelToken || timeout) ?
composeSignals$1([signal, cancelToken], timeout) : [];
let finished, request;
const onFinish = () => {
!finished && setTimeout(() => {
composedSignal && composedSignal.unsubscribe();
});
finished = true;
};
try {
if (onUploadProgress && supportsRequestStreams && method !== 'get' && method !== 'head') {
let requestContentLength = await resolveBodyLength(headers, data);
let _request = new Request(url, {
method,
body: data,
duplex: "half"
});
let contentTypeHeader;
if (utils$1.isFormData(data) && (contentTypeHeader = _request.headers.get('content-type'))) {
headers.setContentType(contentTypeHeader);
}
data = trackStream(_request.body, DEFAULT_CHUNK_SIZE, fetchProgressDecorator(
requestContentLength,
progressEventReducer(onUploadProgress)
));
}
if (!utils$1.isString(withCredentials)) {
withCredentials = withCredentials ? 'cors' : 'omit';
}
request = new Request(url, {
...fetchOptions,
signal: composedSignal,
method,
headers: headers.normalize().toJSON(),
body: data,
duplex: "half",
withCredentials
});
let response = await fetch(request);
const isStreamResponse = responseType === 'stream' || responseType === 'response';
if (onDownloadProgress || isStreamResponse) {
const options = {};
Object.getOwnPropertyNames(response).forEach(prop => {
options[prop] = response[prop];
});
const responseContentLength = utils$1.toFiniteNumber(response.headers.get('content-length'));
response = new Response(
trackStream(response.body, DEFAULT_CHUNK_SIZE, onDownloadProgress && fetchProgressDecorator(
responseContentLength,
progressEventReducer(onDownloadProgress, true)
), isStreamResponse && onFinish),
options
);
}
responseType = responseType || 'text';
let responseData = await resolvers[utils$1.findKey(resolvers, responseType) || 'text'](response, config);
!isStreamResponse && onFinish();
stopTimeout && stopTimeout();
return await new Promise((resolve, reject) => {
settle(resolve, reject, {
data: responseData,
headers: AxiosHeaders$1.from(response.headers),
status: response.status,
statusText: response.statusText,
config,
request
});
})
} catch (err) {
onFinish();
let {code} = err;
if (err.name === 'NetworkError') {
code = AxiosError.ERR_NETWORK;
}
throw AxiosError.from(err, code, config, request);
}
};
const knownAdapters = {
http: httpAdapter,
xhr: xhrAdapter
xhr: xhrAdapter,
fetch: fetchAdapter
};
utils$1.forEach(knownAdapters, (fn, value) => {
@@ -3651,108 +4073,6 @@ function dispatchRequest(config) {
});
}
const headersToObject = (thing) => thing instanceof AxiosHeaders$1 ? { ...thing } : thing;
/**
* Config-specific merge-function which creates a new config-object
* by merging two configuration objects together.
*
* @param {Object} config1
* @param {Object} config2
*
* @returns {Object} New object resulting from merging config2 to config1
*/
function mergeConfig(config1, config2) {
// eslint-disable-next-line no-param-reassign
config2 = config2 || {};
const config = {};
function getMergedValue(target, source, caseless) {
if (utils$1.isPlainObject(target) && utils$1.isPlainObject(source)) {
return utils$1.merge.call({caseless}, target, source);
} else if (utils$1.isPlainObject(source)) {
return utils$1.merge({}, source);
} else if (utils$1.isArray(source)) {
return source.slice();
}
return source;
}
// eslint-disable-next-line consistent-return
function mergeDeepProperties(a, b, caseless) {
if (!utils$1.isUndefined(b)) {
return getMergedValue(a, b, caseless);
} else if (!utils$1.isUndefined(a)) {
return getMergedValue(undefined, a, caseless);
}
}
// eslint-disable-next-line consistent-return
function valueFromConfig2(a, b) {
if (!utils$1.isUndefined(b)) {
return getMergedValue(undefined, b);
}
}
// eslint-disable-next-line consistent-return
function defaultToConfig2(a, b) {
if (!utils$1.isUndefined(b)) {
return getMergedValue(undefined, b);
} else if (!utils$1.isUndefined(a)) {
return getMergedValue(undefined, a);
}
}
// eslint-disable-next-line consistent-return
function mergeDirectKeys(a, b, prop) {
if (prop in config2) {
return getMergedValue(a, b);
} else if (prop in config1) {
return getMergedValue(undefined, a);
}
}
const mergeMap = {
url: valueFromConfig2,
method: valueFromConfig2,
data: valueFromConfig2,
baseURL: defaultToConfig2,
transformRequest: defaultToConfig2,
transformResponse: defaultToConfig2,
paramsSerializer: defaultToConfig2,
timeout: defaultToConfig2,
timeoutMessage: defaultToConfig2,
withCredentials: defaultToConfig2,
withXSRFToken: defaultToConfig2,
adapter: defaultToConfig2,
responseType: defaultToConfig2,
xsrfCookieName: defaultToConfig2,
xsrfHeaderName: defaultToConfig2,
onUploadProgress: defaultToConfig2,
onDownloadProgress: defaultToConfig2,
decompress: defaultToConfig2,
maxContentLength: defaultToConfig2,
maxBodyLength: defaultToConfig2,
beforeRedirect: defaultToConfig2,
transport: defaultToConfig2,
httpAgent: defaultToConfig2,
httpsAgent: defaultToConfig2,
cancelToken: defaultToConfig2,
socketPath: defaultToConfig2,
responseEncoding: defaultToConfig2,
validateStatus: mergeDirectKeys,
headers: (a, b) => mergeDeepProperties(headersToObject(a), headersToObject(b), true)
};
utils$1.forEach(Object.keys(Object.assign({}, config1, config2)), function computeConfigValue(prop) {
const merge = mergeMap[prop] || mergeDeepProperties;
const configValue = merge(config1[prop], config2[prop], prop);
(utils$1.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue);
});
return config;
}
const validators$1 = {};
// eslint-disable-next-line func-names
+1 -1
View File
File diff suppressed because one or more lines are too long