Framework updates

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
root
2026-03-04 23:20:19 +00:00
parent a89daf3d43
commit 3ed8517b2a
891 changed files with 11126 additions and 9600 deletions

View File

@@ -5,24 +5,29 @@ import utils from '../utils.js';
const kInternals = Symbol('internals');
class AxiosTransformStream extends stream.Transform{
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]);
});
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
readableHighWaterMark: options.chunkSize,
});
const internals = this[kInternals] = {
const internals = (this[kInternals] = {
timeWindow: options.timeWindow,
chunkSize: options.chunkSize,
maxRate: options.maxRate,
@@ -32,10 +37,10 @@ class AxiosTransformStream extends stream.Transform{
notifiedBytesLoaded: 0,
ts: Date.now(),
bytes: 0,
onReadCallback: null
};
onReadCallback: null,
});
this.on('newListener', event => {
this.on('newListener', (event) => {
if (event === 'progress') {
if (!internals.isCaptured) {
internals.isCaptured = true;
@@ -63,8 +68,11 @@ class AxiosTransformStream extends stream.Transform{
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;
const bytesThreshold = maxRate / divider;
const minChunkSize =
internals.minChunkSize !== false
? Math.max(internals.minChunkSize, bytesThreshold * 0.01)
: 0;
const pushChunk = (_chunk, _callback) => {
const bytes = Buffer.byteLength(_chunk);
@@ -81,7 +89,7 @@ class AxiosTransformStream extends stream.Transform{
process.nextTick(_callback);
};
}
}
};
const transformChunk = (_chunk, _callback) => {
const chunkSize = Buffer.byteLength(_chunk);
@@ -93,7 +101,7 @@ class AxiosTransformStream extends stream.Transform{
if (maxRate) {
const now = Date.now();
if (!internals.ts || (passed = (now - internals.ts)) >= timeWindow) {
if (!internals.ts || (passed = now - internals.ts) >= timeWindow) {
internals.ts = now;
bytesLeft = bytesThreshold - internals.bytes;
internals.bytes = bytesLeft < 0 ? -bytesLeft : 0;
@@ -116,14 +124,19 @@ class AxiosTransformStream extends stream.Transform{
}
}
if (maxChunkSize && chunkSize > maxChunkSize && (chunkSize - maxChunkSize) > minChunkSize) {
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);
pushChunk(
_chunk,
chunkRemainder
? () => {
process.nextTick(_callback, null, chunkRemainder);
}
: _callback
);
};
transformChunk(chunk, function transformNextChunk(err, _chunk) {

View File

@@ -18,7 +18,7 @@ function encode(str) {
')': '%29',
'~': '%7E',
'%20': '+',
'%00': '\x00'
'%00': '\x00',
};
return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) {
return charMap[match];
@@ -46,13 +46,17 @@ prototype.append = function append(name, value) {
};
prototype.toString = function toString(encoder) {
const _encode = encoder ? function(value) {
return encoder.call(this, value, encode);
} : encode;
const _encode = encoder
? function (value) {
return encoder.call(this, value, encode);
}
: encode;
return this._pairs.map(function each(pair) {
return _encode(pair[0]) + '=' + _encode(pair[1]);
}, '').join('&');
return this._pairs
.map(function each(pair) {
return _encode(pair[0]) + '=' + _encode(pair[1]);
}, '')
.join('&');
};
export default AxiosURLSearchParams;

View File

@@ -1,6 +1,6 @@
"use strict";
'use strict';
import stream from "stream";
import stream from 'stream';
class ZlibHeaderTransformStream extends stream.Transform {
__transform(chunk, encoding, callback) {
@@ -13,10 +13,11 @@ class ZlibHeaderTransformStream extends stream.Transform {
this._transform = this.__transform;
// Add Default Compression headers if no zlib headers are present
if (chunk[0] !== 120) { // Hex: 78
if (chunk[0] !== 120) {
// Hex: 78
const header = Buffer.alloc(2);
header[0] = 120; // Hex: 78
header[1] = 156; // Hex: 9C
header[1] = 156; // Hex: 9C
this.push(header, encoding);
}
}

View File

@@ -12,11 +12,11 @@ import AxiosURLSearchParams from '../helpers/AxiosURLSearchParams.js';
* @returns {string} The encoded value.
*/
function encode(val) {
return encodeURIComponent(val).
replace(/%3A/gi, ':').
replace(/%24/g, '$').
replace(/%2C/gi, ',').
replace(/%20/g, '+');
return encodeURIComponent(val)
.replace(/%3A/gi, ':')
.replace(/%24/g, '$')
.replace(/%2C/gi, ',')
.replace(/%20/g, '+');
}
/**
@@ -33,11 +33,13 @@ export default function buildURL(url, params, options) {
return url;
}
const _encode = options && options.encode || encode;
const _encode = (options && options.encode) || encode;
const _options = utils.isFunction(options) ? {
serialize: options
} : options;
const _options = utils.isFunction(options)
? {
serialize: options,
}
: options;
const serializeFn = _options && _options.serialize;
@@ -46,13 +48,13 @@ export default function buildURL(url, params, options) {
if (serializeFn) {
serializedParams = serializeFn(params, _options);
} else {
serializedParams = utils.isURLSearchParams(params) ?
params.toString() :
new AxiosURLSearchParams(params, _options).toString(_encode);
serializedParams = utils.isURLSearchParams(params)
? params.toString()
: new AxiosURLSearchParams(params, _options).toString(_encode);
}
if (serializedParams) {
const hashmarkIndex = url.indexOf("#");
const hashmarkIndex = url.indexOf('#');
if (hashmarkIndex !== -1) {
url = url.slice(0, hashmarkIndex);

View File

@@ -1,16 +1,18 @@
import utils from "../utils.js";
import utils from '../utils.js';
const callbackify = (fn, reducer) => {
return utils.isAsyncFn(fn) ? function (...args) {
const cb = args.pop();
fn.apply(this, args).then((value) => {
try {
reducer ? cb(null, ...reducer(value)) : cb(null, value);
} catch (err) {
cb(err);
return utils.isAsyncFn(fn)
? function (...args) {
const cb = args.pop();
fn.apply(this, args).then((value) => {
try {
reducer ? cb(null, ...reducer(value)) : cb(null, value);
} catch (err) {
cb(err);
}
}, cb);
}
}, cb);
} : fn;
}
: fn;
};
export default callbackify;

View File

@@ -1,9 +1,9 @@
import CanceledError from "../cancel/CanceledError.js";
import AxiosError from "../core/AxiosError.js";
import CanceledError from '../cancel/CanceledError.js';
import AxiosError from '../core/AxiosError.js';
import utils from '../utils.js';
const composeSignals = (signals, timeout) => {
const {length} = (signals = signals ? signals.filter(Boolean) : []);
const { length } = (signals = signals ? signals.filter(Boolean) : []);
if (timeout || length) {
let controller = new AbortController();
@@ -15,34 +15,42 @@ const composeSignals = (signals, timeout) => {
aborted = true;
unsubscribe();
const err = reason instanceof Error ? reason : this.reason;
controller.abort(err instanceof AxiosError ? err : new CanceledError(err instanceof Error ? err.message : err));
controller.abort(
err instanceof AxiosError
? err
: new CanceledError(err instanceof Error ? err.message : err)
);
}
}
};
let timer = timeout && setTimeout(() => {
timer = null;
onabort(new AxiosError(`timeout of ${timeout}ms exceeded`, AxiosError.ETIMEDOUT))
}, timeout)
let timer =
timeout &&
setTimeout(() => {
timer = null;
onabort(new AxiosError(`timeout of ${timeout}ms exceeded`, AxiosError.ETIMEDOUT));
}, timeout);
const unsubscribe = () => {
if (signals) {
timer && clearTimeout(timer);
timer = null;
signals.forEach(signal => {
signal.unsubscribe ? signal.unsubscribe(onabort) : signal.removeEventListener('abort', onabort);
signals.forEach((signal) => {
signal.unsubscribe
? signal.unsubscribe(onabort)
: signal.removeEventListener('abort', onabort);
});
signals = null;
}
}
};
signals.forEach((signal) => signal.addEventListener('abort', onabort));
const {signal} = controller;
const { signal } = controller;
signal.unsubscribe = () => utils.asap(unsubscribe);
return signal;
}
}
};
export default composeSignals;

View File

@@ -1,53 +1,48 @@
import utils from '../utils.js';
import platform from '../platform/index.js';
export default platform.hasStandardBrowserEnv ?
export default platform.hasStandardBrowserEnv
? // Standard browser envs support document.cookie
{
write(name, value, expires, path, domain, secure, sameSite) {
if (typeof document === 'undefined') return;
// Standard browser envs support document.cookie
{
write(name, value, expires, path, domain, secure, sameSite) {
if (typeof document === 'undefined') return;
const cookie = [`${name}=${encodeURIComponent(value)}`];
const cookie = [`${name}=${encodeURIComponent(value)}`];
if (utils.isNumber(expires)) {
cookie.push(`expires=${new Date(expires).toUTCString()}`);
}
if (utils.isString(path)) {
cookie.push(`path=${path}`);
}
if (utils.isString(domain)) {
cookie.push(`domain=${domain}`);
}
if (secure === true) {
cookie.push('secure');
}
if (utils.isString(sameSite)) {
cookie.push(`SameSite=${sameSite}`);
}
if (utils.isNumber(expires)) {
cookie.push(`expires=${new Date(expires).toUTCString()}`);
}
if (utils.isString(path)) {
cookie.push(`path=${path}`);
}
if (utils.isString(domain)) {
cookie.push(`domain=${domain}`);
}
if (secure === true) {
cookie.push('secure');
}
if (utils.isString(sameSite)) {
cookie.push(`SameSite=${sameSite}`);
}
document.cookie = cookie.join('; ');
},
document.cookie = cookie.join('; ');
},
read(name) {
if (typeof document === 'undefined') return null;
const match = document.cookie.match(new RegExp('(?:^|; )' + name + '=([^;]*)'));
return match ? decodeURIComponent(match[1]) : null;
},
read(name) {
if (typeof document === 'undefined') return null;
const match = document.cookie.match(new RegExp('(?:^|; )' + name + '=([^;]*)'));
return match ? decodeURIComponent(match[1]) : null;
},
remove(name) {
this.write(name, '', Date.now() - 86400000, '/');
remove(name) {
this.write(name, '', Date.now() - 86400000, '/');
},
}
}
:
// Non-standard browser env (web workers, react-native) lack needed support.
{
write() {},
read() {
return null;
},
remove() {}
};
: // Non-standard browser env (web workers, react-native) lack needed support.
{
write() {},
read() {
return null;
},
remove() {},
};

View File

@@ -15,12 +15,17 @@
export default function deprecatedMethod(method, instead, docs) {
try {
console.warn(
'DEPRECATED method `' + method + '`.' +
(instead ? ' Use `' + instead + '` instead.' : '') +
' This method will be removed in a future release.');
'DEPRECATED method `' +
method +
'`.' +
(instead ? ' Use `' + instead + '` instead.' : '') +
' This method will be removed in a future release.'
);
if (docs) {
console.warn('For more information about usage see ' + docs);
}
} catch (e) { /* Ignore */ }
} catch (e) {
/* Ignore */
}
}

View File

@@ -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(match => {
return utils.matchAll(/\w+|\[(\w*)]/g, name).map((match) => {
return match[0] === '[]' ? '' : match[1] || match[0];
});
}

View File

@@ -1,8 +1,8 @@
import util from 'util';
import {Readable} from 'stream';
import utils from "../utils.js";
import readBlob from "./readBlob.js";
import platform from "../platform/index.js";
import { Readable } from 'stream';
import utils from '../utils.js';
import readBlob from './readBlob.js';
import platform from '../platform/index.js';
const BOUNDARY_ALPHABET = platform.ALPHABET.ALPHA_DIGIT + '-_';
@@ -14,7 +14,7 @@ const CRLF_BYTES_COUNT = 2;
class FormDataPart {
constructor(name, value) {
const {escapeName} = this.constructor;
const { escapeName } = this.constructor;
const isStringValue = utils.isString(value);
let headers = `Content-Disposition: form-data; name="${escapeName(name)}"${
@@ -24,7 +24,7 @@ class FormDataPart {
if (isStringValue) {
value = textEncoder.encode(String(value).replace(/\r?\n|\r\n?/g, CRLF));
} else {
headers += `Content-Type: ${value.type || "application/octet-stream"}${CRLF}`
headers += `Content-Type: ${value.type || 'application/octet-stream'}${CRLF}`;
}
this.headers = textEncoder.encode(headers + CRLF);
@@ -37,12 +37,12 @@ class FormDataPart {
this.value = value;
}
async *encode(){
async *encode() {
yield this.headers;
const {value} = this;
const { value } = this;
if(utils.isTypedArray(value)) {
if (utils.isTypedArray(value)) {
yield value;
} else {
yield* readBlob(value);
@@ -52,11 +52,15 @@ class FormDataPart {
}
static escapeName(name) {
return String(name).replace(/[\r\n"]/g, (match) => ({
'\r' : '%0D',
'\n' : '%0A',
'"' : '%22',
}[match]));
return String(name).replace(
/[\r\n"]/g,
(match) =>
({
'\r': '%0D',
'\n': '%0A',
'"': '%22',
})[match]
);
}
}
@@ -64,15 +68,15 @@ const formDataToStream = (form, headersHandler, options) => {
const {
tag = 'form-data-boundary',
size = 25,
boundary = tag + '-' + platform.generateString(size, BOUNDARY_ALPHABET)
boundary = tag + '-' + platform.generateString(size, BOUNDARY_ALPHABET),
} = options || {};
if(!utils.isFormData(form)) {
if (!utils.isFormData(form)) {
throw TypeError('FormData instance required');
}
if (boundary.length < 1 || boundary.length > 70) {
throw Error('boundary must be 10-70 characters long')
throw Error('boundary must be 10-70 characters long');
}
const boundaryBytes = textEncoder.encode('--' + boundary + CRLF);
@@ -90,8 +94,8 @@ const formDataToStream = (form, headersHandler, options) => {
contentLength = utils.toFiniteNumber(contentLength);
const computedHeaders = {
'Content-Type': `multipart/form-data; boundary=${boundary}`
}
'Content-Type': `multipart/form-data; boundary=${boundary}`,
};
if (Number.isFinite(contentLength)) {
computedHeaders['Content-Length'] = contentLength;
@@ -99,14 +103,16 @@ const formDataToStream = (form, headersHandler, options) => {
headersHandler && headersHandler(computedHeaders);
return Readable.from((async function *() {
for(const part of parts) {
yield boundaryBytes;
yield* part.encode();
}
return Readable.from(
(async function* () {
for (const part of parts) {
yield boundaryBytes;
yield* part.encode();
}
yield footerBytes;
})());
yield footerBytes;
})()
);
};
export default formDataToStream;

View File

@@ -17,7 +17,7 @@ const DATA_URL_PATTERN = /^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;
* @returns {Buffer|Blob}
*/
export default function fromDataURI(uri, asBlob, options) {
const _Blob = options && options.Blob || platform.classes.Blob;
const _Blob = (options && options.Blob) || platform.classes.Blob;
const protocol = parseProtocol(uri);
if (asBlob === undefined && _Blob) {
@@ -43,7 +43,7 @@ export default function fromDataURI(uri, asBlob, options) {
throw new AxiosError('Blob is not supported', AxiosError.ERR_NOT_SUPPORT);
}
return new _Blob([buffer], {type: mime});
return new _Blob([buffer], { type: mime });
}
return buffer;

View File

@@ -17,4 +17,3 @@ export default function isAbsoluteURL(url) {
return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url);
}

View File

@@ -10,5 +10,5 @@ import utils from '../utils.js';
* @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
*/
export default function isAxiosError(payload) {
return utils.isObject(payload) && (payload.isAxiosError === true);
return utils.isObject(payload) && payload.isAxiosError === true;
}

View File

@@ -1,14 +1,16 @@
import platform from '../platform/index.js';
export default platform.hasStandardBrowserEnv ? ((origin, isMSIE) => (url) => {
url = new URL(url, platform.origin);
export default platform.hasStandardBrowserEnv
? ((origin, isMSIE) => (url) => {
url = new URL(url, platform.origin);
return (
origin.protocol === url.protocol &&
origin.host === url.host &&
(isMSIE || origin.port === url.port)
);
})(
new URL(platform.origin),
platform.navigator && /(msie|trident)/i.test(platform.navigator.userAgent)
) : () => true;
return (
origin.protocol === url.protocol &&
origin.host === url.host &&
(isMSIE || origin.port === url.port)
);
})(
new URL(platform.origin),
platform.navigator && /(msie|trident)/i.test(platform.navigator.userAgent)
)
: () => true;

View File

@@ -5,10 +5,23 @@ import utils from '../utils.js';
// RawAxiosHeaders whose duplicates are ignored by node
// c.f. https://nodejs.org/api/http.html#http_message_headers
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'
'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',
]);
/**
@@ -25,31 +38,32 @@ const ignoreDuplicateOf = utils.toObjectSet([
*
* @returns {Object} Headers parsed into an object
*/
export default rawHeaders => {
export default (rawHeaders) => {
const parsed = {};
let key;
let val;
let i;
rawHeaders && rawHeaders.split('\n').forEach(function parser(line) {
i = line.indexOf(':');
key = line.substring(0, i).trim().toLowerCase();
val = line.substring(i + 1).trim();
rawHeaders &&
rawHeaders.split('\n').forEach(function parser(line) {
i = line.indexOf(':');
key = line.substring(0, i).trim().toLowerCase();
val = line.substring(i + 1).trim();
if (!key || (parsed[key] && ignoreDuplicateOf[key])) {
return;
}
if (key === 'set-cookie') {
if (parsed[key]) {
parsed[key].push(val);
} else {
parsed[key] = [val];
if (!key || (parsed[key] && ignoreDuplicateOf[key])) {
return;
}
} else {
parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
}
});
if (key === 'set-cookie') {
if (parsed[key]) {
parsed[key].push(val);
} else {
parsed[key] = [val];
}
} else {
parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
}
});
return parsed;
};

View File

@@ -2,5 +2,5 @@
export default function parseProtocol(url) {
const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url);
return match && match[1] || '';
return (match && match[1]) || '';
}

View File

@@ -1,12 +1,12 @@
import speedometer from "./speedometer.js";
import throttle from "./throttle.js";
import utils from "../utils.js";
import speedometer from './speedometer.js';
import throttle from './throttle.js';
import utils from '../utils.js';
export const progressEventReducer = (listener, isDownloadStream, freq = 3) => {
let bytesNotified = 0;
const _speedometer = speedometer(50, 250);
return throttle(e => {
return throttle((e) => {
const loaded = e.loaded;
const total = e.lengthComputable ? e.total : undefined;
const progressBytes = loaded - bytesNotified;
@@ -18,27 +18,34 @@ export const progressEventReducer = (listener, isDownloadStream, freq = 3) => {
const data = {
loaded,
total,
progress: total ? (loaded / total) : undefined,
progress: total ? loaded / total : undefined,
bytes: progressBytes,
rate: rate ? rate : undefined,
estimated: rate && total && inRange ? (total - loaded) / rate : undefined,
event: e,
lengthComputable: total != null,
[isDownloadStream ? 'download' : 'upload']: true
[isDownloadStream ? 'download' : 'upload']: true,
};
listener(data);
}, freq);
}
};
export const progressEventDecorator = (total, throttled) => {
const lengthComputable = total != null;
return [(loaded) => throttled[0]({
lengthComputable,
total,
loaded
}), throttled[1]];
}
return [
(loaded) =>
throttled[0]({
lengthComputable,
total,
loaded,
}),
throttled[1],
];
};
export const asyncDecorator = (fn) => (...args) => utils.asap(() => fn(...args));
export const asyncDecorator =
(fn) =>
(...args) =>
utils.asap(() => fn(...args));

View File

@@ -1,15 +1,15 @@
const {asyncIterator} = Symbol;
const { asyncIterator } = Symbol;
const readBlob = async function* (blob) {
if (blob.stream) {
yield* blob.stream()
yield* blob.stream();
} else if (blob.arrayBuffer) {
yield await blob.arrayBuffer()
yield await blob.arrayBuffer();
} else if (blob[asyncIterator]) {
yield* blob[asyncIterator]();
} else {
yield blob;
}
}
};
export default readBlob;

View File

@@ -1,11 +1,11 @@
import platform from "../platform/index.js";
import utils from "../utils.js";
import isURLSameOrigin from "./isURLSameOrigin.js";
import cookies from "./cookies.js";
import buildFullPath from "../core/buildFullPath.js";
import mergeConfig from "../core/mergeConfig.js";
import AxiosHeaders from "../core/AxiosHeaders.js";
import buildURL from "./buildURL.js";
import platform from '../platform/index.js';
import utils from '../utils.js';
import isURLSameOrigin from './isURLSameOrigin.js';
import cookies from './cookies.js';
import buildFullPath from '../core/buildFullPath.js';
import mergeConfig from '../core/mergeConfig.js';
import AxiosHeaders from '../core/AxiosHeaders.js';
import buildURL from './buildURL.js';
export default (config) => {
const newConfig = mergeConfig({}, config);
@@ -14,12 +14,22 @@ export default (config) => {
newConfig.headers = headers = AxiosHeaders.from(headers);
newConfig.url = buildURL(buildFullPath(newConfig.baseURL, newConfig.url, newConfig.allowAbsoluteUrls), config.params, config.paramsSerializer);
newConfig.url = buildURL(
buildFullPath(newConfig.baseURL, newConfig.url, newConfig.allowAbsoluteUrls),
config.params,
config.paramsSerializer
);
// HTTP basic authentication
if (auth) {
headers.set('Authorization', 'Basic ' +
btoa((auth.username || '') + ':' + (auth.password ? unescape(encodeURIComponent(auth.password)) : ''))
headers.set(
'Authorization',
'Basic ' +
btoa(
(auth.username || '') +
':' +
(auth.password ? unescape(encodeURIComponent(auth.password)) : '')
)
);
}
@@ -37,7 +47,7 @@ export default (config) => {
}
});
}
}
}
// Add xsrf header
// This is only done if running in a standard browser environment.
@@ -57,5 +67,4 @@ export default (config) => {
}
return newConfig;
}
};

View File

@@ -48,7 +48,7 @@ function speedometer(samplesCount, min) {
const passed = startedAt && now - startedAt;
return passed ? Math.round(bytesCount * 1000 / passed) : undefined;
return passed ? Math.round((bytesCount * 1000) / passed) : undefined;
};
}

View File

@@ -18,23 +18,23 @@ function throttle(fn, freq) {
timer = null;
}
fn(...args);
}
};
const throttled = (...args) => {
const now = Date.now();
const passed = now - timestamp;
if ( passed >= threshold) {
if (passed >= threshold) {
invoke(args, now);
} else {
lastArgs = args;
if (!timer) {
timer = setTimeout(() => {
timer = null;
invoke(lastArgs)
invoke(lastArgs);
}, threshold - passed);
}
}
}
};
const flush = () => lastArgs && invoke(lastArgs);

View File

@@ -38,11 +38,14 @@ function removeBrackets(key) {
*/
function renderKey(path, key, dots) {
if (!path) return key;
return path.concat(key).map(function each(token, i) {
// eslint-disable-next-line no-param-reassign
token = removeBrackets(token);
return !dots && i ? '[' + token + ']' : token;
}).join(dots ? '.' : '');
return path
.concat(key)
.map(function each(token, i) {
// eslint-disable-next-line no-param-reassign
token = removeBrackets(token);
return !dots && i ? '[' + token + ']' : token;
})
.join(dots ? '.' : '');
}
/**
@@ -92,21 +95,26 @@ function toFormData(obj, formData, options) {
formData = formData || new (PlatformFormData || FormData)();
// eslint-disable-next-line no-param-reassign
options = utils.toFlatObject(options, {
metaTokens: true,
dots: false,
indexes: false
}, false, function defined(option, source) {
// eslint-disable-next-line no-eq-null,eqeqeq
return !utils.isUndefined(source[option]);
});
options = utils.toFlatObject(
options,
{
metaTokens: true,
dots: false,
indexes: false,
},
false,
function defined(option, source) {
// eslint-disable-next-line no-eq-null,eqeqeq
return !utils.isUndefined(source[option]);
}
);
const metaTokens = options.metaTokens;
// eslint-disable-next-line no-use-before-define
const visitor = options.visitor || defaultVisitor;
const dots = options.dots;
const indexes = options.indexes;
const _Blob = options.Blob || typeof Blob !== 'undefined' && Blob;
const _Blob = options.Blob || (typeof Blob !== 'undefined' && Blob);
const useBlob = _Blob && utils.isSpecCompliantForm(formData);
if (!utils.isFunction(visitor)) {
@@ -148,6 +156,11 @@ function toFormData(obj, formData, options) {
function defaultVisitor(value, key, path) {
let arr = value;
if (utils.isReactNative(formData) && utils.isReactNativeBlob(value)) {
formData.append(renderKey(path, key, dots), convertValue(value));
return false;
}
if (value && !path && typeof value === 'object') {
if (utils.endsWith(key, '{}')) {
// eslint-disable-next-line no-param-reassign
@@ -156,17 +169,22 @@ function toFormData(obj, formData, options) {
value = JSON.stringify(value);
} else if (
(utils.isArray(value) && isFlatArray(value)) ||
((utils.isFileList(value) || utils.endsWith(key, '[]')) && (arr = utils.toArray(value))
)) {
((utils.isFileList(value) || utils.endsWith(key, '[]')) && (arr = utils.toArray(value)))
) {
// eslint-disable-next-line no-param-reassign
key = removeBrackets(key);
arr.forEach(function each(el, index) {
!(utils.isUndefined(el) || el === null) && formData.append(
// eslint-disable-next-line no-nested-ternary
indexes === true ? renderKey([key], index, dots) : (indexes === null ? key : key + '[]'),
convertValue(el)
);
!(utils.isUndefined(el) || el === null) &&
formData.append(
// eslint-disable-next-line no-nested-ternary
indexes === true
? renderKey([key], index, dots)
: indexes === null
? key
: key + '[]',
convertValue(el)
);
});
return false;
}
@@ -186,7 +204,7 @@ function toFormData(obj, formData, options) {
const exposedHelpers = Object.assign(predicates, {
defaultVisitor,
convertValue,
isVisitable
isVisitable,
});
function build(value, path) {
@@ -199,9 +217,9 @@ function toFormData(obj, formData, options) {
stack.push(value);
utils.forEach(value, function each(el, key) {
const result = !(utils.isUndefined(el) || el === null) && visitor.call(
formData, el, utils.isString(key) ? key.trim() : key, path, exposedHelpers
);
const result =
!(utils.isUndefined(el) || el === null) &&
visitor.call(formData, el, utils.isString(key) ? key.trim() : key, path, exposedHelpers);
if (result === true) {
build(el, path ? path.concat(key) : [key]);

View File

@@ -6,7 +6,7 @@ import platform from '../platform/index.js';
export default function toURLEncodedForm(data, options) {
return toFormData(data, new platform.classes.URLSearchParams(), {
visitor: function(value, key, path, helpers) {
visitor: function (value, key, path, helpers) {
if (platform.isNode && utils.isBuffer(value)) {
this.append(key, value.toString('base64'));
return false;
@@ -14,6 +14,6 @@ export default function toURLEncodedForm(data, options) {
return helpers.defaultVisitor.apply(this, arguments);
},
...options
...options,
});
}

View File

@@ -1,4 +1,3 @@
export const streamChunk = function* (chunk, chunkSize) {
let len = chunk.byteLength;
@@ -15,13 +14,13 @@ export const streamChunk = function* (chunk, chunkSize) {
yield chunk.slice(pos, end);
pos = end;
}
}
};
export const readBytes = async function* (iterable, chunkSize) {
for await (const chunk of readStream(iterable)) {
yield* streamChunk(chunk, chunkSize);
}
}
};
const readStream = async function* (stream) {
if (stream[Symbol.asyncIterator]) {
@@ -32,7 +31,7 @@ const readStream = async function* (stream) {
const reader = stream.getReader();
try {
for (;;) {
const {done, value} = await reader.read();
const { done, value } = await reader.read();
if (done) {
break;
}
@@ -41,7 +40,7 @@ const readStream = async function* (stream) {
} finally {
await reader.cancel();
}
}
};
export const trackStream = (stream, chunkSize, onProgress, onFinish) => {
const iterator = readBytes(stream, chunkSize);
@@ -53,35 +52,38 @@ export const trackStream = (stream, chunkSize, onProgress, onFinish) => {
done = true;
onFinish && onFinish(e);
}
}
};
return new ReadableStream({
async pull(controller) {
try {
const {done, value} = await iterator.next();
return new ReadableStream(
{
async pull(controller) {
try {
const { done, value } = await iterator.next();
if (done) {
_onFinish();
controller.close();
return;
if (done) {
_onFinish();
controller.close();
return;
}
let len = value.byteLength;
if (onProgress) {
let loadedBytes = (bytes += len);
onProgress(loadedBytes);
}
controller.enqueue(new Uint8Array(value));
} catch (err) {
_onFinish(err);
throw err;
}
let len = value.byteLength;
if (onProgress) {
let loadedBytes = bytes += len;
onProgress(loadedBytes);
}
controller.enqueue(new Uint8Array(value));
} catch (err) {
_onFinish(err);
throw err;
}
},
cancel(reason) {
_onFinish(reason);
return iterator.return();
},
},
cancel(reason) {
_onFinish(reason);
return iterator.return();
{
highWaterMark: 2,
}
}, {
highWaterMark: 2
})
}
);
};

View File

@@ -1,6 +1,6 @@
'use strict';
import {VERSION} from '../env/data.js';
import { VERSION } from '../env/data.js';
import AxiosError from '../core/AxiosError.js';
const validators = {};
@@ -25,7 +25,15 @@ const deprecatedWarnings = {};
*/
validators.transitional = function transitional(validator, version, message) {
function formatMessage(opt, desc) {
return '[Axios v' + VERSION + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : '');
return (
'[Axios v' +
VERSION +
"] Transitional option '" +
opt +
"'" +
desc +
(message ? '. ' + message : '')
);
}
// eslint-disable-next-line func-names
@@ -57,7 +65,7 @@ validators.spelling = function spelling(correctSpelling) {
// eslint-disable-next-line no-console
console.warn(`${opt} is likely a misspelling of ${correctSpelling}`);
return true;
}
};
};
/**
@@ -83,7 +91,10 @@ function assertOptions(options, schema, allowUnknown) {
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);
throw new AxiosError(
'option ' + opt + ' must be ' + result,
AxiosError.ERR_BAD_OPTION_VALUE
);
}
continue;
}
@@ -95,5 +106,5 @@ function assertOptions(options, schema, allowUnknown) {
export default {
assertOptions,
validators
validators,
};