From cd1c223bec450dcdad9d111baa02ebd7be69989b Mon Sep 17 00:00:00 2001 From: Raj Kumar Panda Date: Mon, 3 Feb 2025 11:15:47 +0530 Subject: [PATCH] Revert "Merge pull request #194 from step-security/fix_Alerts-Vuln" This reverts commit 86c1f7ee491c8725c89991f5d0aa37b1307b6db2, reversing changes made to f2305043983a6284c2d536eac6e1cec33c2b719e. --- dist/index.js | 2803 +++++++++++++-------------------------------- package-lock.json | 60 +- 2 files changed, 845 insertions(+), 2018 deletions(-) diff --git a/dist/index.js b/dist/index.js index d1f2c90..90e6f53 100644 --- a/dist/index.js +++ b/dist/index.js @@ -8557,8 +8557,8 @@ const braces = (input, options = {}) => { let output = []; if (Array.isArray(input)) { - for (const pattern of input) { - const result = braces.create(pattern, options); + for (let pattern of input) { + let result = braces.create(pattern, options); if (Array.isArray(result)) { output.push(...result); } else { @@ -8692,7 +8692,7 @@ braces.create = (input, options = {}) => { return [input]; } - return options.expand !== true + return options.expand !== true ? braces.compile(input, options) : braces.expand(input, options); }; @@ -8716,32 +8716,30 @@ const fill = __nccwpck_require__(6330); const utils = __nccwpck_require__(5207); const compile = (ast, options = {}) => { - const walk = (node, parent = {}) => { - const invalidBlock = utils.isInvalidBrace(parent); - const invalidNode = node.invalid === true && options.escapeInvalid === true; - const invalid = invalidBlock === true || invalidNode === true; - const prefix = options.escapeInvalid === true ? '\\' : ''; + let walk = (node, parent = {}) => { + let invalidBlock = utils.isInvalidBrace(parent); + let invalidNode = node.invalid === true && options.escapeInvalid === true; + let invalid = invalidBlock === true || invalidNode === true; + let prefix = options.escapeInvalid === true ? '\\' : ''; let output = ''; if (node.isOpen === true) { return prefix + node.value; } - if (node.isClose === true) { - console.log('node.isClose', prefix, node.value); return prefix + node.value; } if (node.type === 'open') { - return invalid ? prefix + node.value : '('; + return invalid ? (prefix + node.value) : '('; } if (node.type === 'close') { - return invalid ? prefix + node.value : ')'; + return invalid ? (prefix + node.value) : ')'; } if (node.type === 'comma') { - return node.prev.type === 'comma' ? '' : invalid ? node.value : '|'; + return node.prev.type === 'comma' ? '' : (invalid ? node.value : '|'); } if (node.value) { @@ -8749,8 +8747,8 @@ const compile = (ast, options = {}) => { } if (node.nodes && node.ranges > 0) { - const args = utils.reduce(node.nodes); - const range = fill(...args, { ...options, wrap: false, toRegex: true, strictZeros: true }); + let args = utils.reduce(node.nodes); + let range = fill(...args, { ...options, wrap: false, toRegex: true }); if (range.length !== 0) { return args.length > 1 && range.length > 1 ? `(${range})` : range; @@ -8758,11 +8756,10 @@ const compile = (ast, options = {}) => { } if (node.nodes) { - for (const child of node.nodes) { + for (let child of node.nodes) { output += walk(child, node); } } - return output; }; @@ -8781,7 +8778,7 @@ module.exports = compile; module.exports = { - MAX_LENGTH: 10000, + MAX_LENGTH: 1024 * 64, // Digits CHAR_0: '0', /* 0 */ @@ -8850,7 +8847,7 @@ const stringify = __nccwpck_require__(8750); const utils = __nccwpck_require__(5207); const append = (queue = '', stash = '', enclose = false) => { - const result = []; + let result = []; queue = [].concat(queue); stash = [].concat(stash); @@ -8860,15 +8857,15 @@ const append = (queue = '', stash = '', enclose = false) => { return enclose ? utils.flatten(stash).map(ele => `{${ele}}`) : stash; } - for (const item of queue) { + for (let item of queue) { if (Array.isArray(item)) { - for (const value of item) { + for (let value of item) { result.push(append(value, stash, enclose)); } } else { for (let ele of stash) { if (enclose === true && typeof ele === 'string') ele = `{${ele}}`; - result.push(Array.isArray(ele) ? append(item, ele, enclose) : item + ele); + result.push(Array.isArray(ele) ? append(item, ele, enclose) : (item + ele)); } } } @@ -8876,9 +8873,9 @@ const append = (queue = '', stash = '', enclose = false) => { }; const expand = (ast, options = {}) => { - const rangeLimit = options.rangeLimit === undefined ? 1000 : options.rangeLimit; + let rangeLimit = options.rangeLimit === void 0 ? 1000 : options.rangeLimit; - const walk = (node, parent = {}) => { + let walk = (node, parent = {}) => { node.queue = []; let p = parent; @@ -8900,7 +8897,7 @@ const expand = (ast, options = {}) => { } if (node.nodes && node.ranges > 0) { - const args = utils.reduce(node.nodes); + let args = utils.reduce(node.nodes); if (utils.exceedsLimit(...args, options.step, rangeLimit)) { throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.'); @@ -8916,7 +8913,7 @@ const expand = (ast, options = {}) => { return; } - const enclose = utils.encloseBrace(node); + let enclose = utils.encloseBrace(node); let queue = node.queue; let block = node; @@ -8926,7 +8923,7 @@ const expand = (ast, options = {}) => { } for (let i = 0; i < node.nodes.length; i++) { - const child = node.nodes[i]; + let child = node.nodes[i]; if (child.type === 'comma' && node.type === 'brace') { if (i === 1) queue.push(''); @@ -8999,21 +8996,22 @@ const parse = (input, options = {}) => { throw new TypeError('Expected a string'); } - const opts = options || {}; - const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; + let opts = options || {}; + let max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; if (input.length > max) { throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`); } - const ast = { type: 'root', input, nodes: [] }; - const stack = [ast]; + let ast = { type: 'root', input, nodes: [] }; + let stack = [ast]; let block = ast; let prev = ast; let brackets = 0; - const length = input.length; + let length = input.length; let index = 0; let depth = 0; let value; + let memo = {}; /** * Helpers @@ -9076,6 +9074,7 @@ const parse = (input, options = {}) => { if (value === CHAR_LEFT_SQUARE_BRACKET) { brackets++; + let closed = true; let next; while (index < length && (next = advance())) { @@ -9131,7 +9130,7 @@ const parse = (input, options = {}) => { */ if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) { - const open = value; + let open = value; let next; if (options.keepQuotes !== true) { @@ -9163,8 +9162,8 @@ const parse = (input, options = {}) => { if (value === CHAR_LEFT_CURLY_BRACE) { depth++; - const dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true; - const brace = { + let dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true; + let brace = { type: 'brace', open: true, close: false, @@ -9191,7 +9190,7 @@ const parse = (input, options = {}) => { continue; } - const type = 'close'; + let type = 'close'; block = stack.pop(); block.close = true; @@ -9209,7 +9208,7 @@ const parse = (input, options = {}) => { if (value === CHAR_COMMA && depth > 0) { if (block.ranges > 0) { block.ranges = 0; - const open = block.nodes.shift(); + let open = block.nodes.shift(); block.nodes = [open, { type: 'text', value: stringify(block) }]; } @@ -9223,7 +9222,7 @@ const parse = (input, options = {}) => { */ if (value === CHAR_DOT && depth > 0 && block.commas === 0) { - const siblings = block.nodes; + let siblings = block.nodes; if (depth === 0 || siblings.length === 0) { push({ type: 'text', value }); @@ -9250,7 +9249,7 @@ const parse = (input, options = {}) => { if (prev.type === 'range') { siblings.pop(); - const before = siblings[siblings.length - 1]; + let before = siblings[siblings.length - 1]; before.value += prev.value + value; prev = before; block.ranges--; @@ -9283,8 +9282,8 @@ const parse = (input, options = {}) => { }); // get the location of the block on parent.nodes (block's siblings) - const parent = stack[stack.length - 1]; - const index = parent.nodes.indexOf(block); + let parent = stack[stack.length - 1]; + let index = parent.nodes.indexOf(block); // replace the (invalid) block with it's nodes parent.nodes.splice(index, 1, ...block.nodes); } @@ -9308,9 +9307,9 @@ module.exports = parse; const utils = __nccwpck_require__(5207); module.exports = (ast, options = {}) => { - const stringify = (node, parent = {}) => { - const invalidBlock = options.escapeInvalid && utils.isInvalidBrace(parent); - const invalidNode = node.invalid === true && options.escapeInvalid === true; + let stringify = (node, parent = {}) => { + let invalidBlock = options.escapeInvalid && utils.isInvalidBrace(parent); + let invalidNode = node.invalid === true && options.escapeInvalid === true; let output = ''; if (node.value) { @@ -9325,7 +9324,7 @@ module.exports = (ast, options = {}) => { } if (node.nodes) { - for (const child of node.nodes) { + for (let child of node.nodes) { output += stringify(child); } } @@ -9376,7 +9375,7 @@ exports.exceedsLimit = (min, max, step = 1, limit) => { */ exports.escapeNode = (block, n = 0, type) => { - const node = block.nodes[n]; + let node = block.nodes[n]; if (!node) return; if ((type && node.type === type) || node.type === 'open' || node.type === 'close') { @@ -9445,23 +9444,13 @@ exports.reduce = nodes => nodes.reduce((acc, node) => { exports.flatten = (...args) => { const result = []; - const flat = arr => { for (let i = 0; i < arr.length; i++) { - const ele = arr[i]; - - if (Array.isArray(ele)) { - flat(ele); - continue; - } - - if (ele !== undefined) { - result.push(ele); - } + let ele = arr[i]; + Array.isArray(ele) ? flat(ele, result) : ele !== void 0 && result.push(ele); } return result; }; - flat(args); return result; }; @@ -10736,7 +10725,7 @@ const toMaxLen = (input, maxLength) => { return negative ? ('-' + input) : input; }; -const toSequence = (parts, options, maxLen) => { +const toSequence = (parts, options) => { parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0); parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0); @@ -10746,11 +10735,11 @@ const toSequence = (parts, options, maxLen) => { let result; if (parts.positives.length) { - positives = parts.positives.map(v => toMaxLen(String(v), maxLen)).join('|'); + positives = parts.positives.join('|'); } if (parts.negatives.length) { - negatives = `-(${prefix}${parts.negatives.map(v => toMaxLen(String(v), maxLen)).join('|')})`; + negatives = `-(${prefix}${parts.negatives.join('|')})`; } if (positives && negatives) { @@ -10848,7 +10837,7 @@ const fillNumbers = (start, end, step = 1, options = {}) => { if (options.toRegex === true) { return step > 1 - ? toSequence(parts, options, maxLen) + ? toSequence(parts, options) : toRegex(range, null, { wrap: false, ...options }); } @@ -10860,6 +10849,7 @@ const fillLetters = (start, end, step = 1, options = {}) => { return invalidRange(start, end, options); } + let format = options.transform || (val => String.fromCharCode(val)); let a = `${start}`.charCodeAt(0); let b = `${end}`.charCodeAt(0); @@ -10959,30 +10949,6 @@ var Writable = (__nccwpck_require__(2781).Writable); var assert = __nccwpck_require__(9491); var debug = __nccwpck_require__(1133); -// Whether to use the native URL object or the legacy url module -var useNativeURL = false; -try { - assert(new URL()); -} -catch (error) { - useNativeURL = error.code === "ERR_INVALID_URL"; -} - -// URL fields to preserve in copy operations -var preservedUrlFields = [ - "auth", - "host", - "hostname", - "href", - "path", - "pathname", - "port", - "protocol", - "query", - "search", - "hash", -]; - // Create handlers that pass events from native requests var events = ["abort", "aborted", "connect", "error", "socket", "timeout"]; var eventHandlers = Object.create(null); @@ -10992,20 +10958,19 @@ events.forEach(function (event) { }; }); -// Error types with codes var InvalidUrlError = createErrorType( "ERR_INVALID_URL", "Invalid URL", TypeError ); +// Error types with codes var RedirectionError = createErrorType( "ERR_FR_REDIRECTION_FAILURE", "Redirected request failed" ); var TooManyRedirectsError = createErrorType( "ERR_FR_TOO_MANY_REDIRECTS", - "Maximum number of redirects exceeded", - RedirectionError + "Maximum number of redirects exceeded" ); var MaxBodyLengthExceededError = createErrorType( "ERR_FR_MAX_BODY_LENGTH_EXCEEDED", @@ -11040,13 +11005,7 @@ function RedirectableRequest(options, responseCallback) { // React to responses of native requests var self = this; this._onNativeResponse = function (response) { - try { - self._processResponse(response); - } - catch (cause) { - self.emit("error", cause instanceof RedirectionError ? - cause : new RedirectionError({ cause: cause })); - } + self._processResponse(response); }; // Perform the first request @@ -11264,7 +11223,8 @@ RedirectableRequest.prototype._performRequest = function () { var protocol = this._options.protocol; var nativeProtocol = this._options.nativeProtocols[protocol]; if (!nativeProtocol) { - throw new TypeError("Unsupported protocol " + protocol); + this.emit("error", new TypeError("Unsupported protocol " + protocol)); + return; } // If specified, use the agent corresponding to the protocol @@ -11363,7 +11323,8 @@ RedirectableRequest.prototype._processResponse = function (response) { // RFC7231§6.4: A client SHOULD detect and intervene // in cyclical redirections (i.e., "infinite" redirection loops). if (++this._redirectCount > this._options.maxRedirects) { - throw new TooManyRedirectsError(); + this.emit("error", new TooManyRedirectsError()); + return; } // Store the request headers if applicable @@ -11397,24 +11358,34 @@ RedirectableRequest.prototype._processResponse = function (response) { var currentHostHeader = removeMatchingHeaders(/^host$/i, this._options.headers); // If the redirect is relative, carry over the host of the last request - var currentUrlParts = parseUrl(this._currentUrl); + var currentUrlParts = url.parse(this._currentUrl); var currentHost = currentHostHeader || currentUrlParts.host; var currentUrl = /^\w+:/.test(location) ? this._currentUrl : url.format(Object.assign(currentUrlParts, { host: currentHost })); + // Determine the URL of the redirection + var redirectUrl; + try { + redirectUrl = url.resolve(currentUrl, location); + } + catch (cause) { + this.emit("error", new RedirectionError({ cause: cause })); + return; + } + // Create the redirected request - var redirectUrl = resolveUrl(location, currentUrl); - debug("redirecting to", redirectUrl.href); + debug("redirecting to", redirectUrl); this._isRedirect = true; - spreadUrlObject(redirectUrl, this._options); + var redirectUrlParts = url.parse(redirectUrl); + Object.assign(this._options, redirectUrlParts); // Drop confidential headers when redirecting to a less secure protocol // or to a different domain that is not a superdomain - if (redirectUrl.protocol !== currentUrlParts.protocol && - redirectUrl.protocol !== "https:" || - redirectUrl.host !== currentHost && - !isSubdomain(redirectUrl.host, currentHost)) { - removeMatchingHeaders(/^(?:(?:proxy-)?authorization|cookie)$/i, this._options.headers); + if (redirectUrlParts.protocol !== currentUrlParts.protocol && + redirectUrlParts.protocol !== "https:" || + redirectUrlParts.host !== currentHost && + !isSubdomain(redirectUrlParts.host, currentHost)) { + removeMatchingHeaders(/^(?:authorization|cookie)$/i, this._options.headers); } // Evaluate the beforeRedirect callback @@ -11428,12 +11399,23 @@ RedirectableRequest.prototype._processResponse = function (response) { method: method, headers: requestHeaders, }; - beforeRedirect(this._options, responseDetails, requestDetails); + try { + beforeRedirect(this._options, responseDetails, requestDetails); + } + catch (err) { + this.emit("error", err); + return; + } this._sanitizeOptions(this._options); } // Perform the redirected request - this._performRequest(); + try { + this._performRequest(); + } + catch (cause) { + this.emit("error", new RedirectionError({ cause: cause })); + } }; // Wraps the key/value object of protocols with redirect functionality @@ -11453,16 +11435,27 @@ function wrap(protocols) { // Executes a request, following redirects function request(input, options, callback) { - // Parse parameters, ensuring that input is an object - if (isURL(input)) { - input = spreadUrlObject(input); + // Parse parameters + if (isString(input)) { + var parsed; + try { + parsed = urlToOptions(new URL(input)); + } + catch (err) { + /* istanbul ignore next */ + parsed = url.parse(input); + } + if (!isString(parsed.protocol)) { + throw new InvalidUrlError({ input }); + } + input = parsed; } - else if (isString(input)) { - input = spreadUrlObject(parseUrl(input)); + else if (URL && (input instanceof URL)) { + input = urlToOptions(input); } else { callback = options; - options = validateUrl(input); + options = input; input = { protocol: protocol }; } if (isFunction(options)) { @@ -11501,57 +11494,27 @@ function wrap(protocols) { return exports; } +/* istanbul ignore next */ function noop() { /* empty */ } -function parseUrl(input) { - var parsed; - /* istanbul ignore else */ - if (useNativeURL) { - parsed = new URL(input); - } - else { - // Ensure the URL is valid and absolute - parsed = validateUrl(url.parse(input)); - if (!isString(parsed.protocol)) { - throw new InvalidUrlError({ input }); - } - } - return parsed; -} - -function resolveUrl(relative, base) { - /* istanbul ignore next */ - return useNativeURL ? new URL(relative, base) : parseUrl(url.resolve(base, relative)); -} - -function validateUrl(input) { - if (/^\[/.test(input.hostname) && !/^\[[:0-9a-f]+\]$/i.test(input.hostname)) { - throw new InvalidUrlError({ input: input.href || input }); - } - if (/^\[/.test(input.host) && !/^\[[:0-9a-f]+\](:\d+)?$/i.test(input.host)) { - throw new InvalidUrlError({ input: input.href || input }); - } - return input; -} - -function spreadUrlObject(urlObject, target) { - var spread = target || {}; - for (var key of preservedUrlFields) { - spread[key] = urlObject[key]; - } - - // Fix IPv6 hostname - if (spread.hostname.startsWith("[")) { - spread.hostname = spread.hostname.slice(1, -1); - } - // Ensure port is a number - if (spread.port !== "") { - spread.port = Number(spread.port); +// from https://github.com/nodejs/node/blob/master/lib/internal/url.js +function urlToOptions(urlObject) { + var options = { + protocol: urlObject.protocol, + hostname: urlObject.hostname.startsWith("[") ? + /* istanbul ignore next */ + urlObject.hostname.slice(1, -1) : + urlObject.hostname, + hash: urlObject.hash, + search: urlObject.search, + pathname: urlObject.pathname, + path: urlObject.pathname + urlObject.search, + href: urlObject.href, + }; + if (urlObject.port !== "") { + options.port = Number(urlObject.port); } - // Concatenate path - spread.path = spread.search ? spread.pathname + spread.search : spread.pathname; - - return spread; + return options; } function removeMatchingHeaders(regex, headers) { @@ -11577,16 +11540,8 @@ function createErrorType(code, message, baseClass) { // Attach constructor and set default properties CustomError.prototype = new (baseClass || Error)(); - Object.defineProperties(CustomError.prototype, { - constructor: { - value: CustomError, - enumerable: false, - }, - name: { - value: "Error [" + code + "]", - enumerable: false, - }, - }); + CustomError.prototype.constructor = CustomError; + CustomError.prototype.name = "Error [" + code + "]"; return CustomError; } @@ -11616,10 +11571,6 @@ function isBuffer(value) { return typeof value === "object" && ("length" in value); } -function isURL(value) { - return URL && value instanceof URL; -} - // Exports module.exports = wrap({ http: http, https: https }); module.exports.wrap = wrap; @@ -16358,12 +16309,7 @@ const util = __nccwpck_require__(3837); const braces = __nccwpck_require__(610); const picomatch = __nccwpck_require__(8569); const utils = __nccwpck_require__(479); - -const isEmptyString = v => v === '' || v === './'; -const hasBraces = v => { - const index = v.indexOf('{'); - return index > -1 && v.indexOf('}', index) > -1; -}; +const isEmptyString = val => val === '' || val === './'; /** * Returns an array of strings that match one or more glob patterns. @@ -16804,7 +16750,7 @@ micromatch.parse = (patterns, options) => { micromatch.braces = (pattern, options) => { if (typeof pattern !== 'string') throw new TypeError('Expected a string'); - if ((options && options.nobrace === true) || !hasBraces(pattern)) { + if ((options && options.nobrace === true) || !/\{.*\}/.test(pattern)) { return [pattern]; } return braces(pattern, options); @@ -16823,8 +16769,6 @@ micromatch.braceExpand = (pattern, options) => { * Expose micromatch */ -// exposed for tests -micromatch.hasBraces = hasBraces; module.exports = micromatch; @@ -20237,7 +20181,6 @@ const MockAgent = __nccwpck_require__(6771) const MockPool = __nccwpck_require__(6193) const mockErrors = __nccwpck_require__(888) const ProxyAgent = __nccwpck_require__(7858) -const RetryHandler = __nccwpck_require__(2286) const { getGlobalDispatcher, setGlobalDispatcher } = __nccwpck_require__(1892) const DecoratorHandler = __nccwpck_require__(6930) const RedirectHandler = __nccwpck_require__(2860) @@ -20259,7 +20202,6 @@ module.exports.Pool = Pool module.exports.BalancedPool = BalancedPool module.exports.Agent = Agent module.exports.ProxyAgent = ProxyAgent -module.exports.RetryHandler = RetryHandler module.exports.DecoratorHandler = DecoratorHandler module.exports.RedirectHandler = RedirectHandler @@ -21160,7 +21102,6 @@ function request (opts, callback) { } module.exports = request -module.exports.RequestHandler = RequestHandler /***/ }), @@ -21543,8 +21484,6 @@ const kBody = Symbol('kBody') const kAbort = Symbol('abort') const kContentType = Symbol('kContentType') -const noop = () => {} - module.exports = class BodyReadable extends Readable { constructor ({ resume, @@ -21678,50 +21617,37 @@ module.exports = class BodyReadable extends Readable { return this[kBody] } - dump (opts) { + async dump (opts) { let limit = opts && Number.isFinite(opts.limit) ? opts.limit : 262144 const signal = opts && opts.signal - + const abortFn = () => { + this.destroy() + } + let signalListenerCleanup if (signal) { - try { - if (typeof signal !== 'object' || !('aborted' in signal)) { - throw new InvalidArgumentError('signal must be an AbortSignal') - } - util.throwIfAborted(signal) - } catch (err) { - return Promise.reject(err) + if (typeof signal !== 'object' || !('aborted' in signal)) { + throw new InvalidArgumentError('signal must be an AbortSignal') } + util.throwIfAborted(signal) + signalListenerCleanup = util.addAbortListener(signal, abortFn) } - - if (this.closed) { - return Promise.resolve(null) + try { + for await (const chunk of this) { + util.throwIfAborted(signal) + limit -= Buffer.byteLength(chunk) + if (limit < 0) { + return + } + } + } catch { + util.throwIfAborted(signal) + } finally { + if (typeof signalListenerCleanup === 'function') { + signalListenerCleanup() + } else if (signalListenerCleanup) { + signalListenerCleanup[Symbol.dispose]() + } } - - return new Promise((resolve, reject) => { - const signalListenerCleanup = signal - ? util.addAbortListener(signal, () => { - this.destroy() - }) - : noop - - this - .on('close', function () { - signalListenerCleanup() - if (signal && signal.aborted) { - reject(signal.reason || Object.assign(new Error('The operation was aborted'), { name: 'AbortError' })) - } else { - resolve(null) - } - }) - .on('error', noop) - .on('data', function (chunk) { - limit -= chunk.length - if (limit <= 0) { - this.destroy() - } - }) - .resume() - }) } } @@ -23101,13 +23027,13 @@ module.exports = { /***/ }), /***/ 9174: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ ((module) => { "use strict"; module.exports = { - kConstruct: (__nccwpck_require__(2785).kConstruct) + kConstruct: Symbol('constructable') } @@ -24093,9 +24019,11 @@ class Parser { socket[kReset] = true } - const pause = request.onHeaders(statusCode, headers, this.resume, statusText) === false - - if (request.aborted) { + let pause + try { + pause = request.onHeaders(statusCode, headers, this.resume, statusText) === false + } catch (err) { + util.destroy(socket, err) return -1 } @@ -24142,8 +24070,13 @@ class Parser { this.bytesRead += buf.length - if (request.onData(buf) === false) { - return constants.ERROR.PAUSED + try { + if (request.onData(buf) === false) { + return constants.ERROR.PAUSED + } + } catch (err) { + util.destroy(socket, err) + return -1 } } @@ -24184,7 +24117,11 @@ class Parser { return -1 } - request.onComplete(headers) + try { + request.onComplete(headers) + } catch (err) { + errorRequest(client, request, err) + } client[kQueue][client[kRunningIdx]++] = null @@ -24348,7 +24285,7 @@ async function connect (client) { const idx = hostname.indexOf(']') assert(idx !== -1) - const ip = hostname.substring(1, idx) + const ip = hostname.substr(1, idx - 1) assert(net.isIP(ip)) hostname = ip @@ -24847,7 +24784,6 @@ function writeH2 (client, session, request) { return false } - /** @type {import('node:http2').ClientHttp2Stream} */ let stream const h2State = client[kHTTP2SessionState] @@ -24943,10 +24879,14 @@ function writeH2 (client, session, request) { const shouldEndStream = method === 'GET' || method === 'HEAD' if (expectContinue) { headers[HTTP2_HEADER_EXPECT] = '100-continue' + /** + * @type {import('node:http2').ClientHttp2Stream} + */ stream = session.request(headers, { endStream: shouldEndStream, signal }) stream.once('continue', writeBodyH2) } else { + /** @type {import('node:http2').ClientHttp2Stream} */ stream = session.request(headers, { endStream: shouldEndStream, signal @@ -24958,9 +24898,7 @@ function writeH2 (client, session, request) { ++h2State.openStreams stream.once('response', headers => { - const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers - - if (request.onHeaders(Number(statusCode), realHeaders, stream.resume.bind(stream), '') === false) { + if (request.onHeaders(Number(headers[HTTP2_HEADER_STATUS]), headers, stream.resume.bind(stream), '') === false) { stream.pause() } }) @@ -24970,17 +24908,13 @@ function writeH2 (client, session, request) { }) stream.on('data', (chunk) => { - if (request.onData(chunk) === false) { - stream.pause() - } + if (request.onData(chunk) === false) stream.pause() }) stream.once('close', () => { h2State.openStreams -= 1 // TODO(HTTP/2): unref only if current streams count is 0 - if (h2State.openStreams === 0) { - session.unref() - } + if (h2State.openStreams === 0) session.unref() }) stream.once('error', function (err) { @@ -25140,11 +25074,7 @@ function writeStream ({ h2stream, body, client, request, socket, contentLength, } } const onAbort = function () { - if (finished) { - return - } - const err = new RequestAbortedError() - queueMicrotask(() => onFinished(err)) + onFinished(new RequestAbortedError()) } const onFinished = function (err) { if (finished) { @@ -26548,132 +26478,6 @@ function onConnectTimeout (socket) { module.exports = buildConnector -/***/ }), - -/***/ 4462: -/***/ ((module) => { - -"use strict"; - - -/** @type {Record} */ -const headerNameLowerCasedRecord = {} - -// https://developer.mozilla.org/docs/Web/HTTP/Headers -const wellknownHeaderNames = [ - 'Accept', - 'Accept-Encoding', - 'Accept-Language', - 'Accept-Ranges', - 'Access-Control-Allow-Credentials', - 'Access-Control-Allow-Headers', - 'Access-Control-Allow-Methods', - 'Access-Control-Allow-Origin', - 'Access-Control-Expose-Headers', - 'Access-Control-Max-Age', - 'Access-Control-Request-Headers', - 'Access-Control-Request-Method', - 'Age', - 'Allow', - 'Alt-Svc', - 'Alt-Used', - 'Authorization', - 'Cache-Control', - 'Clear-Site-Data', - 'Connection', - 'Content-Disposition', - 'Content-Encoding', - 'Content-Language', - 'Content-Length', - 'Content-Location', - 'Content-Range', - 'Content-Security-Policy', - 'Content-Security-Policy-Report-Only', - 'Content-Type', - 'Cookie', - 'Cross-Origin-Embedder-Policy', - 'Cross-Origin-Opener-Policy', - 'Cross-Origin-Resource-Policy', - 'Date', - 'Device-Memory', - 'Downlink', - 'ECT', - 'ETag', - 'Expect', - 'Expect-CT', - 'Expires', - 'Forwarded', - 'From', - 'Host', - 'If-Match', - 'If-Modified-Since', - 'If-None-Match', - 'If-Range', - 'If-Unmodified-Since', - 'Keep-Alive', - 'Last-Modified', - 'Link', - 'Location', - 'Max-Forwards', - 'Origin', - 'Permissions-Policy', - 'Pragma', - 'Proxy-Authenticate', - 'Proxy-Authorization', - 'RTT', - 'Range', - 'Referer', - 'Referrer-Policy', - 'Refresh', - 'Retry-After', - 'Sec-WebSocket-Accept', - 'Sec-WebSocket-Extensions', - 'Sec-WebSocket-Key', - 'Sec-WebSocket-Protocol', - 'Sec-WebSocket-Version', - 'Server', - 'Server-Timing', - 'Service-Worker-Allowed', - 'Service-Worker-Navigation-Preload', - 'Set-Cookie', - 'SourceMap', - 'Strict-Transport-Security', - 'Supports-Loading-Mode', - 'TE', - 'Timing-Allow-Origin', - 'Trailer', - 'Transfer-Encoding', - 'Upgrade', - 'Upgrade-Insecure-Requests', - 'User-Agent', - 'Vary', - 'Via', - 'WWW-Authenticate', - 'X-Content-Type-Options', - 'X-DNS-Prefetch-Control', - 'X-Frame-Options', - 'X-Permitted-Cross-Domain-Policies', - 'X-Powered-By', - 'X-Requested-With', - 'X-XSS-Protection' -] - -for (let i = 0; i < wellknownHeaderNames.length; ++i) { - const key = wellknownHeaderNames[i] - const lowerCasedKey = key.toLowerCase() - headerNameLowerCasedRecord[key] = headerNameLowerCasedRecord[lowerCasedKey] = - lowerCasedKey -} - -// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`. -Object.setPrototypeOf(headerNameLowerCasedRecord, null) - -module.exports = { - wellknownHeaderNames, - headerNameLowerCasedRecord -} - - /***/ }), /***/ 8045: @@ -26875,19 +26679,6 @@ class ResponseExceededMaxSizeError extends UndiciError { } } -class RequestRetryError extends UndiciError { - constructor (message, code, { headers, data }) { - super(message) - Error.captureStackTrace(this, RequestRetryError) - this.name = 'RequestRetryError' - this.message = message || 'Request retry error' - this.code = 'UND_ERR_REQ_RETRY' - this.statusCode = code - this.data = data - this.headers = headers - } -} - module.exports = { HTTPParserError, UndiciError, @@ -26907,8 +26698,7 @@ module.exports = { NotSupportedError, ResponseContentLengthMismatchError, BalancedPoolMissingUpstreamError, - ResponseExceededMaxSizeError, - RequestRetryError + ResponseExceededMaxSizeError } @@ -27150,9 +26940,9 @@ class Request { onBodySent (chunk) { if (this[kHandler].onBodySent) { try { - return this[kHandler].onBodySent(chunk) + this[kHandler].onBodySent(chunk) } catch (err) { - this.abort(err) + this.onError(err) } } } @@ -27164,9 +26954,9 @@ class Request { if (this[kHandler].onRequestSent) { try { - return this[kHandler].onRequestSent() + this[kHandler].onRequestSent() } catch (err) { - this.abort(err) + this.onError(err) } } } @@ -27191,23 +26981,14 @@ class Request { channels.headers.publish({ request: this, response: { statusCode, headers, statusText } }) } - try { - return this[kHandler].onHeaders(statusCode, headers, resume, statusText) - } catch (err) { - this.abort(err) - } + return this[kHandler].onHeaders(statusCode, headers, resume, statusText) } onData (chunk) { assert(!this.aborted) assert(!this.completed) - try { - return this[kHandler].onData(chunk) - } catch (err) { - this.abort(err) - return false - } + return this[kHandler].onData(chunk) } onUpgrade (statusCode, headers, socket) { @@ -27226,13 +27007,7 @@ class Request { if (channels.trailers.hasSubscribers) { channels.trailers.publish({ request: this, trailers }) } - - try { - return this[kHandler].onComplete(trailers) - } catch (err) { - // TODO (fix): This might be a bad idea? - this.onError(err) - } + return this[kHandler].onComplete(trailers) } onError (error) { @@ -27246,7 +27021,6 @@ class Request { return } this.aborted = true - return this[kHandler].onError(error) } @@ -27483,9 +27257,7 @@ module.exports = { kHTTP2BuildRequest: Symbol('http2 build request'), kHTTP1BuildRequest: Symbol('http1 build request'), kHTTP2CopyHeaders: Symbol('http2 copy headers'), - kHTTPConnVersion: Symbol('http connection version'), - kRetryHandlerDefaultRetry: Symbol('retry agent default retry'), - kConstruct: Symbol('constructable') + kHTTPConnVersion: Symbol('http connection version') } @@ -27506,7 +27278,6 @@ const { InvalidArgumentError } = __nccwpck_require__(8045) const { Blob } = __nccwpck_require__(4300) const nodeUtil = __nccwpck_require__(3837) const { stringify } = __nccwpck_require__(3477) -const { headerNameLowerCasedRecord } = __nccwpck_require__(4462) const [nodeMajor, nodeMinor] = process.versions.node.split('.').map(v => Number(v)) @@ -27623,13 +27394,13 @@ function getHostname (host) { const idx = host.indexOf(']') assert(idx !== -1) - return host.substring(1, idx) + return host.substr(1, idx - 1) } const idx = host.indexOf(':') if (idx === -1) return host - return host.substring(0, idx) + return host.substr(0, idx) } // IP addresses are not valid server names per RFC6066 @@ -27716,15 +27487,6 @@ function parseKeepAliveTimeout (val) { return m ? parseInt(m[1], 10) * 1000 : null } -/** - * Retrieves a header name and returns its lowercase value. - * @param {string | Buffer} value Header name - * @returns {string} - */ -function headerNameToString (value) { - return headerNameLowerCasedRecord[value] || value.toLowerCase() -} - function parseHeaders (headers, obj = {}) { // For H2 support if (!Array.isArray(headers)) return headers @@ -27735,7 +27497,7 @@ function parseHeaders (headers, obj = {}) { if (!val) { if (Array.isArray(headers[i + 1])) { - obj[key] = headers[i + 1].map(x => x.toString('utf8')) + obj[key] = headers[i + 1] } else { obj[key] = headers[i + 1].toString('utf8') } @@ -27938,7 +27700,16 @@ function throwIfAborted (signal) { } } +let events function addAbortListener (signal, listener) { + if (typeof Symbol.dispose === 'symbol') { + if (!events) { + events = __nccwpck_require__(2361) + } + if (typeof events.addAbortListener === 'function' && 'aborted' in signal) { + return events.addAbortListener(signal, listener) + } + } if ('addEventListener' in signal) { signal.addEventListener('abort', listener, { once: true }) return () => signal.removeEventListener('abort', listener) @@ -27962,21 +27733,6 @@ function toUSVString (val) { return `${val}` } -// Parsed accordingly to RFC 9110 -// https://www.rfc-editor.org/rfc/rfc9110#field.content-range -function parseRangeHeader (range) { - if (range == null || range === '') return { start: 0, end: null, size: null } - - const m = range ? range.match(/^bytes (\d+)-(\d+)\/(\d+)?$/) : null - return m - ? { - start: parseInt(m[1]), - end: m[2] ? parseInt(m[2]) : null, - size: m[3] ? parseInt(m[3]) : null - } - : null -} - const kEnumerableProperty = Object.create(null) kEnumerableProperty.enumerable = true @@ -27996,7 +27752,6 @@ module.exports = { isIterable, isAsyncIterable, isDestroyed, - headerNameToString, parseRawHeaders, parseHeaders, parseKeepAliveTimeout, @@ -28011,11 +27766,9 @@ module.exports = { buildURL, throwIfAborted, addAbortListener, - parseRangeHeader, nodeMajor, nodeMinor, - nodeHasAutoSelectFamily: nodeMajor > 18 || (nodeMajor === 18 && nodeMinor >= 13), - safeHTTPMethods: ['GET', 'HEAD', 'OPTIONS', 'TRACE'] + nodeHasAutoSelectFamily: nodeMajor > 18 || (nodeMajor === 18 && nodeMinor >= 13) } @@ -28276,14 +28029,6 @@ const { isUint8Array, isArrayBuffer } = __nccwpck_require__(9830) const { File: UndiciFile } = __nccwpck_require__(8511) const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(685) -let random -try { - const crypto = __nccwpck_require__(6005) - random = (max) => crypto.randomInt(0, max) -} catch { - random = (max) => Math.floor(Math.random(max)) -} - let ReadableStream = globalThis.ReadableStream /** @type {globalThis['File']} */ @@ -28369,7 +28114,7 @@ function extractBody (object, keepalive = false) { // Set source to a copy of the bytes held by object. source = new Uint8Array(object.buffer.slice(object.byteOffset, object.byteOffset + object.byteLength)) } else if (util.isFormDataLike(object)) { - const boundary = `----formdata-undici-0${`${random(1e11)}`.padStart(11, '0')}` + const boundary = `----formdata-undici-0${`${Math.floor(Math.random() * 1e11)}`.padStart(11, '0')}` const prefix = `--${boundary}\r\nContent-Disposition: form-data` /*! formdata-polyfill. MIT License. Jimmy Wärting */ @@ -29152,14 +28897,17 @@ function dataURLProcessor (dataURL) { * @param {boolean} excludeFragment */ function URLSerializer (url, excludeFragment = false) { + const href = url.href + if (!excludeFragment) { - return url.href + return href } - const href = url.href - const hashLength = url.hash.length - - return hashLength === 0 ? href : href.substring(0, href.length - hashLength) + const hash = href.lastIndexOf('#') + if (hash === -1) { + return href + } + return href.slice(0, hash) } // https://infra.spec.whatwg.org/#collect-a-sequence-of-code-points @@ -30343,7 +30091,7 @@ module.exports = { -const { kHeadersList, kConstruct } = __nccwpck_require__(2785) +const { kHeadersList } = __nccwpck_require__(2785) const { kGuard } = __nccwpck_require__(5861) const { kEnumerableProperty } = __nccwpck_require__(3983) const { @@ -30357,13 +30105,6 @@ const assert = __nccwpck_require__(9491) const kHeadersMap = Symbol('headers map') const kHeadersSortedMap = Symbol('headers map sorted') -/** - * @param {number} code - */ -function isHTTPWhiteSpaceCharCode (code) { - return code === 0x00a || code === 0x00d || code === 0x009 || code === 0x020 -} - /** * @see https://fetch.spec.whatwg.org/#concept-header-value-normalize * @param {string} potentialValue @@ -30372,12 +30113,12 @@ function headerValueNormalize (potentialValue) { // To normalize a byte sequence potentialValue, remove // any leading and trailing HTTP whitespace bytes from // potentialValue. - let i = 0; let j = potentialValue.length - while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(j - 1))) --j - while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(i))) ++i - - return i === 0 && j === potentialValue.length ? potentialValue : potentialValue.substring(i, j) + // Trimming the end with `.replace()` and a RegExp is typically subject to + // ReDoS. This is safer and faster. + let i = potentialValue.length + while (/[\r\n\t ]/.test(potentialValue.charAt(--i))); + return potentialValue.slice(0, i + 1).replace(/^[\r\n\t ]+/, '') } function fill (headers, object) { @@ -30386,8 +30127,7 @@ function fill (headers, object) { // 1. If object is a sequence, then for each header in object: // Note: webidl conversion to array has already been done. if (Array.isArray(object)) { - for (let i = 0; i < object.length; ++i) { - const header = object[i] + for (const header of object) { // 1. If header does not contain exactly two items, then throw a TypeError. if (header.length !== 2) { throw webidl.errors.exception({ @@ -30397,16 +30137,15 @@ function fill (headers, object) { } // 2. Append (header’s first item, header’s second item) to headers. - appendHeader(headers, header[0], header[1]) + headers.append(header[0], header[1]) } } else if (typeof object === 'object' && object !== null) { // Note: null should throw // 2. Otherwise, object is a record, then for each key → value in object, // append (key, value) to headers - const keys = Object.keys(object) - for (let i = 0; i < keys.length; ++i) { - appendHeader(headers, keys[i], object[keys[i]]) + for (const [key, value] of Object.entries(object)) { + headers.append(key, value) } } else { throw webidl.errors.conversionFailed({ @@ -30417,50 +30156,6 @@ function fill (headers, object) { } } -/** - * @see https://fetch.spec.whatwg.org/#concept-headers-append - */ -function appendHeader (headers, name, value) { - // 1. Normalize value. - value = headerValueNormalize(value) - - // 2. If name is not a header name or value is not a - // header value, then throw a TypeError. - if (!isValidHeaderName(name)) { - throw webidl.errors.invalidArgument({ - prefix: 'Headers.append', - value: name, - type: 'header name' - }) - } else if (!isValidHeaderValue(value)) { - throw webidl.errors.invalidArgument({ - prefix: 'Headers.append', - value, - type: 'header value' - }) - } - - // 3. If headers’s guard is "immutable", then throw a TypeError. - // 4. Otherwise, if headers’s guard is "request" and name is a - // forbidden header name, return. - // Note: undici does not implement forbidden header names - if (headers[kGuard] === 'immutable') { - throw new TypeError('immutable') - } else if (headers[kGuard] === 'request-no-cors') { - // 5. Otherwise, if headers’s guard is "request-no-cors": - // TODO - } - - // 6. Otherwise, if headers’s guard is "response" and name is a - // forbidden response-header name, return. - - // 7. Append (name, value) to headers’s header list. - return headers[kHeadersList].append(name, value) - - // 8. If headers’s guard is "request-no-cors", then remove - // privileged no-CORS request headers from headers -} - class HeadersList { /** @type {[string, string][]|null} */ cookies = null @@ -30469,7 +30164,7 @@ class HeadersList { if (init instanceof HeadersList) { this[kHeadersMap] = new Map(init[kHeadersMap]) this[kHeadersSortedMap] = init[kHeadersSortedMap] - this.cookies = init.cookies === null ? null : [...init.cookies] + this.cookies = init.cookies } else { this[kHeadersMap] = new Map(init) this[kHeadersSortedMap] = null @@ -30531,7 +30226,7 @@ class HeadersList { // the first such header to value and remove the // others. // 2. Otherwise, append header (name, value) to list. - this[kHeadersMap].set(lowercaseName, { name, value }) + return this[kHeadersMap].set(lowercaseName, { name, value }) } // https://fetch.spec.whatwg.org/#concept-header-list-delete @@ -30544,18 +30239,20 @@ class HeadersList { this.cookies = null } - this[kHeadersMap].delete(name) + return this[kHeadersMap].delete(name) } // https://fetch.spec.whatwg.org/#concept-header-list-get get (name) { - const value = this[kHeadersMap].get(name.toLowerCase()) - // 1. If list does not contain name, then return null. + if (!this.contains(name)) { + return null + } + // 2. Return the values of all headers in list whose name // is a byte-case-insensitive match for name, // separated from each other by 0x2C 0x20, in order. - return value === undefined ? null : value.value + return this[kHeadersMap].get(name.toLowerCase())?.value ?? null } * [Symbol.iterator] () { @@ -30581,9 +30278,6 @@ class HeadersList { // https://fetch.spec.whatwg.org/#headers-class class Headers { constructor (init = undefined) { - if (init === kConstruct) { - return - } this[kHeadersList] = new HeadersList() // The new Headers(init) constructor steps are: @@ -30607,7 +30301,43 @@ class Headers { name = webidl.converters.ByteString(name) value = webidl.converters.ByteString(value) - return appendHeader(this, name, value) + // 1. Normalize value. + value = headerValueNormalize(value) + + // 2. If name is not a header name or value is not a + // header value, then throw a TypeError. + if (!isValidHeaderName(name)) { + throw webidl.errors.invalidArgument({ + prefix: 'Headers.append', + value: name, + type: 'header name' + }) + } else if (!isValidHeaderValue(value)) { + throw webidl.errors.invalidArgument({ + prefix: 'Headers.append', + value, + type: 'header value' + }) + } + + // 3. If headers’s guard is "immutable", then throw a TypeError. + // 4. Otherwise, if headers’s guard is "request" and name is a + // forbidden header name, return. + // Note: undici does not implement forbidden header names + if (this[kGuard] === 'immutable') { + throw new TypeError('immutable') + } else if (this[kGuard] === 'request-no-cors') { + // 5. Otherwise, if headers’s guard is "request-no-cors": + // TODO + } + + // 6. Otherwise, if headers’s guard is "response" and name is a + // forbidden response-header name, return. + + // 7. Append (name, value) to headers’s header list. + // 8. If headers’s guard is "request-no-cors", then remove + // privileged no-CORS request headers from headers + return this[kHeadersList].append(name, value) } // https://fetch.spec.whatwg.org/#dom-headers-delete @@ -30652,7 +30382,7 @@ class Headers { // 7. Delete name from this’s header list. // 8. If this’s guard is "request-no-cors", then remove // privileged no-CORS request headers from this. - this[kHeadersList].delete(name) + return this[kHeadersList].delete(name) } // https://fetch.spec.whatwg.org/#dom-headers-get @@ -30745,7 +30475,7 @@ class Headers { // 7. Set (name, value) in this’s header list. // 8. If this’s guard is "request-no-cors", then remove // privileged no-CORS request headers from this - this[kHeadersList].set(name, value) + return this[kHeadersList].set(name, value) } // https://fetch.spec.whatwg.org/#dom-headers-getsetcookie @@ -30781,8 +30511,7 @@ class Headers { const cookies = this[kHeadersList].cookies // 3. For each name of names: - for (let i = 0; i < names.length; ++i) { - const [name, value] = names[i] + for (const [name, value] of names) { // 1. If name is `set-cookie`, then: if (name === 'set-cookie') { // 1. Let values be a list of all values of headers in list whose name @@ -30790,8 +30519,8 @@ class Headers { // 2. For each value of values: // 1. Append (name, value) to headers. - for (let j = 0; j < cookies.length; ++j) { - headers.push([name, cookies[j]]) + for (const value of cookies) { + headers.push([name, value]) } } else { // 2. Otherwise: @@ -30815,12 +30544,6 @@ class Headers { keys () { webidl.brandCheck(this, Headers) - if (this[kGuard] === 'immutable') { - const value = this[kHeadersSortedMap] - return makeIterator(() => value, 'Headers', - 'key') - } - return makeIterator( () => [...this[kHeadersSortedMap].values()], 'Headers', @@ -30831,12 +30554,6 @@ class Headers { values () { webidl.brandCheck(this, Headers) - if (this[kGuard] === 'immutable') { - const value = this[kHeadersSortedMap] - return makeIterator(() => value, 'Headers', - 'value') - } - return makeIterator( () => [...this[kHeadersSortedMap].values()], 'Headers', @@ -30847,12 +30564,6 @@ class Headers { entries () { webidl.brandCheck(this, Headers) - if (this[kGuard] === 'immutable') { - const value = this[kHeadersSortedMap] - return makeIterator(() => value, 'Headers', - 'key+value') - } - return makeIterator( () => [...this[kHeadersSortedMap].values()], 'Headers', @@ -31224,7 +30935,7 @@ function finalizeAndReportTiming (response, initiatorType = 'other') { } // 8. If response’s timing allow passed flag is not set, then: - if (!response.timingAllowPassed) { + if (!timingInfo.timingAllowPassed) { // 1. Set timingInfo to a the result of creating an opaque timing info for timingInfo. timingInfo = createOpaqueTimingInfo({ startTime: timingInfo.startTime @@ -32141,9 +31852,6 @@ function httpRedirectFetch (fetchParams, response) { // https://fetch.spec.whatwg.org/#cors-non-wildcard-request-header-name request.headersList.delete('authorization') - // https://fetch.spec.whatwg.org/#authentication-entries - request.headersList.delete('proxy-authorization', true) - // "Cookie" and "Host" are forbidden request-headers, which undici doesn't implement. request.headersList.delete('cookie') request.headersList.delete('host') @@ -32898,7 +32606,7 @@ async function httpNetworkFetch ( path: url.pathname + url.search, origin: url.origin, method: request.method, - body: fetchParams.controller.dispatcher.isMockActive ? request.body && (request.body.source || request.body.stream) : body, + body: fetchParams.controller.dispatcher.isMockActive ? request.body && request.body.source : body, headers: request.headersList.entries, maxRedirections: 0, upgrade: request.mode === 'websocket' ? 'websocket' : undefined @@ -32943,7 +32651,7 @@ async function httpNetworkFetch ( location = val } - headers[kHeadersList].append(key, val) + headers.append(key, val) } } else { const keys = Object.keys(headersList) @@ -32957,7 +32665,7 @@ async function httpNetworkFetch ( location = val } - headers[kHeadersList].append(key, val) + headers.append(key, val) } } @@ -33061,7 +32769,7 @@ async function httpNetworkFetch ( const key = headersList[n + 0].toString('latin1') const val = headersList[n + 1].toString('latin1') - headers[kHeadersList].append(key, val) + headers.append(key, val) } resolve({ @@ -33104,8 +32812,7 @@ const { isValidHTTPToken, sameOrigin, normalizeMethod, - makePolicyContainer, - normalizeMethodRecord + makePolicyContainer } = __nccwpck_require__(2538) const { forbiddenMethodsSet, @@ -33122,12 +32829,13 @@ const { kHeaders, kSignal, kState, kGuard, kRealm } = __nccwpck_require__(5861) const { webidl } = __nccwpck_require__(1744) const { getGlobalOrigin } = __nccwpck_require__(1246) const { URLSerializer } = __nccwpck_require__(685) -const { kHeadersList, kConstruct } = __nccwpck_require__(2785) +const { kHeadersList } = __nccwpck_require__(2785) const assert = __nccwpck_require__(9491) const { getMaxListeners, setMaxListeners, getEventListeners, defaultMaxListeners } = __nccwpck_require__(2361) let TransformStream = globalThis.TransformStream +const kInit = Symbol('init') const kAbortController = Symbol('abortController') const requestFinalizer = new FinalizationRegistry(({ signal, abort }) => { @@ -33138,7 +32846,7 @@ const requestFinalizer = new FinalizationRegistry(({ signal, abort }) => { class Request { // https://fetch.spec.whatwg.org/#dom-request constructor (input, init = {}) { - if (input === kConstruct) { + if (input === kInit) { return } @@ -33277,10 +32985,8 @@ class Request { urlList: [...request.urlList] }) - const initHasKey = Object.keys(init).length !== 0 - // 13. If init is not empty, then: - if (initHasKey) { + if (Object.keys(init).length > 0) { // 1. If request’s mode is "navigate", then set it to "same-origin". if (request.mode === 'navigate') { request.mode = 'same-origin' @@ -33395,7 +33101,7 @@ class Request { } // 23. If init["integrity"] exists, then set request’s integrity metadata to it. - if (init.integrity != null) { + if (init.integrity !== undefined && init.integrity != null) { request.integrity = String(init.integrity) } @@ -33411,16 +33117,16 @@ class Request { // 2. If method is not a method or method is a forbidden method, then // throw a TypeError. - if (!isValidHTTPToken(method)) { - throw new TypeError(`'${method}' is not a valid HTTP method.`) + if (!isValidHTTPToken(init.method)) { + throw TypeError(`'${init.method}' is not a valid HTTP method.`) } if (forbiddenMethodsSet.has(method.toUpperCase())) { - throw new TypeError(`'${method}' HTTP method is unsupported.`) + throw TypeError(`'${init.method}' HTTP method is unsupported.`) } // 3. Normalize method. - method = normalizeMethodRecord[method] ?? normalizeMethod(method) + method = normalizeMethod(init.method) // 4. Set request’s method to method. request.method = method @@ -33491,7 +33197,7 @@ class Request { // 30. Set this’s headers to a new Headers object with this’s relevant // Realm, whose header list is request’s header list and guard is // "request". - this[kHeaders] = new Headers(kConstruct) + this[kHeaders] = new Headers() this[kHeaders][kHeadersList] = request.headersList this[kHeaders][kGuard] = 'request' this[kHeaders][kRealm] = this[kRealm] @@ -33511,25 +33217,25 @@ class Request { } // 32. If init is not empty, then: - if (initHasKey) { - /** @type {HeadersList} */ - const headersList = this[kHeaders][kHeadersList] + if (Object.keys(init).length !== 0) { // 1. Let headers be a copy of this’s headers and its associated header // list. + let headers = new Headers(this[kHeaders]) + // 2. If init["headers"] exists, then set headers to init["headers"]. - const headers = init.headers !== undefined ? init.headers : new HeadersList(headersList) + if (init.headers !== undefined) { + headers = init.headers + } // 3. Empty this’s headers’s header list. - headersList.clear() + this[kHeaders][kHeadersList].clear() // 4. If headers is a Headers object, then for each header in its header // list, append header’s name/header’s value to this’s headers. - if (headers instanceof HeadersList) { + if (headers.constructor.name === 'Headers') { for (const [key, val] of headers) { - headersList.append(key, val) + this[kHeaders].append(key, val) } - // Note: Copy the `set-cookie` meta-data. - headersList.cookies = headers.cookies } else { // 5. Otherwise, fill this’s headers with headers. fillHeaders(this[kHeaders], headers) @@ -33818,10 +33524,10 @@ class Request { // 3. Let clonedRequestObject be the result of creating a Request object, // given clonedRequest, this’s headers’s guard, and this’s relevant Realm. - const clonedRequestObject = new Request(kConstruct) + const clonedRequestObject = new Request(kInit) clonedRequestObject[kState] = clonedRequest clonedRequestObject[kRealm] = this[kRealm] - clonedRequestObject[kHeaders] = new Headers(kConstruct) + clonedRequestObject[kHeaders] = new Headers() clonedRequestObject[kHeaders][kHeadersList] = clonedRequest.headersList clonedRequestObject[kHeaders][kGuard] = this[kHeaders][kGuard] clonedRequestObject[kHeaders][kRealm] = this[kHeaders][kRealm] @@ -34071,7 +33777,7 @@ const { webidl } = __nccwpck_require__(1744) const { FormData } = __nccwpck_require__(2015) const { getGlobalOrigin } = __nccwpck_require__(1246) const { URLSerializer } = __nccwpck_require__(685) -const { kHeadersList, kConstruct } = __nccwpck_require__(2785) +const { kHeadersList } = __nccwpck_require__(2785) const assert = __nccwpck_require__(9491) const { types } = __nccwpck_require__(3837) @@ -34192,7 +33898,7 @@ class Response { // 2. Set this’s headers to a new Headers object with this’s relevant // Realm, whose header list is this’s response’s header list and guard // is "response". - this[kHeaders] = new Headers(kConstruct) + this[kHeaders] = new Headers() this[kHeaders][kGuard] = 'response' this[kHeaders][kHeadersList] = this[kState].headersList this[kHeaders][kRealm] = this[kRealm] @@ -34562,7 +34268,11 @@ webidl.converters.XMLHttpRequestBodyInit = function (V) { return webidl.converters.Blob(V, { strict: false }) } - if (types.isArrayBuffer(V) || types.isTypedArray(V) || types.isDataView(V)) { + if ( + types.isAnyArrayBuffer(V) || + types.isTypedArray(V) || + types.isDataView(V) + ) { return webidl.converters.BufferSource(V) } @@ -34652,18 +34362,14 @@ const { isBlobLike, toUSVString, ReadableStreamFrom } = __nccwpck_require__(3983 const assert = __nccwpck_require__(9491) const { isUint8Array } = __nccwpck_require__(9830) -let supportedHashes = [] - // https://nodejs.org/api/crypto.html#determining-if-crypto-support-is-unavailable /** @type {import('crypto')|undefined} */ let crypto try { crypto = __nccwpck_require__(6113) - const possibleRelevantHashes = ['sha256', 'sha384', 'sha512'] - supportedHashes = crypto.getHashes().filter((hash) => possibleRelevantHashes.includes(hash)) -/* c8 ignore next 3 */ } catch { + } function responseURL (response) { @@ -34752,57 +34458,52 @@ function isValidReasonPhrase (statusText) { return true } -/** - * @see https://tools.ietf.org/html/rfc7230#section-3.2.6 - * @param {number} c - */ -function isTokenCharCode (c) { - switch (c) { - case 0x22: - case 0x28: - case 0x29: - case 0x2c: - case 0x2f: - case 0x3a: - case 0x3b: - case 0x3c: - case 0x3d: - case 0x3e: - case 0x3f: - case 0x40: - case 0x5b: - case 0x5c: - case 0x5d: - case 0x7b: - case 0x7d: - // DQUOTE and "(),/:;<=>?@[\]{}" - return false - default: - // VCHAR %x21-7E - return c >= 0x21 && c <= 0x7e - } +function isTokenChar (c) { + return !( + c >= 0x7f || + c <= 0x20 || + c === '(' || + c === ')' || + c === '<' || + c === '>' || + c === '@' || + c === ',' || + c === ';' || + c === ':' || + c === '\\' || + c === '"' || + c === '/' || + c === '[' || + c === ']' || + c === '?' || + c === '=' || + c === '{' || + c === '}' + ) } -/** - * @param {string} characters - */ +// See RFC 7230, Section 3.2.6. +// https://github.com/chromium/chromium/blob/d7da0240cae77824d1eda25745c4022757499131/third_party/blink/renderer/platform/network/http_parsers.cc#L321 function isValidHTTPToken (characters) { - if (characters.length === 0) { + if (!characters || typeof characters !== 'string') { return false } for (let i = 0; i < characters.length; ++i) { - if (!isTokenCharCode(characters.charCodeAt(i))) { + const c = characters.charCodeAt(i) + if (c > 0x7f || !isTokenChar(c)) { return false } } return true } -/** - * @see https://fetch.spec.whatwg.org/#header-name - * @param {string} potentialValue - */ +// https://fetch.spec.whatwg.org/#header-name +// https://github.com/chromium/chromium/blob/b3d37e6f94f87d59e44662d6078f6a12de845d17/net/http/http_util.cc#L342 function isValidHeaderName (potentialValue) { + if (potentialValue.length === 0) { + return false + } + return isValidHTTPToken(potentialValue) } @@ -35191,56 +34892,66 @@ function bytesMatch (bytes, metadataList) { return true } - // 3. If response is not eligible for integrity validation, return false. - // TODO - - // 4. If parsedMetadata is the empty set, return true. + // 3. If parsedMetadata is the empty set, return true. if (parsedMetadata.length === 0) { return true } - // 5. Let metadata be the result of getting the strongest + // 4. Let metadata be the result of getting the strongest // metadata from parsedMetadata. - const strongest = getStrongestMetadata(parsedMetadata) - const metadata = filterMetadataListByAlgorithm(parsedMetadata, strongest) + const list = parsedMetadata.sort((c, d) => d.algo.localeCompare(c.algo)) + // get the strongest algorithm + const strongest = list[0].algo + // get all entries that use the strongest algorithm; ignore weaker + const metadata = list.filter((item) => item.algo === strongest) - // 6. For each item in metadata: + // 5. For each item in metadata: for (const item of metadata) { // 1. Let algorithm be the alg component of item. const algorithm = item.algo // 2. Let expectedValue be the val component of item. - const expectedValue = item.hash + let expectedValue = item.hash // See https://github.com/web-platform-tests/wpt/commit/e4c5cc7a5e48093220528dfdd1c4012dc3837a0e // "be liberal with padding". This is annoying, and it's not even in the spec. + if (expectedValue.endsWith('==')) { + expectedValue = expectedValue.slice(0, -2) + } + // 3. Let actualValue be the result of applying algorithm to bytes. let actualValue = crypto.createHash(algorithm).update(bytes).digest('base64') - if (actualValue[actualValue.length - 1] === '=') { - if (actualValue[actualValue.length - 2] === '=') { - actualValue = actualValue.slice(0, -2) - } else { - actualValue = actualValue.slice(0, -1) - } + if (actualValue.endsWith('==')) { + actualValue = actualValue.slice(0, -2) } // 4. If actualValue is a case-sensitive match for expectedValue, // return true. - if (compareBase64Mixed(actualValue, expectedValue)) { + if (actualValue === expectedValue) { + return true + } + + let actualBase64URL = crypto.createHash(algorithm).update(bytes).digest('base64url') + + if (actualBase64URL.endsWith('==')) { + actualBase64URL = actualBase64URL.slice(0, -2) + } + + if (actualBase64URL === expectedValue) { return true } } - // 7. Return false. + // 6. Return false. return false } // https://w3c.github.io/webappsec-subresource-integrity/#grammardef-hash-with-options // https://www.w3.org/TR/CSP2/#source-list-syntax // https://www.rfc-editor.org/rfc/rfc5234#appendix-B.1 -const parseHashWithOptions = /(?sha256|sha384|sha512)-((?[A-Za-z0-9+/]+|[A-Za-z0-9_-]+)={0,2}(?:\s|$)( +[!-~]*)?)?/i +const parseHashWithOptions = /((?sha256|sha384|sha512)-(?[A-z0-9+/]{1}.*={0,2}))( +[\x21-\x7e]?)?/i /** * @see https://w3c.github.io/webappsec-subresource-integrity/#parse-metadata @@ -35254,6 +34965,8 @@ function parseMetadata (metadata) { // 2. Let empty be equal to true. let empty = true + const supportedHashes = crypto.getHashes() + // 3. For each token returned by splitting metadata on spaces: for (const token of metadata.split(' ')) { // 1. Set empty to false. @@ -35263,11 +34976,7 @@ function parseMetadata (metadata) { const parsedToken = parseHashWithOptions.exec(token) // 3. If token does not parse, continue to the next token. - if ( - parsedToken === null || - parsedToken.groups === undefined || - parsedToken.groups.algo === undefined - ) { + if (parsedToken === null || parsedToken.groups === undefined) { // Note: Chromium blocks the request at this point, but Firefox // gives a warning that an invalid integrity was given. The // correct behavior is to ignore these, and subsequently not @@ -35276,11 +34985,11 @@ function parseMetadata (metadata) { } // 4. Let algorithm be the hash-algo component of token. - const algorithm = parsedToken.groups.algo.toLowerCase() + const algorithm = parsedToken.groups.algo // 5. If algorithm is a hash function recognized by the user // agent, add the parsed token to result. - if (supportedHashes.includes(algorithm)) { + if (supportedHashes.includes(algorithm.toLowerCase())) { result.push(parsedToken.groups) } } @@ -35293,82 +35002,6 @@ function parseMetadata (metadata) { return result } -/** - * @param {{ algo: 'sha256' | 'sha384' | 'sha512' }[]} metadataList - */ -function getStrongestMetadata (metadataList) { - // Let algorithm be the algo component of the first item in metadataList. - // Can be sha256 - let algorithm = metadataList[0].algo - // If the algorithm is sha512, then it is the strongest - // and we can return immediately - if (algorithm[3] === '5') { - return algorithm - } - - for (let i = 1; i < metadataList.length; ++i) { - const metadata = metadataList[i] - // If the algorithm is sha512, then it is the strongest - // and we can break the loop immediately - if (metadata.algo[3] === '5') { - algorithm = 'sha512' - break - // If the algorithm is sha384, then a potential sha256 or sha384 is ignored - } else if (algorithm[3] === '3') { - continue - // algorithm is sha256, check if algorithm is sha384 and if so, set it as - // the strongest - } else if (metadata.algo[3] === '3') { - algorithm = 'sha384' - } - } - return algorithm -} - -function filterMetadataListByAlgorithm (metadataList, algorithm) { - if (metadataList.length === 1) { - return metadataList - } - - let pos = 0 - for (let i = 0; i < metadataList.length; ++i) { - if (metadataList[i].algo === algorithm) { - metadataList[pos++] = metadataList[i] - } - } - - metadataList.length = pos - - return metadataList -} - -/** - * Compares two base64 strings, allowing for base64url - * in the second string. - * -* @param {string} actualValue always base64 - * @param {string} expectedValue base64 or base64url - * @returns {boolean} - */ -function compareBase64Mixed (actualValue, expectedValue) { - if (actualValue.length !== expectedValue.length) { - return false - } - for (let i = 0; i < actualValue.length; ++i) { - if (actualValue[i] !== expectedValue[i]) { - if ( - (actualValue[i] === '+' && expectedValue[i] === '-') || - (actualValue[i] === '/' && expectedValue[i] === '_') - ) { - continue - } - return false - } - } - - return true -} - // https://w3c.github.io/webappsec-upgrade-insecure-requests/#upgrade-request function tryUpgradeRequestToAPotentiallyTrustworthyURL (request) { // TODO @@ -35415,30 +35048,11 @@ function isCancelled (fetchParams) { fetchParams.controller.state === 'terminated' } -const normalizeMethodRecord = { - delete: 'DELETE', - DELETE: 'DELETE', - get: 'GET', - GET: 'GET', - head: 'HEAD', - HEAD: 'HEAD', - options: 'OPTIONS', - OPTIONS: 'OPTIONS', - post: 'POST', - POST: 'POST', - put: 'PUT', - PUT: 'PUT' -} - -// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`. -Object.setPrototypeOf(normalizeMethodRecord, null) - -/** - * @see https://fetch.spec.whatwg.org/#concept-method-normalize - * @param {string} method - */ +// https://fetch.spec.whatwg.org/#concept-method-normalize function normalizeMethod (method) { - return normalizeMethodRecord[method.toLowerCase()] ?? method + return /^(DELETE|GET|HEAD|OPTIONS|POST|PUT)$/i.test(method) + ? method.toUpperCase() + : method } // https://infra.spec.whatwg.org/#serialize-a-javascript-value-to-a-json-string @@ -35783,9 +35397,7 @@ module.exports = { urlIsLocal, urlHasHttpsScheme, urlIsHttpHttpsScheme, - readAllBytes, - normalizeMethodRecord, - parseMetadata + readAllBytes } @@ -36224,10 +35836,12 @@ webidl.converters.ByteString = function (V) { // 2. If the value of any element of x is greater than // 255, then throw a TypeError. for (let index = 0; index < x.length; index++) { - if (x.charCodeAt(index) > 255) { + const charCode = x.charCodeAt(index) + + if (charCode > 255) { throw new TypeError( 'Cannot convert argument to a ByteString because the character at ' + - `index ${index} has a value of ${x.charCodeAt(index)} which is greater than 255.` + `index ${index} has a value of ${charCode} which is greater than 255.` ) } } @@ -37872,17 +37486,12 @@ function parseLocation (statusCode, headers) { // https://tools.ietf.org/html/rfc7231#section-6.4.4 function shouldRemoveHeader (header, removeContent, unknownOrigin) { - if (header.length === 4) { - return util.headerNameToString(header) === 'host' - } - if (removeContent && util.headerNameToString(header).startsWith('content-')) { - return true - } - if (unknownOrigin && (header.length === 13 || header.length === 6 || header.length === 19)) { - const name = util.headerNameToString(header) - return name === 'authorization' || name === 'cookie' || name === 'proxy-authorization' - } - return false + return ( + (header.length === 4 && header.toString().toLowerCase() === 'host') || + (removeContent && header.toString().toLowerCase().indexOf('content-') === 0) || + (unknownOrigin && header.length === 13 && header.toString().toLowerCase() === 'authorization') || + (unknownOrigin && header.length === 6 && header.toString().toLowerCase() === 'cookie') + ) } // https://tools.ietf.org/html/rfc7231#section-6.4 @@ -37909,349 +37518,6 @@ function cleanRequestHeaders (headers, removeContent, unknownOrigin) { module.exports = RedirectHandler -/***/ }), - -/***/ 2286: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const assert = __nccwpck_require__(9491) - -const { kRetryHandlerDefaultRetry } = __nccwpck_require__(2785) -const { RequestRetryError } = __nccwpck_require__(8045) -const { isDisturbed, parseHeaders, parseRangeHeader } = __nccwpck_require__(3983) - -function calculateRetryAfterHeader (retryAfter) { - const current = Date.now() - const diff = new Date(retryAfter).getTime() - current - - return diff -} - -class RetryHandler { - constructor (opts, handlers) { - const { retryOptions, ...dispatchOpts } = opts - const { - // Retry scoped - retry: retryFn, - maxRetries, - maxTimeout, - minTimeout, - timeoutFactor, - // Response scoped - methods, - errorCodes, - retryAfter, - statusCodes - } = retryOptions ?? {} - - this.dispatch = handlers.dispatch - this.handler = handlers.handler - this.opts = dispatchOpts - this.abort = null - this.aborted = false - this.retryOpts = { - retry: retryFn ?? RetryHandler[kRetryHandlerDefaultRetry], - retryAfter: retryAfter ?? true, - maxTimeout: maxTimeout ?? 30 * 1000, // 30s, - timeout: minTimeout ?? 500, // .5s - timeoutFactor: timeoutFactor ?? 2, - maxRetries: maxRetries ?? 5, - // What errors we should retry - methods: methods ?? ['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE', 'TRACE'], - // Indicates which errors to retry - statusCodes: statusCodes ?? [500, 502, 503, 504, 429], - // List of errors to retry - errorCodes: errorCodes ?? [ - 'ECONNRESET', - 'ECONNREFUSED', - 'ENOTFOUND', - 'ENETDOWN', - 'ENETUNREACH', - 'EHOSTDOWN', - 'EHOSTUNREACH', - 'EPIPE' - ] - } - - this.retryCount = 0 - this.start = 0 - this.end = null - this.etag = null - this.resume = null - - // Handle possible onConnect duplication - this.handler.onConnect(reason => { - this.aborted = true - if (this.abort) { - this.abort(reason) - } else { - this.reason = reason - } - }) - } - - onRequestSent () { - if (this.handler.onRequestSent) { - this.handler.onRequestSent() - } - } - - onUpgrade (statusCode, headers, socket) { - if (this.handler.onUpgrade) { - this.handler.onUpgrade(statusCode, headers, socket) - } - } - - onConnect (abort) { - if (this.aborted) { - abort(this.reason) - } else { - this.abort = abort - } - } - - onBodySent (chunk) { - if (this.handler.onBodySent) return this.handler.onBodySent(chunk) - } - - static [kRetryHandlerDefaultRetry] (err, { state, opts }, cb) { - const { statusCode, code, headers } = err - const { method, retryOptions } = opts - const { - maxRetries, - timeout, - maxTimeout, - timeoutFactor, - statusCodes, - errorCodes, - methods - } = retryOptions - let { counter, currentTimeout } = state - - currentTimeout = - currentTimeout != null && currentTimeout > 0 ? currentTimeout : timeout - - // Any code that is not a Undici's originated and allowed to retry - if ( - code && - code !== 'UND_ERR_REQ_RETRY' && - code !== 'UND_ERR_SOCKET' && - !errorCodes.includes(code) - ) { - cb(err) - return - } - - // If a set of method are provided and the current method is not in the list - if (Array.isArray(methods) && !methods.includes(method)) { - cb(err) - return - } - - // If a set of status code are provided and the current status code is not in the list - if ( - statusCode != null && - Array.isArray(statusCodes) && - !statusCodes.includes(statusCode) - ) { - cb(err) - return - } - - // If we reached the max number of retries - if (counter > maxRetries) { - cb(err) - return - } - - let retryAfterHeader = headers != null && headers['retry-after'] - if (retryAfterHeader) { - retryAfterHeader = Number(retryAfterHeader) - retryAfterHeader = isNaN(retryAfterHeader) - ? calculateRetryAfterHeader(retryAfterHeader) - : retryAfterHeader * 1e3 // Retry-After is in seconds - } - - const retryTimeout = - retryAfterHeader > 0 - ? Math.min(retryAfterHeader, maxTimeout) - : Math.min(currentTimeout * timeoutFactor ** counter, maxTimeout) - - state.currentTimeout = retryTimeout - - setTimeout(() => cb(null), retryTimeout) - } - - onHeaders (statusCode, rawHeaders, resume, statusMessage) { - const headers = parseHeaders(rawHeaders) - - this.retryCount += 1 - - if (statusCode >= 300) { - this.abort( - new RequestRetryError('Request failed', statusCode, { - headers, - count: this.retryCount - }) - ) - return false - } - - // Checkpoint for resume from where we left it - if (this.resume != null) { - this.resume = null - - if (statusCode !== 206) { - return true - } - - const contentRange = parseRangeHeader(headers['content-range']) - // If no content range - if (!contentRange) { - this.abort( - new RequestRetryError('Content-Range mismatch', statusCode, { - headers, - count: this.retryCount - }) - ) - return false - } - - // Let's start with a weak etag check - if (this.etag != null && this.etag !== headers.etag) { - this.abort( - new RequestRetryError('ETag mismatch', statusCode, { - headers, - count: this.retryCount - }) - ) - return false - } - - const { start, size, end = size } = contentRange - - assert(this.start === start, 'content-range mismatch') - assert(this.end == null || this.end === end, 'content-range mismatch') - - this.resume = resume - return true - } - - if (this.end == null) { - if (statusCode === 206) { - // First time we receive 206 - const range = parseRangeHeader(headers['content-range']) - - if (range == null) { - return this.handler.onHeaders( - statusCode, - rawHeaders, - resume, - statusMessage - ) - } - - const { start, size, end = size } = range - - assert( - start != null && Number.isFinite(start) && this.start !== start, - 'content-range mismatch' - ) - assert(Number.isFinite(start)) - assert( - end != null && Number.isFinite(end) && this.end !== end, - 'invalid content-length' - ) - - this.start = start - this.end = end - } - - // We make our best to checkpoint the body for further range headers - if (this.end == null) { - const contentLength = headers['content-length'] - this.end = contentLength != null ? Number(contentLength) : null - } - - assert(Number.isFinite(this.start)) - assert( - this.end == null || Number.isFinite(this.end), - 'invalid content-length' - ) - - this.resume = resume - this.etag = headers.etag != null ? headers.etag : null - - return this.handler.onHeaders( - statusCode, - rawHeaders, - resume, - statusMessage - ) - } - - const err = new RequestRetryError('Request failed', statusCode, { - headers, - count: this.retryCount - }) - - this.abort(err) - - return false - } - - onData (chunk) { - this.start += chunk.length - - return this.handler.onData(chunk) - } - - onComplete (rawTrailers) { - this.retryCount = 0 - return this.handler.onComplete(rawTrailers) - } - - onError (err) { - if (this.aborted || isDisturbed(this.opts.body)) { - return this.handler.onError(err) - } - - this.retryOpts.retry( - err, - { - state: { counter: this.retryCount++, currentTimeout: this.retryAfter }, - opts: { retryOptions: this.retryOpts, ...this.opts } - }, - onRetry.bind(this) - ) - - function onRetry (err) { - if (err != null || this.aborted || isDisturbed(this.opts.body)) { - return this.handler.onError(err) - } - - if (this.start !== 0) { - this.opts = { - ...this.opts, - headers: { - ...this.opts.headers, - range: `bytes=${this.start}-${this.end ?? ''}` - } - } - } - - try { - this.dispatch(this.opts, this) - } catch (err) { - this.handler.onError(err) - } - } - } -} - -module.exports = RetryHandler - - /***/ }), /***/ 8861: @@ -40174,9 +39440,6 @@ class ProxyAgent extends DispatcherBase { this[kProxyTls] = opts.proxyTls this[kProxyHeaders] = opts.headers || {} - const resolvedUrl = new URL(opts.uri) - const { origin, port, host, username, password } = resolvedUrl - if (opts.auth && opts.token) { throw new InvalidArgumentError('opts.auth cannot be used in combination with opts.token') } else if (opts.auth) { @@ -40184,10 +39447,11 @@ class ProxyAgent extends DispatcherBase { this[kProxyHeaders]['proxy-authorization'] = `Basic ${opts.auth}` } else if (opts.token) { this[kProxyHeaders]['proxy-authorization'] = opts.token - } else if (username && password) { - this[kProxyHeaders]['proxy-authorization'] = `Basic ${Buffer.from(`${decodeURIComponent(username)}:${decodeURIComponent(password)}`).toString('base64')}` } + const resolvedUrl = new URL(opts.uri) + const { origin, port, host } = resolvedUrl + const connect = buildConnector({ ...opts.proxyTls }) this[kConnectEndpoint] = buildConnector({ ...opts.requestTls }) this[kClient] = clientFactory(resolvedUrl, { connect }) @@ -40211,7 +39475,7 @@ class ProxyAgent extends DispatcherBase { }) if (statusCode !== 200) { socket.on('error', () => {}).destroy() - callback(new RequestAbortedError(`Proxy response (${statusCode}) !== 200 when HTTP Tunneling`)) + callback(new RequestAbortedError('Proxy response !== 200 when HTTP Tunneling')) } if (opts.protocol !== 'https:') { callback(null, socket) @@ -43192,14 +42456,6 @@ module.exports = require("net"); /***/ }), -/***/ 6005: -/***/ ((module) => { - -"use strict"; -module.exports = require("node:crypto"); - -/***/ }), - /***/ 5673: /***/ ((module) => { @@ -44959,7 +44215,7 @@ module.exports = parseParams /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -// Axios v1.7.9 Copyright (c) 2024 Matt Zabriskie and contributors +// Axios v1.6.2 Copyright (c) 2023 Matt Zabriskie and contributors const FormData$1 = __nccwpck_require__(4334); @@ -44971,19 +44227,19 @@ const util = __nccwpck_require__(3837); const followRedirects = __nccwpck_require__(7707); const zlib = __nccwpck_require__(9796); const stream = __nccwpck_require__(2781); -const events = __nccwpck_require__(2361); +const EventEmitter = __nccwpck_require__(2361); function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } const FormData__default = /*#__PURE__*/_interopDefaultLegacy(FormData$1); const url__default = /*#__PURE__*/_interopDefaultLegacy(url); -const proxyFromEnv__default = /*#__PURE__*/_interopDefaultLegacy(proxyFromEnv); const http__default = /*#__PURE__*/_interopDefaultLegacy(http); const https__default = /*#__PURE__*/_interopDefaultLegacy(https); const util__default = /*#__PURE__*/_interopDefaultLegacy(util); const followRedirects__default = /*#__PURE__*/_interopDefaultLegacy(followRedirects); const zlib__default = /*#__PURE__*/_interopDefaultLegacy(zlib); const stream__default = /*#__PURE__*/_interopDefaultLegacy(stream); +const EventEmitter__default = /*#__PURE__*/_interopDefaultLegacy(EventEmitter); function bind(fn, thisArg) { return function wrap() { @@ -45198,8 +44454,6 @@ 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 * @@ -45588,7 +44842,8 @@ const toObjectSet = (arrayOrString, delimiter) => { const noop = () => {}; const toFiniteNumber = (value, defaultValue) => { - return value != null && Number.isFinite(value = +value) ? value : defaultValue; + value = +value; + return Number.isFinite(value) ? value : defaultValue; }; const ALPHA = 'abcdefghijklmnopqrstuvwxyz'; @@ -45658,36 +44913,6 @@ const isAsyncFn = kindOfTest('AsyncFunction'); const isThenable = (thing) => thing && (isObject(thing) || isFunction(thing)) && isFunction(thing.then) && isFunction(thing.catch); -// original code -// https://github.com/DigitalBrainJS/AxiosPromise/blob/16deab13710ec09779922131f3fa5954320f83ab/lib/utils.js#L11-L34 - -const _setImmediate = ((setImmediateSupported, postMessageSupported) => { - if (setImmediateSupported) { - return setImmediate; - } - - return postMessageSupported ? ((token, callbacks) => { - _global.addEventListener("message", ({source, data}) => { - if (source === _global && data === token) { - callbacks.length && callbacks.shift()(); - } - }, false); - - return (cb) => { - callbacks.push(cb); - _global.postMessage(token, "*"); - } - })(`axios@${Math.random()}`, []) : (cb) => setTimeout(cb); -})( - typeof setImmediate === 'function', - isFunction(_global.postMessage) -); - -const asap = typeof queueMicrotask !== 'undefined' ? - queueMicrotask.bind(_global) : ( typeof process !== 'undefined' && process.nextTick || _setImmediate); - -// ********************* - const utils$1 = { isArray, isArrayBuffer, @@ -45699,10 +44924,6 @@ const utils$1 = { isBoolean, isObject, isPlainObject, - isReadableStream, - isRequest, - isResponse, - isHeaders, isUndefined, isDate, isFile, @@ -45743,9 +44964,7 @@ const utils$1 = { isSpecCompliantForm, toJSONObject, isAsyncFn, - isThenable, - setImmediate: _setImmediate, - asap + isThenable }; /** @@ -45773,10 +44992,7 @@ function AxiosError(message, code, config, request, response) { code && (this.code = code); config && (this.config = config); request && (this.request = request); - if (response) { - this.response = response; - this.status = response.status ? response.status : null; - } + response && (this.response = response); } utils$1.inherits(AxiosError, Error, { @@ -45796,7 +45012,7 @@ utils$1.inherits(AxiosError, Error, { // Axios config: utils$1.toJSONObject(this.config), code: this.code, - status: this.status + status: this.response && this.response.status ? this.response.status : null }; } }); @@ -46133,7 +45349,7 @@ function encode(val) { * * @param {string} url The base of the url (e.g., http://www.google.com) * @param {object} [params] The params to be appended - * @param {?(object|Function)} options + * @param {?object} options * * @returns {string} The formatted url */ @@ -46145,12 +45361,6 @@ function buildURL(url, params, options) { const _encode = options && options.encode || encode; - if (utils$1.isFunction(options)) { - options = { - serialize: options - }; - } - const serializeFn = options && options.serialize; let serializedParams; @@ -46263,8 +45473,6 @@ const platform$1 = { const hasBrowserEnv = typeof window !== 'undefined' && typeof document !== 'undefined'; -const _navigator = typeof navigator === 'object' && navigator || undefined; - /** * Determine if we're running in a standard browser environment * @@ -46282,8 +45490,10 @@ const _navigator = typeof navigator === 'object' && navigator || undefined; * * @returns {boolean} */ -const hasStandardBrowserEnv = hasBrowserEnv && - (!_navigator || ['ReactNative', 'NativeScript', 'NS'].indexOf(_navigator.product) < 0); +const hasStandardBrowserEnv = ( + (product) => { + return hasBrowserEnv && ['ReactNative', 'NativeScript', 'NS'].indexOf(product) < 0 + })(typeof navigator !== 'undefined' && navigator.product); /** * Determine if we're running in a standard browser webWorker environment @@ -46303,15 +45513,11 @@ const hasStandardBrowserWebWorkerEnv = (() => { ); })(); -const origin = hasBrowserEnv && window.location.href || 'http://localhost'; - const utils = /*#__PURE__*/Object.freeze({ __proto__: null, hasBrowserEnv: hasBrowserEnv, hasStandardBrowserWebWorkerEnv: hasStandardBrowserWebWorkerEnv, - hasStandardBrowserEnv: hasStandardBrowserEnv, - navigator: _navigator, - origin: origin + hasStandardBrowserEnv: hasStandardBrowserEnv }); const platform = { @@ -46379,9 +45585,6 @@ function arrayToObject(arr) { function formDataToJSON(formData) { function buildPath(path, value, target, index) { let name = path[index++]; - - if (name === '__proto__') return true; - const isNumericKey = Number.isFinite(+name); const isLast = index >= path.length; name = !name && utils$1.isArray(target) ? target.length : name; @@ -46451,7 +45654,7 @@ const defaults = { transitional: transitionalDefaults, - adapter: ['xhr', 'http', 'fetch'], + adapter: ['xhr', 'http'], transformRequest: [function transformRequest(data, headers) { const contentType = headers.getContentType() || ''; @@ -46465,6 +45668,9 @@ const defaults = { const isFormData = utils$1.isFormData(data); if (isFormData) { + if (!hasJSONContentType) { + return data; + } return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data; } @@ -46472,8 +45678,7 @@ const defaults = { utils$1.isBuffer(data) || utils$1.isStream(data) || utils$1.isFile(data) || - utils$1.isBlob(data) || - utils$1.isReadableStream(data) + utils$1.isBlob(data) ) { return data; } @@ -46516,10 +45721,6 @@ 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; @@ -46723,10 +45924,6 @@ 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); } @@ -47018,7 +46215,7 @@ function isAbsoluteURL(url) { */ function combineURLs(baseURL, relativeURL) { return relativeURL - ? baseURL.replace(/\/?\/$/, '') + '/' + relativeURL.replace(/^\/+/, '') + ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '') : baseURL; } @@ -47039,7 +46236,7 @@ function buildFullPath(baseURL, requestedURL) { return requestedURL; } -const VERSION = "1.7.9"; +const VERSION = "1.6.2"; function parseProtocol(url) { const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url); @@ -47094,6 +46291,88 @@ function fromDataURI(uri, asBlob, options) { throw new AxiosError('Unsupported protocol ' + protocol, AxiosError.ERR_NOT_SUPPORT); } +/** + * 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)); + } + }; +} + +/** + * 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; + }; +} + const kInternals = Symbol('internals'); class AxiosTransformStream extends stream__default["default"].Transform{ @@ -47113,8 +46392,12 @@ class AxiosTransformStream extends stream__default["default"].Transform{ 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, @@ -47126,6 +46409,8 @@ class AxiosTransformStream extends stream__default["default"].Transform{ onReadCallback: null }; + const _speedometer = speedometer(internals.ticksRate * options.samplesCount, internals.timeWindow); + this.on('newListener', event => { if (event === 'progress') { if (!internals.isCaptured) { @@ -47133,6 +46418,38 @@ class AxiosTransformStream extends stream__default["default"].Transform{ } } }); + + 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) { @@ -47146,6 +46463,7 @@ class AxiosTransformStream extends stream__default["default"].Transform{ } _transform(chunk, encoding, callback) { + const self = this; const internals = this[kInternals]; const maxRate = internals.maxRate; @@ -47157,14 +46475,16 @@ class AxiosTransformStream extends stream__default["default"].Transform{ const bytesThreshold = (maxRate / divider); const minChunkSize = internals.minChunkSize !== false ? Math.max(internals.minChunkSize, bytesThreshold * 0.01) : 0; - const pushChunk = (_chunk, _callback) => { + function pushChunk(_chunk, _callback) { const bytes = Buffer.byteLength(_chunk); internals.bytesSeen += bytes; internals.bytes += bytes; - internals.isCaptured && this.emit('progress', internals.bytesSeen); + if (internals.isCaptured) { + internals.updateProgress(); + } - if (this.push(_chunk)) { + if (self.push(_chunk)) { process.nextTick(_callback); } else { internals.onReadCallback = () => { @@ -47172,7 +46492,7 @@ class AxiosTransformStream extends stream__default["default"].Transform{ process.nextTick(_callback); }; } - }; + } const transformChunk = (_chunk, _callback) => { const chunkSize = Buffer.byteLength(_chunk); @@ -47229,6 +46549,11 @@ class AxiosTransformStream extends stream__default["default"].Transform{ } }); } + + setLength(length) { + this[kInternals].length = +length; + return this; + } } const AxiosTransformStream$1 = AxiosTransformStream; @@ -47251,7 +46576,7 @@ const readBlob$1 = readBlob; const BOUNDARY_ALPHABET = utils$1.ALPHABET.ALPHA_DIGIT + '-_'; -const textEncoder = typeof TextEncoder === 'function' ? new TextEncoder() : new util__default["default"].TextEncoder(); +const textEncoder = new util.TextEncoder(); const CRLF = '\r\n'; const CRLF_BYTES = textEncoder.encode(CRLF); @@ -47396,142 +46721,6 @@ const callbackify = (fn, reducer) => { const callbackify$1 = callbackify; -/** - * 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; - }; -} - -/** - * Throttle decorator - * @param {Function} fn - * @param {Number} freq - * @return {Function} - */ -function throttle(fn, freq) { - let timestamp = 0; - let threshold = 1000 / freq; - let lastArgs; - let timer; - - const invoke = (args, now = Date.now()) => { - timestamp = now; - lastArgs = null; - if (timer) { - clearTimeout(timer); - timer = null; - } - fn.apply(null, args); - }; - - const throttled = (...args) => { - const now = Date.now(); - const passed = now - timestamp; - if ( passed >= threshold) { - invoke(args, now); - } else { - lastArgs = args; - if (!timer) { - timer = setTimeout(() => { - timer = null; - invoke(lastArgs); - }, threshold - passed); - } - } - }; - - const flush = () => lastArgs && invoke(lastArgs); - - return [throttled, flush]; -} - -const progressEventReducer = (listener, isDownloadStream, freq = 3) => { - let bytesNotified = 0; - const _speedometer = speedometer(50, 250); - - 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; - - 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, - event: e, - lengthComputable: total != null, - [isDownloadStream ? 'download' : 'upload']: true - }; - - listener(data); - }, freq); -}; - -const progressEventDecorator = (total, throttled) => { - const lengthComputable = total != null; - - return [(loaded) => throttled[0]({ - lengthComputable, - total, - loaded - }), throttled[1]]; -}; - -const asyncDecorator = (fn) => (...args) => utils$1.asap(() => fn(...args)); - const zlibOptions = { flush: zlib__default["default"].constants.Z_SYNC_FLUSH, finishFlush: zlib__default["default"].constants.Z_SYNC_FLUSH @@ -47552,14 +46741,6 @@ const supportedProtocols = platform.protocols.map(protocol => { return protocol + ':'; }); -const flushOnFinish = (stream, [throttled, flush]) => { - stream - .on('end', flush) - .on('error', flush); - - return throttled; -}; - /** * If the proxy or config beforeRedirects functions are defined, call them with the options * object. @@ -47568,12 +46749,12 @@ const flushOnFinish = (stream, [throttled, flush]) => { * * @returns {Object} */ -function dispatchBeforeRedirect(options, responseDetails) { +function dispatchBeforeRedirect(options) { if (options.beforeRedirects.proxy) { options.beforeRedirects.proxy(options); } if (options.beforeRedirects.config) { - options.beforeRedirects.config(options, responseDetails); + options.beforeRedirects.config(options); } } @@ -47589,7 +46770,7 @@ function dispatchBeforeRedirect(options, responseDetails) { function setProxy(options, configProxy, location) { let proxy = configProxy; if (!proxy && proxy !== false) { - const proxyUrl = proxyFromEnv__default["default"].getProxyForUrl(location); + const proxyUrl = proxyFromEnv.getProxyForUrl(location); if (proxyUrl) { proxy = new URL(proxyUrl); } @@ -47686,10 +46867,6 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { // hotfix to support opt.all option which is required for node 20.x lookup = (hostname, opt, cb) => { _lookup(hostname, opt, (err, arg0, arg1) => { - if (err) { - return cb(err); - } - const addresses = utils$1.isArray(arg0) ? arg0.map(addr => buildAddressEntry(addr)) : [buildAddressEntry(arg0, arg1)]; opt.all ? cb(err, addresses) : cb(err, addresses[0].address, addresses[0].family); @@ -47698,7 +46875,7 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { } // temporary internal emitter until the AxiosRequest class will be implemented - const emitter = new events.EventEmitter(); + const emitter = new EventEmitter__default["default"](); const onFinished = () => { if (config.cancelToken) { @@ -47735,7 +46912,7 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { // Parse url const fullPath = buildFullPath(config.baseURL, config.url); - const parsed = new URL(fullPath, platform.hasBrowserEnv ? platform.origin : undefined); + const parsed = new URL(fullPath, 'http://localhost'); const protocol = parsed.protocol || supportedProtocols[0]; if (protocol === 'data:') { @@ -47793,7 +46970,8 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { // Only set header if it hasn't been set in config headers.set('User-Agent', 'axios/' + VERSION, false); - const {onUploadProgress, onDownloadProgress} = config; + const onDownloadProgress = config.onDownloadProgress; + const onUploadProgress = config.onUploadProgress; const maxRate = config.maxRate; let maxUploadRate = undefined; let maxDownloadRate = undefined; @@ -47820,7 +46998,7 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { } catch (e) { } } - } else if (utils$1.isBlob(data) || utils$1.isFile(data)) { + } else if (utils$1.isBlob(data)) { data.size && headers.setContentType(data.type || 'application/octet-stream'); headers.setContentLength(data.size || 0); data = stream__default["default"].Readable.from(readBlob$1(data)); @@ -47864,16 +47042,15 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { } data = stream__default["default"].pipeline([data, new AxiosTransformStream$1({ + length: contentLength, maxRate: utils$1.toFiniteNumber(maxUploadRate) })], utils$1.noop); - onUploadProgress && data.on('progress', flushOnFinish( - data, - progressEventDecorator( - contentLength, - progressEventReducer(asyncDecorator(onUploadProgress), false, 3) - ) - )); + onUploadProgress && data.on('progress', progress => { + onUploadProgress(Object.assign(progress, { + upload: true + })); + }); } // HTTP basic authentication @@ -47931,7 +47108,7 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { if (config.socketPath) { options.socketPath = config.socketPath; } else { - options.hostname = parsed.hostname.startsWith("[") ? parsed.hostname.slice(1, -1) : parsed.hostname; + options.hostname = parsed.hostname; options.port = parsed.port; setProxy(options, config.proxy, protocol + '//' + parsed.hostname + (parsed.port ? ':' + parsed.port : '') + options.path); } @@ -47972,18 +47149,17 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { const responseLength = +res.headers['content-length']; - if (onDownloadProgress || maxDownloadRate) { + if (onDownloadProgress) { const transformStream = new AxiosTransformStream$1({ + length: utils$1.toFiniteNumber(responseLength), maxRate: utils$1.toFiniteNumber(maxDownloadRate) }); - onDownloadProgress && transformStream.on('progress', flushOnFinish( - transformStream, - progressEventDecorator( - responseLength, - progressEventReducer(asyncDecorator(onDownloadProgress), true, 3) - ) - )); + onDownloadProgress && transformStream.on('progress', progress => { + onDownloadProgress(Object.assign(progress, { + download: true + })); + }); streams.push(transformStream); } @@ -48073,7 +47249,7 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { } const err = new AxiosError( - 'stream has been aborted', + 'maxContentLength size of ' + config.maxContentLength + ' exceeded', AxiosError.ERR_BAD_RESPONSE, config, lastRequest @@ -48196,19 +47372,6 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { }); }; -const isURLSameOrigin = 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; - const cookies = platform.hasStandardBrowserEnv ? // Standard browser envs support document.cookie @@ -48248,183 +47411,143 @@ const cookies = platform.hasStandardBrowserEnv ? remove() {} }; -const headersToObject = (thing) => thing instanceof AxiosHeaders$1 ? { ...thing } : thing; +const isURLSameOrigin = platform.hasStandardBrowserEnv ? -/** - * 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 = {}; +// 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; - function getMergedValue(target, source, prop, 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, prop , caseless) { - if (!utils$1.isUndefined(b)) { - return getMergedValue(a, b, prop , caseless); - } else if (!utils$1.isUndefined(a)) { - return getMergedValue(undefined, a, prop , 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); + /** + * Parse a URL to discover its 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); + href = urlParsingNode.href; + } + + 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 + }; } - } - 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 , prop) => mergeDeepProperties(headersToObject(a), headersToObject(b),prop, true) - }; + originURL = resolveURL(window.location.href); - 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)) : '')) - ); - } + /** + * 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$1.isString(requestURL)) ? resolveURL(requestURL) : requestURL; + return (parsed.protocol === originURL.protocol && + parsed.host === originURL.host); + }; + })() : - let contentType; + // Non standard browser envs (web workers, react-native) lack needed support. + (function nonStandardBrowserEnv() { + return function isURLSameOrigin() { + return true; + }; + })(); - 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('; ')); - } - } +function progressEventReducer(listener, isDownloadStream) { + let bytesNotified = 0; + const _speedometer = speedometer(50, 250); - // 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. + 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; - if (platform.hasStandardBrowserEnv) { - withXSRFToken && utils$1.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(newConfig)); + bytesNotified = loaded; - if (withXSRFToken || (withXSRFToken !== false && isURLSameOrigin(newConfig.url))) { - // Add xsrf header - const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName); + 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 + }; - if (xsrfValue) { - headers.set(xsrfHeaderName, xsrfValue); - } - } - } + data[isDownloadStream ? 'download' : 'upload'] = true; - return newConfig; -}; + listener(data); + }; +} const isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined'; const xhrAdapter = isXHRAdapterSupported && function (config) { return new Promise(function dispatchXhrRequest(resolve, reject) { - const _config = resolveConfig(config); - let requestData = _config.data; - const requestHeaders = AxiosHeaders$1.from(_config.headers).normalize(); - let {responseType, onUploadProgress, onDownloadProgress} = _config; + let requestData = config.data; + const requestHeaders = AxiosHeaders$1.from(config.headers).normalize(); + let {responseType, withXSRFToken} = config; let onCanceled; - let uploadThrottled, downloadThrottled; - let flushUpload, flushDownload; - function done() { - flushUpload && flushUpload(); // flush events - flushDownload && flushDownload(); // flush events + if (config.cancelToken) { + config.cancelToken.unsubscribe(onCanceled); + } + + if (config.signal) { + config.signal.removeEventListener('abort', onCanceled); + } + } - _config.cancelToken && _config.cancelToken.unsubscribe(onCanceled); + let contentType; - _config.signal && _config.signal.removeEventListener('abort', onCanceled); + 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('; ')); + } } let request = new XMLHttpRequest(); - request.open(_config.method.toUpperCase(), _config.url, true); + // 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); // Set the request timeout in MS - request.timeout = _config.timeout; + request.timeout = config.timeout; function onloadend() { if (!request) { @@ -48504,10 +47627,10 @@ 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, @@ -48519,6 +47642,22 @@ const xhrAdapter = isXHRAdapterSupported && function (config) { 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); @@ -48530,31 +47669,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 (onDownloadProgress) { - ([downloadThrottled, flushDownload] = progressEventReducer(onDownloadProgress, true)); - request.addEventListener('progress', downloadThrottled); + if (typeof config.onDownloadProgress === 'function') { + request.addEventListener('progress', progressEventReducer(config.onDownloadProgress, true)); } // Not all browsers support upload events - if (onUploadProgress && request.upload) { - ([uploadThrottled, flushUpload] = progressEventReducer(onUploadProgress)); - - request.upload.addEventListener('progress', uploadThrottled); - - request.upload.addEventListener('loadend', flushUpload); + 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 => { @@ -48566,13 +47700,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(_config.url); + const protocol = parseProtocol(fullPath); if (protocol && platform.protocols.indexOf(protocol) === -1) { reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config)); @@ -48585,360 +47719,9 @@ const xhrAdapter = isXHRAdapterSupported && function (config) { }); }; -const composeSignals = (signals, timeout) => { - const {length} = (signals = signals ? signals.filter(Boolean) : []); - - if (timeout || length) { - let controller = new AbortController(); - - let aborted; - - const onabort = function (reason) { - if (!aborted) { - 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)); - } - }; - - let timer = timeout && setTimeout(() => { - timer = null; - onabort(new AxiosError(`timeout ${timeout} of 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 = null; - } - }; - - signals.forEach((signal) => signal.addEventListener('abort', onabort)); - - const {signal} = controller; - - signal.unsubscribe = () => utils$1.asap(unsubscribe); - - return signal; - } -}; - -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 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]) { - yield* stream; - return; - } - - const reader = stream.getReader(); - try { - for (;;) { - const {done, value} = await reader.read(); - if (done) { - break; - } - yield value; - } - } finally { - await reader.cancel(); - } -}; - -const trackStream = (stream, chunkSize, onProgress, onFinish) => { - const iterator = readBytes(stream, chunkSize); - - let bytes = 0; - let done; - let _onFinish = (e) => { - if (!done) { - done = true; - onFinish && onFinish(e); - } - }; - - return new ReadableStream({ - async pull(controller) { - try { - const {done, value} = await iterator.next(); - - 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; - } - }, - cancel(reason) { - _onFinish(reason); - return iterator.return(); - } - }, { - highWaterMark: 2 - }) -}; - -const isFetchSupported = typeof fetch === 'function' && typeof Request === 'function' && typeof Response === 'function'; -const isReadableStreamSupported = isFetchSupported && typeof ReadableStream === 'function'; - -// used only inside the fetch adapter -const encodeText = isFetchSupported && (typeof TextEncoder === 'function' ? - ((encoder) => (str) => encoder.encode(str))(new TextEncoder()) : - async (str) => new Uint8Array(await new Response(str).arrayBuffer()) -); - -const test = (fn, ...args) => { - try { - return !!fn(...args); - } catch (e) { - return false - } -}; - -const supportsRequestStream = isReadableStreamSupported && test(() => { - 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 supportsResponseStream = isReadableStreamSupported && - test(() => utils$1.isReadableStream(new Response('').body)); - - -const resolvers = { - stream: supportsResponseStream && ((res) => res.body) -}; - -isFetchSupported && (((res) => { - ['text', 'arrayBuffer', 'blob', 'formData', 'stream'].forEach(type => { - !resolvers[type] && (resolvers[type] = utils$1.isFunction(res[type]) ? (res) => res[type]() : - (_, config) => { - throw new AxiosError(`Response type '${type}' is not supported`, AxiosError.ERR_NOT_SUPPORT, config); - }); - }); -})(new Response)); - -const getBodyLength = async (body) => { - if (body == null) { - return 0; - } - - if(utils$1.isBlob(body)) { - return body.size; - } - - if(utils$1.isSpecCompliantForm(body)) { - const _request = new Request(platform.origin, { - method: 'POST', - body, - }); - return (await _request.arrayBuffer()).byteLength; - } - - if(utils$1.isArrayBufferView(body) || utils$1.isArrayBuffer(body)) { - return body.byteLength; - } - - if(utils$1.isURLSearchParams(body)) { - body = body + ''; - } - - if(utils$1.isString(body)) { - return (await encodeText(body)).byteLength; - } -}; - -const resolveBodyLength = async (headers, body) => { - const length = utils$1.toFiniteNumber(headers.getContentLength()); - - return length == null ? getBodyLength(body) : length; -}; - -const fetchAdapter = isFetchSupported && (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 = composeSignals$1([signal, cancelToken && cancelToken.toAbortSignal()], timeout); - - let request; - - const unsubscribe = composedSignal && composedSignal.unsubscribe && (() => { - composedSignal.unsubscribe(); - }); - - let requestContentLength; - - try { - if ( - onUploadProgress && supportsRequestStream && method !== 'get' && method !== 'head' && - (requestContentLength = await resolveBodyLength(headers, data)) !== 0 - ) { - let _request = new Request(url, { - method: 'POST', - body: data, - duplex: "half" - }); - - let contentTypeHeader; - - if (utils$1.isFormData(data) && (contentTypeHeader = _request.headers.get('content-type'))) { - headers.setContentType(contentTypeHeader); - } - - if (_request.body) { - const [onProgress, flush] = progressEventDecorator( - requestContentLength, - progressEventReducer(asyncDecorator(onUploadProgress)) - ); - - data = trackStream(_request.body, DEFAULT_CHUNK_SIZE, onProgress, flush); - } - } - - if (!utils$1.isString(withCredentials)) { - withCredentials = withCredentials ? 'include' : 'omit'; - } - - // Cloudflare Workers throws when credentials are defined - // see https://github.com/cloudflare/workerd/issues/902 - const isCredentialsSupported = "credentials" in Request.prototype; - request = new Request(url, { - ...fetchOptions, - signal: composedSignal, - method: method.toUpperCase(), - headers: headers.normalize().toJSON(), - body: data, - duplex: "half", - credentials: isCredentialsSupported ? withCredentials : undefined - }); - - let response = await fetch(request); - - const isStreamResponse = supportsResponseStream && (responseType === 'stream' || responseType === 'response'); - - if (supportsResponseStream && (onDownloadProgress || (isStreamResponse && unsubscribe))) { - const options = {}; - - ['status', 'statusText', 'headers'].forEach(prop => { - options[prop] = response[prop]; - }); - - const responseContentLength = utils$1.toFiniteNumber(response.headers.get('content-length')); - - const [onProgress, flush] = onDownloadProgress && progressEventDecorator( - responseContentLength, - progressEventReducer(asyncDecorator(onDownloadProgress), true) - ) || []; - - response = new Response( - trackStream(response.body, DEFAULT_CHUNK_SIZE, onProgress, () => { - flush && flush(); - unsubscribe && unsubscribe(); - }), - options - ); - } - - responseType = responseType || 'text'; - - let responseData = await resolvers[utils$1.findKey(resolvers, responseType) || 'text'](response, config); - - !isStreamResponse && unsubscribe && unsubscribe(); - - 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) { - unsubscribe && unsubscribe(); - - if (err && err.name === 'TypeError' && /fetch/i.test(err.message)) { - throw Object.assign( - new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request), - { - cause: err.cause || err - } - ) - } - - throw AxiosError.from(err, err && err.code, config, request); - } -}); - const knownAdapters = { http: httpAdapter, - xhr: xhrAdapter, - fetch: fetchAdapter + xhr: xhrAdapter }; utils$1.forEach(knownAdapters, (fn, value) => { @@ -49082,6 +47865,108 @@ function dispatchRequest(config) { }); } +const headersToObject = (thing) => thing instanceof AxiosHeaders$1 ? thing.toJSON() : 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 @@ -49131,14 +48016,6 @@ validators$1.transitional = function transitional(validator, version, message) { }; }; -validators$1.spelling = function spelling(correctSpelling) { - return (value, opt) => { - // eslint-disable-next-line no-console - console.warn(`${opt} is likely a misspelling of ${correctSpelling}`); - return true; - } -}; - /** * Assert object's properties type * @@ -49203,34 +48080,7 @@ class Axios { * * @returns {Promise} The Promise to be fulfilled */ - async request(configOrUrl, config) { - try { - return await this._request(configOrUrl, config); - } catch (err) { - if (err instanceof Error) { - let dummy = {}; - - Error.captureStackTrace ? Error.captureStackTrace(dummy) : (dummy = new Error()); - - // slice off the Error: ... line - const stack = dummy.stack ? dummy.stack.replace(/^.+\n/, '') : ''; - try { - if (!err.stack) { - err.stack = stack; - // match without the 2 top stack lines - } else if (stack && !String(err.stack).endsWith(stack.replace(/^.+\n.+\n/, ''))) { - err.stack += '\n' + stack; - } - } catch (e) { - // ignore the case where "stack" is an un-writable property - } - } - - throw err; - } - } - - _request(configOrUrl, config) { + request(configOrUrl, config) { /*eslint no-param-reassign:0*/ // Allow for axios('example/url'[, config]) a la fetch API if (typeof configOrUrl === 'string') { @@ -49265,11 +48115,6 @@ class Axios { } } - validator.assertOptions(config, { - baseUrl: validators.spelling('baseURL'), - withXsrfToken: validators.spelling('withXSRFToken') - }, true); - // Set config.method config.method = (config.method || this.defaults.method || 'get').toLowerCase(); @@ -49500,20 +48345,6 @@ class CancelToken { } } - toAbortSignal() { - const controller = new AbortController(); - - const abort = (err) => { - controller.abort(err); - }; - - this.subscribe(abort); - - controller.signal.unsubscribe = () => this.unsubscribe(abort); - - return controller.signal; - } - /** * Returns an object that contains a new `CancelToken` and a function that, when called, * cancels the `CancelToken`. diff --git a/package-lock.json b/package-lock.json index a151f57..0af9c34 100644 --- a/package-lock.json +++ b/package-lock.json @@ -979,13 +979,12 @@ } }, "node_modules/axios": { - "version": "1.7.9", - "resolved": "https://registry.npmjs.org/axios/-/axios-1.7.9.tgz", - "integrity": "sha512-LhLcE7Hbiryz8oMDdDptSrWowmB4Bl6RCt6sIJKpRB4XtVf0iEgewX3au/pJqm+Py1kCASkb/FFKjxQaLtxJvw==", + "version": "1.6.2", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.6.2.tgz", + "integrity": "sha512-7i24Ri4pmDRfJTR7LDBhsOTtcm+9kjX5WiY1X3wIisx6G9So3pfMkEiU7emUBe46oceVImccTEM3k6C5dbVW8A==", "dev": true, - "license": "MIT", "dependencies": { - "follow-redirects": "^1.15.6", + "follow-redirects": "^1.15.0", "form-data": "^4.0.0", "proxy-from-env": "^1.1.0" } @@ -1195,11 +1194,10 @@ "dev": true }, "node_modules/cross-spawn": { - "version": "7.0.6", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", - "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", + "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==", "dev": true, - "license": "MIT", "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", @@ -3277,13 +3275,12 @@ } }, "node_modules/micromatch": { - "version": "4.0.8", - "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", - "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.5.tgz", + "integrity": "sha512-DMy+ERcEW2q8Z2Po+WNXuw3c5YaUSFjAO5GsJqfEl7UjvtIuFKO6ZrKvcItdy98dwFI2N1tg3zNIdKaQT+aNdA==", "dev": true, - "license": "MIT", "dependencies": { - "braces": "^3.0.3", + "braces": "^3.0.2", "picomatch": "^2.3.1" }, "engines": { @@ -4406,11 +4403,10 @@ } }, "node_modules/undici": { - "version": "5.28.5", - "resolved": "https://registry.npmjs.org/undici/-/undici-5.28.5.tgz", - "integrity": "sha512-zICwjrDrcrUE0pyyJc1I2QzBkLM8FINsgOrt6WjA+BgajVq9Nxu2PbFFXUrAggLfDXlZGZBVZYw7WNV5KiBiBA==", + "version": "5.28.4", + "resolved": "https://registry.npmjs.org/undici/-/undici-5.28.4.tgz", + "integrity": "sha512-72RFADWFqKmUb2hmmvNODKL3p9hcB6Gt2DOQMis1SEBaV6a4MH8soBvzg+95CYhCKPFedut2JY9bMfrDl9D23g==", "dev": true, - "license": "MIT", "dependencies": { "@fastify/busboy": "^2.0.0" }, @@ -5330,12 +5326,12 @@ "dev": true }, "axios": { - "version": "1.7.9", - "resolved": "https://registry.npmjs.org/axios/-/axios-1.7.9.tgz", - "integrity": "sha512-LhLcE7Hbiryz8oMDdDptSrWowmB4Bl6RCt6sIJKpRB4XtVf0iEgewX3au/pJqm+Py1kCASkb/FFKjxQaLtxJvw==", + "version": "1.6.2", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.6.2.tgz", + "integrity": "sha512-7i24Ri4pmDRfJTR7LDBhsOTtcm+9kjX5WiY1X3wIisx6G9So3pfMkEiU7emUBe46oceVImccTEM3k6C5dbVW8A==", "dev": true, "requires": { - "follow-redirects": "^1.15.6", + "follow-redirects": "^1.15.0", "form-data": "^4.0.0", "proxy-from-env": "^1.1.0" } @@ -5486,9 +5482,9 @@ "dev": true }, "cross-spawn": { - "version": "7.0.6", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", - "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", + "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==", "dev": true, "requires": { "path-key": "^3.1.0", @@ -6968,12 +6964,12 @@ "dev": true }, "micromatch": { - "version": "4.0.8", - "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", - "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.5.tgz", + "integrity": "sha512-DMy+ERcEW2q8Z2Po+WNXuw3c5YaUSFjAO5GsJqfEl7UjvtIuFKO6ZrKvcItdy98dwFI2N1tg3zNIdKaQT+aNdA==", "dev": true, "requires": { - "braces": "^3.0.3", + "braces": "^3.0.2", "picomatch": "^2.3.1" } }, @@ -7739,9 +7735,9 @@ } }, "undici": { - "version": "5.28.5", - "resolved": "https://registry.npmjs.org/undici/-/undici-5.28.5.tgz", - "integrity": "sha512-zICwjrDrcrUE0pyyJc1I2QzBkLM8FINsgOrt6WjA+BgajVq9Nxu2PbFFXUrAggLfDXlZGZBVZYw7WNV5KiBiBA==", + "version": "5.28.4", + "resolved": "https://registry.npmjs.org/undici/-/undici-5.28.4.tgz", + "integrity": "sha512-72RFADWFqKmUb2hmmvNODKL3p9hcB6Gt2DOQMis1SEBaV6a4MH8soBvzg+95CYhCKPFedut2JY9bMfrDl9D23g==", "dev": true, "requires": { "@fastify/busboy": "^2.0.0"