deps: update undici to 7.29.1

PR-URL: https://github.com/nodejs/node/pull/65789
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Filip Skokan <panva.ip@gmail.com>
Reviewed-By: Trivikram Kamat <trivikr.dev@gmail.com>
This commit is contained in:
Node.js GitHub Bot authored and Antoine du Hamel committed 2026-09-07 11:54:03 +02:00
1 parent 39e0457e86
commit 53cba013c7
19 files changed
+2011 -1096

No files matched your search

+4 -2
View File
@@ -49,14 +49,16 @@ function defaultFactory (origin, opts) {
}
class BalancedPool extends PoolBase {
constructor (upstreams = [], { factory = defaultFactory, ...opts } = {}) {
constructor (upstreams = [], { factory = defaultFactory, connect, tls, ...opts } = {}) {
if (typeof factory !== 'function') {
throw new InvalidArgumentError('factory must be a function.')
}
super(opts)
this[kOptions] = { ...util.deepClone(opts) }
if (connect && typeof connect !== 'function') connect = { ...connect }
if (tls && typeof tls !== 'function') tls = { ...tls }
this[kOptions] = { ...util.deepClone(opts), connect, tls }
this[kOptions].interceptors = opts.interceptors
? { ...opts.interceptors }
: undefined
+12 -4
View File
@@ -1012,7 +1012,7 @@ function onSocketClose () {
function clearIdleSocketValidation (socket) {
if (socket[kIdleSocketValidationTimeout]) {
clearTimeout(socket[kIdleSocketValidationTimeout])
clearImmediate(socket[kIdleSocketValidationTimeout])
socket[kIdleSocketValidationTimeout] = null
}
@@ -1021,15 +1021,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?.()
})
}
/**
+70 -14
View File
@@ -8,7 +8,9 @@ const {
RequestAbortedError,
SocketError,
InformationalError,
InvalidArgumentError
InvalidArgumentError,
HeadersTimeoutError,
BodyTimeoutError
} = require('../core/errors.js')
const {
kUrl,
@@ -33,6 +35,7 @@ const {
kHTTPContext,
kClosed,
kBodyTimeout,
kHeadersTimeout,
kEnableConnectProtocol,
kRemoteSettings,
kHTTP2Stream,
@@ -219,7 +222,11 @@ function resumeH2 (client) {
const socket = client[kSocket]
if (socket?.destroyed === false) {
if (client[kSize] === 0 || client[kMaxConcurrentStreams] === 0) {
// Only let the process exit when there is genuinely nothing outstanding.
// Unreffing because the peer advertised MAX_CONCURRENT_STREAMS = 0 left
// queued requests with nothing holding the event loop open, so the process
// could exit with status 0 while an awaited request never settled.
if (client[kSize] === 0) {
socket.unref()
client[kHTTP2Session].unref()
} else {
@@ -314,6 +321,36 @@ function onHttp2SessionEnd () {
* @this {import('http2').ClientHttp2Session}
* @param {number} errorCode
*/
// Backport of #5410 and #5569. HTTP/2 multiplexes, so requests complete out of
// order; advancing kRunningIdx blindly retired whichever request happened to
// sit at the head instead of the one that actually finished, which both lost
// requests and left phantom running slots behind.
function completeRequest (client, request, resetPendingIdx = false) {
const queue = client[kQueue]
const runningIdx = client[kRunningIdx]
// In-order completion: clear the request and advance without splicing.
// The client's resume loop compacts cleared slots once the index grows.
if (runningIdx < client[kPendingIdx] && queue[runningIdx] === request) {
queue[runningIdx] = null
client[kRunningIdx] = runningIdx + 1
return
}
const index = queue.indexOf(request, runningIdx)
if (index === -1 || index >= client[kPendingIdx]) {
return
}
queue.splice(index, 1)
client[kPendingIdx]--
if (resetPendingIdx && client[kPendingIdx] < client[kRunningIdx]) {
client[kPendingIdx] = client[kRunningIdx]
}
}
function onHttp2SessionGoAway (errorCode) {
// TODO(mcollina): Verify if GOAWAY implements the spec correctly:
// https://datatracker.ietf.org/doc/html/rfc7540#section-6.8
@@ -335,7 +372,9 @@ function onHttp2SessionGoAway (errorCode) {
if (client[kRunningIdx] < client[kQueue].length) {
const request = client[kQueue][client[kRunningIdx]]
client[kQueue][client[kRunningIdx]++] = null
util.errorRequest(client, request, err)
if (request != null) {
util.errorRequest(client, request, err)
}
client[kPendingIdx] = client[kRunningIdx]
}
@@ -368,7 +407,9 @@ function onHttp2SessionClose () {
const requests = client[kQueue].splice(client[kRunningIdx])
for (let i = 0; i < requests.length; i++) {
const request = requests[i]
util.errorRequest(client, request, err)
if (request != null) {
util.errorRequest(client, request, err)
}
}
}
}
@@ -416,7 +457,10 @@ function shouldSendContentLength (method) {
}
function writeH2 (client, request) {
const requestTimeout = request.bodyTimeout ?? client[kBodyTimeout]
// Time to the response headers, then time between body chunks. Using
// bodyTimeout for both made headersTimeout a no-op over HTTP/2.
const headersTimeout = request.headersTimeout ?? client[kHeadersTimeout]
const bodyTimeout = request.bodyTimeout ?? client[kBodyTimeout]
const session = client[kHTTP2Session]
const { method, path, host, upgrade, expectContinue, signal, protocol, headers: reqHeaders } = request
let { body } = request
@@ -483,6 +527,7 @@ function writeH2 (client, request) {
// We move the running index to the next request
client[kOnError](err)
completeRequest(client, request)
client[kResume]()
}
@@ -537,7 +582,7 @@ function writeH2 (client, request) {
request.onUpgrade(statusCode, parseH2Headers(realHeaders), stream)
++session[kOpenStreams]
client[kQueue][client[kRunningIdx]++] = null
completeRequest(client, request)
})
stream.on('error', () => {
@@ -554,7 +599,7 @@ function writeH2 (client, request) {
if (session[kOpenStreams] === 0) session.unref()
})
stream.setTimeout(requestTimeout)
stream.setTimeout(headersTimeout)
return true
}
@@ -570,13 +615,14 @@ function writeH2 (client, request) {
request.onUpgrade(statusCode, parseH2Headers(realHeaders), stream)
++session[kOpenStreams]
client[kQueue][client[kRunningIdx]++] = null
completeRequest(client, request)
})
stream.on('error', abort)
stream.once('close', () => {
session[kOpenStreams] -= 1
if (session[kOpenStreams] === 0) session.unref()
})
stream.setTimeout(requestTimeout)
stream.setTimeout(headersTimeout)
return true
}
@@ -677,7 +723,7 @@ function writeH2 (client, request) {
// Increment counter as we have new streams open
++session[kOpenStreams]
stream.setTimeout(requestTimeout)
stream.setTimeout(headersTimeout)
// Track whether we received a response (headers)
let responseReceived = false
@@ -686,6 +732,7 @@ function writeH2 (client, request) {
const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers
request.onResponseStarted()
responseReceived = true
stream.setTimeout(bodyTimeout)
// Due to the stream nature, it is possible we face a race condition
// where the stream has been assigned, but the request has been aborted
@@ -720,14 +767,13 @@ function writeH2 (client, request) {
request.onComplete({})
}
client[kQueue][client[kRunningIdx]++] = null
completeRequest(client, request)
client[kResume]()
} else {
// Stream ended without receiving a response - this is an error
// (e.g., server destroyed the stream before sending headers)
abort(new InformationalError('HTTP/2: stream half-closed (remote)'))
client[kQueue][client[kRunningIdx]++] = null
client[kPendingIdx] = client[kRunningIdx]
completeRequest(client, request, true)
client[kResume]()
}
})
@@ -738,6 +784,14 @@ function writeH2 (client, request) {
if (session[kOpenStreams] === 0) {
session.unref()
}
// A stream can close without ever emitting 'end' or 'error': a peer's
// RST_STREAM(CANCEL) received before the response is reported by Node as a
// bare 'close', and destroying the stream unenrolls its timeout, so no
// 'timeout' follows either. Nothing else would ever settle this request.
if (!request.aborted && !request.completed) {
abort(new InformationalError('HTTP/2: stream closed before the response was complete'))
}
})
stream.once('error', function (err) {
@@ -755,7 +809,9 @@ function writeH2 (client, request) {
})
stream.on('timeout', () => {
const err = new InformationalError(`HTTP/2: "stream timeout after ${requestTimeout}"`)
const err = responseReceived
? new BodyTimeoutError(`HTTP/2: "body timeout after ${bodyTimeout}"`)
: new HeadersTimeoutError(`HTTP/2: "headers timeout after ${headersTimeout}"`)
stream.removeAllListeners('data')
session[kOpenStreams] -= 1
+6 -2
View File
@@ -374,7 +374,9 @@ class Client extends DispatcherBase {
const requests = this[kQueue].splice(this[kPendingIdx])
for (let i = 0; i < requests.length; i++) {
const request = requests[i]
util.errorRequest(this, request, err)
if (request != null) {
util.errorRequest(this, request, err)
}
}
const callback = () => {
@@ -413,7 +415,9 @@ function onError (client, err) {
for (let i = 0; i < requests.length; i++) {
const request = requests[i]
util.errorRequest(client, request, err)
if (request != null) {
util.errorRequest(client, request, err)
}
}
assert(client[kSize] === 0)
}
+21 -5
View File
@@ -207,6 +207,13 @@ class CacheHandler {
}
const cacheControlHeader = resHeaders['cache-control']
const cacheControlDirectives = cacheControlHeader ? parseCacheControlHeader(cacheControlHeader) : {}
if (revalidationResponseDisallowsCachedReuse(this.#cacheType, resHeaders, cacheControlDirectives)) {
deleteCachedValue(this.#store, this.#cacheKey)
return downstreamOnHeaders()
}
const heuristicallyCacheable = resHeaders['last-modified'] && arrayIncludes(HEURISTICALLY_CACHEABLE_STATUS_CODES, statusCode)
if (
!cacheControlHeader &&
@@ -223,8 +230,7 @@ class CacheHandler {
return downstreamOnHeaders()
}
const cacheControlDirectives = cacheControlHeader ? parseCacheControlHeader(cacheControlHeader) : {}
if (!canCacheResponse(this.#cacheType, statusCode, resHeaders, cacheControlDirectives, this.#cacheKey.headers)) {
if (!canCacheResponse(this.#cacheType, this.#cacheKey.method, statusCode, resHeaders, cacheControlDirectives, this.#cacheKey.headers)) {
if (statusCode === 304 && (cacheControlHeader || revalidationResponseDisallowsCachedReuse(this.#cacheType, resHeaders, cacheControlDirectives))) {
deleteCachedValue(this.#store, this.#cacheKey)
}
@@ -465,7 +471,10 @@ function deleteCachedValueIfNotModified (statusCode, store, cacheKey) {
*/
function revalidationResponseDisallowsCachedReuse (cacheType, resHeaders, cacheControlDirectives) {
return cacheControlDirectives['no-store'] === true ||
(cacheType === 'shared' && cacheControlDirectives.private === true) ||
(cacheType === 'shared' && (
cacheControlDirectives.private === true ||
Object.hasOwn(resHeaders, 'set-cookie')
)) ||
(resHeaders.vary ? isInvalidOrWildcardVaryHeader(resHeaders.vary) : false)
}
@@ -473,12 +482,16 @@ function revalidationResponseDisallowsCachedReuse (cacheType, resHeaders, cacheC
* @see https://www.rfc-editor.org/rfc/rfc9111.html#name-storing-responses-to-authen
*
* @param {import('../../types/cache-interceptor.d.ts').default.CacheOptions['type']} cacheType
* @param {string} method
* @param {number} statusCode
* @param {import('../../types/header.d.ts').IncomingHttpHeaders} resHeaders
* @param {import('../../types/cache-interceptor.d.ts').default.CacheControlDirectives} cacheControlDirectives
* @param {import('../../types/header.d.ts').IncomingHttpHeaders} [reqHeaders]
*/
function canCacheResponse (cacheType, statusCode, resHeaders, cacheControlDirectives, reqHeaders) {
function canCacheResponse (cacheType, method, statusCode, resHeaders, cacheControlDirectives, reqHeaders) {
if (!arrayIncludes(util.safeHTTPMethods, method)) {
return false
}
// Status code must be final and understood.
if (statusCode < 200 || arrayIncludes(NOT_UNDERSTOOD_STATUS_CODES, statusCode)) {
return false
@@ -499,7 +512,10 @@ function canCacheResponse (cacheType, statusCode, resHeaders, cacheControlDirect
return false
}
if (cacheType === 'shared' && cacheControlDirectives.private === true) {
if (cacheType === 'shared' && (
cacheControlDirectives.private === true ||
Object.hasOwn(resHeaders, 'set-cookie')
)) {
return false
}
+42 -7
View File
@@ -95,8 +95,16 @@ class RetryHandler {
if (this.retryOpts.throwOnError) {
// Preserve old behavior for status codes that are not eligible for retry
if (this.retryOpts.statusCodes.includes(statusCode) === false) {
this.headersSent = true
this.handler.onResponseStart?.(controller, statusCode, headers, statusMessage)
if (this.headersSent) {
// The downstream handler already received the response from an
// earlier attempt. Forwarding this response would replace the
// downstream body and leave the original body pending forever.
this.handler.onResponseError?.(controller, err)
} else {
this.headersSent = true
this.checkpointResponseEnd(headers)
this.handler.onResponseStart?.(controller, statusCode, headers, statusMessage)
}
} else {
this.error = err
}
@@ -106,14 +114,23 @@ class RetryHandler {
if (isDisturbed(this.opts.body)) {
this.headersSent = true
this.checkpointResponseEnd(headers)
this.handler.onResponseStart?.(controller, statusCode, headers, statusMessage)
return
}
function shouldRetry (passedErr) {
if (passedErr) {
this.headersSent = true
this.handler.onResponseStart?.(controller, statusCode, headers, statusMessage)
if (this.headersSent) {
// The downstream handler already received the response from an
// earlier attempt. Forwarding this response would replace the
// downstream body and leave the original body pending forever.
this.handler.onResponseError?.(controller, passedErr)
} else {
this.headersSent = true
this.checkpointResponseEnd(headers)
this.handler.onResponseStart?.(controller, statusCode, headers, statusMessage)
}
controller.resume()
return
}
@@ -133,6 +150,20 @@ class RetryHandler {
)
}
checkpointResponseEnd (headers) {
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
}
}
onRequestStart (controller, context) {
if (!this.headersSent) {
this.handler.onRequestStart?.(controller, context)
@@ -253,8 +284,12 @@ class RetryHandler {
const { start, size, end = size ? size - 1 : null } = 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)) {
throw new RequestRetryError('Content-Range mismatch', statusCode, {
headers,
data: { count: this.retryCount }
})
}
return
}
@@ -379,7 +414,7 @@ class RetryHandler {
}
onResponseError (controller, err) {
if (controller?.aborted || isDisturbed(this.opts.body)) {
if (controller?.aborted || isDisturbed(this.opts.body) || (this.headersSent && !this.resume)) {
this.handler.onResponseError?.(controller, err)
return
}
+20 -1
View File
@@ -117,7 +117,10 @@ function staleResponseRequiresRevalidation (result, cacheType) {
* @returns {boolean}
*/
function revalidationResponseDisallowsCachedReuse (cacheType, headers) {
if (headers.vary && isInvalidOrWildcardVaryHeader(headers.vary)) {
if (
(headers.vary && isInvalidOrWildcardVaryHeader(headers.vary)) ||
(cacheType === 'shared' && Object.hasOwn(headers, 'set-cookie'))
) {
return true
}
@@ -376,6 +379,17 @@ function handleResult (
return handleUncachedResponse(dispatch, globalOpts, cacheKey, handler, opts, reqCacheControl)
}
// Shared stores may outlive the Undici version that wrote them. Do not
// re-serve a Set-Cookie header from an existing shared-cache entry.
if (globalOpts.type === 'shared' && Object.hasOwn(result.headers, 'set-cookie')) {
if (util.isStream(result.body)) {
result.body.on('error', nop).destroy()
}
deleteCachedValue(globalOpts.store, cacheKey)
return handleUncachedResponse(dispatch, globalOpts, cacheKey, handler, opts, reqCacheControl)
}
const now = Date.now()
if (now > result.deleteAt) {
// Response is expired, cache store shouldn't have given this to us
@@ -574,6 +588,11 @@ module.exports = (opts = {}) => {
* @type {import('../../types/cache-interceptor.d.ts').default.CacheKey}
*/
const cacheKey = makeCacheKey(opts)
if (!arrayIncludes(util.safeHTTPMethods, opts.method)) {
return dispatch(opts, new CacheHandler(globalOpts, cacheKey, handler))
}
const result = store.get(cacheKey)
if (result && typeof result.then === 'function') {
+147 -15
View File
@@ -1,7 +1,8 @@
'use strict'
const { createInflate, createGunzip, createBrotliDecompress, createZstdDecompress } = require('node:zlib')
const { pipeline } = require('node:stream')
const { pipeline, Transform: TransformStream } = require('node:stream')
const { InvalidArgumentError, ResponseExceededMaxSizeError } = require('../core/errors')
const DecoratorHandler = require('../handler/decorator-handler')
const { runtimeFeatures } = require('../util/runtime-features')
@@ -21,6 +22,31 @@ const supportedEncodings = {
}
const defaultSkipStatusCodes = /** @type {const} */ ([204, 304])
const defaultMaxSize = 64 * 1024 * 1024
/**
* Limits the output of one stage in a decompression chain.
* @param {number} maxSize - Maximum output size in bytes
* @returns {Transform}
*/
function createMaxSizeLimiter (maxSize) {
let size = 0
return new TransformStream({
transform (chunk, _encoding, callback) {
const decompressedSize = size + chunk.length
if (decompressedSize > maxSize) {
callback(new ResponseExceededMaxSizeError(
`Decompressed response size (${decompressedSize}) exceeded maxSize (${maxSize})`
))
return
}
size = decompressedSize
callback(null, chunk)
}
})
}
let warningEmitted = /** @type {boolean} */ (false)
@@ -28,20 +54,36 @@ let warningEmitted = /** @type {boolean} */ (false)
* @typedef {Object} DecompressHandlerOptions
* @property {number[]|Readonly<number[]>} [skipStatusCodes=[204, 304]] - List of status codes to skip decompression for
* @property {boolean} [skipErrorResponses] - Whether to skip decompression for error responses (status codes >= 400)
* @property {number} [maxSize=67108864] - Maximum decompressed response size in bytes
*/
class DecompressHandler extends DecoratorHandler {
/** @type {Transform[]} */
#decompressors = []
/** @type {Record<string, string | string[]> | undefined} */
#trailers
/** @type {Readonly<number[]>} */
#skipStatusCodes
/** @type {boolean} */
#skipErrorResponses
/** @type {number} */
#maxSize
/** @type {number} */
#decompressedSize = 0
/** @type {boolean} */
#terminated = false
/** @type {boolean} */
#inputEnded = false
constructor (handler, { skipStatusCodes = defaultSkipStatusCodes, skipErrorResponses = true, maxSize = defaultMaxSize } = {}) {
if (!Number.isSafeInteger(maxSize) || maxSize < 1) {
throw new InvalidArgumentError('maxSize must be a positive integer')
}
constructor (handler, { skipStatusCodes = defaultSkipStatusCodes, skipErrorResponses = true } = {}) {
super(handler)
this.#skipStatusCodes = skipStatusCodes
this.#skipErrorResponses = skipErrorResponses
this.#maxSize = maxSize
}
/**
@@ -61,7 +103,7 @@ class DecompressHandler extends DecoratorHandler {
* Creates a chain of decompressors for multiple content encodings
*
* @param {string} encodings - Comma-separated list of content encodings
* @returns {Array<DecompressorStream>} - Array of decompressor streams
* @returns {Array<Transform>} - Array of decompressor and limiting streams
* @throws {Error} - If the number of content-encodings exceeds the maximum allowed
*/
#createDecompressionChain (encodings) {
@@ -89,7 +131,40 @@ class DecompressHandler extends DecoratorHandler {
decompressors.push(supportedEncodings[encoding]())
}
return decompressors
if (decompressors.length < 2) {
return decompressors
}
/** @type {Transform[]} */
const streams = []
for (let i = 0; i < decompressors.length; i++) {
streams.push(decompressors[i])
if (i < decompressors.length - 1) {
streams.push(createMaxSizeLimiter(this.#maxSize))
}
}
return streams
}
/**
* Stops decompression and reports an error.
* @param {Controller} controller - The controller to coordinate with
* @param {Error} error - The decompression error
* @returns {void}
*/
#fail (controller, error) {
if (this.#terminated) {
return
}
if (this.#inputEnded) {
// The request is already marked complete once the compressed input ends,
// so controller.abort() can no longer propagate decoder flush errors.
this.onResponseError(controller, error)
} else {
controller.abort(error)
}
}
/**
@@ -100,8 +175,21 @@ class DecompressHandler extends DecoratorHandler {
*/
#setupDecompressorEvents (decompressor, controller) {
decompressor.on('readable', () => {
if (this.#terminated) {
return
}
let chunk
while ((chunk = decompressor.read()) !== null) {
const decompressedSize = this.#decompressedSize + chunk.length
if (decompressedSize > this.#maxSize) {
this.#fail(controller, new ResponseExceededMaxSizeError(
`Decompressed response size (${decompressedSize}) exceeded maxSize (${this.#maxSize})`
))
return
}
this.#decompressedSize = decompressedSize
const result = super.onResponseData(controller, chunk)
if (result === false) {
break
@@ -110,7 +198,7 @@ class DecompressHandler extends DecoratorHandler {
})
decompressor.on('error', (error) => {
super.onResponseError(controller, error)
this.#fail(controller, error)
})
}
@@ -124,7 +212,13 @@ class DecompressHandler extends DecoratorHandler {
this.#setupDecompressorEvents(decompressor, controller)
decompressor.on('end', () => {
super.onResponseEnd(controller, {})
if (this.#terminated) {
return
}
this.#terminated = true
this.#cleanupDecompressors()
super.onResponseEnd(controller, this.#trailers)
})
}
@@ -138,11 +232,18 @@ class DecompressHandler extends DecoratorHandler {
this.#setupDecompressorEvents(lastDecompressor, controller)
pipeline(this.#decompressors, (err) => {
if (err) {
super.onResponseError(controller, err)
if (this.#terminated) {
return
}
super.onResponseEnd(controller, {})
if (err) {
this.#fail(controller, err)
return
}
this.#terminated = true
this.#cleanupDecompressors()
super.onResponseEnd(controller, this.#trailers)
})
}
@@ -181,6 +282,33 @@ class DecompressHandler extends DecoratorHandler {
// Remove compression headers since we're decompressing
const { 'content-encoding': _, 'content-length': __, ...newHeaders } = headers
if (controller?.rawHeaders) {
const rawHeaders = controller.rawHeaders
if (Array.isArray(rawHeaders)) {
const filteredHeaders = []
for (let i = 0; i < rawHeaders.length; i += 2) {
const headerName = rawHeaders[i]
const name = Buffer.isBuffer(headerName) ? headerName.toString('latin1') : `${headerName}`
const lowerName = name.toLowerCase()
if (lowerName === 'content-encoding' || lowerName === 'content-length') {
continue
}
filteredHeaders.push(rawHeaders[i], rawHeaders[i + 1])
}
rawHeaders.splice(0, rawHeaders.length, ...filteredHeaders)
} else if (typeof rawHeaders === 'object') {
for (const name of Object.keys(rawHeaders)) {
const lowerName = name.toLowerCase()
if (lowerName === 'content-encoding' || lowerName === 'content-length') {
delete rawHeaders[name]
}
}
}
}
if (this.#decompressors.length === 1) {
this.#setupSingleDecompressor(controller)
} else {
@@ -210,8 +338,9 @@ class DecompressHandler extends DecoratorHandler {
*/
onResponseEnd (controller, trailers) {
if (this.#decompressors.length > 0) {
this.#inputEnded = true
this.#trailers = trailers
this.#decompressors[0].end()
this.#cleanupDecompressors()
return
}
super.onResponseEnd(controller, trailers)
@@ -223,12 +352,15 @@ class DecompressHandler extends DecoratorHandler {
* @returns {void}
*/
onResponseError (controller, err) {
if (this.#decompressors.length > 0) {
for (const decompressor of this.#decompressors) {
decompressor.destroy(err)
}
this.#cleanupDecompressors()
if (this.#terminated) {
return
}
this.#terminated = true
for (const decompressor of this.#decompressors) {
decompressor.destroy()
}
this.#cleanupDecompressors()
super.onResponseError(controller, err)
}
}
+10 -23
View File
@@ -7,7 +7,6 @@ class DumpHandler extends DecoratorHandler {
#maxSize = 1024 * 1024
#dumped = false
#size = 0
#controller = null
aborted = false
reason = false
@@ -29,7 +28,6 @@ class DumpHandler extends DecoratorHandler {
onRequestStart (controller, context) {
controller.abort = this.#abort.bind(this)
this.#controller = controller
return super.onRequestStart(controller, context)
}
@@ -53,43 +51,32 @@ class DumpHandler extends DecoratorHandler {
}
onResponseError (controller, err) {
if (this.#dumped) {
return
}
// On network errors before connect, controller will be null
err = this.#controller?.reason ?? err
super.onResponseError(controller, err)
super.onResponseError(controller, this.aborted === true ? this.reason : err)
}
onResponseData (controller, chunk) {
this.#size = this.#size + chunk.length
if (this.#size >= this.#maxSize) {
this.#dumped = true
if (this.#size > this.#maxSize) {
throw new RequestAbortedError(
`Response size (${this.#size}) larger than maxSize (${this.#maxSize})`
)
}
if (this.aborted === true) {
super.onResponseError(controller, this.reason)
} else {
super.onResponseEnd(controller, {})
}
if (this.#size === this.#maxSize) {
this.#dumped = true
}
return true
}
onResponseEnd (controller, trailers) {
if (this.#dumped) {
return
}
if (this.#controller.aborted === true) {
if (this.aborted === true) {
super.onResponseError(controller, this.reason)
return
}
super.onResponseEnd(controller, trailers)
super.onResponseEnd(controller, this.#dumped ? {} : trailers)
}
}
+1 -1
View File
@@ -1,5 +1,5 @@
> undici@7.29.0 build:wasm
> undici@7.29.1 build:wasm
> node build/wasm.js --docker
> docker run --rm --platform=linux/x86_64 --user 1001:1001 --mount type=bind,source=/home/runner/work/node/node/deps/undici/src/lib/llhttp,target=/home/node/build/lib/llhttp --mount type=bind,source=/home/runner/work/node/node/deps/undici/src/build,target=/home/node/build/build --mount type=bind,source=/home/runner/work/node/node/deps/undici/src/deps,target=/home/node/build/deps -t ghcr.io/nodejs/wasm-builder@sha256:975f391d907e42a75b8c72eb77c782181e941608687d4d8694c3e9df415a0970 node build/wasm.js
+245 -150
View File
@@ -23,6 +23,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}
@@ -63,11 +106,14 @@ class EventSourceStream extends Transform {
eventEndCheck = false
/**
* @type {Buffer|null}
* @type {Buffer[]}
*/
buffer = null
chunks = []
chunkIndex = 0
pos = 0
lineChunkIndex = 0
linePos = 0
event = {
data: undefined,
@@ -107,92 +153,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) {
@@ -205,10 +179,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
@@ -224,19 +197,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 !== undefined || this.event.retry) {
this.consumeCurrentByte()
if (this.hasPendingEvent()) {
this.processEvent(this.event)
}
this.clearEvent()
@@ -250,22 +221,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.
@@ -273,7 +240,7 @@ class EventSourceStream extends Transform {
continue
}
this.pos++
this.advanceCursor()
}
callback()
@@ -298,64 +265,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
}
}
}
@@ -385,13 +341,152 @@ 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()
}
}
module.exports = {
+1 -1
View File
@@ -200,7 +200,7 @@ function establishWebSocketConnection (url, protocols, client, handler, options)
// 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(handler, 1002, 'Protocol was not set in the opening handshake.')
return
}
@@ -63,7 +63,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
}
+8 -10
View File
@@ -34,9 +34,9 @@ class WebSocketStream {
/** @type {ReadableStreamDefaultController} */
#readableStreamController
// Each WebSocketStream object has an associated writable stream , which is a WritableStream .
/** @type {WritableStream} */
#writableStream
// Retain the controller so the writable stream can be errored while locked.
/** @type {WritableStreamDefaultController} */
#writableStreamController
// Each WebSocketStream object has an associated boolean handshake aborted , which is initially false.
#handshakeAborted = false
@@ -300,6 +300,9 @@ class WebSocketStream {
// 12. Let writable be a new WritableStream .
// 13. Set up writable with writeAlgorithm , closeAlgorithm , and abortAlgorithm .
const writable = new WritableStream({
start: (controller) => {
this.#writableStreamController = controller
},
write: (chunk) => this.#write(chunk),
close: () => closeWebSocketConnection(this.#handler, null, null),
abort: (reason) => this.#closeUsingReason(reason)
@@ -308,9 +311,6 @@ class WebSocketStream {
// Set stream ’s readable stream to readable .
this.#readableStream = readable
// Set stream ’s writable stream to writable .
this.#writableStream = writable
// Resolve stream ’s opened promise with WebSocketOpenInfo «[ " extensions " → extensions , " protocol " → protocol , " readable " → readable , " writable " → writable ]».
this.#openedPromise.resolve({
extensions,
@@ -396,9 +396,7 @@ class WebSocketStream {
this.#readableStreamController.close()
// 6.2. Error stream ’s writable stream with an " InvalidStateError " DOMException indicating that a closed WebSocketStream cannot be written to.
if (!this.#writableStream.locked) {
this.#writableStream.abort(new DOMException('A closed WebSocketStream cannot be written to', 'InvalidStateError'))
}
this.#writableStreamController.error(new DOMException('A closed WebSocketStream cannot be written to', 'InvalidStateError'))
// 6.3. Resolve stream ’s closed promise with WebSocketCloseInfo «[ " closeCode " → code , " reason " → reason ]».
this.#closedPromise.resolve({
@@ -415,7 +413,7 @@ class WebSocketStream {
this.#readableStreamController?.error(error)
// 7.3. Error stream ’s writable stream with error .
this.#writableStream?.abort(error)
this.#writableStreamController?.error(error)
// 7.4. Reject stream ’s closed promise with error .
this.#closedPromise.reject(error)
+1155 -748
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "undici",
"version": "7.29.0",
"version": "7.29.1",
"description": "An HTTP/1.1 client, written from scratch for Node.js",
"homepage": "https://undici.nodejs.org",
"bugs": {
+2
View File
@@ -12,6 +12,8 @@ declare namespace Interceptors {
export type DecompressInterceptorOpts = {
skipErrorResponses?: boolean
skipStatusCodes?: number[]
/** Maximum decompressed response size in bytes. @default 67108864 */
maxSize?: number
}
export type ResponseErrorInterceptorOpts = { throwOnError: boolean }
+260 -111
View File
@@ -7871,7 +7871,7 @@ var require_client_h1 = __commonJS({
__name(onSocketClose, "onSocketClose");
function clearIdleSocketValidation(socket) {
if (socket[kIdleSocketValidationTimeout]) {
clearTimeout(socket[kIdleSocketValidationTimeout]);
clearImmediate(socket[kIdleSocketValidationTimeout]);
socket[kIdleSocketValidationTimeout] = null;
}
socket[kIdleSocketValidation] = 0;
@@ -7879,14 +7879,13 @@ var require_client_h1 = __commonJS({
__name(clearIdleSocketValidation, "clearIdleSocketValidation");
function scheduleIdleSocketValidation(client, socket) {
socket[kIdleSocketValidation] = 1;
socket[kIdleSocketValidationTimeout] = setTimeout(() => {
socket[kIdleSocketValidationTimeout] = setImmediate(() => {
socket[kIdleSocketValidationTimeout] = null;
socket[kIdleSocketValidation] = 2;
if (client[kSocket] === socket && !socket.destroyed) {
client[kResume]();
}
}, 0);
socket[kIdleSocketValidationTimeout].unref?.();
});
}
__name(scheduleIdleSocketValidation, "scheduleIdleSocketValidation");
function resumeH1(client) {
@@ -8388,7 +8387,9 @@ var require_client_h2 = __commonJS({
RequestAbortedError,
SocketError,
InformationalError,
InvalidArgumentError
InvalidArgumentError,
HeadersTimeoutError,
BodyTimeoutError
} = require_errors();
var {
kUrl,
@@ -8413,6 +8414,7 @@ var require_client_h2 = __commonJS({
kHTTPContext,
kClosed,
kBodyTimeout,
kHeadersTimeout,
kEnableConnectProtocol,
kRemoteSettings,
kHTTP2Stream,
@@ -8551,7 +8553,7 @@ var require_client_h2 = __commonJS({
function resumeH2(client) {
const socket = client[kSocket];
if (socket?.destroyed === false) {
if (client[kSize] === 0 || client[kMaxConcurrentStreams] === 0) {
if (client[kSize] === 0) {
socket.unref();
client[kHTTP2Session].unref();
} else {
@@ -8625,6 +8627,25 @@ var require_client_h2 = __commonJS({
util.destroy(this[kSocket], err);
}
__name(onHttp2SessionEnd, "onHttp2SessionEnd");
function completeRequest(client, request, resetPendingIdx = false) {
const queue = client[kQueue];
const runningIdx = client[kRunningIdx];
if (runningIdx < client[kPendingIdx] && queue[runningIdx] === request) {
queue[runningIdx] = null;
client[kRunningIdx] = runningIdx + 1;
return;
}
const index = queue.indexOf(request, runningIdx);
if (index === -1 || index >= client[kPendingIdx]) {
return;
}
queue.splice(index, 1);
client[kPendingIdx]--;
if (resetPendingIdx && client[kPendingIdx] < client[kRunningIdx]) {
client[kPendingIdx] = client[kRunningIdx];
}
}
__name(completeRequest, "completeRequest");
function onHttp2SessionGoAway(errorCode) {
const err = this[kError] || new SocketError(`HTTP/2: "GOAWAY" frame received with code ${errorCode}`, util.getSocketInfo(this[kSocket]));
const client = this[kClient];
@@ -8636,7 +8657,9 @@ var require_client_h2 = __commonJS({
if (client[kRunningIdx] < client[kQueue].length) {
const request = client[kQueue][client[kRunningIdx]];
client[kQueue][client[kRunningIdx]++] = null;
util.errorRequest(client, request, err);
if (request != null) {
util.errorRequest(client, request, err);
}
client[kPendingIdx] = client[kRunningIdx];
}
assert(client[kRunning] === 0);
@@ -8660,7 +8683,9 @@ var require_client_h2 = __commonJS({
const requests = client[kQueue].splice(client[kRunningIdx]);
for (let i = 0; i < requests.length; i++) {
const request = requests[i];
util.errorRequest(client, request, err);
if (request != null) {
util.errorRequest(client, request, err);
}
}
}
}
@@ -8698,7 +8723,8 @@ var require_client_h2 = __commonJS({
}
__name(shouldSendContentLength, "shouldSendContentLength");
function writeH2(client, request) {
const requestTimeout = request.bodyTimeout ?? client[kBodyTimeout];
const headersTimeout = request.headersTimeout ?? client[kHeadersTimeout];
const bodyTimeout = request.bodyTimeout ?? client[kBodyTimeout];
const session = client[kHTTP2Session];
const { method, path, host, upgrade, expectContinue, signal, protocol, headers: reqHeaders } = request;
let { body } = request;
@@ -8746,6 +8772,7 @@ var require_client_h2 = __commonJS({
stream.removeAllListeners("data");
stream.close();
client[kOnError](err);
completeRequest(client, request);
client[kResume]();
}
util.destroy(body, err);
@@ -8780,7 +8807,7 @@ var require_client_h2 = __commonJS({
const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers2;
request.onUpgrade(statusCode, parseH2Headers(realHeaders), stream);
++session[kOpenStreams];
client[kQueue][client[kRunningIdx]++] = null;
completeRequest(client, request);
});
stream.on("error", () => {
if (stream.rstCode === NGHTTP2_REFUSED_STREAM || stream.rstCode === NGHTTP2_CANCEL) {
@@ -8791,7 +8818,7 @@ var require_client_h2 = __commonJS({
session[kOpenStreams] -= 1;
if (session[kOpenStreams] === 0) session.unref();
});
stream.setTimeout(requestTimeout);
stream.setTimeout(headersTimeout);
return true;
}
stream = session.request(headers, { endStream: false, signal });
@@ -8800,13 +8827,14 @@ var require_client_h2 = __commonJS({
const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers2;
request.onUpgrade(statusCode, parseH2Headers(realHeaders), stream);
++session[kOpenStreams];
client[kQueue][client[kRunningIdx]++] = null;
completeRequest(client, request);
});
stream.on("error", abort);
stream.once("close", () => {
session[kOpenStreams] -= 1;
if (session[kOpenStreams] === 0) session.unref();
});
stream.setTimeout(requestTimeout);
stream.setTimeout(headersTimeout);
return true;
}
headers[HTTP2_HEADER_PATH] = path;
@@ -8864,12 +8892,13 @@ var require_client_h2 = __commonJS({
writeBodyH2();
}
++session[kOpenStreams];
stream.setTimeout(requestTimeout);
stream.setTimeout(headersTimeout);
let responseReceived = false;
stream.once("response", (headers2) => {
const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers2;
request.onResponseStarted();
responseReceived = true;
stream.setTimeout(bodyTimeout);
if (request.aborted) {
stream.removeAllListeners("data");
return;
@@ -8892,12 +8921,11 @@ var require_client_h2 = __commonJS({
if (!request.aborted && !request.completed) {
request.onComplete({});
}
client[kQueue][client[kRunningIdx]++] = null;
completeRequest(client, request);
client[kResume]();
} else {
abort(new InformationalError("HTTP/2: stream half-closed (remote)"));
client[kQueue][client[kRunningIdx]++] = null;
client[kPendingIdx] = client[kRunningIdx];
completeRequest(client, request, true);
client[kResume]();
}
});
@@ -8907,6 +8935,9 @@ var require_client_h2 = __commonJS({
if (session[kOpenStreams] === 0) {
session.unref();
}
if (!request.aborted && !request.completed) {
abort(new InformationalError("HTTP/2: stream closed before the response was complete"));
}
});
stream.once("error", function(err) {
stream.removeAllListeners("data");
@@ -8920,7 +8951,7 @@ var require_client_h2 = __commonJS({
stream.removeAllListeners("data");
});
stream.on("timeout", () => {
const err = new InformationalError(`HTTP/2: "stream timeout after ${requestTimeout}"`);
const err = responseReceived ? new BodyTimeoutError(`HTTP/2: "body timeout after ${bodyTimeout}"`) : new HeadersTimeoutError(`HTTP/2: "headers timeout after ${headersTimeout}"`);
stream.removeAllListeners("data");
session[kOpenStreams] -= 1;
if (session[kOpenStreams] === 0) {
@@ -9430,7 +9461,9 @@ var require_client = __commonJS({
const requests = this[kQueue].splice(this[kPendingIdx]);
for (let i = 0; i < requests.length; i++) {
const request = requests[i];
util.errorRequest(this, request, err);
if (request != null) {
util.errorRequest(this, request, err);
}
}
const callback = /* @__PURE__ */ __name(() => {
if (this[kClosedResolve]) {
@@ -9455,7 +9488,9 @@ var require_client = __commonJS({
const requests = client[kQueue].splice(client[kRunningIdx]);
for (let i = 0; i < requests.length; i++) {
const request = requests[i];
util.errorRequest(client, request, err);
if (request != null) {
util.errorRequest(client, request, err);
}
}
assert(client[kSize] === 0);
}
@@ -14767,7 +14802,7 @@ var require_connection = __commonJS({
const secProtocol = response.headersList.get("Sec-WebSocket-Protocol");
if (secProtocol !== null) {
const requestProtocols = getDecodeSplit("sec-websocket-protocol", request.headersList);
if (!requestProtocols.includes(secProtocol)) {
if (requestProtocols === null || !requestProtocols.includes(secProtocol)) {
failWebsocketConnection(handler, 1002, "Protocol was not set in the opening handshake.");
return;
}
@@ -14891,6 +14926,7 @@ var require_permessage_deflate = __commonJS({
if (this.#maxPayloadSize > 0 && this.#inflate[kLength] > this.#maxPayloadSize) {
callback(new MessageSizeExceededError());
this.#inflate.removeAllListeners();
this.#inflate.destroy();
this.#inflate = null;
return;
}
@@ -15902,6 +15938,43 @@ var require_eventsource_stream = __commonJS({
var CR = 13;
var COLON = 58;
var SPACE = 32;
var DATA = Buffer.from("data");
var EVENT = Buffer.from("event");
var ID = Buffer.from("id");
var 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] < 48 || buffer[i] > 57) {
return false;
}
}
return true;
}
__name(isASCIINumberBytes, "isASCIINumberBytes");
function isValidLastEventIdBytes(buffer, start) {
for (let i = start; i < buffer.length; i++) {
if (buffer[i] === 0) {
return false;
}
}
return true;
}
__name(isValidLastEventIdBytes, "isValidLastEventIdBytes");
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;
}
__name(isFieldName, "isFieldName");
var EventSourceStream = class extends Transform {
static {
__name(this, "EventSourceStream");
@@ -15924,10 +15997,13 @@ var require_eventsource_stream = __commonJS({
*/
eventEndCheck = false;
/**
* @type {Buffer|null}
* @type {Buffer[]}
*/
buffer = null;
chunks = [];
chunkIndex = 0;
pos = 0;
lineChunkIndex = 0;
linePos = 0;
event = {
data: void 0,
event: void 0,
@@ -15959,63 +16035,30 @@ var require_eventsource_stream = __commonJS({
callback();
return;
}
if (this.buffer) {
this.buffer = Buffer.concat([this.buffer, chunk]);
} else {
this.buffer = chunk;
}
this.chunks.push(chunk);
if (this.checkBOM) {
switch (this.buffer.length) {
case 1:
if (this.buffer[0] === BOM[0]) {
callback();
return;
}
this.checkBOM = false;
callback();
return;
case 2:
if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1]) {
callback();
return;
}
this.checkBOM = false;
break;
case 3:
if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) {
this.buffer = Buffer.alloc(0);
this.checkBOM = false;
callback();
return;
}
this.checkBOM = false;
break;
default:
if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) {
this.buffer = this.buffer.subarray(3);
}
this.checkBOM = false;
break;
if (this.handleBOM()) {
callback();
return;
}
}
while (this.pos < this.buffer.length) {
while (this.hasCurrentByte()) {
const byte = this.currentByte();
if (this.eventEndCheck) {
if (this.crlfCheck) {
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();
continue;
}
this.crlfCheck = false;
}
if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) {
if (this.buffer[this.pos] === CR) {
if (byte === LF || byte === CR) {
if (byte === CR) {
this.crlfCheck = true;
}
this.buffer = this.buffer.subarray(this.pos + 1);
this.pos = 0;
if (this.event.data !== void 0 || this.event.event || this.event.id !== void 0 || this.event.retry) {
this.consumeCurrentByte();
if (this.hasPendingEvent()) {
this.processEvent(this.event);
}
this.clearEvent();
@@ -16024,17 +16067,16 @@ var require_eventsource_stream = __commonJS({
this.eventEndCheck = false;
continue;
}
if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) {
if (this.buffer[this.pos] === CR) {
if (byte === LF || byte === CR) {
if (byte === CR) {
this.crlfCheck = true;
}
this.parseLine(this.buffer.subarray(0, this.pos), this.event);
this.buffer = this.buffer.subarray(this.pos + 1);
this.pos = 0;
this.parseLine(this.readLine(), this.event);
this.consumeCurrentByte();
this.eventEndCheck = true;
continue;
}
this.pos++;
this.advanceCursor();
}
callback();
}
@@ -16050,43 +16092,42 @@ var require_eventsource_stream = __commonJS({
if (colonPosition === 0) {
return;
}
let field = "";
let value = "";
let fieldLength = line.length;
let valueStart = line.length;
if (colonPosition !== -1) {
field = line.subarray(0, colonPosition).toString("utf8");
let valueStart = colonPosition + 1;
fieldLength = colonPosition;
valueStart = colonPosition + 1;
if (line[valueStart] === SPACE) {
++valueStart;
}
value = line.subarray(valueStart).toString("utf8");
} else {
field = line.toString("utf8");
value = "";
}
switch (field) {
case "data":
if (event[field] === void 0) {
event[field] = value;
} else {
event[field] += `
if (isFieldName(line, fieldLength, DATA)) {
const value = line.toString("utf8", valueStart);
if (event.data === void 0) {
event.data = value;
} else {
event.data += `
${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;
}
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;
}
}
}
/**
@@ -16111,12 +16152,120 @@ ${value}`;
}
}
clearEvent() {
this.event = {
data: void 0,
event: void 0,
id: void 0,
retry: void 0
};
this.event.data = void 0;
this.event.event = void 0;
this.event.id = void 0;
this.event.retry = void 0;
}
hasPendingEvent() {
return this.event.data !== void 0 || this.event.event !== void 0 || this.event.id !== void 0 || this.event.retry !== void 0;
}
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 === void 0) {
if (first === BOM[0]) {
return true;
}
this.checkBOM = false;
return true;
}
if (third === void 0) {
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();
}
};
module2.exports = {
+1 -1
View File
@@ -2,5 +2,5 @@
// Refer to tools/dep_updaters/update-undici.sh
#ifndef SRC_UNDICI_VERSION_H_
#define SRC_UNDICI_VERSION_H_
#define UNDICI_VERSION "7.29.0"
#define UNDICI_VERSION "7.29.1"
#endif // SRC_UNDICI_VERSION_H_