diff --git a/dist/index.js b/dist/index.js index 9f294b8..f198822 100644 --- a/dist/index.js +++ b/dist/index.js @@ -10748,11 +10748,77 @@ class Request { } } - onUpgrade (statusCode, headers, socket) { + /** + * @param {number|null} statusCode + * @param {Buffer[]|null} headers + * @param {import('node:stream').Duplex} socket + * @param {string} [statusText] + */ + onUpgrade (statusCode, headers, socket, statusText = '') { + this.onFinally() + assert(!this.aborted) assert(!this.completed) - return this[kHandler].onUpgrade(statusCode, headers, socket) + if (statusCode !== null) { + this.#publishUpgradeHeaders(statusCode, headers, statusText) + } + + const result = this[kHandler].onUpgrade(statusCode, headers, socket) + + if (!this.aborted) { + this.completed = true + if (statusCode !== null) { + this.#publishUpgradeTrailers() + } + } + + return result + } + + /** + * @param {number} statusCode + * @param {import('node:http2').IncomingHttpHeaders} headers + * @param {(headers: import('node:http2').IncomingHttpHeaders) => Buffer[]} parseHeaders + * @param {string} [statusText] + */ + onUpgradeResponse (statusCode, headers, parseHeaders, statusText = '') { + assert(!this.aborted) + assert(this.completed) + + if (channels.headers.hasSubscribers) { + this.#publishUpgradeHeaders(statusCode, parseHeaders(headers), statusText) + } + this.#publishUpgradeTrailers() + } + + /** + * @param {Error} error + */ + onUpgradeError (error) { + assert(!this.aborted) + assert(this.completed) + + if (channels.error.hasSubscribers) { + channels.error.publish({ request: this, error }) + } + } + + /** + * @param {number} statusCode + * @param {Buffer[]} headers + * @param {string} statusText + */ + #publishUpgradeHeaders (statusCode, headers, statusText) { + if (channels.headers.hasSubscribers) { + channels.headers.publish({ request: this, response: { statusCode, headers, statusText } }) + } + } + + #publishUpgradeTrailers () { + if (channels.trailers.hasSubscribers) { + channels.trailers.publish({ request: this, trailers: [] }) + } } onComplete (trailers) { @@ -12651,7 +12717,7 @@ class Parser { } onUpgrade (head) { - const { upgrade, client, socket, headers, statusCode } = this + const { upgrade, client, socket, headers, statusCode, statusText } = this assert(upgrade) assert(client[kSocket] === socket) @@ -12686,9 +12752,10 @@ class Parser { client.emit('disconnect', client[kUrl], [client], new InformationalError('upgrade')) try { - request.onUpgrade(statusCode, headers, socket) - } catch (err) { - util.destroy(socket, err) + request.onUpgrade(statusCode, headers, socket, statusText) + } catch (error) { + util.errorRequest(client, request, error) + util.destroy(socket, error) } client[kResume]() @@ -13095,7 +13162,7 @@ async function connectH1 (client, socket) { function clearIdleSocketValidation (socket) { if (socket[kIdleSocketValidationTimeout]) { - clearTimeout(socket[kIdleSocketValidationTimeout]) + clearImmediate(socket[kIdleSocketValidationTimeout]) socket[kIdleSocketValidationTimeout] = null } @@ -13104,15 +13171,23 @@ function clearIdleSocketValidation (socket) { function scheduleIdleSocketValidation (client, socket) { socket[kIdleSocketValidation] = 1 - socket[kIdleSocketValidationTimeout] = setTimeout(() => { + // Yield to the check phase (after poll) so unsolicited bytes / FIN / RST + // already pending on this idle keep-alive socket are processed before the + // next request is written (GHSA-35p6-xmwp-9g52). + // + // setTimeout(0) pays Node's ~1ms timer floor on every sequential reuse + // (#5493). setImmediate avoids that, but an *unref'd* Immediate lets poll + // block for ~500ms when the event loop is otherwise idle (#5600 / #5606). + // A ref'd Immediate both keeps the pending request alive and makes poll + // return immediately — the hybrid those issues asked for. + socket[kIdleSocketValidationTimeout] = setImmediate(() => { socket[kIdleSocketValidationTimeout] = null socket[kIdleSocketValidation] = 2 if (client[kSocket] === socket && !socket.destroyed) { client[kResume]() } - }, 0) - socket[kIdleSocketValidationTimeout].unref?.() + }) } /** @@ -13261,12 +13336,22 @@ function writeH1 (client, request) { const socket = client[kSocket] clearIdleSocketValidation(socket) - const abort = (err) => { - if (request.aborted || request.completed) { + /** + * @param {Error} [error] + */ + const abort = (error) => { + if (request.aborted) { + return + } + + if (request.completed) { + if (request.upgrade || request.method === 'CONNECT') { + util.destroy(socket, new InformationalError('aborted')) + } return } - util.errorRequest(client, request, err || new RequestAbortedError()) + util.errorRequest(client, request, error || new RequestAbortedError()) util.destroy(body) util.destroy(socket, new InformationalError('aborted')) @@ -13723,6 +13808,7 @@ module.exports = connectH1 const assert = __nccwpck_require__(4589) +const { errorMonitor } = __nccwpck_require__(8474) const { pipeline } = __nccwpck_require__(7075) const util = __nccwpck_require__(3440) const { @@ -13799,6 +13885,15 @@ function parseH2Headers (headers) { return result } +/** + * @param {import('node:http2').IncomingHttpHeaders} headers + * @returns {Buffer[]} + */ +function parseH2ResponseHeaders (headers) { + const { [HTTP2_HEADER_STATUS]: _statusCode, ...realHeaders } = headers + return parseH2Headers(realHeaders) +} + async function connectH2 (client, socket) { client[kSocket] = socket @@ -14019,22 +14114,32 @@ function writeH2 (client, request) { headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ''}` headers[HTTP2_HEADER_METHOD] = method - const abort = (err) => { - if (request.aborted || request.completed) { + /** + * @param {Error} [error] + */ + const abort = (error) => { + if (request.aborted) { return } - err = err || new RequestAbortedError() + if (request.completed) { + if (method === 'CONNECT' && stream != null) { + util.destroy(stream, error || new RequestAbortedError()) + } + return + } - util.errorRequest(client, request, err) + error = error || new RequestAbortedError() + + util.errorRequest(client, request, error) if (stream != null) { - util.destroy(stream, err) + util.destroy(stream, error) } // We do not destroy the socket as we can continue using the session // the stream get's destroyed and the session remains to create new streams - util.destroy(body, err) + util.destroy(body, error) client[kQueue][client[kRunningIdx]++] = null client[kResume]() } @@ -14053,25 +14158,57 @@ function writeH2 (client, request) { if (method === 'CONNECT') { session.ref() - // We are already connected, streams are pending, first request - // will create a new stream. We trigger a request to create the stream and wait until - // `ready` event is triggered // We disabled endStream to allow the user to write to the stream stream = session.request(headers, { endStream: false, signal }) + let upgradeResponseFinished = false - if (stream.id && !stream.pending) { - request.onUpgrade(null, null, stream) - ++session[kOpenStreams] - client[kQueue][client[kRunningIdx]++] = null - } else { - stream.once('ready', () => { + /** + * @param {import('node:http2').IncomingHttpHeaders} headers + */ + const onResponse = (headers) => { + upgradeResponseFinished = true + stream.off(errorMonitor, onUpgradeError) + request.onUpgradeResponse(Number(headers[HTTP2_HEADER_STATUS]), headers, parseH2ResponseHeaders) + } + + /** + * @param {Error} error + */ + const onUpgradeError = (error) => { + upgradeResponseFinished = true + stream.off('response', onResponse) + request.onUpgradeError(error) + } + + const onReady = () => { + try { request.onUpgrade(null, null, stream) - ++session[kOpenStreams] - client[kQueue][client[kRunningIdx]++] = null - }) + } catch (error) { + stream.off('response', onResponse) + abort(error) + return + } + + if (request.aborted) { + return + } + + stream.off('error', abort) + stream.once(errorMonitor, onUpgradeError) + client[kQueue][client[kRunningIdx]++] = null } + stream.once('response', onResponse) + stream.once('error', abort) + ++session[kOpenStreams] + onReady() + stream.once('close', () => { + if (!upgradeResponseFinished && request.completed) { + stream.off('response', onResponse) + stream.off(errorMonitor, onUpgradeError) + request.onUpgradeError(new InformationalError(`HTTP/2: "stream error" received - code ${stream.rstCode}`)) + } session[kOpenStreams] -= 1 if (session[kOpenStreams] === 0) session.unref() }) @@ -16770,6 +16907,7 @@ class RetryHandler { this.end = null this.etag = null this.resume = null + this.headersSent = false // Handle possible onConnect duplication this.handler.onConnect(reason => { @@ -16782,6 +16920,20 @@ class RetryHandler { }) } + checkpointResponseEnd (headers, resume) { + if (this.end == null && this.opts.method !== 'HEAD') { + const contentLength = headers['content-length'] + this.end = contentLength != null ? Number(contentLength) - 1 : null + + assert( + this.end == null || Number.isFinite(this.end), + 'invalid content-length' + ) + } + + this.resume = this.end != null ? resume : null + } + onRequestSent () { if (this.handler.onRequestSent) { this.handler.onRequestSent() @@ -16870,7 +17022,12 @@ class RetryHandler { this.retryCount += 1 if (statusCode >= 300) { - if (this.retryOpts.statusCodes.includes(statusCode) === false) { + // Only expose a response if no earlier attempt has reached the caller. + // Otherwise abort this attempt so the error settles the existing body + // instead of replacing it with a new response. + if (!this.headersSent && this.retryOpts.statusCodes.includes(statusCode) === false) { + this.headersSent = true + this.checkpointResponseEnd(headers, resume) return this.handler.onHeaders( statusCode, rawHeaders, @@ -16939,8 +17096,15 @@ class RetryHandler { const { start, size, end = size - 1 } = contentRange - assert(this.start === start, 'content-range mismatch') - assert(this.end == null || this.end === end, 'content-range mismatch') + if (this.start !== start || (this.end != null && this.end !== end)) { + this.abort( + new RequestRetryError('Content-Range mismatch', statusCode, { + headers, + data: { count: this.retryCount } + }) + ) + return false + } this.resume = resume return true @@ -16952,6 +17116,7 @@ class RetryHandler { const range = parseRangeHeader(headers['content-range']) if (range == null) { + this.headersSent = true return this.handler.onHeaders( statusCode, rawHeaders, @@ -16990,6 +17155,7 @@ class RetryHandler { ) this.resume = resume + this.headersSent = true this.etag = headers.etag != null ? headers.etag : null // Weak etags are not useful for comparison nor cache @@ -17029,7 +17195,7 @@ class RetryHandler { } onError (err) { - if (this.aborted || isDisturbed(this.opts.body)) { + if (this.aborted || isDisturbed(this.opts.body) || (this.headersSent && this.resume == null)) { return this.handler.onError(err) } @@ -21487,6 +21653,49 @@ const COLON = 0x3A */ const SPACE = 0x20 +const DATA = Buffer.from('data') +const EVENT = Buffer.from('event') +const ID = Buffer.from('id') +const RETRY = Buffer.from('retry') + +function isASCIINumberBytes (buffer, start) { + if (start >= buffer.length) { + return false + } + + for (let i = start; i < buffer.length; i++) { + if (buffer[i] < 0x30 || buffer[i] > 0x39) { + return false + } + } + + return true +} + +function isValidLastEventIdBytes (buffer, start) { + for (let i = start; i < buffer.length; i++) { + if (buffer[i] === 0x00) { + return false + } + } + + return true +} + +function isFieldName (line, length, field) { + if (length !== field.length) { + return false + } + + for (let i = 0; i < length; i++) { + if (line[i] !== field[i]) { + return false + } + } + + return true +} + /** * @typedef {object} EventSourceStreamEvent * @type {object} @@ -21527,11 +21736,14 @@ class EventSourceStream extends Transform { eventEndCheck = false /** - * @type {Buffer} + * @type {Buffer[]} */ - buffer = null + chunks = [] + chunkIndex = 0 pos = 0 + lineChunkIndex = 0 + linePos = 0 event = { data: undefined, @@ -21570,92 +21782,20 @@ class EventSourceStream extends Transform { return } - // Cache the chunk in the buffer, as the data might not be complete while - // processing it - // TODO: Investigate if there is a more performant way to handle - // incoming chunks - // see: https://github.com/nodejs/undici/issues/2630 - if (this.buffer) { - this.buffer = Buffer.concat([this.buffer, chunk]) - } else { - this.buffer = chunk - } + this.chunks.push(chunk) // Strip leading byte-order-mark if we opened the stream and started // the processing of the incoming data if (this.checkBOM) { - switch (this.buffer.length) { - case 1: - // Check if the first byte is the same as the first byte of the BOM - if (this.buffer[0] === BOM[0]) { - // If it is, we need to wait for more data - callback() - return - } - // Set the checkBOM flag to false as we don't need to check for the - // BOM anymore - this.checkBOM = false - - // The buffer only contains one byte so we need to wait for more data - callback() - return - case 2: - // Check if the first two bytes are the same as the first two bytes - // of the BOM - if ( - this.buffer[0] === BOM[0] && - this.buffer[1] === BOM[1] - ) { - // If it is, we need to wait for more data, because the third byte - // is needed to determine if it is the BOM or not - callback() - return - } - - // Set the checkBOM flag to false as we don't need to check for the - // BOM anymore - this.checkBOM = false - break - case 3: - // Check if the first three bytes are the same as the first three - // bytes of the BOM - if ( - this.buffer[0] === BOM[0] && - this.buffer[1] === BOM[1] && - this.buffer[2] === BOM[2] - ) { - // If it is, we can drop the buffered data, as it is only the BOM - this.buffer = Buffer.alloc(0) - // Set the checkBOM flag to false as we don't need to check for the - // BOM anymore - this.checkBOM = false - - // Await more data - callback() - return - } - // If it is not the BOM, we can start processing the data - this.checkBOM = false - break - default: - // The buffer is longer than 3 bytes, so we can drop the BOM if it is - // present - if ( - this.buffer[0] === BOM[0] && - this.buffer[1] === BOM[1] && - this.buffer[2] === BOM[2] - ) { - // Remove the BOM from the buffer - this.buffer = this.buffer.subarray(3) - } - - // Set the checkBOM flag to false as we don't need to check for the - this.checkBOM = false - break + if (this.handleBOM()) { + callback() + return } } - while (this.pos < this.buffer.length) { + while (this.hasCurrentByte()) { + const byte = this.currentByte() + // If the previous line ended with an end-of-line, we need to check // if the next character is also an end-of-line. if (this.eventEndCheck) { @@ -21668,10 +21808,9 @@ class EventSourceStream extends Transform { if (this.crlfCheck) { // If the current character is a line feed, we can remove it // from the buffer and reset the crlfCheck flag - if (this.buffer[this.pos] === LF) { - this.buffer = this.buffer.subarray(this.pos + 1) - this.pos = 0 + if (byte === LF) { this.crlfCheck = false + this.consumeCurrentByte() // It is possible that the line feed is not the end of the // event. We need to check if the next character is an @@ -21687,19 +21826,17 @@ class EventSourceStream extends Transform { this.crlfCheck = false } - if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (byte === LF || byte === CR) { // If the current character is a carriage return, we need to // set the crlfCheck flag to true, as we need to check if the // next character is a line feed so we can remove it from the // buffer - if (this.buffer[this.pos] === CR) { + if (byte === CR) { this.crlfCheck = true } - this.buffer = this.buffer.subarray(this.pos + 1) - this.pos = 0 - if ( - this.event.data !== undefined || this.event.event || this.event.id || this.event.retry) { + this.consumeCurrentByte() + if (this.hasPendingEvent()) { this.processEvent(this.event) } this.clearEvent() @@ -21713,22 +21850,18 @@ class EventSourceStream extends Transform { // If the current character is an end-of-line, we can process the // line - if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (byte === LF || byte === CR) { // If the current character is a carriage return, we need to // set the crlfCheck flag to true, as we need to check if the // next character is a line feed - if (this.buffer[this.pos] === CR) { + if (byte === CR) { this.crlfCheck = true } // In any case, we can process the line as we reached an // end-of-line character - this.parseLine(this.buffer.subarray(0, this.pos), this.event) - - // Remove the processed line from the buffer - this.buffer = this.buffer.subarray(this.pos + 1) - // Reset the position as we removed the processed line from the buffer - this.pos = 0 + this.parseLine(this.readLine(), this.event) + this.consumeCurrentByte() // A line was processed and this could be the end of the event. We need // to check if the next line is empty to determine if the event is // finished. @@ -21736,7 +21869,7 @@ class EventSourceStream extends Transform { continue } - this.pos++ + this.advanceCursor() } callback() @@ -21761,64 +21894,53 @@ class EventSourceStream extends Transform { return } - let field = '' - let value = '' + let fieldLength = line.length + let valueStart = line.length // If the line contains a U+003A COLON character (:) if (colonPosition !== -1) { - // Collect the characters on the line before the first U+003A COLON - // character (:), and let field be that string. - // TODO: Investigate if there is a more performant way to extract the - // field - // see: https://github.com/nodejs/undici/issues/2630 - field = line.subarray(0, colonPosition).toString('utf8') + fieldLength = colonPosition // Collect the characters on the line after the first U+003A COLON // character (:), and let value be that string. // If value starts with a U+0020 SPACE character, remove it from value. - let valueStart = colonPosition + 1 + valueStart = colonPosition + 1 if (line[valueStart] === SPACE) { ++valueStart } - // TODO: Investigate if there is a more performant way to extract the - // value - // see: https://github.com/nodejs/undici/issues/2630 - value = line.subarray(valueStart).toString('utf8') + } - // Otherwise, the string is not empty but does not contain a U+003A COLON - // character (:) - } else { - // Process the field using the steps described below, using the whole - // line as the field name, and the empty string as the field value. - field = line.toString('utf8') - value = '' - } - - // Modify the event with the field name and value. The value is also - // decoded as UTF-8 - switch (field) { - case 'data': - if (event[field] === undefined) { - event[field] = value - } else { - event[field] += `\n${value}` - } - break - case 'retry': - if (isASCIINumber(value)) { - event[field] = value - } - break - case 'id': - if (isValidLastEventId(value)) { - event[field] = value - } - break - case 'event': - if (value.length > 0) { - event[field] = value - } - break + if (isFieldName(line, fieldLength, DATA)) { + const value = line.toString('utf8', valueStart) + + if (event.data === undefined) { + event.data = value + } else { + event.data += `\n${value}` + } + return + } + + if (isFieldName(line, fieldLength, RETRY)) { + if (isASCIINumberBytes(line, valueStart)) { + event.retry = line.toString('utf8', valueStart) + } + return + } + + if (isFieldName(line, fieldLength, ID)) { + if (isValidLastEventIdBytes(line, valueStart)) { + event.id = line.toString('utf8', valueStart) + } + return + } + + if (isFieldName(line, fieldLength, EVENT)) { + const value = line.toString('utf8', valueStart) + + if (value.length > 0) { + event.event = value + } } } @@ -21848,12 +21970,151 @@ class EventSourceStream extends Transform { } clearEvent () { - this.event = { - data: undefined, - event: undefined, - id: undefined, - retry: undefined + this.event.data = undefined + this.event.event = undefined + this.event.id = undefined + this.event.retry = undefined + } + + hasPendingEvent () { + return this.event.data !== undefined || + this.event.event !== undefined || + this.event.id !== undefined || + this.event.retry !== undefined + } + + hasCurrentByte () { + return this.chunkIndex < this.chunks.length && + this.pos < this.chunks[this.chunkIndex].length + } + + currentByte () { + return this.chunks[this.chunkIndex][this.pos] + } + + consumeCurrentByte () { + this.advanceCursor() + this.syncLineStartToCursor() + } + + advanceCursor () { + this.pos++ + + while (this.chunkIndex < this.chunks.length && this.pos >= this.chunks[this.chunkIndex].length) { + this.chunkIndex++ + this.pos = 0 + } + } + + syncLineStartToCursor () { + this.lineChunkIndex = this.chunkIndex + this.linePos = this.pos + this.dropConsumedChunks() + } + + dropConsumedChunks () { + while (this.lineChunkIndex > 0) { + this.chunks.shift() + this.lineChunkIndex-- + this.chunkIndex-- + } + + if (this.chunkIndex === this.chunks.length) { + this.chunks.length = 0 + this.chunkIndex = 0 + this.pos = 0 + this.lineChunkIndex = 0 + this.linePos = 0 + } + } + + readLine () { + if (this.lineChunkIndex === this.chunkIndex) { + return this.chunks[this.chunkIndex].subarray(this.linePos, this.pos) + } + + const chunks = [] + let length = 0 + + for (let i = this.lineChunkIndex; i <= this.chunkIndex; i++) { + const chunk = this.chunks[i] + const start = i === this.lineChunkIndex ? this.linePos : 0 + const end = i === this.chunkIndex ? this.pos : chunk.length + const slice = chunk.subarray(start, end) + length += slice.length + chunks.push(slice) + } + + return Buffer.concat(chunks, length) + } + + peekBufferedByte (offset) { + let chunkIndex = this.lineChunkIndex + let pos = this.linePos + + while (chunkIndex < this.chunks.length) { + const chunk = this.chunks[chunkIndex] + const remaining = chunk.length - pos + + if (offset < remaining) { + return chunk[pos + offset] + } + + offset -= remaining + chunkIndex++ + pos = 0 + } + } + + discardLeadingBytes (count) { + while (count > 0 && this.lineChunkIndex < this.chunks.length) { + const chunk = this.chunks[this.lineChunkIndex] + const remaining = chunk.length - this.linePos + + if (count < remaining) { + this.linePos += count + count = 0 + } else { + count -= remaining + this.lineChunkIndex++ + this.linePos = 0 + } + } + + this.chunkIndex = this.lineChunkIndex + this.pos = this.linePos + this.dropConsumedChunks() + } + + handleBOM () { + const first = this.peekBufferedByte(0) + const second = this.peekBufferedByte(1) + const third = this.peekBufferedByte(2) + + if (second === undefined) { + if (first === BOM[0]) { + return true + } + + this.checkBOM = false + return true + } + + if (third === undefined) { + if (first === BOM[0] && second === BOM[1]) { + return true + } + + this.checkBOM = false + return false } + + if (first === BOM[0] && second === BOM[1] && third === BOM[2]) { + this.discardLeadingBytes(3) + } + + this.checkBOM = false + return !this.hasCurrentByte() } } @@ -33122,7 +33383,7 @@ function establishWebSocketConnection (url, protocols, client, ws, onEstablish, // is specified, the server needs to include the same field and one of // the selected subprotocol values in its response for the connection to // be established. - if (!requestProtocols.includes(secProtocol)) { + if (requestProtocols === null || !requestProtocols.includes(secProtocol)) { failWebsocketConnection(ws, 'Protocol was not set in the opening handshake.') return } @@ -33883,7 +34144,12 @@ class PerMessageDeflate { if (this.#maxPayloadSize > 0 && this.#inflate[kLength] > this.#maxPayloadSize) { callback(new MessageSizeExceededError()) + // The inflater may still hold buffered input that can emit a late + // zlib error. Remove the data listener, then deterministically stop + // the stream so a subsequent 'error' cannot fire without a listener + // (which would terminate the process as an unhandled error event). this.#inflate.removeAllListeners() + this.#inflate.destroy() this.#inflate = null return } @@ -38863,12 +39129,65 @@ const utils_hasOwnProperty = ( hasOwnProperty.call(obj, prop) )(Object.prototype); +const isUnsafeObjectKey = (prop) => + typeof prop === 'string' && + (prop === '__proto__' || prop === 'constructor' || prop === 'prototype'); + +/** + * Determine whether an inherited object must be treated as a shared-prototype + * boundary. Cross-realm Object.prototype objects cannot be distinguished + * reliably from application-created null-prototype objects because their + * properties are mutable, so all inherited terminal prototypes are excluded + * as a fail-closed boundary. A null-prototype source still keeps its own + * properties, as produced by mergeConfig and other safe materialization paths. + * + * @param {*} obj The object to inspect + * @param {*} prototype The object's prototype + * @param {boolean} source Whether obj is the original traversal source + * + * @returns {boolean} True when obj is a safe prototype traversal boundary + */ +const isPrototypeBoundary = (obj, prototype, source) => + obj === Object.prototype || (!source && prototype === null); + +/** + * Determine whether an object can retain its identity through code paths that + * add, replace, and remove config properties without bypassing unsafe-key + * filtering. Immutable objects, unsafe-key-bearing objects, and objects with + * accessor or restricted data properties must be materialized instead. + * + * @param {*} obj The object to inspect + * + * @returns {boolean} True when every own property is safe and fully mutable + */ +const isSafeAndFullyMutable = (obj) => { + if (!Object.isExtensible(obj)) { + return false; + } + + const props = Object.getOwnPropertyNames(obj); + + if (Object.getOwnPropertySymbols) { + props.push(...Object.getOwnPropertySymbols(obj)); + } + + return props.every((prop) => { + if (isUnsafeObjectKey(prop)) { + return false; + } + + const descriptor = Object.getOwnPropertyDescriptor(obj, prop); + + return !!descriptor && descriptor.configurable && descriptor.writable === true; + }); +}; + /** - * Walk the prototype chain (excluding the shared Object.prototype) looking for - * an own `prop`. This distinguishes genuine own/inherited members — including - * class accessors and template prototypes — from members injected via - * Object.prototype pollution (e.g. `Object.prototype.username = '...'`), which - * live on Object.prototype itself and are therefore never matched. + * Walk the prototype chain (excluding the source realm's Object.prototype) + * looking for an own `prop`. This distinguishes genuine own/inherited members + * — including class accessors and template prototypes — from members injected + * via Object.prototype pollution (e.g. `Object.prototype.username = '...'`), + * which live on Object.prototype itself and are therefore never matched. * * @param {*} thing The value whose chain to inspect * @param {string|symbol} prop The property key to look for @@ -38879,16 +39198,22 @@ const hasOwnInPrototypeChain = (thing, prop) => { let obj = thing; const seen = []; - while (obj != null && obj !== Object.prototype) { + while (obj != null) { if (seen.indexOf(obj) !== -1) { return false; } seen.push(obj); + const prototype = getPrototypeOf(obj); + + if (isPrototypeBoundary(obj, prototype, obj === thing)) { + return false; + } + if (utils_hasOwnProperty(obj, prop)) { return true; } - obj = getPrototypeOf(obj); + obj = prototype; } return false; }; @@ -38907,6 +39232,69 @@ const hasOwnInPrototypeChain = (thing, prop) => { const getSafeProp = (obj, prop) => obj != null && hasOwnInPrototypeChain(obj, prop) ? obj[prop] : undefined; +/** + * Flatten an object and its application-defined prototype chain into a + * null-prototype object. Members inherited only from the source realm's + * Object.prototype are deliberately excluded, while class/template members + * below that boundary are preserved. + * + * @param {*} thing The value to flatten + * + * @returns {*} A null-prototype copy, or the original value when it is already + * structurally safe or is not an object + */ +const toSafeFlatObject = (thing) => { + if (thing == null || (typeof thing !== 'object' && typeof thing !== 'function')) { + return thing; + } + + const sourcePrototype = getPrototypeOf(thing); + + if (sourcePrototype === null && isSafeAndFullyMutable(thing)) { + return thing; + } + + const result = Object.create(null); + const merged = Object.create(null); + const seen = []; + let current = thing; + + while (current != null) { + if (seen.indexOf(current) !== -1) { + break; + } + + seen.push(current); + + const prototype = current === thing ? sourcePrototype : getPrototypeOf(current); + + if (isPrototypeBoundary(current, prototype, current === thing)) { + break; + } + + const props = Object.getOwnPropertyNames(current); + + if (Object.getOwnPropertySymbols) { + props.push(...Object.getOwnPropertySymbols(current)); + } + + for (const prop of props) { + if (isUnsafeObjectKey(prop)) { + continue; + } + + if (!utils_hasOwnProperty(merged, prop)) { + result[prop] = thing[prop]; + merged[prop] = true; + } + } + + current = prototype; + } + + return result; +}; + const kindOf = ((cache) => (thing) => { const str = utils_toString.call(thing); return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase()); @@ -39038,12 +39426,10 @@ const isPlainObject = (val) => { const prototype = getPrototypeOf(val); return ( - (prototype === null || - prototype === Object.prototype || - getPrototypeOf(prototype) === null) && - // Treat any genuine (non-Object.prototype-polluted) Symbol.toStringTag or - // Symbol.iterator as evidence the value is a tagged/iterable type rather - // than a plain object, while ignoring keys injected onto Object.prototype. + (prototype === null || prototype === Object.prototype || getPrototypeOf(prototype) === null) && + // Treat safe own/inherited Symbol.toStringTag or Symbol.iterator members as + // evidence the value is tagged/iterable, while ignoring members reachable + // only through shared or terminal prototype boundaries. !hasOwnInPrototypeChain(val, toStringTag) && !hasOwnInPrototypeChain(val, iterator) ); @@ -39130,6 +39516,7 @@ const isBlob = kindOfTest('Blob'); * @returns {boolean} True if value is a FileList, otherwise false */ const isFileList = kindOfTest('FileList'); +const isSet = kindOfTest('Set'); /** * Determine if a value is a Stream @@ -39695,12 +40082,23 @@ const toJSONObject = (obj) => { if (!('toJSON' in source)) { // add-on descent / delete-on-ascent: preserves path semantics, so DAG nodes serialise at every occurrence (see #7230). visited.add(source); - const target = isArray(source) ? [] : {}; - forEach(source, (value, key) => { - const reducedValue = visit(value); - !isUndefined(reducedValue) && (target[key] = reducedValue); - }); + let target; + + if (isSet(source)) { + target = []; + for (const value of source) { + const reducedValue = visit(value); + !isUndefined(reducedValue) && target.push(reducedValue); + } + } else { + target = isArray(source) ? [] : {}; + + forEach(source, (value, key) => { + const reducedValue = visit(value); + !isUndefined(reducedValue) && (target[key] = reducedValue); + }); + } visited.delete(source); @@ -39845,6 +40243,7 @@ const isSafeIterable = (thing) => hasOwnProp: utils_hasOwnProperty, // an alias to avoid ESLint no-prototype-builtins detection hasOwnInPrototypeChain, getSafeProp, + toSafeFlatObject, reduceDescriptors, freezeMethods, toObjectSet, @@ -39917,18 +40316,20 @@ const ignoreDuplicateOf = utils.toObjectSet([ key = line.substring(0, i).trim().toLowerCase(); val = line.substring(i + 1).trim(); - if (!key || (parsed[key] && ignoreDuplicateOf[key])) { + const hasKey = utils.hasOwnProp(parsed, key); + + if (!key || (hasKey && utils.hasOwnProp(ignoreDuplicateOf, key))) { return; } if (key === 'set-cookie') { - if (parsed[key]) { + if (hasKey) { parsed[key].push(val); } else { parsed[key] = [val]; } } else { - parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; + parsed[key] = hasKey ? parsed[key] + ', ' + val : val; } }); @@ -40030,6 +40431,124 @@ function parseTokens(str) { return tokens; } +const parameterNameRE = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/; + +function trimOWS(value) { + let start = 0; + let end = value.length; + + while (start < end) { + const code = value.charCodeAt(start); + + if (code !== 0x09 && code !== 0x20) { + break; + } + + start += 1; + } + + while (end > start) { + const code = value.charCodeAt(end - 1); + + if (code !== 0x09 && code !== 0x20) { + break; + } + + end -= 1; + } + + return start === 0 && end === value.length ? value : value.slice(start, end); +} + +function decodeQuotedString(value) { + const last = value.length - 1; + + if (last < 1 || value.charCodeAt(0) !== 0x22 || value.charCodeAt(last) !== 0x22) { + return value; + } + + let decoded = ''; + + for (let i = 1; i < last; i++) { + const code = value.charCodeAt(i); + + if (code === 0x22) { + return value; + } + + if (code === 0x5c) { + i += 1; + + if (i >= last) { + return value; + } + } + + decoded += value[i]; + } + + return decoded; +} + +function parseParameters(value) { + const parameters = Object.create(null); + const str = String(value); + let start = 0; + let quoted = false; + let escaped = false; + + function parseParameter(end) { + const part = trimOWS(str.slice(start, end)); + const equals = part.indexOf('='); + + if (equals < 1) { + return; + } + + const name = trimOWS(part.slice(0, equals)); + + if (!parameterNameRE.test(name)) { + return; + } + + const normalizedName = name.toLowerCase(); + + if ( + normalizedName === '__proto__' || + normalizedName === 'constructor' || + normalizedName === 'prototype' + ) { + return; + } + + const parameterValue = trimOWS(part.slice(equals + 1)); + parameters[normalizedName] = decodeQuotedString(parameterValue); + } + + for (let i = 0; i < str.length; i++) { + const code = str.charCodeAt(i); + + if (quoted) { + if (escaped) { + escaped = false; + } else if (code === 0x5c) { + escaped = true; + } else if (code === 0x22) { + quoted = false; + } + } else if (code === 0x22) { + quoted = true; + } else if (code === 0x2c || code === 0x3b) { + parseParameter(i); + start = i + 1; + } + } + + parseParameter(str.length); + + return parameters; +} + const isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim()); function matchHeaderValue(context, value, header, filter, isHeaderNameFilter) { @@ -40281,7 +40800,8 @@ class AxiosHeaders { } getSetCookie() { - return this.get('set-cookie') || []; + const value = this.get('set-cookie'); + return utils.isArray(value) ? value : value == null || value === false ? [] : [value]; } get [Symbol.toStringTag]() { @@ -40292,6 +40812,10 @@ class AxiosHeaders { return thing instanceof this ? thing : new this(thing); } + static parseParameters(value) { + return parseParameters(value); + } + static concat(first, ...targets) { const computed = new this(first); @@ -40425,9 +40949,40 @@ function redactConfig(config, redactKeys) { return visit(config); } +function stringifySafely(value) { + try { + return String(value); + } catch (err) { + return ''; + } +} + +function aggregateErrorMessage(error) { + const message = error.errors + .map((entry) => { + try { + return entry && entry.message ? stringifySafely(entry.message) : stringifySafely(entry); + } catch (err) { + return ''; + } + }) + .filter(Boolean) + .join('; '); + + return message || error.name || 'AggregateError'; +} + class AxiosError extends Error { static from(error, code, config, request, response, customProps) { - const axiosError = new AxiosError(error.message, code || error.code, config, request, response); + // `AggregateError` (thrown by Node on dual-stack/Happy-Eyeballs connection + // failures) has an empty `message`; its detail lives in `errors[]`. Without + // this, the wrapped error surfaces with a blank message (see #6721). + let message = error.message; + if (!message && utils.isArray(error.errors) && error.errors.length) { + message = aggregateErrorMessage(error); + } + + const axiosError = new AxiosError(message, code || error.code, config, request, response); // Match native `Error` `cause` semantics: non-enumerable. The wrapped // error often carries circular internals (sockets, requests, agents), so // an enumerable `cause` makes structured loggers (pino/winston) and any @@ -40547,6 +41102,19 @@ var form_data = __nccwpck_require__(6454); /* harmony default export */ const classes_FormData = (form_data); +;// CONCATENATED MODULE: ./node_modules/axios/lib/platform/node/classes/Buffer.js + + +/* harmony default export */ const classes_Buffer = ({ + isBufferAvailable() { + return typeof Buffer !== 'undefined'; + }, + + from(value) { + return Buffer.from(value); + } +}); + ;// CONCATENATED MODULE: ./node_modules/axios/lib/helpers/toFormData.js @@ -40555,6 +41123,7 @@ var form_data = __nccwpck_require__(6454); // temporary hotfix to avoid circular references until AxiosURLSearchParams is refactored + // Default nesting limit shared with the inverse transform (formDataToJSON) so // the FormData <-> JSON round-trip stays symmetric. const DEFAULT_FORM_DATA_MAX_DEPTH = 100; @@ -40648,28 +41217,18 @@ function toFormData(obj, formData, options) { // eslint-disable-next-line no-param-reassign formData = formData || new (classes_FormData || FormData)(); - // eslint-disable-next-line no-param-reassign - options = utils.toFlatObject( - options, - { - metaTokens: true, - dots: false, - indexes: false, - }, - false, - function defined(option, source) { - // eslint-disable-next-line no-eq-null,eqeqeq - return !utils.isUndefined(source[option]); - } - ); + const option = (name, fallback) => { + const value = utils.getSafeProp(options, name); + return utils.isUndefined(value) ? fallback : value; + }; - const metaTokens = options.metaTokens; + const metaTokens = option('metaTokens', true); // eslint-disable-next-line no-use-before-define - const visitor = options.visitor || defaultVisitor; - const dots = options.dots; - const indexes = options.indexes; - const _Blob = options.Blob || (typeof Blob !== 'undefined' && Blob); - const maxDepth = options.maxDepth === undefined ? DEFAULT_FORM_DATA_MAX_DEPTH : options.maxDepth; + const visitor = option('visitor') || defaultVisitor; + const dots = option('dots', false); + const indexes = option('indexes', false); + const _Blob = option('Blob') || (typeof Blob !== 'undefined' && Blob); + const maxDepth = option('maxDepth', DEFAULT_FORM_DATA_MAX_DEPTH); const useBlob = _Blob && utils.isSpecCompliantForm(formData); const stack = []; @@ -40696,10 +41255,13 @@ function toFormData(obj, formData, options) { if (useBlob && typeof _Blob === 'function') { return new _Blob([value]); } - if (typeof Buffer !== 'undefined') { - return Buffer.from(value); + if (classes_Buffer && classes_Buffer.isBufferAvailable()) { + return classes_Buffer.from(value); } - throw new core_AxiosError('Blob is not supported. Use a Buffer instead.', core_AxiosError.ERR_NOT_SUPPORT); + throw new core_AxiosError( + 'Blob is not supported. Use a Buffer instead.', + core_AxiosError.ERR_NOT_SUPPORT + ); } return value; @@ -40971,9 +41533,57 @@ function buildURL(url, params, options) { +const InterceptorManager_$internals = Symbol('internals'); + +// `handlers` is public and may be replaced with a nullish value by user code; +// `clear()` has always tolerated that. Treat it as an empty stack rather than +// dereferencing it. +function countHandlers(handlers) { + return handlers ? handlers.length : 0; +} + +function trimHandlers(handlers) { + if (!handlers) { + return; + } + + while (handlers.length && handlers[handlers.length - 1] === null) { + handlers.pop(); + } +} + +function syncHandlerEntries(manager, internals) { + const handlers = manager.handlers; + const length = countHandlers(handlers); + + if (handlers !== internals.handlersRef) { + internals.handlersRef = handlers; + internals.handlerEntries.clear(); + } else if (length !== internals.handlersLength) { + if (!length) { + internals.handlerEntries.clear(); + } else { + internals.handlerEntries.forEach(function removeStaleEntry(entry, id) { + if (handlers[entry.index] !== entry.handler) { + internals.handlerEntries.delete(id); + } + }); + } + } + + internals.handlersLength = length; +} + class InterceptorManager { constructor() { this.handlers = []; + this[InterceptorManager_$internals] = { + handlersRef: this.handlers, + handlersLength: this.handlers.length, + handlerEntries: new Map(), + iterationDepth: 0, + nextId: 0, + }; } /** @@ -40986,13 +41596,30 @@ class InterceptorManager { * @return {Number} An ID used to remove interceptor later */ use(fulfilled, rejected, options) { - this.handlers.push({ + const handler = { fulfilled, rejected, synchronous: options ? options.synchronous : false, runWhen: options ? options.runWhen : null, + }; + const internals = this[InterceptorManager_$internals]; + + if (this.handlers == null) { + this.handlers = []; + } + + syncHandlerEntries(this, internals); + + const id = internals.nextId++; + + this.handlers.push(handler); + internals.handlerEntries.set(id, { + handler, + index: this.handlers.length - 1, }); - return this.handlers.length - 1; + internals.handlersLength = this.handlers.length; + + return id; } /** @@ -41003,8 +41630,27 @@ class InterceptorManager { * @returns {void} */ eject(id) { - if (this.handlers[id]) { - this.handlers[id] = null; + const internals = this[InterceptorManager_$internals]; + + syncHandlerEntries(this, internals); + + const entry = internals.handlerEntries.get(id); + + if (entry) { + internals.handlerEntries.delete(id); + + // Ignore IDs invalidated by clear or direct replacement of handlers. + if (this.handlers[entry.index] !== entry.handler) { + return; + } + + this.handlers[entry.index] = null; + + // Do not reuse an index while forEach is walking its length snapshot. + if (!internals.iterationDepth) { + trimHandlers(this.handlers); + internals.handlersLength = this.handlers.length; + } } } @@ -41016,6 +41662,7 @@ class InterceptorManager { clear() { if (this.handlers) { this.handlers = []; + syncHandlerEntries(this, this[InterceptorManager_$internals]); } } @@ -41030,11 +41677,25 @@ class InterceptorManager { * @returns {void} */ forEach(fn) { - utils.forEach(this.handlers, function forEachHandler(h) { - if (h !== null) { - fn(h); + const internals = this[InterceptorManager_$internals]; + + syncHandlerEntries(this, internals); + + internals.iterationDepth++; + + try { + utils.forEach(this.handlers, function forEachHandler(h) { + if (h !== null) { + fn(h); + } + }); + } finally { + if (!--internals.iterationDepth) { + syncHandlerEntries(this, internals); + trimHandlers(this.handlers); + internals.handlersLength = countHandlers(this.handlers); } - }); + } } } @@ -41203,12 +41864,18 @@ function throwIfDepthExceeded(index) { * @returns An array of strings. */ function parsePropPath(name) { - // foo[x][y][z] - // foo.x.y.z - // foo-x-y-z - // foo x y z + // foo[x][y][z] -> ['foo', 'x', 'y', 'z'] + // foo.x.y.z -> ['foo', 'x', 'y', 'z'] + // A path is split on `.` and on `[...]` groups. A segment — whether written + // in dot notation or captured inside brackets — may contain any character + // except `.`, `[` and `]`, so a key like `user-name` or `user name` is kept + // literal instead of being split (#5402). `.`, `[` and `]` keep their existing + // meaning, e.g. `foo[bar.baz]` -> ['foo', 'bar', 'baz'] and `[]` is an array push. + // Excluding `[` from the bracket group also makes the match fail fast at the + // next `[`, so a malformed name cannot rescan to the end of the string from + // every unmatched `[` — parsing stays linear in the length of the name. const path = []; - const pattern = /\w+|\[(\w*)]/g; + const pattern = /[^.[\]]+|\[([^.[\]]*)]/g; let match; while ((match = pattern.exec(name)) !== null) { @@ -41298,6 +41965,25 @@ function formDataToJSON(formData) { /* harmony default export */ const helpers_formDataToJSON = (formDataToJSON); +;// CONCATENATED MODULE: ./node_modules/axios/lib/core/methodList.js + + +const methodList = Object.freeze([ + 'get', + 'delete', + 'head', + 'options', + 'post', + 'put', + 'patch', + 'purge', + 'link', + 'unlink', + 'query', +]); + +/* harmony default export */ const core_methodList = (methodList); + ;// CONCATENATED MODULE: ./node_modules/axios/lib/defaults/index.js @@ -41309,6 +41995,7 @@ function formDataToJSON(formData) { + const own = (obj, key) => (obj != null && utils.hasOwnProp(obj, key) ? obj[key] : undefined); /** @@ -41321,7 +42008,7 @@ const own = (obj, key) => (obj != null && utils.hasOwnProp(obj, key) ? obj[key] * * @returns {string} A stringified version of the rawValue. */ -function stringifySafely(rawValue, parser, encoder) { +function defaults_stringifySafely(rawValue, parser, encoder) { if (utils.isString(rawValue)) { try { (parser || JSON.parse)(rawValue); @@ -41400,7 +42087,7 @@ const defaults = { if (isObjectPayload || hasJSONContentType) { headers.setContentType('application/json', false); - return stringifySafely(data); + return defaults_stringifySafely(data); } return data; @@ -41471,7 +42158,7 @@ const defaults = { }, }; -utils.forEach(['delete', 'get', 'head', 'post', 'put', 'patch', 'query'], (method) => { +utils.forEach(core_methodList, (method) => { defaults.headers[method] = {}; }); @@ -41600,9 +42287,43 @@ function isAbsoluteURL(url) { * @returns {string} The combined URL */ function combineURLs(baseURL, relativeURL) { - return relativeURL - ? baseURL.replace(/\/?\/$/, '') + '/' + relativeURL.replace(/^\/+/, '') - : baseURL; + if (!relativeURL) { + return baseURL; + } + + let end = baseURL.length; + + while (end > 0 && baseURL.charCodeAt(end - 1) === 47) { + end--; + } + + return baseURL.slice(0, end) + '/' + relativeURL.replace(/^\/+/, ''); +} + +;// CONCATENATED MODULE: ./node_modules/axios/lib/helpers/normalizeURLForProtocolCheck.js + + +const urlParserControlCharacters = /[\t\n\r]/g; + +/** + * Match WHATWG URL preprocessing before checking a URL's protocol. + * + * @param {string} url + * + * @returns {string} + */ +function normalizeURLForProtocolCheck(url) { + if (typeof url !== 'string') { + return url; + } + + let start = 0; + + while (start < url.length && url.charCodeAt(start) <= 0x20) { + start++; + } + + return url.slice(start).replace(urlParserControlCharacters, ''); } ;// CONCATENATED MODULE: ./node_modules/axios/lib/core/buildFullPath.js @@ -41612,28 +42333,54 @@ function combineURLs(baseURL, relativeURL) { + const malformedHttpProtocol = /^https?:(?!\/\/)/i; -const httpProtocolControlCharacters = /[\t\n\r]/g; -function stripLeadingC0ControlOrSpace(url) { - let i = 0; - while (i < url.length && url.charCodeAt(i) <= 0x20) { - i++; - } - return url.slice(i); +// Redact the parts of a URL that can carry secrets before it is embedded in an +// error message. AxiosError.toJSON() serializes `message` verbatim and errors +// are commonly logged, while the opt-in `config.redact` model only cleans +// config keys — it cannot reach the message. Redact only the genuinely +// sensitive substrings — userinfo (credentials), query parameter values and +// fragment contents — with the same REDACTED marker the config redaction uses, +// while keeping the scheme, host, path and parameter names so the offending +// request stays accurately identifiable. +function redactFragment(fragment) { + if (!fragment) { + return fragment; + } + + return fragment.replace(/(^|&)([^=&]*=)?[^&]+/g, (match, separator, parameterName = '') => { + return `${separator}${parameterName}${REDACTED}`; + }); } -function normalizeURLForProtocolCheck(url) { - return stripLeadingC0ControlOrSpace(url).replace(httpProtocolControlCharacters, ''); +function redactSensitiveURLParts(url) { + const redactedURL = url.replace(/^(https?:\/{0,2})[^/?#]*@/i, `$1${REDACTED}@`); + const fragmentIndex = redactedURL.indexOf('#'); + const urlWithoutFragment = + fragmentIndex === -1 ? redactedURL : redactedURL.slice(0, fragmentIndex); + const redactedURLWithoutFragment = urlWithoutFragment.replace( + /([?&][^=&#]*=)[^&#]*/g, + `$1${REDACTED}` + ); + + if (fragmentIndex === -1) { + return redactedURLWithoutFragment; + } + + return `${redactedURLWithoutFragment}#${redactFragment(redactedURL.slice(fragmentIndex + 1))}`; } function assertValidHttpProtocolURL(url, config) { - if (typeof url === 'string' && malformedHttpProtocol.test(normalizeURLForProtocolCheck(url))) { - throw new core_AxiosError( - 'Invalid URL: missing "//" after protocol', - core_AxiosError.ERR_INVALID_URL, - config - ); + if (typeof url === 'string') { + const normalizedURL = normalizeURLForProtocolCheck(url); + if (malformedHttpProtocol.test(normalizedURL)) { + throw new core_AxiosError( + `Invalid URL ${JSON.stringify(redactSensitiveURLParts(normalizedURL))}: missing "//" after protocol`, + core_AxiosError.ERR_INVALID_URL, + config + ); + } } } @@ -41773,7 +42520,7 @@ var follow_redirects = __nccwpck_require__(1573); ;// CONCATENATED MODULE: external "zlib" const external_zlib_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("zlib"); ;// CONCATENATED MODULE: ./node_modules/axios/lib/env/data.js -const VERSION = "1.18.1"; +const VERSION = "1.20.0"; ;// CONCATENATED MODULE: ./node_modules/axios/lib/helpers/parseProtocol.js @@ -41791,7 +42538,7 @@ function parseProtocol(url) { // RFC 2397: data:[][;base64], // mediatype = type/subtype followed by optional ;name=value parameters -const DATA_URL_PATTERN = /^([^,;]+\/[^,;]+)?((?:;[^,;=]+=[^,;]+)*)(;base64)?,([\s\S]*)$/; +const DATA_URL_PATTERN = /^([^,;/]+\/[^,;/]+)?((?:;[^,;=]+=[^,;]+)*)(;base64)?,([\s\S]*)$/; /** * Parse data uri to a Buffer or Blob @@ -41834,9 +42581,10 @@ function fromDataURI(uri, asBlob, options) { mime = 'text/plain' + params; } - const buffer = encoding === 'base64' - ? Buffer.from(body, 'base64') - : Buffer.from(decodeURIComponent(body), encoding); + const buffer = + encoding === 'base64' + ? Buffer.from(body, 'base64') + : Buffer.from(decodeURIComponent(body), encoding); if (asBlob) { if (!_Blob) { @@ -41854,6 +42602,35 @@ function fromDataURI(uri, asBlob, options) { // EXTERNAL MODULE: external "stream" var external_stream_ = __nccwpck_require__(2203); +;// CONCATENATED MODULE: ./node_modules/axios/lib/core/setFormDataHeaders.js + + +const FORM_DATA_CONTENT_HEADERS = ['content-type', 'content-length']; + +/** + * Apply the headers generated by a FormData implementation to the request headers, + * honoring the `formDataHeaderPolicy` option: with 'content-only', copy only the + * content-* headers; otherwise merge all of them. + * + * @param {AxiosHeaders} headers - the request headers to mutate + * @param {Object | null | undefined} formHeaders - headers produced by the FormData implementation + * @param {String} [policy] - the resolved `formDataHeaderPolicy` config value + * + * @returns {void} + */ +function setFormDataHeaders(headers, formHeaders, policy) { + if (policy !== 'content-only') { + headers.set(formHeaders); + return; + } + + Object.entries(formHeaders || {}).forEach(([key, val]) => { + if (FORM_DATA_CONTENT_HEADERS.includes(key.toLowerCase())) { + headers.set(key, val); + } + }); +} + ;// CONCATENATED MODULE: ./node_modules/axios/lib/helpers/AxiosTransformStream.js @@ -42199,6 +42976,7 @@ class Http2Sessions { getSession(authority, options) { options = Object.assign( + Object.create(null), { sessionTimeout: 1000, }, @@ -42289,6 +43067,7 @@ class Http2Sessions { } session.once('close', removeSession); + session.once('error', removeSession); let entry = [session, options]; @@ -42325,6 +43104,16 @@ const callbackify = (fn, reducer) => { ;// CONCATENATED MODULE: ./node_modules/axios/lib/helpers/shouldBypassProxy.js const LOOPBACK_HOSTNAMES = new Set(['localhost', '0.0.0.0']); +const trimTrailingDots = (value) => { + let end = value.length; + + while (end && value.charCodeAt(end - 1) === 46) { + end--; + } + + return end === value.length ? value : value.slice(0, end); +}; + const isIPv4Loopback = (host) => { const parts = host.split('.'); if (parts.length !== 4) return false; @@ -42332,6 +43121,112 @@ const isIPv4Loopback = (host) => { return parts.every((p) => /^\d+$/.test(p) && Number(p) >= 0 && Number(p) <= 255); }; +/** + * Canonicalize an IPv4 address written in shorthand, octal, or hex form into + * dotted-decimal. IPv6 addresses and non-IP strings are returned unchanged so + * the existing IPv4-mapped IPv6 unmap path and the isLoopback path can still + * see them. + * + * Shorthand expansion mirrors Node's URL parser: literal parts fill from the + * left, the final part fills the remaining octets from the right with + * zero-padding on the left. + * 127.1 -> 127.0.0.1 + * 127.0.1 -> 127.0.0.1 + * 1.2.3 -> 1.2.0.3 + * + * Each octet is parsed with an explicit base: 16 for `0x`/`0X` prefix, 8 for + * zero-prefixed multi-digit all-`0-7` parts, 10 otherwise. Zero-prefixed + * decimal-looking parts that contain `8` or `9` are rejected to match Node's + * URL parser, and the comparison layer falls through to non-bypass if either + * side rejects the form (fail-safe). + * + * Returns the input unchanged on any parse failure, out-of-range octet, or + * unusual shape (1-part, 5+ parts) so the comparison layer fails closed. + */ +const parseIPv4Octet = (text) => { + if (/^0[xX][0-9a-fA-F]+$/.test(text)) { + const n = parseInt(text.slice(2), 16); + return Number.isFinite(n) ? n : null; + } + if (text.length > 1 && /^0[0-7]+$/.test(text)) { + const n = parseInt(text, 8); + return Number.isFinite(n) ? n : null; + } + if (text.length > 1 && /^0[0-9]+$/.test(text)) { + return null; + } + if (/^[0-9]+$/.test(text)) { + const n = parseInt(text, 10); + return Number.isFinite(n) ? n : null; + } + return null; +}; + +const normalizeIPAddress = (host) => { + if (typeof host !== 'string' || !host || host.indexOf(':') !== -1) { + return host; + } + + let h = host; + if (h.charAt(0) === '[' && h.charAt(h.length - 1) === ']') { + h = h.slice(1, -1); + } + h = trimTrailingDots(h); + + // Allowed characters for any IPv4 shape: digits, dot, 'x', 'X', hex digits. + if (!/^[0-9.xXa-fA-F]+$/.test(h)) return host; + + const parts = h.split('.'); + + // No part may be empty (e.g. "127..0.1" or "127.0.0."). Trailing dots are + // already stripped above; this guards against the empty-middle case. + if (parts.some((p) => p === '')) return host; + + if (parts.length === 4) { + // Full IPv4 form: each part is an octet. + const octets = parts.map(parseIPv4Octet); + if (octets.some((n) => n === null || n < 0 || n > 255)) return host; + return octets.join('.'); + } + + if (parts.length > 4) { + return host; + } + + // Shorthand: 1..3 parts. Node's URL parser treats a 1-part input as a 32-bit + // integer split into octets, which has surprising semantics (e.g. "127" -> + // "0.0.0.127"). Reject 1-part inputs to keep the helper predictable: the + // fail-safe returns the input unchanged and the comparison layer falls + // through to non-bypass. + if (parts.length === 1) return host; + + // 2..3 parts: literal parts fill from the left, tail fills remaining octets + // from the right with zero-padding. + const literalOctets = parts.slice(0, -1); + const tail = parts[parts.length - 1]; + const tailSlots = 4 - literalOctets.length; + + // Tail is parsed as a full IPv4 number (hex/octal/decimal) and packed + // low-byte-right into the remaining octets, matching Node's URL parser. + // e.g. 127.65535 (tail 0xFFFF into 3 slots) -> 127.0.255.255; + // 127.0x00ff (tail 0xFF into 3 slots) -> 127.0.0.255; + // 127.0.65535 (tail 0xFFFF into 2 slots) -> 127.0.255.255. + const tailValue = parseIPv4Octet(tail); + if (tailValue === null) return host; + const maxTail = (1 << (8 * tailSlots)) - 1; + if (tailValue < 0 || tailValue > maxTail) return host; + + const tailOctets = new Array(tailSlots).fill(0); + for (let i = tailSlots - 1, v = tailValue; i >= 0; i--, v >>= 8) { + tailOctets[i] = v & 0xff; + } + + const literal = literalOctets.map(parseIPv4Octet); + if (literal.some((n) => n === null || n < 0 || n > 255)) return host; + + return [...literal, ...tailOctets].join('.'); +}; + const isIPv6ZeroGroup = (group) => /^0{1,4}$/.test(group); // The unspecified address (IPv4 0.0.0.0 / IPv6 ::) resolves to the local host @@ -42353,9 +43248,7 @@ const isIPv6Unspecified = (host) => { const explicitGroups = leftGroups.length + rightGroups.length; return ( - explicitGroups < 8 && - leftGroups.every(isIPv6ZeroGroup) && - rightGroups.every(isIPv6ZeroGroup) + explicitGroups < 8 && leftGroups.every(isIPv6ZeroGroup) && rightGroups.every(isIPv6ZeroGroup) ); } @@ -42451,7 +43344,8 @@ const parseNoProxyEntry = (entry) => { // allowing the proxy-bypass policy to be circumvented by using the alternate // representation. Returns the input unchanged when not IPv4-mapped. const IPV4_MAPPED_DOTTED_RE = /^(?:::|(?:0{1,4}:){1,4}:|(?:0{1,4}:){5})ffff:(\d+\.\d+\.\d+\.\d+)$/i; -const IPV4_MAPPED_HEX_RE = /^(?:::|(?:0{1,4}:){1,4}:|(?:0{1,4}:){5})ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i; +const IPV4_MAPPED_HEX_RE = + /^(?:::|(?:0{1,4}:){1,4}:|(?:0{1,4}:){5})ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i; const unmapIPv4MappedIPv6 = (host) => { if (typeof host !== 'string' || host.indexOf(':') === -1) return host; @@ -42469,6 +43363,57 @@ const unmapIPv4MappedIPv6 = (host) => { return host; }; +const IPV4_OCTET_RE = /^(?:0|[1-9]\d{0,2})$/; + +const ipv4ToBytes = (host) => { + const parts = host.split('.'); + + return parts.length === 4 && + parts.every((part) => IPV4_OCTET_RE.test(part) && Number(part) <= 255) + ? parts.map(Number) + : null; +}; + +const IPV6_GROUP_RE = /^[0-9a-f]{1,4}$/i; + +const ipv6ToBytes = (host) => { + const halves = host.split('::'); + + if (halves.length > 2) { + return null; + } + + const groups = halves[0] ? halves[0].split(':') : []; + + if (halves.length === 2) { + const rear = halves[1] ? halves[1].split(':') : []; + const missing = 8 - groups.length - rear.length; + + if (missing < 1) { + return null; + } + + groups.push(...new Array(missing).fill('0'), ...rear); + } + + if (groups.length !== 8 || groups.some((group) => !IPV6_GROUP_RE.test(group))) { + return null; + } + + return groups.flatMap((group) => { + const value = Number.parseInt(group, 16); + return [(value >> 8) & 0xff, value & 0xff]; + }); +}; + +const ipToBytes = (host) => { + if (typeof host !== 'string' || !host) { + return null; + } + + return host.indexOf(':') !== -1 ? ipv6ToBytes(host) : ipv4ToBytes(host); +}; + const normalizeNoProxyHost = (hostname) => { if (!hostname) { return hostname; @@ -42478,7 +43423,120 @@ const normalizeNoProxyHost = (hostname) => { hostname = hostname.slice(1, -1); } - return unmapIPv4MappedIPv6(hostname.replace(/\.+$/, '')); + const trimmed = trimTrailingDots(hostname); + + // IPv4 shorthand/octal/hex → dotted-decimal; helper is a no-op for inputs + // containing ':' (IPv6 and IPv4-mapped IPv6) so we fall through to unmap. + const ipv4 = normalizeIPAddress(trimmed); + if (ipv4 !== trimmed) { + return ipv4; + } + + return unmapIPv4MappedIPv6(trimmed); +}; + +const normalizeCidrBase = (input) => { + let base = input; + const startsBracket = base.charAt(0) === '['; + const endsBracket = base.charAt(base.length - 1) === ']'; + const hasBracket = base.includes('[') || base.includes(']'); + + if (startsBracket || endsBracket) { + if (!startsBracket || !endsBracket) { + return null; + } + + base = base.slice(1, -1); + + if (base.indexOf(':') === -1 || base.includes('[') || base.includes(']')) { + return null; + } + } else if (hasBracket) { + return null; + } + + if (!base || base.charAt(base.length - 1) === '.') { + return null; + } + + const wasIPv6 = base.indexOf(':') !== -1; + + if (wasIPv6) { + try { + base = new URL(`http://[${base}]/`).hostname.slice(1, -1); + } catch (_err) { + return null; + } + } else { + base = normalizeIPAddress(base); + + if (!ipv4ToBytes(base)) { + return null; + } + } + + return { normalized: unmapIPv4MappedIPv6(base), wasIPv6 }; +}; + +const CIDR_ENTRY_RE = /^(.+)\/(0|[1-9]\d{0,2})$/; + +const parseCidrEntry = (entry) => { + if (entry.indexOf('/') === -1) { + return undefined; + } + + const match = CIDR_ENTRY_RE.exec(entry); + + if (!match) { + return null; + } + + let prefix = Number(match[2]); + const parsedBase = normalizeCidrBase(match[1]); + + if (!parsedBase) { + return null; + } + + const { normalized, wasIPv6 } = parsedBase; + + if (wasIPv6 && normalized.indexOf(':') === -1) { + if (prefix < 96) { + return null; + } + + prefix -= 96; + } + + const bytes = ipToBytes(normalized); + + if (!bytes || prefix > bytes.length * 8) { + return null; + } + + return { bytes, prefix }; +}; + +const isInSubnet = (addressBytes, networkBytes, prefix) => { + const fullBytes = prefix >> 3; + + for (let i = 0; i < fullBytes; i++) { + if (addressBytes[i] !== networkBytes[i]) { + return false; + } + } + + const remainingBits = prefix & 7; + + if (remainingBits) { + const mask = (0xff << (8 - remainingBits)) & 0xff; + + if ((addressBytes[fullBytes] & mask) !== (networkBytes[fullBytes] & mask)) { + return false; + } + } + + return true; }; function shouldBypassProxy(location) { @@ -42504,12 +43562,28 @@ function shouldBypassProxy(location) { Number.parseInt(parsed.port, 10) || shouldBypassProxy_DEFAULT_PORTS[parsed.protocol.split(':', 1)[0]] || 0; const hostname = normalizeNoProxyHost(parsed.hostname.toLowerCase()); + const hostnameBytes = ipToBytes(hostname); return noProxy.split(/[\s,]+/).some((entry) => { if (!entry) { return false; } + if (entry === '*') { + return true; + } + + const cidr = parseCidrEntry(entry); + + if (cidr !== undefined) { + return ( + cidr !== null && + !!hostnameBytes && + hostnameBytes.length === cidr.bytes.length && + isInSubnet(hostnameBytes, cidr.bytes, cidr.prefix) + ); + } + let [entryHost, entryPort] = parseNoProxyEntry(entry); entryHost = normalizeNoProxyHost(entryHost); @@ -42596,7 +43670,7 @@ function speedometer(samplesCount, min) { * Throttle decorator * @param {Function} fn * @param {Number} freq - * @return {Function} + * @return {Array} */ function throttle(fn, freq) { let timestamp = 0; @@ -42631,8 +43705,9 @@ function throttle(fn, freq) { }; const flush = () => lastArgs && invoke(lastArgs); + const flushWith = (...args) => invoke(args); - return [throttled, flush]; + return [throttled, flush, flushWith]; } /* harmony default export */ const helpers_throttle = (throttle); @@ -42647,12 +43722,12 @@ const progressEventReducer = (listener, isDownloadStream, freq = 3) => { const _speedometer = helpers_speedometer(50, 250); return helpers_throttle((e) => { - if (!e || typeof e.loaded !== 'number') { + if (!e || !utils.isNumber(e.loaded)) { return; } const rawLoaded = e.loaded; const total = e.lengthComputable ? e.total : undefined; - const loaded = total != null ? Math.min(rawLoaded, total) : rawLoaded; + const loaded = Math.max(0, total != null ? Math.min(rawLoaded, total) : rawLoaded); const progressBytes = Math.max(0, loaded - bytesNotified); const rate = _speedometer(progressBytes); @@ -42689,19 +43764,17 @@ const progressEventDecorator = (total, throttled) => { }; const asyncDecorator = - (fn) => + (fn, scheduler = utils.asap) => (...args) => - utils.asap(() => fn(...args)); + scheduler(() => fn(...args)); ;// CONCATENATED MODULE: ./node_modules/axios/lib/helpers/estimateDataURLDecodedBytes.js /** - * Estimate decoded byte length of a data:// URL *without* allocating large buffers. - * - For base64: compute exact decoded size using length and padding; - * handle %XX at the character-count level (no string allocation). - * - For non-base64: compute the exact percent-decoded UTF-8 byte length. - * - * @param {string} url - * @returns {number} + * Estimate data: URL byte lengths *without* allocating large buffers. + * - Fetch percent-decodes a base64 body before decoding it. + * - Node's Buffer.from(body, 'base64') sizes its backing allocation from the + * raw body, including ignored characters and content after padding. + * - Non-base64 data is percent-decoded and then encoded as UTF-8. */ const isHexDigit = (charCode) => (charCode >= 48 && charCode <= 57) || @@ -42711,64 +43784,101 @@ const isHexDigit = (charCode) => const isPercentEncodedByte = (str, i, len) => i + 2 < len && isHexDigit(str.charCodeAt(i + 1)) && isHexDigit(str.charCodeAt(i + 2)); -function estimateDataURLDecodedBytes(url) { - if (!url || typeof url !== 'string') return 0; - if (!url.startsWith('data:')) return 0; +const hexValue = (charCode) => (charCode <= 57 ? charCode - 48 : (charCode & 0xdf) - 55); - const comma = url.indexOf(','); - if (comma < 0) return 0; +const isBase64Char = (charCode) => + (charCode >= 65 && charCode <= 90) || // A-Z + (charCode >= 97 && charCode <= 122) || // a-z + (charCode >= 48 && charCode <= 57) || // 0-9 + charCode === 43 || // + + charCode === 47 || // / + charCode === 45 || // - (base64url) + charCode === 95; // _ (base64url) - const meta = url.slice(5, comma); - const body = url.slice(comma + 1); - const isBase64 = /;base64/i.test(meta); +const isBase64Whitespace = (charCode) => + charCode === 9 || charCode === 10 || charCode === 12 || charCode === 13 || charCode === 32; - if (isBase64) { - let effectiveLen = body.length; - const len = body.length; // cache length +const base64Bytes = (significant) => { + const groups = Math.floor(significant / 4); + const remainder = significant % 4; + return groups * 3 + (remainder === 2 ? 1 : remainder === 3 ? 2 : 0); +}; - for (let i = 0; i < len; i++) { - if (body.charCodeAt(i) === 37 /* '%' */ && i + 2 < len) { - const a = body.charCodeAt(i + 1); - const b = body.charCodeAt(i + 2); - const isHex = isHexDigit(a) && isHexDigit(b); +// Buffer.byteLength(body, 'base64') uses the raw string length as an allocation +// upper bound even when Buffer.from later ignores characters or stops at '='. +const estimateBase64BufferAllocation = (body) => { + const len = body.length; + let padding = 0; - if (isHex) { - effectiveLen -= 2; - i += 2; - } - } + if (len > 0 && body.charCodeAt(len - 1) === 61 /* '=' */) { + padding++; + + if (len > 1 && body.charCodeAt(len - 2) === 61 /* '=' */) { + padding++; } + } - let pad = 0; - let idx = len - 1; + return Math.floor(((len - padding) * 3) / 4); +}; - const tailIsPct3D = (j) => - j >= 2 && - body.charCodeAt(j - 2) === 37 && // '%' - body.charCodeAt(j - 1) === 51 && // '3' - (body.charCodeAt(j) === 68 || body.charCodeAt(j) === 100); // 'D' or 'd' +const estimatePercentDecodedBase64Bytes = (body) => { + const len = body.length; + let significant = 0; + let padding = 0; + let invalid = false; - if (idx >= 0) { - if (body.charCodeAt(idx) === 61 /* '=' */) { - pad++; - idx--; - } else if (tailIsPct3D(idx)) { - pad++; - idx -= 3; - } + for (let i = 0; i < len; i++) { + let code = body.charCodeAt(i); + + if (code === 37 /* '%' */ && isPercentEncodedByte(body, i, len)) { + code = hexValue(body.charCodeAt(i + 1)) * 16 + hexValue(body.charCodeAt(i + 2)); + i += 2; } - if (pad === 1 && idx >= 0) { - if (body.charCodeAt(idx) === 61 /* '=' */) { - pad++; - } else if (tailIsPct3D(idx)) { - pad++; - } + if (isBase64Whitespace(code)) { + continue; + } + + if (code === 61 /* '=' */) { + padding++; + continue; + } + + if (!isBase64Char(code) || padding > 0) { + invalid = true; + continue; } - const groups = Math.floor(effectiveLen / 4); - const bytes = groups * 3 - (pad || 0); - return bytes > 0 ? bytes : 0; + significant++; + } + + // Fetch rejects malformed forgiving-base64 input. Returning the raw-size + // allocation bound keeps that invalid input from becoming a pre-check bypass. + if ( + invalid || + padding > 2 || + (padding > 0 && (significant + padding) % 4 !== 0) || + significant % 4 === 1 + ) { + return estimateBase64BufferAllocation(body); + } + + return base64Bytes(significant); +}; + +const estimateDataURLBytes = (url, estimateBase64) => { + if (!url || typeof url !== 'string') return 0; + if (!url.startsWith('data:')) return 0; + + const comma = url.indexOf(','); + if (comma < 0) return 0; + + const meta = url.slice(5, comma); + const body = url.slice(comma + 1); + const isBase64 = /;base64/i.test(meta); + + if (isBase64) { + return estimateBase64(body); } // Compute UTF-8 byte length directly from UTF-16 code units without allocating @@ -42798,6 +43908,32 @@ function estimateDataURLDecodedBytes(url) { } } return bytes; +}; + +/** + * Estimate the percent-decoded payload size used by Fetch data: URLs. + * + * @param {string} url + * @returns {number} + */ +function estimateDataURLDecodedBytes(url) { + // Fetch removes URL fragments before processing a data: URL. + const fragmentIndex = typeof url === 'string' ? url.indexOf('#') : -1; + + return estimateDataURLBytes( + fragmentIndex === -1 ? url : url.slice(0, fragmentIndex), + estimatePercentDecodedBase64Bytes + ); +} + +/** + * Estimate the Buffer backing allocation used by Node's raw base64 decoder. + * + * @param {string} url + * @returns {number} + */ +function estimateDataURLBufferAllocation(url) { + return estimateDataURLBytes(url, estimateBase64BufferAllocation); } ;// CONCATENATED MODULE: ./node_modules/axios/lib/adapters/http.js @@ -42832,6 +43968,7 @@ function estimateDataURLDecodedBytes(url) { + const zlibOptions = { @@ -42853,30 +43990,27 @@ const isBrotliSupported = utils.isFunction(external_zlib_namespaceObject.createB const isZstdSupported = utils.isFunction(external_zlib_namespaceObject.createZstdDecompress); const ACCEPT_ENCODING = 'gzip, compress, deflate' + (isBrotliSupported ? ', br' : ''); const ACCEPT_ENCODING_WITH_ZSTD = ACCEPT_ENCODING + (isZstdSupported ? ', zstd' : ''); +const scheduleProgress = + typeof process !== 'undefined' && process.nextTick ? process.nextTick.bind(process) : utils.asap; const { http: httpFollow, https: httpsFollow } = follow_redirects; const http_isHttps = /https:?/; -const FORM_DATA_CONTENT_HEADERS = ['content-type', 'content-length']; - -function setFormDataHeaders(headers, formHeaders, policy) { - if (policy !== 'content-only') { - headers.set(formHeaders); - return; - } - - Object.entries(formHeaders).forEach(([key, val]) => { - if (FORM_DATA_CONTENT_HEADERS.includes(key.toLowerCase())) { - headers.set(key, val); - } - }); -} // Symbols used to bind a single 'error' listener to a pooled socket and track // the request currently owning that socket across keep-alive reuse (issue #10780). const kAxiosSocketListener = Symbol('axios.http.socketListener'); const kAxiosCurrentReq = Symbol('axios.http.currentReq'); +// A shared listener avoids retaining an adapter context for the lifetime of a +// pooled socket. EventEmitter invokes listeners with `this` set to the emitter. +function handleSocketError(err) { + const current = this[kAxiosCurrentReq]; + if (current && !current.destroyed) { + current.destroy(err); + } +} + // Tags HttpsProxyAgent instances installed by setProxy() so the redirect path // can strip them without clobbering a user-supplied agent that happens to be // an HttpsProxyAgent. @@ -42924,16 +44058,14 @@ function isNodeEnvProxyEnabled(agent, nodeVersion = process.versions && process. const agentOptions = agent && agent.options; return Boolean( - agentOptions && - utils.hasOwnProp(agentOptions, 'proxyEnv') && - agentOptions.proxyEnv != null + agentOptions && utils.hasOwnProp(agentOptions, 'proxyEnv') && agentOptions.proxyEnv != null ); } function getProxyEnvAgent(options, configHttpAgent, configHttpsAgent) { return http_isHttps.test(options.protocol) - ? (configHttpsAgent || external_https_.globalAgent) - : (configHttpAgent || external_http_.globalAgent); + ? configHttpsAgent || external_https_.globalAgent + : configHttpAgent || external_http_.globalAgent; } function getTunnelingAgent(agentOptions, userHttpsAgent) { @@ -42946,17 +44078,18 @@ function getTunnelingAgent(agentOptions, userHttpsAgent) { '#' + (agentOptions.auth || ''); const cache = userHttpsAgent - ? (tunnelingAgentCacheUser.get(userHttpsAgent) || - tunnelingAgentCacheUser.set(userHttpsAgent, new Map()).get(userHttpsAgent)) + ? tunnelingAgentCacheUser.get(userHttpsAgent) || + tunnelingAgentCacheUser.set(userHttpsAgent, new Map()).get(userHttpsAgent) : tunnelingAgentCache; let agent = cache.get(key); if (agent) return agent; // Forward the user's TLS options (custom CA, rejectUnauthorized, client cert, // etc.) into the tunneling agent so they apply to the origin TLS upgrade // performed after CONNECT. Our proxy fields take precedence on conflict. - const merged = userHttpsAgent && userHttpsAgent.options - ? { ...userHttpsAgent.options, ...agentOptions } - : agentOptions; + const merged = + userHttpsAgent && userHttpsAgent.options + ? { ...userHttpsAgent.options, ...agentOptions } + : agentOptions; agent = new dist(merged); if (userHttpsAgent && userHttpsAgent.options) { const originTLSOptions = { ...userHttpsAgent.options }; @@ -43053,13 +44186,22 @@ function isSameOriginRedirect(redirectOptions, requestDetails) { * @param {http.ClientRequestArgs} options * @param {AxiosProxyConfig} configProxy configuration from Axios options object * @param {string} location - * - * @returns {http.ClientRequestArgs} - */ -function setProxy(options, configProxy, location, isRedirect, configHttpsAgent, configHttpAgent) { + * @param {boolean} [allowEnvProxy=true] whether environment proxy configuration can be used + * + * @returns {boolean} whether a proxy applies to the selected transport + */ +function setProxy( + options, + configProxy, + location, + isRedirect, + configHttpsAgent, + configHttpAgent, + allowEnvProxy = true +) { let proxy = configProxy; const proxyEnvAgent = getProxyEnvAgent(options, configHttpAgent, configHttpsAgent); - if (!proxy && proxy !== false && !isNodeEnvProxyEnabled(proxyEnvAgent)) { + if (!proxy && proxy !== false && allowEnvProxy && !isNodeEnvProxyEnabled(proxyEnvAgent)) { const proxyUrl = getProxyForUrl(location); if (proxyUrl) { if (!shouldBypassProxy(location)) { @@ -43216,9 +44358,15 @@ function setProxy(options, configProxy, location, isRedirect, configHttpsAgent, redirectOptions.href, true, configHttpsAgent, - configHttpAgent + configHttpAgent, + allowEnvProxy ); }; + + return Boolean( + proxy || + (configProxy !== false && allowEnvProxy && isNodeEnvProxyEnabled(proxyEnvAgent)) + ); } const isHttpAdapterSupported = @@ -43253,7 +44401,7 @@ const wrapAsync = (asyncExecutor) => { const resolveFamily = ({ address, family }) => { if (!utils.isString(address)) { - throw TypeError('address must be a string'); + throw new core_AxiosError('address must be a string', core_AxiosError.ERR_BAD_OPTION_VALUE); } return { address, @@ -43264,6 +44412,43 @@ const resolveFamily = ({ address, family }) => { const buildAddressEntry = (address, family) => resolveFamily(utils.isObject(address) ? address : { address, family }); +const normalizedLookupCache = new WeakMap(); + +const normalizeLookup = (lookup) => { + let normalized = normalizedLookupCache.get(lookup); + + if (normalized) { + return normalized; + } + + const callbackLookup = helpers_callbackify(lookup, (value) => (utils.isArray(value) ? value : [value])); + + // Support opt.all, which is required by current Node.js releases. + normalized = (hostname, opt, cb) => { + callbackLookup(hostname, opt, (err, arg0, arg1) => { + if (err) { + return cb(err); + } + + let addresses; + + try { + addresses = utils.isArray(arg0) + ? arg0.map((addr) => buildAddressEntry(addr)) + : [buildAddressEntry(arg0, arg1)]; + } catch (error) { + return cb(error); + } + + opt.all ? cb(err, addresses) : cb(err, addresses[0].address, addresses[0].family); + }); + }; + + normalizedLookupCache.set(lookup, normalized); + + return normalized; +}; + const http2Transport = { request(options, cb) { const authority = @@ -43328,6 +44513,7 @@ const http2Transport = { let family = own('family'); let httpVersion = own('httpVersion'); if (httpVersion === undefined) httpVersion = 1; + const rawHttpVersion = httpVersion; let http2Options = own('http2Options'); const httpAgent = own('httpAgent'); const httpsAgent = own('httpsAgent'); @@ -43345,34 +44531,36 @@ const http2Transport = { let req; let connectPhaseTimer; - httpVersion = +httpVersion; + try { + httpVersion = +httpVersion; + } catch (err) { + throw new core_AxiosError( + 'Invalid protocol version: value is not a number', + core_AxiosError.ERR_BAD_OPTION_VALUE, + config + ); + } if (Number.isNaN(httpVersion)) { - throw TypeError(`Invalid protocol version: '${config.httpVersion}' is not a number`); + throw new core_AxiosError( + `Invalid protocol version: '${rawHttpVersion}' is not a number`, + core_AxiosError.ERR_BAD_OPTION_VALUE, + config + ); } if (httpVersion !== 1 && httpVersion !== 2) { - throw TypeError(`Unsupported protocol version '${httpVersion}'`); + throw new core_AxiosError( + `Unsupported protocol version '${httpVersion}'`, + core_AxiosError.ERR_BAD_OPTION_VALUE, + config + ); } const isHttp2 = httpVersion === 2; if (lookup) { - const _lookup = helpers_callbackify(lookup, (value) => (utils.isArray(value) ? value : [value])); - // 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.isArray(arg0) - ? arg0.map((addr) => buildAddressEntry(addr)) - : [buildAddressEntry(arg0, arg1)]; - - opt.all ? cb(err, addresses) : cb(err, addresses[0].address, addresses[0].family); - }); - }; + lookup = normalizeLookup(lookup); } const abortEmitter = new external_events_.EventEmitter(); @@ -43465,7 +44653,9 @@ const http2Transport = { // prototype cannot influence URL base selection. const urlBase = socketPath ? 'http://localhost' - : (lib_platform.hasBrowserEnv ? lib_platform.origin : undefined); + : lib_platform.hasBrowserEnv + ? lib_platform.origin + : undefined; const parsed = new URL(fullPath, urlBase); const protocol = parsed.protocol || supportedProtocols[0]; @@ -43474,7 +44664,7 @@ const http2Transport = { if (maxContentLength > -1) { // Use the exact string passed to fromDataURI (the configured url); fall back to fullPath if needed. const dataUrl = String(own('url') || fullPath || ''); - const estimated = estimateDataURLDecodedBytes(dataUrl); + const estimated = estimateDataURLBufferAllocation(dataUrl); if (estimated > maxContentLength) { return reject( @@ -43641,7 +44831,7 @@ const http2Transport = { data, progressEventDecorator( contentLength, - progressEventReducer(asyncDecorator(onUploadProgress), false, 3) + progressEventReducer(asyncDecorator(onUploadProgress, scheduleProgress), false, 3) ) ) ); @@ -43676,7 +44866,7 @@ const http2Transport = { return reject( core_AxiosError.from(err, core_AxiosError.ERR_BAD_REQUEST, config, null, null, { url: own('url'), - exists: true + exists: true, }) ); } @@ -43684,10 +44874,16 @@ const http2Transport = { headers.set( 'Accept-Encoding', utils.hasOwnProp(transitional, 'advertiseZstdAcceptEncoding') && - transitional.advertiseZstdAcceptEncoding === true ? ACCEPT_ENCODING_WITH_ZSTD : ACCEPT_ENCODING, + transitional.advertiseZstdAcceptEncoding === true + ? ACCEPT_ENCODING_WITH_ZSTD + : ACCEPT_ENCODING, false ); + if (isHttp2 && lookup) { + http2Options = Object.assign(Object.create(null), http2Options, { lookup }); + } + // Null-prototype to block prototype pollution gadgets on properties read // directly by Node's http.request (e.g. insecureHTTPParser, lookup). const options = Object.assign(Object.create(null), { @@ -43701,11 +44897,14 @@ const http2Transport = { beforeRedirect: dispatchBeforeRedirect, beforeRedirects: Object.create(null), http2Options, + createConnection: undefined, }); // cacheable-lookup integration hotfix !utils.isUndefined(lookup) && (options.lookup = lookup); + let proxyApplied = false; + if (socketPath) { if (typeof socketPath !== 'string') { return reject( @@ -43741,13 +44940,17 @@ const http2Transport = { ? parsed.hostname.slice(1, -1) : parsed.hostname; options.port = parsed.port; - setProxy( + proxyApplied = setProxy( options, configProxy, protocol + '//' + parsed.hostname + (parsed.port ? ':' + parsed.port : '') + options.path, false, httpsAgent, - httpAgent + httpAgent, + // The HTTP/2 transport connects independently of HTTP/1 agents, so it + // cannot apply either axios-resolved or agent-local environment proxies. + // Explicit proxy config is still processed and rejected below. + !isHttp2 ); } let transport; @@ -43765,6 +44968,16 @@ const http2Transport = { } if (isHttp2) { + if (proxyApplied) { + return reject( + new core_AxiosError( + 'HTTP/2 requests with a proxy are not supported', + core_AxiosError.ERR_NOT_SUPPORT, + config + ) + ); + } + transport = http2Transport; } else { const configTransport = own('transport'); @@ -43879,7 +45092,11 @@ const http2Transport = { transformStream, progressEventDecorator( responseLength, - progressEventReducer(asyncDecorator(onDownloadProgress), true, 3) + progressEventReducer( + asyncDecorator(onDownloadProgress, scheduleProgress), + true, + 3 + ) ) ) ); @@ -44077,18 +45294,10 @@ const http2Transport = { socket.setKeepAlive(true, 1000 * 60); } - // Install a single 'error' listener per socket (not per request) to avoid - // accumulating listeners on pooled keep-alive sockets that get reassigned - // to new requests before the previous request's 'close' fires (issue #10780). - // The listener is bound to the socket's currently-active request via a - // symbol, which is swapped as the socket is reassigned. + // Install one shared 'error' listener per socket. The symbol follows the + // currently-active request as pooled sockets are reassigned (issue #10780). if (!socket[kAxiosSocketListener]) { - socket.on('error', function handleSocketError(err) { - const current = socket[kAxiosCurrentReq]; - if (current && !current.destroyed) { - current.destroy(err); - } - }); + socket.on('error', handleSocketError); socket[kAxiosSocketListener] = true; } @@ -44307,6 +45516,17 @@ const __isSameOriginRedirect = (/* unused pure expression or super */ null && (i const headersToObject = (thing) => (thing instanceof core_AxiosHeaders ? { ...thing } : thing); +const ownEnumerableKeys = (thing) => { + if (Object.getOwnPropertySymbols && Object.getOwnPropertyDescriptor) { + return Object.keys(thing).concat( + Object.getOwnPropertySymbols(thing).filter( + (symbol) => Object.getOwnPropertyDescriptor(thing, symbol).enumerable + ) + ); + } + return Object.keys(thing); +}; + /** * Config-specific merge-function which creates a new config-object * by merging two configuration objects together. @@ -44372,7 +45592,9 @@ function mergeConfig(config1, config2) { } function getMergedTransitionalOption(prop) { - const transitional2 = utils.hasOwnProp(config2, 'transitional') ? config2.transitional : undefined; + const transitional2 = utils.hasOwnProp(config2, 'transitional') + ? config2.transitional + : undefined; if (!utils.isUndefined(transitional2)) { if (utils.isPlainObject(transitional2)) { @@ -44384,7 +45606,9 @@ function mergeConfig(config1, config2) { } } - const transitional1 = utils.hasOwnProp(config1, 'transitional') ? config1.transitional : undefined; + const transitional1 = utils.hasOwnProp(config1, 'transitional') + ? config1.transitional + : undefined; if (utils.isPlainObject(transitional1) && utils.hasOwnProp(transitional1, prop)) { return transitional1[prop]; @@ -44411,7 +45635,7 @@ function mergeConfig(config1, config2) { transformResponse: defaultToConfig2, paramsSerializer: defaultToConfig2, timeout: defaultToConfig2, - timeoutMessage: defaultToConfig2, + timeoutErrorMessage: defaultToConfig2, withCredentials: defaultToConfig2, withXSRFToken: defaultToConfig2, adapter: defaultToConfig2, @@ -44436,7 +45660,7 @@ function mergeConfig(config1, config2) { mergeDeepProperties(headersToObject(a), headersToObject(b), prop, true), }; - utils.forEach(Object.keys({ ...config1, ...config2 }), function computeConfigValue(prop) { + utils.forEach(ownEnumerableKeys({ ...config1, ...config2 }), function computeConfigValue(prop) { if (prop === '__proto__' || prop === 'constructor' || prop === 'prototype') return; const merge = utils.hasOwnProp(mergeMap, prop) ? mergeMap[prop] : mergeDeepProperties; const a = utils.hasOwnProp(config1, prop) ? config1[prop] : undefined; @@ -44471,20 +45695,6 @@ function mergeConfig(config1, config2) { -const resolveConfig_FORM_DATA_CONTENT_HEADERS = ['content-type', 'content-length']; - -function resolveConfig_setFormDataHeaders(headers, formHeaders, policy) { - if (policy !== 'content-only') { - headers.set(formHeaders); - return; - } - - Object.entries(formHeaders || {}).forEach(([key, val]) => { - if (resolveConfig_FORM_DATA_CONTENT_HEADERS.includes(key.toLowerCase())) { - headers.set(key, val); - } - }); -} /** * Encode a UTF-8 string to a Latin-1 byte string for use with btoa(). @@ -44540,15 +45750,17 @@ function resolveConfig(config) { } if (utils.isFormData(data)) { + const getHeaders = utils.getSafeProp(data, 'getHeaders'); + if ( lib_platform.hasStandardBrowserEnv || lib_platform.hasStandardBrowserWebWorkerEnv || utils.isReactNative(data) ) { headers.setContentType(undefined); // browser/web worker/RN handles it - } else if (utils.isFunction(data.getHeaders)) { + } else if (utils.isFunction(getHeaders)) { // Node.js FormData (like form-data package) - resolveConfig_setFormDataHeaders(headers, data.getHeaders(), own('formDataHeaderPolicy')); + setFormDataHeaders(headers, getHeaders.call(data), own('formDataHeaderPolicy')); } } @@ -44594,6 +45806,7 @@ function resolveConfig(config) { + const isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined'; /* harmony default export */ const xhr = (isXHRAdapterSupported && @@ -44605,7 +45818,7 @@ const isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined'; let { responseType, onUploadProgress, onDownloadProgress } = _config; let onCanceled; let uploadThrottled, downloadThrottled; - let flushUpload, flushDownload; + let flushUpload, flushDownload, flushDownloadWithEvent; function done() { flushUpload && flushUpload(); // flush events @@ -44623,10 +45836,55 @@ const isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined'; // Set the request timeout in MS request.timeout = _config.timeout; - function onloadend() { + function onloadend(event) { + if (!request) { + return; + } + + // Status 0 means no response was received, which onerror and onabort normally + // reject before this runs. Firefox 152 fires only readystatechange and loadend for + // navigation-canceled requests (https://bugzilla.mozilla.org/show_bug.cgi?id=1505389), + // leaving settle() to resolve them as an empty success. ECONNABORTED is the error + // onabort raised on Firefox 151. Reads over file:, which some environments report as + // status 0 on success, are excluded by the request URL's scheme after browser-style + // preprocessing, by the page origin's scheme for relative URLs (which inherit it), or + // by responseURL where implemented. + if ( + request.status === 0 && + (parseProtocol(normalizeURLForProtocolCheck(_config.url)) || + parseProtocol(lib_platform.origin)) !== 'file' && + !(request.responseURL && request.responseURL.startsWith('file:')) + ) { + reject(new core_AxiosError('Request aborted', core_AxiosError.ECONNABORTED, config, request)); + done(); + + // Clean up request + request = null; + return; + } + + // When loadend is still dispatching, flushing with it gives progress + // listeners a final delivery whose event has a live target. The legacy + // ready-state fallback has no event, so replay its pending progress. + // A throwing listener must not block settlement; rethrow asynchronously, + // matching how listener errors surface on the throttle timer path. + try { + if (event) { + flushDownloadWithEvent && flushDownloadWithEvent(event); + } else { + flushDownload && flushDownload(); + } + } catch (err) { + setTimeout(() => { + throw err; + }); + } + + // A final progress callback can cancel the request synchronously. if (!request) { return; } + // Prepare the response const responseHeaders = core_AxiosHeaders.from( 'getAllResponseHeaders' in request && request.getAllResponseHeaders() @@ -44758,7 +46016,10 @@ const isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined'; // Handle progress if needed if (onDownloadProgress) { - [downloadThrottled, flushDownload] = progressEventReducer(onDownloadProgress, true); + [downloadThrottled, flushDownload, flushDownloadWithEvent] = progressEventReducer( + onDownloadProgress, + true + ); request.addEventListener('progress', downloadThrottled); } @@ -44859,7 +46120,18 @@ const composeSignals = (signals, timeout) => { signals = null; }; - signals.forEach((signal) => signal.addEventListener('abort', onabort, { once: true })); + signals.forEach((signal) => { + if (aborted) { + return; + } + + if (signal.aborted) { + onabort.call(signal); + return; + } + + signal.addEventListener('abort', onabort, { once: true }); + }); const { signal } = controller; @@ -44977,6 +46249,18 @@ const trackStream = (stream, chunkSize, onProgress, onFinish) => { const DEFAULT_CHUNK_SIZE = 64 * 1024; +const DEFAULT_REQUEST_OPTIONS = { + cache: 'default', + redirect: 'follow', + referrer: 'about:client', + referrerPolicy: '', + mode: 'cors', + integrity: '', + keepalive: false, + priority: 'auto', + window: null, +}; + const { isFunction: fetch_isFunction } = utils; /** @@ -45027,9 +46311,7 @@ const maybeWithAuthCredentials = (url) => { const factory = (env) => { const globalObject = - utils.global !== undefined && utils.global !== null - ? utils.global - : globalThis; + utils.global !== undefined && utils.global !== null ? utils.global : globalThis; const { ReadableStream, TextEncoder } = globalObject; env = utils.merge.call( @@ -45168,6 +46450,7 @@ const factory = (env) => { fetchOptions, maxContentLength, maxBodyLength, + maxRedirects, } = helpers_resolveConfig(config); const hasMaxContentLength = utils.isNumber(maxContentLength) && maxContentLength > -1; @@ -45218,7 +46501,7 @@ const factory = (env) => { const password = utils.getSafeProp(configAuth, 'password') || ''; auth = { username, - password + password, }; } @@ -45230,7 +46513,7 @@ const factory = (env) => { const urlPassword = fetch_decodeURIComponentSafe(parsedURL.password); auth = { username: urlUsername, - password: urlPassword + password: urlPassword, }; } @@ -45304,7 +46587,9 @@ const factory = (env) => { (onUploadProgress || mustEnforceStreamBody) ) { requestContentLength = - requestContentLength == null ? await resolveBodyLength(headers, data) : requestContentLength; + requestContentLength == null + ? await resolveBodyLength(headers, data) + : requestContentLength; // A declared length of 0 is only trusted to skip the wrap when we are // not enforcing a stream limit (which must not rely on that header). @@ -45317,7 +46602,10 @@ const factory = (env) => { let contentTypeHeader; - if (utils.isFormData(data) && (contentTypeHeader = _request.headers.get('content-type'))) { + if ( + utils.isFormData(data) && + (contentTypeHeader = _request.headers.get('content-type')) + ) { headers.setContentType(contentTypeHeader); } @@ -45380,20 +46668,57 @@ const factory = (env) => { // Set User-Agent header if not already set (fetch defaults to 'node' in Node.js) headers.set('User-Agent', 'axios/' + VERSION, false); - const resolvedOptions = { - ...fetchOptions, + const safeFetchOptions = + fetchOptions == null ? fetchOptions : Object.assign(Object.create(null), fetchOptions); + + if (safeFetchOptions) { + // These options are owned by Axios and are already reflected in the + // resolved Request passed to fetch. + delete safeFetchOptions.body; + delete safeFetchOptions.headers; + delete safeFetchOptions.method; + delete safeFetchOptions.signal; + delete safeFetchOptions.duplex; + delete safeFetchOptions.credentials; + } + + const resolvedOptions = Object.assign(Object.create(null), safeFetchOptions, { signal: composedSignal, method: method.toUpperCase(), headers: toByteStringHeaderObject(headers.normalize()), body: data, duplex: 'half', credentials: isCredentialsSupported ? withCredentials : undefined, - }; + }); + + if (isRequestSupported) { + utils.forEach(DEFAULT_REQUEST_OPTIONS, (value, key) => { + if (resolvedOptions[key] === undefined) { + resolvedOptions[key] = value; + } + }); + + if (resolvedOptions.signal === undefined) { + resolvedOptions.signal = null; + } + + if (resolvedOptions.body === undefined) { + resolvedOptions.body = null; + } + } + + if (maxRedirects === 0) { + resolvedOptions.redirect = 'manual'; + + if (safeFetchOptions) { + safeFetchOptions.redirect = 'manual'; + } + } request = isRequestSupported && new Request(url, resolvedOptions); let response = await (isRequestSupported - ? _fetch(request, fetchOptions) + ? _fetch(request, safeFetchOptions) : _fetch(url, resolvedOptions)); const responseHeaders = core_AxiosHeaders.from(response.headers); @@ -45746,6 +47071,7 @@ function getAdapter(adapters, config) { + /** * Throws a `CanceledError` if cancellation has been requested. * @@ -45770,10 +47096,15 @@ function throwIfCancellationRequested(config) { * * @returns {Promise} The Promise to be fulfilled */ -function dispatchRequest(config) { +function dispatchRequest(_config) { + // Interceptors may replace the merged config with an ordinary object. Flatten + // it at the dispatch boundary so shared prototype members cannot become + // request behavior, while preserving intentional template/class members. + const config = utils.toSafeFlatObject(_config); + throwIfCancellationRequested(config); - config.headers = core_AxiosHeaders.from(config.headers); + config.headers = core_AxiosHeaders.from(utils.getSafeProp(config, 'headers')); // Transform request data config.data = transformData.call(config, config.transformRequest); @@ -45954,6 +47285,7 @@ function assertOptions(options, schema, allowUnknown) { + const Axios_validators = validator.validators; /** @@ -45985,21 +47317,21 @@ class Axios { return await this._request(configOrUrl, config); } catch (err) { if (err instanceof Error) { - let dummy = {}; + try { + let dummy = {}; - Error.captureStackTrace ? Error.captureStackTrace(dummy) : (dummy = new Error()); + Error.captureStackTrace ? Error.captureStackTrace(dummy) : (dummy = new Error()); - // slice off the Error: ... line - const stack = (() => { - if (!dummy.stack) { - return ''; - } + const dummyStack = dummy.stack; + let stack = ''; - const firstNewlineIndex = dummy.stack.indexOf('\n'); + // slice off the Error: ... line + if (typeof dummyStack === 'string') { + const firstNewlineIndex = dummyStack.indexOf('\n'); + + stack = firstNewlineIndex === -1 ? '' : dummyStack.slice(firstNewlineIndex + 1); + } - return firstNewlineIndex === -1 ? '' : dummy.stack.slice(firstNewlineIndex + 1); - })(); - try { if (!err.stack) { err.stack = stack; // match without the 2 top stack lines @@ -46015,7 +47347,7 @@ class Axios { } } } catch (e) { - // ignore the case where "stack" is an un-writable property + // Ignore failures from custom stack hooks or un-writable stack properties. } } @@ -46088,13 +47420,17 @@ class Axios { ); // Set config.method - config.method = (config.method || this.defaults.method || 'get').toLowerCase(); + config.method = ( + utils.getSafeProp(config, 'method') || + utils.getSafeProp(this.defaults, 'method') || + 'get' + ).toLowerCase(); // Flatten headers let contextHeaders = headers && utils.merge(headers.common, headers[config.method]); headers && - utils.forEach(['delete', 'get', 'head', 'post', 'put', 'patch', 'query', 'common'], (method) => { + utils.forEach(core_methodList.concat('common'), (method) => { delete headers[method]; }); @@ -46153,17 +47489,35 @@ class Axios { const onFulfilled = requestInterceptorChain[i++]; const onRejected = requestInterceptorChain[i++]; try { - newConfig = onFulfilled(newConfig); + newConfig = onFulfilled ? onFulfilled(newConfig) : newConfig; } catch (error) { - onRejected.call(this, error); + if (!onRejected) { + promise = Promise.reject(error); + break; + } + + try { + const rejectedResult = onRejected.call(this, error); + + if (utils.isThenable(rejectedResult)) { + promise = Promise.resolve(rejectedResult).then(() => + dispatchRequest.call(this, newConfig) + ); + } + } catch (rejectedError) { + promise = Promise.reject(rejectedError); + } + break; } } - try { - promise = dispatchRequest.call(this, newConfig); - } catch (error) { - return Promise.reject(error); + if (!promise) { + try { + promise = dispatchRequest.call(this, newConfig); + } catch (error) { + promise = Promise.reject(error); + } } i = 0; @@ -46447,14 +47801,22 @@ const HttpStatusCode = { Gone: 410, LengthRequired: 411, PreconditionFailed: 412, + /** + * @deprecated Use `ContentTooLarge` instead. + */ PayloadTooLarge: 413, + ContentTooLarge: 413, UriTooLong: 414, UnsupportedMediaType: 415, RangeNotSatisfiable: 416, ExpectationFailed: 417, ImATeapot: 418, MisdirectedRequest: 421, + /** + * @deprecated Use `UnprocessableContent` instead. + */ UnprocessableEntity: 422, + UnprocessableContent: 422, Locked: 423, FailedDependency: 424, TooEarly: 425, @@ -46474,6 +47836,7 @@ const HttpStatusCode = { LoopDetected: 508, NotExtended: 510, NetworkAuthenticationRequired: 511, + WebServerReturnsAnUnknownError: 520, WebServerIsDown: 521, ConnectionTimedOut: 522, OriginIsUnreachable: 523, @@ -46483,7 +47846,9 @@ const HttpStatusCode = { }; Object.entries(HttpStatusCode).forEach(([key, value]) => { - HttpStatusCode[value] = key; + if (HttpStatusCode[value] === undefined) { + HttpStatusCode[value] = key; + } }); /* harmony default export */ const helpers_HttpStatusCode = (HttpStatusCode); diff --git a/package-lock.json b/package-lock.json index 5e05b62..82c024a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -755,13 +755,13 @@ "license": "MIT" }, "node_modules/axios": { - "version": "1.18.1", - "resolved": "https://registry.npmjs.org/axios/-/axios-1.18.1.tgz", - "integrity": "sha512-3nTvFlvpn9Zu/RkHUqtc7/+al4UpRW5az71ap5zccp6e8RAYEzhMTecX8Dz1wWDYrPpUoB1HAQEGEAEvUr7S9g==", + "version": "1.20.0", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.20.0.tgz", + "integrity": "sha512-r8aOh8j9cGKpgQAqpzrUHnSIc6a59Y3Xf/cv8sy1DrHCkZHzQGEuoq1tARk6qSyDdtQGSDgpb9kFlruzPvrgwg==", "license": "MIT", "dependencies": { "follow-redirects": "^1.16.0", - "form-data": "^4.0.5", + "form-data": "^4.0.6", "https-proxy-agent": "^5.0.1", "proxy-from-env": "^2.1.0" } @@ -1668,9 +1668,9 @@ } }, "node_modules/undici": { - "version": "6.28.0", - "resolved": "https://registry.npmjs.org/undici/-/undici-6.28.0.tgz", - "integrity": "sha512-LIY910g9TI13YS95lrMFrs8Rm/u/irgHeTWoKCoteeJ04CUJ92eEfj0rVn+7VKMPBpUPiUoBKfhNyLI23EE/KA==", + "version": "6.29.0", + "resolved": "https://registry.npmjs.org/undici/-/undici-6.29.0.tgz", + "integrity": "sha512-R+RODBqp6i2pPflGdq+xIOUkl+RNfGgHwoinecKu/JCuf2uO06cOKoDbI2P7Dn6KcswdKwrczbU6IYJ6K8X+wg==", "license": "MIT", "engines": { "node": ">=18.17"