diff --git a/.github/actions/javascript/authorChecklist/index.js b/.github/actions/javascript/authorChecklist/index.js index b06a43adc37e..f76542955ddf 100644 --- a/.github/actions/javascript/authorChecklist/index.js +++ b/.github/actions/javascript/authorChecklist/index.js @@ -1863,66 +1863,10 @@ var require_request = __commonJS({ return false; } } - /** - * @param {number|null} statusCode - * @param {Buffer[]|null} headers - * @param {import('node:stream').Duplex} socket - * @param {string} [statusText] - */ - onUpgrade(statusCode, headers, socket, statusText = "") { - this.onFinally(); + onUpgrade(statusCode, headers, socket) { assert(!this.aborted); assert(!this.completed); - 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(error2) { - assert(!this.aborted); - assert(this.completed); - if (channels.error.hasSubscribers) { - channels.error.publish({ request: this, error: error2 }); - } - } - /** - * @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: [] }); - } + return this[kHandler].onUpgrade(statusCode, headers, socket); } onComplete(trailers) { this.onFinally(); @@ -1989,11 +1933,7 @@ var require_request = __commonJS({ } else if (typeof val[i] === "object") { throw new InvalidArgumentError(`invalid ${key} header`); } else { - const str = `${val[i]}`; - if (!isValidHeaderValue(str)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } - arr.push(str); + arr.push(`${val[i]}`); } } val = arr; @@ -2005,9 +1945,6 @@ var require_request = __commonJS({ val = ""; } else { val = `${val}`; - if (!isValidHeaderValue(val)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } } if (headerName === "host") { if (request2.host !== null) { @@ -2117,21 +2054,13 @@ var require_dispatcher_base = __commonJS({ var kOnDestroyed = /* @__PURE__ */ Symbol("onDestroyed"); var kOnClosed = /* @__PURE__ */ Symbol("onClosed"); var kInterceptedDispatch = /* @__PURE__ */ Symbol("Intercepted Dispatch"); - var kWebSocketOptions = /* @__PURE__ */ Symbol("webSocketOptions"); var DispatcherBase = class extends Dispatcher { - constructor(opts) { + constructor() { super(); this[kDestroyed] = false; this[kOnDestroyed] = null; this[kClosed] = false; this[kOnClosed] = []; - this[kWebSocketOptions] = opts?.webSocket ?? {}; - } - get webSocketOptions() { - return { - maxFragments: this[kWebSocketOptions].maxFragments ?? 131072, - maxPayloadSize: this[kWebSocketOptions].maxPayloadSize ?? 128 * 1024 * 1024 - }; } get destroyed() { return this[kDestroyed]; @@ -5738,7 +5667,6 @@ var require_client_h1 = __commonJS({ RequestContentLengthMismatchError, ResponseContentLengthMismatchError, RequestAbortedError, - InvalidArgumentError, HeadersTimeoutError, HeadersOverflowError, SocketError, @@ -5785,9 +5713,6 @@ var require_client_h1 = __commonJS({ var FastBuffer = Buffer[Symbol.species]; var addListener = util.addListener; var removeAllListeners = util.removeAllListeners; - var kIdleSocketValidation = /* @__PURE__ */ Symbol("kIdleSocketValidation"); - var kIdleSocketValidationTimeout = /* @__PURE__ */ Symbol("kIdleSocketValidationTimeout"); - var kSocketUsed = /* @__PURE__ */ Symbol("kSocketUsed"); var extractBody; async function lazyllhttp() { const llhttpWasmData = process.env.JEST_WORKER_ID ? require_llhttp_wasm() : void 0; @@ -5950,55 +5875,24 @@ var require_client_h1 = __commonJS({ currentBufferRef = null; } const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr; - if (ret !== constants3.ERROR.OK) { - const body = data.subarray(offset); - if (ret === constants3.ERROR.PAUSED_UPGRADE) { - this.onUpgrade(body); - } else if (ret === constants3.ERROR.PAUSED) { - this.paused = true; - socket.unshift(body); - } else { - throw this.createError(ret, body); + if (ret === constants3.ERROR.PAUSED_UPGRADE) { + this.onUpgrade(data.slice(offset)); + } else if (ret === constants3.ERROR.PAUSED) { + this.paused = true; + socket.unshift(data.slice(offset)); + } else if (ret !== constants3.ERROR.OK) { + const ptr = llhttp.llhttp_get_error_reason(this.ptr); + let message = ""; + if (ptr) { + const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); + message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; } + throw new HTTPParserError(message, constants3.ERROR[ret], data.slice(offset)); } } catch (err) { util.destroy(socket, err); } } - finish() { - assert(currentParser === null); - assert(this.ptr != null); - assert(!this.paused); - const { llhttp } = this; - let ret; - try { - currentParser = this; - ret = llhttp.llhttp_finish(this.ptr); - } finally { - currentParser = null; - } - if (ret === constants3.ERROR.OK) { - return null; - } - if (ret === constants3.ERROR.PAUSED || ret === constants3.ERROR.PAUSED_UPGRADE) { - this.paused = true; - return null; - } - return this.createError(ret, EMPTY_BUF); - } - createError(ret, data) { - const { llhttp, contentLength, bytesRead } = this; - if (contentLength && bytesRead !== parseInt(contentLength, 10)) { - return new ResponseContentLengthMismatchError(); - } - const ptr = llhttp.llhttp_get_error_reason(this.ptr); - let message = ""; - if (ptr) { - const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); - message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; - } - return new HTTPParserError(message, constants3.ERROR[ret], data); - } destroy() { assert(this.ptr != null); assert(currentParser == null); @@ -6018,10 +5912,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6065,7 +5955,7 @@ var require_client_h1 = __commonJS({ } } onUpgrade(head) { - const { upgrade, client, socket, headers, statusCode, statusText } = this; + const { upgrade, client, socket, headers, statusCode } = this; assert(upgrade); assert(client[kSocket] === socket); assert(!socket.destroyed); @@ -6090,10 +5980,9 @@ var require_client_h1 = __commonJS({ client[kQueue][client[kRunningIdx]++] = null; client.emit("disconnect", client[kUrl], [client], new InformationalError("upgrade")); try { - request2.onUpgrade(statusCode, headers, socket, statusText); - } catch (error2) { - util.errorRequest(client, request2, error2); - util.destroy(socket, error2); + request2.onUpgrade(statusCode, headers, socket); + } catch (err) { + util.destroy(socket, err); } client[kResume](); } @@ -6102,10 +5991,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6231,7 +6116,6 @@ var require_client_h1 = __commonJS({ } request2.onComplete(headers); client[kQueue][client[kRunningIdx]++] = null; - socket[kSocketUsed] = true; if (socket[kWriting]) { assert(client[kRunning] === 0); util.destroy(socket, new InformationalError("reset")); @@ -6275,19 +6159,12 @@ var require_client_h1 = __commonJS({ socket[kWriting] = false; socket[kReset] = false; socket[kBlocking] = false; - socket[kIdleSocketValidation] = 0; - socket[kIdleSocketValidationTimeout] = null; - socket[kSocketUsed] = false; socket[kParser] = new Parser(client, socket, llhttpInstance); addListener(socket, "error", function(err) { assert(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID"); const parser = this[kParser]; if (err.code === "ECONNRESET" && parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - this[kError] = parserErr; - this[kClient][kOnError](parserErr); - } + parser.onMessageComplete(); return; } this[kError] = err; @@ -6302,10 +6179,7 @@ var require_client_h1 = __commonJS({ addListener(socket, "end", function() { const parser = this[kParser]; if (parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - util.destroy(this, parserErr); - } + parser.onMessageComplete(); return; } util.destroy(this, new SocketError("other side closed", util.getSocketInfo(this))); @@ -6313,10 +6187,9 @@ var require_client_h1 = __commonJS({ addListener(socket, "close", function() { const client2 = this[kClient]; const parser = this[kParser]; - clearIdleSocketValidation(this); if (parser) { if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { - this[kError] = parser.finish() || this[kError]; + parser.onMessageComplete(); } this[kParser].destroy(); this[kParser] = null; @@ -6365,7 +6238,7 @@ var require_client_h1 = __commonJS({ return socket.destroyed; }, busy(request2) { - if (socket[kWriting] || socket[kReset] || socket[kBlocking] || socket[kIdleSocketValidation] === 1) { + if (socket[kWriting] || socket[kReset] || socket[kBlocking]) { return true; } if (request2) { @@ -6383,23 +6256,6 @@ var require_client_h1 = __commonJS({ } }; } - function clearIdleSocketValidation(socket) { - if (socket[kIdleSocketValidationTimeout]) { - clearImmediate(socket[kIdleSocketValidationTimeout]); - socket[kIdleSocketValidationTimeout] = null; - } - socket[kIdleSocketValidation] = 0; - } - function scheduleIdleSocketValidation(client, socket) { - socket[kIdleSocketValidation] = 1; - socket[kIdleSocketValidationTimeout] = setImmediate(() => { - socket[kIdleSocketValidationTimeout] = null; - socket[kIdleSocketValidation] = 2; - if (client[kSocket] === socket && !socket.destroyed) { - client[kResume](); - } - }); - } function resumeH1(client) { const socket = client[kSocket]; if (socket && !socket.destroyed) { @@ -6412,29 +6268,6 @@ var require_client_h1 = __commonJS({ socket.ref(); socket[kNoRef] = false; } - if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) { - if (socket[kIdleSocketValidation] === 0) { - scheduleIdleSocketValidation(client, socket); - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - if (socket[kIdleSocketValidation] === 1) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - } - if (client[kRunning] === 0) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - } if (client[kSize] === 0) { if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) { socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE); @@ -6465,16 +6298,8 @@ var require_client_h1 = __commonJS({ } body = bodyStream.stream; contentLength = bodyStream.length; - } else if (util.isBlobLike(body) && request2.contentType == null) { - const contentType = body.type; - if (contentType) { - const contentTypeValue = `${contentType}`; - if (!util.isValidHeaderValue(contentTypeValue)) { - util.errorRequest(client, request2, new InvalidArgumentError("invalid content-type header")); - return false; - } - headers.push("content-type", contentTypeValue); - } + } else if (util.isBlobLike(body) && request2.contentType == null && body.type) { + headers.push("content-type", body.type); } if (body && typeof body.read === "function") { body.read(0); @@ -6495,18 +6320,11 @@ var require_client_h1 = __commonJS({ process.emitWarning(new RequestContentLengthMismatchError()); } const socket = client[kSocket]; - clearIdleSocketValidation(socket); - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (request2.upgrade || request2.method === "CONNECT") { - util.destroy(socket, new InformationalError("aborted")); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - util.errorRequest(client, request2, error2 || new RequestAbortedError()); + util.errorRequest(client, request2, err || new RequestAbortedError()); util.destroy(body); util.destroy(socket, new InformationalError("aborted")); }; @@ -6862,7 +6680,6 @@ var require_client_h2 = __commonJS({ "node_modules/undici/lib/dispatcher/client-h2.js"(exports, module) { "use strict"; var assert = __require("node:assert"); - var { errorMonitor } = __require("node:events"); var { pipeline } = __require("node:stream"); var util = require_util(); var { @@ -6923,10 +6740,6 @@ var require_client_h2 = __commonJS({ } return result; } - function parseH2ResponseHeaders(headers) { - const { [HTTP2_HEADER_STATUS]: _statusCode, ...realHeaders } = headers; - return parseH2Headers(realHeaders); - } async function connectH2(client, socket) { client[kSocket] = socket; if (!h2ExperimentalWarned) { @@ -7090,22 +6903,16 @@ var require_client_h2 = __commonJS({ const { hostname, port } = client[kUrl]; headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ""}`; headers[HTTP2_HEADER_METHOD] = method; - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (method === "CONNECT" && stream != null) { - util.destroy(stream, error2 || new RequestAbortedError()); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - error2 = error2 || new RequestAbortedError(); - util.errorRequest(client, request2, error2); + err = err || new RequestAbortedError(); + util.errorRequest(client, request2, err); if (stream != null) { - util.destroy(stream, error2); + util.destroy(stream, err); } - util.destroy(body, error2); + util.destroy(body, err); client[kQueue][client[kRunningIdx]++] = null; client[kResume](); }; @@ -7120,42 +6927,18 @@ var require_client_h2 = __commonJS({ if (method === "CONNECT") { session.ref(); stream = session.request(headers, { endStream: false, signal }); - let upgradeResponseFinished = false; - const onResponse = (headers2) => { - upgradeResponseFinished = true; - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeResponse(Number(headers2[HTTP2_HEADER_STATUS]), headers2, parseH2ResponseHeaders); - }; - const onUpgradeError = (error2) => { - upgradeResponseFinished = true; - stream.off("response", onResponse); - request2.onUpgradeError(error2); - }; - const onReady = () => { - try { - request2.onUpgrade(null, null, stream); - } catch (error2) { - stream.off("response", onResponse); - abort(error2); - return; - } - if (request2.aborted) { - return; - } - stream.off("error", abort); - stream.once(errorMonitor, onUpgradeError); + if (stream.id && !stream.pending) { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; client[kQueue][client[kRunningIdx]++] = null; - }; - stream.once("response", onResponse); - stream.once("error", abort); - ++session[kOpenStreams]; - onReady(); + } else { + stream.once("ready", () => { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; + client[kQueue][client[kRunningIdx]++] = null; + }); + } stream.once("close", () => { - if (!upgradeResponseFinished && request2.completed) { - stream.off("response", onResponse); - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeError(new InformationalError(`HTTP/2: "stream error" received - code ${stream.rstCode}`)); - } session[kOpenStreams] -= 1; if (session[kOpenStreams] === 0) session.unref(); }); @@ -7716,10 +7499,9 @@ var require_client = __commonJS({ autoSelectFamilyAttemptTimeout, // h2 maxConcurrentStreams, - allowH2, - webSocket + allowH2 } = {}) { - super({ webSocket }); + super(); if (keepAlive !== void 0) { throw new InvalidArgumentError("unsupported keepAlive, use pipelining=0 instead"); } @@ -8225,8 +8007,8 @@ var require_pool_base = __commonJS({ var kRemoveClient = /* @__PURE__ */ Symbol("remove client"); var kStats = /* @__PURE__ */ Symbol("stats"); var PoolBase = class extends DispatcherBase { - constructor(opts) { - super(opts); + constructor() { + super(); this[kQueue] = new FixedQueue(); this[kClients] = []; this[kQueued] = 0; @@ -8397,6 +8179,7 @@ var require_pool = __commonJS({ allowH2, ...options } = {}) { + super(); if (connections != null && (!Number.isFinite(connections) || connections < 0)) { throw new InvalidArgumentError("invalid connections"); } @@ -8417,7 +8200,6 @@ var require_pool = __commonJS({ ...connect }); } - super(options); this[kInterceptors] = options.interceptors?.Pool && Array.isArray(options.interceptors.Pool) ? options.interceptors.Pool : []; this[kConnections] = connections || null; this[kUrl] = util.parseOrigin(origin); @@ -8617,6 +8399,7 @@ var require_agent = __commonJS({ } var Agent = class extends DispatcherBase { constructor({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { + super(); if (typeof factory !== "function") { throw new InvalidArgumentError("factory must be a function."); } @@ -8626,7 +8409,6 @@ var require_agent = __commonJS({ if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { throw new InvalidArgumentError("maxRedirections must be a positive number"); } - super(options); if (connect && typeof connect !== "function") { connect = { ...connect }; } @@ -9067,24 +8849,6 @@ var require_retry_handler = __commonJS({ const current = Date.now(); return new Date(retryAfter).getTime() - current; } - function validatePartialResponseContentLength(headers, range, statusCode, retryCount) { - const contentLength = headers["content-length"]; - if (contentLength == null) { - return null; - } - if (!Number.isFinite(range.start) || !Number.isFinite(range.end)) { - return null; - } - const length = Number(contentLength); - const expectedLength = range.end - range.start + 1; - if (!Number.isFinite(length) || length !== expectedLength) { - return new RequestRetryError("Content-Length mismatch", statusCode, { - headers, - data: { count: retryCount } - }); - } - return null; - } var RetryHandler = class _RetryHandler { constructor(opts, handlers) { const { retryOptions, ...dispatchOpts } = opts; @@ -9138,7 +8902,6 @@ var require_retry_handler = __commonJS({ this.end = null; this.etag = null; this.resume = null; - this.headersSent = false; this.handler.onConnect((reason) => { this.aborted = true; if (this.abort) { @@ -9148,17 +8911,6 @@ var require_retry_handler = __commonJS({ } }); } - 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(); @@ -9220,9 +8972,7 @@ var require_retry_handler = __commonJS({ const headers = parseHeaders(rawHeaders); this.retryCount += 1; if (statusCode >= 300) { - if (!this.headersSent && this.retryOpts.statusCodes.includes(statusCode) === false) { - this.headersSent = true; - this.checkpointResponseEnd(headers, resume); + if (this.retryOpts.statusCodes.includes(statusCode) === false) { return this.handler.onHeaders( statusCode, rawHeaders, @@ -9271,21 +9021,9 @@ var require_retry_handler = __commonJS({ ); return false; } - const contentLengthError = validatePartialResponseContentLength(headers, contentRange, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = contentRange; - 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; - } + assert(this.start === start, "content-range mismatch"); + assert(this.end == null || this.end === end, "content-range mismatch"); this.resume = resume; return true; } @@ -9293,7 +9031,6 @@ var require_retry_handler = __commonJS({ if (statusCode === 206) { const range = parseRangeHeader(headers["content-range"]); if (range == null) { - this.headersSent = true; return this.handler.onHeaders( statusCode, rawHeaders, @@ -9301,11 +9038,6 @@ var require_retry_handler = __commonJS({ statusMessage ); } - const contentLengthError = validatePartialResponseContentLength(headers, range, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = range; assert( start != null && Number.isFinite(start), @@ -9325,7 +9057,6 @@ var require_retry_handler = __commonJS({ "invalid content-length" ); this.resume = resume; - this.headersSent = true; this.etag = headers.etag != null ? headers.etag : null; if (this.etag != null && this.etag.startsWith("W/")) { this.etag = null; @@ -9353,7 +9084,7 @@ var require_retry_handler = __commonJS({ return this.handler.onComplete(rawTrailers); } onError(err) { - if (this.aborted || isDisturbed(this.opts.body) || this.headersSent && this.resume == null) { + if (this.aborted || isDisturbed(this.opts.body)) { return this.handler.onError(err); } if (this.retryCount - this.retryCountCheckpoint > 0) { @@ -16152,48 +15883,14 @@ var require_util6 = __commonJS({ for (let i = 0; i < path.length; ++i) { const code = path.charCodeAt(i); if (code < 32 || // exclude CTLs (0-31) - code > 126 || // exclude DEL and non-ascii + code === 127 || // DEL code === 59) { throw new Error("Invalid cookie path"); } } } - function isLetterOrDigit(code) { - return code >= 48 && code <= 57 || // 0-9 - code >= 65 && code <= 90 || // A-Z - code >= 97 && code <= 122; - } function validateCookieDomain(domain) { - if (domain === " ") { - return; - } - if (domain.length > 255) { - throw new Error("Invalid cookie domain"); - } - let labelLength = 0; - for (let i = 0; i < domain.length; ++i) { - const code = domain.charCodeAt(i); - if (code === 46) { - if (labelLength === 0) { - throw new Error("Invalid cookie domain"); - } - if (domain.charCodeAt(i - 1) === 45) { - throw new Error("Invalid cookie domain"); - } - labelLength = 0; - continue; - } - if (labelLength === 0 && !isLetterOrDigit(code)) { - throw new Error("Invalid cookie domain"); - } - if (!isLetterOrDigit(code) && code !== 45) { - throw new Error("Invalid cookie domain"); - } - if (++labelLength > 63) { - throw new Error("Invalid cookie domain"); - } - } - if (labelLength === 0 || domain.charCodeAt(domain.length - 1) === 45) { + if (domain.startsWith("-") || domain.endsWith(".") || domain.endsWith("-")) { throw new Error("Invalid cookie domain"); } } @@ -16276,11 +15973,7 @@ var require_util6 = __commonJS({ throw new Error("Invalid unparsed"); } const [key, ...value] = part.split("="); - const trimmedKey = key.trim(); - const joinedValue = value.join("="); - validateCookieName(trimmedKey); - validateCookieValue(joinedValue); - out.push(`${trimmedKey}=${joinedValue}`); + out.push(`${key.trim()}=${value.join("=")}`); } return out.join("; "); } @@ -16410,14 +16103,18 @@ var require_parse = __commonJS({ } else if (attributeNameLowercase === "httponly") { cookieAttributeList.httpOnly = true; } else if (attributeNameLowercase === "samesite") { + let enforcement = "Default"; const attributeValueLowercase = attributeValue.toLowerCase(); - if (attributeValueLowercase === "none") { - cookieAttributeList.sameSite = "None"; - } else if (attributeValueLowercase === "strict") { - cookieAttributeList.sameSite = "Strict"; - } else if (attributeValueLowercase === "lax") { - cookieAttributeList.sameSite = "Lax"; + if (attributeValueLowercase.includes("none")) { + enforcement = "None"; + } + if (attributeValueLowercase.includes("strict")) { + enforcement = "Strict"; + } + if (attributeValueLowercase.includes("lax")) { + enforcement = "Lax"; } + cookieAttributeList.sameSite = enforcement; } else { cookieAttributeList.unparsed ??= []; cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`); @@ -17239,7 +16936,7 @@ var require_connection = __commonJS({ const secProtocol = response.headersList.get("Sec-WebSocket-Protocol"); if (secProtocol !== null) { const requestProtocols = getDecodeSplit("sec-websocket-protocol", request2.headersList); - if (requestProtocols === null || !requestProtocols.includes(secProtocol)) { + if (!requestProtocols.includes(secProtocol)) { failWebsocketConnection(ws, "Protocol was not set in the opening handshake."); return; } @@ -17345,26 +17042,31 @@ var require_permessage_deflate = __commonJS({ var tail = Buffer.from([0, 0, 255, 255]); var kBuffer = /* @__PURE__ */ Symbol("kBuffer"); var kLength = /* @__PURE__ */ Symbol("kLength"); + var kDefaultMaxDecompressedSize = 4 * 1024 * 1024; var PerMessageDeflate = class { /** @type {import('node:zlib').InflateRaw} */ #inflate; #options = {}; - #maxPayloadSize = 0; + /** @type {number} */ + #maxDecompressedSize; + /** @type {boolean} */ + #aborted = false; + /** @type {Function|null} */ + #currentCallback = null; /** * @param {Map} extensions + * @param {{ maxDecompressedMessageSize?: number }} [options] */ - constructor(extensions, options) { + constructor(extensions, options = {}) { this.#options.serverNoContextTakeover = extensions.has("server_no_context_takeover"); this.#options.serverMaxWindowBits = extensions.get("server_max_window_bits"); - this.#maxPayloadSize = options.maxPayloadSize; + this.#maxDecompressedSize = options.maxDecompressedMessageSize ?? kDefaultMaxDecompressedSize; } - /** - * Decompress a compressed payload. - * @param {Buffer} chunk Compressed data - * @param {boolean} fin Final fragment flag - * @param {Function} callback Callback function - */ decompress(chunk, fin, callback) { + if (this.#aborted) { + callback(new MessageSizeExceededError()); + return; + } if (!this.#inflate) { let windowBits = Z_DEFAULT_WINDOWBITS; if (this.#options.serverMaxWindowBits) { @@ -17383,12 +17085,20 @@ var require_permessage_deflate = __commonJS({ this.#inflate[kBuffer] = []; this.#inflate[kLength] = 0; this.#inflate.on("data", (data) => { + if (this.#aborted) { + return; + } this.#inflate[kLength] += data.length; - if (this.#maxPayloadSize > 0 && this.#inflate[kLength] > this.#maxPayloadSize) { - callback(new MessageSizeExceededError()); + if (this.#inflate[kLength] > this.#maxDecompressedSize) { + this.#aborted = true; this.#inflate.removeAllListeners(); this.#inflate.destroy(); this.#inflate = null; + if (this.#currentCallback) { + const cb = this.#currentCallback; + this.#currentCallback = null; + cb(new MessageSizeExceededError()); + } return; } this.#inflate[kBuffer].push(data); @@ -17398,17 +17108,19 @@ var require_permessage_deflate = __commonJS({ callback(err); }); } + this.#currentCallback = callback; this.#inflate.write(chunk); if (fin) { this.#inflate.write(tail); } this.#inflate.flush(() => { - if (!this.#inflate) { + if (this.#aborted || !this.#inflate) { return; } const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]); this.#inflate[kBuffer].length = 0; this.#inflate[kLength] = 0; + this.#currentCallback = null; callback(null, full); }); } @@ -17439,14 +17151,8 @@ var require_receiver = __commonJS({ var { WebsocketFrameSend } = require_frame(); var { closeWebSocketConnection } = require_connection(); var { PerMessageDeflate } = require_permessage_deflate(); - var { MessageSizeExceededError } = require_errors(); - function failWebsocketConnectionWithCode(ws, code, reason) { - closeWebSocketConnection(ws, code, reason, Buffer.byteLength(reason)); - failWebsocketConnection(ws, reason); - } var ByteParser = class extends Writable { #buffers = []; - #fragmentsBytes = 0; #byteOffset = 0; #loop = false; #state = parserStates.INFO; @@ -17454,21 +17160,18 @@ var require_receiver = __commonJS({ #fragments = []; /** @type {Map} */ #extensions; - /** @type {number} */ - #maxFragments; - /** @type {number} */ - #maxPayloadSize; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {import('./websocket').WebSocket} ws * @param {Map|null} extensions - * @param {{ maxFragments?: number, maxPayloadSize?: number }} [options] + * @param {{ maxDecompressedMessageSize?: number }} [options] */ constructor(ws, extensions, options = {}) { super(); this.ws = ws; this.#extensions = extensions == null ? /* @__PURE__ */ new Map() : extensions; - this.#maxFragments = options.maxFragments ?? 0; - this.#maxPayloadSize = options.maxPayloadSize ?? 0; + this.#options = options; if (this.#extensions.has("permessage-deflate")) { this.#extensions.set("permessage-deflate", new PerMessageDeflate(extensions, options)); } @@ -17483,13 +17186,6 @@ var require_receiver = __commonJS({ this.#loop = true; this.run(callback); } - #validatePayloadLength() { - if (this.#maxPayloadSize > 0 && !isControlFrame(this.#info.opcode) && this.#info.payloadLength + this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, "Payload size exceeds maximum allowed size"); - return false; - } - return true; - } /** * Runs whenever a new chunk is received. * Callback is called whenever there are no more chunks buffering, @@ -17549,9 +17245,6 @@ var require_receiver = __commonJS({ if (payloadLength <= 125) { this.#info.payloadLength = payloadLength; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (payloadLength === 126) { this.#state = parserStates.PAYLOADLENGTH_16; } else if (payloadLength === 127) { @@ -17572,9 +17265,6 @@ var require_receiver = __commonJS({ const buffer = this.consume(2); this.#info.payloadLength = buffer.readUInt16BE(0); this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.PAYLOADLENGTH_64) { if (this.#byteOffset < 8) { return callback(); @@ -17588,9 +17278,6 @@ var require_receiver = __commonJS({ } this.#info.payloadLength = lower; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.READ_DATA) { if (this.#byteOffset < this.#info.payloadLength) { return callback(); @@ -17601,46 +17288,32 @@ var require_receiver = __commonJS({ this.#state = parserStates.INFO; } else { if (!this.#info.compressed) { - if (!this.writeFragments(body)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } + this.#fragments.push(body); if (!this.#info.fragmented && this.#info.fin) { - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); + const fullMessage = Buffer.concat(this.#fragments); + websocketMessageReceived(this.ws, this.#info.binaryType, fullMessage); + this.#fragments.length = 0; } this.#state = parserStates.INFO; } else { - this.#extensions.get("permessage-deflate").decompress( - body, - this.#info.fin, - (error2, data) => { - if (error2) { - const code = error2 instanceof MessageSizeExceededError ? 1009 : 1007; - failWebsocketConnectionWithCode(this.ws, code, error2.message); - return; - } - if (!this.writeFragments(data)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } - if (!this.#info.fin) { - this.#state = parserStates.INFO; - this.#loop = true; - this.run(callback); - return; - } - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); - this.#loop = true; + this.#extensions.get("permessage-deflate").decompress(body, this.#info.fin, (error2, data) => { + if (error2) { + failWebsocketConnection(this.ws, error2.message); + return; + } + this.#fragments.push(data); + if (!this.#info.fin) { this.#state = parserStates.INFO; + this.#loop = true; this.run(callback); + return; } - ); + websocketMessageReceived(this.ws, this.#info.binaryType, Buffer.concat(this.#fragments)); + this.#loop = true; + this.#state = parserStates.INFO; + this.#fragments.length = 0; + this.run(callback); + }); this.#loop = false; break; } @@ -17683,26 +17356,6 @@ var require_receiver = __commonJS({ this.#byteOffset -= n; return buffer; } - writeFragments(fragment) { - if (this.#maxFragments > 0 && this.#fragments.length === this.#maxFragments) { - failWebsocketConnectionWithCode(this.ws, 1008, "Too many message fragments"); - return false; - } - this.#fragmentsBytes += fragment.length; - this.#fragments.push(fragment); - return true; - } - consumeFragments() { - const fragments = this.#fragments; - if (fragments.length === 1) { - this.#fragmentsBytes = 0; - return fragments.shift(); - } - const output = Buffer.concat(fragments, this.#fragmentsBytes); - this.#fragments = []; - this.#fragmentsBytes = 0; - return output; - } parseCloseBody(data) { assert(data.length !== 1); let code; @@ -17914,6 +17567,8 @@ var require_websocket = __commonJS({ #extensions = ""; /** @type {SendQueue} */ #sendQueue; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {string} url * @param {string|string[]} protocols @@ -17957,6 +17612,9 @@ var require_websocket = __commonJS({ throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError"); } this[kWebSocketURL] = new URL(urlRecord.href); + this.#options = { + maxDecompressedMessageSize: options.maxDecompressedMessageSize + }; const client = environmentSettingsObject.settingsObject; this[kController] = establishWebSocketConnection( urlRecord, @@ -18140,13 +17798,7 @@ var require_websocket = __commonJS({ */ #onConnectionEstablished(response, parsedExtensions) { this[kResponse] = response; - const webSocketOptions = this[kController]?.dispatcher?.webSocketOptions; - const maxFragments = webSocketOptions?.maxFragments; - const maxPayloadSize = webSocketOptions?.maxPayloadSize; - const parser = new ByteParser(this, parsedExtensions, { - maxFragments, - maxPayloadSize - }); + const parser = new ByteParser(this, parsedExtensions, this.#options); parser.on("drain", onParserDrain); parser.on("error", onParserError.bind(this)); response.socket.ws = this; @@ -18221,6 +17873,19 @@ var require_websocket = __commonJS({ { key: "headers", converter: webidl.nullableConverter(webidl.converters.HeadersInit) + }, + { + key: "maxDecompressedMessageSize", + converter: webidl.nullableConverter((V) => { + V = webidl.converters["unsigned long long"](V); + if (V <= 0) { + throw webidl.errors.exception({ + header: "WebSocket constructor", + message: "maxDecompressedMessageSize must be greater than 0" + }); + } + return V; + }) } ]); webidl.converters["DOMString or sequence or WebSocketInit"] = function(V) { @@ -18299,40 +17964,6 @@ 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; - } - function isValidLastEventIdBytes(buffer, start) { - for (let i = start; i < buffer.length; i++) { - if (buffer[i] === 0) { - 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; - } var EventSourceStream = class extends Transform { /** * @type {eventSourceSettings} @@ -18352,13 +17983,10 @@ var require_eventsource_stream = __commonJS({ */ eventEndCheck = false; /** - * @type {Buffer[]} + * @type {Buffer} */ - chunks = []; - chunkIndex = 0; + buffer = null; pos = 0; - lineChunkIndex = 0; - linePos = 0; event = { data: void 0, event: void 0, @@ -18389,30 +18017,63 @@ var require_eventsource_stream = __commonJS({ callback(); return; } - this.chunks.push(chunk); + if (this.buffer) { + this.buffer = Buffer.concat([this.buffer, chunk]); + } else { + this.buffer = chunk; + } if (this.checkBOM) { - if (this.handleBOM()) { - callback(); - return; + 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; } } - while (this.hasCurrentByte()) { - const byte = this.currentByte(); + while (this.pos < this.buffer.length) { if (this.eventEndCheck) { if (this.crlfCheck) { - if (byte === LF) { + if (this.buffer[this.pos] === LF) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.crlfCheck = false; - this.consumeCurrentByte(); continue; } this.crlfCheck = false; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.consumeCurrentByte(); - if (this.hasPendingEvent()) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; + if (this.event.data !== void 0 || this.event.event || this.event.id || this.event.retry) { this.processEvent(this.event); } this.clearEvent(); @@ -18421,16 +18082,17 @@ var require_eventsource_stream = __commonJS({ this.eventEndCheck = false; continue; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.parseLine(this.readLine(), this.event); - this.consumeCurrentByte(); + this.parseLine(this.buffer.subarray(0, this.pos), this.event); + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.eventEndCheck = true; continue; } - this.advanceCursor(); + this.pos++; } callback(); } @@ -18446,42 +18108,43 @@ var require_eventsource_stream = __commonJS({ if (colonPosition === 0) { return; } - let fieldLength = line.length; - let valueStart = line.length; + let field = ""; + let value = ""; if (colonPosition !== -1) { - fieldLength = colonPosition; - valueStart = colonPosition + 1; + field = line.subarray(0, colonPosition).toString("utf8"); + let valueStart = colonPosition + 1; if (line[valueStart] === SPACE) { ++valueStart; } + value = line.subarray(valueStart).toString("utf8"); + } else { + field = line.toString("utf8"); + value = ""; } - if (isFieldName(line, fieldLength, DATA)) { - const value = line.toString("utf8", valueStart); - if (event.data === void 0) { - event.data = value; - } else { - event.data += ` + switch (field) { + case "data": + if (event[field] === void 0) { + event[field] = value; + } else { + event[field] += ` ${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; - } + } + 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; } } /** @@ -18506,120 +18169,12 @@ ${value}`; } } clearEvent() { - 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(); + this.event = { + data: void 0, + event: void 0, + id: void 0, + retry: void 0 + }; } }; module.exports = { diff --git a/.github/actions/javascript/awaitStagingDeploys/index.js b/.github/actions/javascript/awaitStagingDeploys/index.js index 00e2f735fcb4..906a5fe20da8 100644 --- a/.github/actions/javascript/awaitStagingDeploys/index.js +++ b/.github/actions/javascript/awaitStagingDeploys/index.js @@ -1863,66 +1863,10 @@ var require_request = __commonJS({ return false; } } - /** - * @param {number|null} statusCode - * @param {Buffer[]|null} headers - * @param {import('node:stream').Duplex} socket - * @param {string} [statusText] - */ - onUpgrade(statusCode, headers, socket, statusText = "") { - this.onFinally(); + onUpgrade(statusCode, headers, socket) { assert(!this.aborted); assert(!this.completed); - 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(error2) { - assert(!this.aborted); - assert(this.completed); - if (channels.error.hasSubscribers) { - channels.error.publish({ request: this, error: error2 }); - } - } - /** - * @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: [] }); - } + return this[kHandler].onUpgrade(statusCode, headers, socket); } onComplete(trailers) { this.onFinally(); @@ -1989,11 +1933,7 @@ var require_request = __commonJS({ } else if (typeof val[i] === "object") { throw new InvalidArgumentError(`invalid ${key} header`); } else { - const str = `${val[i]}`; - if (!isValidHeaderValue(str)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } - arr.push(str); + arr.push(`${val[i]}`); } } val = arr; @@ -2005,9 +1945,6 @@ var require_request = __commonJS({ val = ""; } else { val = `${val}`; - if (!isValidHeaderValue(val)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } } if (headerName === "host") { if (request2.host !== null) { @@ -2117,21 +2054,13 @@ var require_dispatcher_base = __commonJS({ var kOnDestroyed = /* @__PURE__ */ Symbol("onDestroyed"); var kOnClosed = /* @__PURE__ */ Symbol("onClosed"); var kInterceptedDispatch = /* @__PURE__ */ Symbol("Intercepted Dispatch"); - var kWebSocketOptions = /* @__PURE__ */ Symbol("webSocketOptions"); var DispatcherBase = class extends Dispatcher { - constructor(opts) { + constructor() { super(); this[kDestroyed] = false; this[kOnDestroyed] = null; this[kClosed] = false; this[kOnClosed] = []; - this[kWebSocketOptions] = opts?.webSocket ?? {}; - } - get webSocketOptions() { - return { - maxFragments: this[kWebSocketOptions].maxFragments ?? 131072, - maxPayloadSize: this[kWebSocketOptions].maxPayloadSize ?? 128 * 1024 * 1024 - }; } get destroyed() { return this[kDestroyed]; @@ -5738,7 +5667,6 @@ var require_client_h1 = __commonJS({ RequestContentLengthMismatchError, ResponseContentLengthMismatchError, RequestAbortedError, - InvalidArgumentError, HeadersTimeoutError, HeadersOverflowError, SocketError, @@ -5785,9 +5713,6 @@ var require_client_h1 = __commonJS({ var FastBuffer = Buffer[Symbol.species]; var addListener = util.addListener; var removeAllListeners = util.removeAllListeners; - var kIdleSocketValidation = /* @__PURE__ */ Symbol("kIdleSocketValidation"); - var kIdleSocketValidationTimeout = /* @__PURE__ */ Symbol("kIdleSocketValidationTimeout"); - var kSocketUsed = /* @__PURE__ */ Symbol("kSocketUsed"); var extractBody; async function lazyllhttp() { const llhttpWasmData = process.env.JEST_WORKER_ID ? require_llhttp_wasm() : void 0; @@ -5950,55 +5875,24 @@ var require_client_h1 = __commonJS({ currentBufferRef = null; } const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr; - if (ret !== constants3.ERROR.OK) { - const body = data.subarray(offset); - if (ret === constants3.ERROR.PAUSED_UPGRADE) { - this.onUpgrade(body); - } else if (ret === constants3.ERROR.PAUSED) { - this.paused = true; - socket.unshift(body); - } else { - throw this.createError(ret, body); + if (ret === constants3.ERROR.PAUSED_UPGRADE) { + this.onUpgrade(data.slice(offset)); + } else if (ret === constants3.ERROR.PAUSED) { + this.paused = true; + socket.unshift(data.slice(offset)); + } else if (ret !== constants3.ERROR.OK) { + const ptr = llhttp.llhttp_get_error_reason(this.ptr); + let message = ""; + if (ptr) { + const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); + message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; } + throw new HTTPParserError(message, constants3.ERROR[ret], data.slice(offset)); } } catch (err) { util.destroy(socket, err); } } - finish() { - assert(currentParser === null); - assert(this.ptr != null); - assert(!this.paused); - const { llhttp } = this; - let ret; - try { - currentParser = this; - ret = llhttp.llhttp_finish(this.ptr); - } finally { - currentParser = null; - } - if (ret === constants3.ERROR.OK) { - return null; - } - if (ret === constants3.ERROR.PAUSED || ret === constants3.ERROR.PAUSED_UPGRADE) { - this.paused = true; - return null; - } - return this.createError(ret, EMPTY_BUF); - } - createError(ret, data) { - const { llhttp, contentLength, bytesRead } = this; - if (contentLength && bytesRead !== parseInt(contentLength, 10)) { - return new ResponseContentLengthMismatchError(); - } - const ptr = llhttp.llhttp_get_error_reason(this.ptr); - let message = ""; - if (ptr) { - const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); - message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; - } - return new HTTPParserError(message, constants3.ERROR[ret], data); - } destroy() { assert(this.ptr != null); assert(currentParser == null); @@ -6018,10 +5912,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6065,7 +5955,7 @@ var require_client_h1 = __commonJS({ } } onUpgrade(head) { - const { upgrade, client, socket, headers, statusCode, statusText } = this; + const { upgrade, client, socket, headers, statusCode } = this; assert(upgrade); assert(client[kSocket] === socket); assert(!socket.destroyed); @@ -6090,10 +5980,9 @@ var require_client_h1 = __commonJS({ client[kQueue][client[kRunningIdx]++] = null; client.emit("disconnect", client[kUrl], [client], new InformationalError("upgrade")); try { - request2.onUpgrade(statusCode, headers, socket, statusText); - } catch (error2) { - util.errorRequest(client, request2, error2); - util.destroy(socket, error2); + request2.onUpgrade(statusCode, headers, socket); + } catch (err) { + util.destroy(socket, err); } client[kResume](); } @@ -6102,10 +5991,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6231,7 +6116,6 @@ var require_client_h1 = __commonJS({ } request2.onComplete(headers); client[kQueue][client[kRunningIdx]++] = null; - socket[kSocketUsed] = true; if (socket[kWriting]) { assert(client[kRunning] === 0); util.destroy(socket, new InformationalError("reset")); @@ -6275,19 +6159,12 @@ var require_client_h1 = __commonJS({ socket[kWriting] = false; socket[kReset] = false; socket[kBlocking] = false; - socket[kIdleSocketValidation] = 0; - socket[kIdleSocketValidationTimeout] = null; - socket[kSocketUsed] = false; socket[kParser] = new Parser(client, socket, llhttpInstance); addListener(socket, "error", function(err) { assert(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID"); const parser = this[kParser]; if (err.code === "ECONNRESET" && parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - this[kError] = parserErr; - this[kClient][kOnError](parserErr); - } + parser.onMessageComplete(); return; } this[kError] = err; @@ -6302,10 +6179,7 @@ var require_client_h1 = __commonJS({ addListener(socket, "end", function() { const parser = this[kParser]; if (parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - util.destroy(this, parserErr); - } + parser.onMessageComplete(); return; } util.destroy(this, new SocketError("other side closed", util.getSocketInfo(this))); @@ -6313,10 +6187,9 @@ var require_client_h1 = __commonJS({ addListener(socket, "close", function() { const client2 = this[kClient]; const parser = this[kParser]; - clearIdleSocketValidation(this); if (parser) { if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { - this[kError] = parser.finish() || this[kError]; + parser.onMessageComplete(); } this[kParser].destroy(); this[kParser] = null; @@ -6365,7 +6238,7 @@ var require_client_h1 = __commonJS({ return socket.destroyed; }, busy(request2) { - if (socket[kWriting] || socket[kReset] || socket[kBlocking] || socket[kIdleSocketValidation] === 1) { + if (socket[kWriting] || socket[kReset] || socket[kBlocking]) { return true; } if (request2) { @@ -6383,23 +6256,6 @@ var require_client_h1 = __commonJS({ } }; } - function clearIdleSocketValidation(socket) { - if (socket[kIdleSocketValidationTimeout]) { - clearImmediate(socket[kIdleSocketValidationTimeout]); - socket[kIdleSocketValidationTimeout] = null; - } - socket[kIdleSocketValidation] = 0; - } - function scheduleIdleSocketValidation(client, socket) { - socket[kIdleSocketValidation] = 1; - socket[kIdleSocketValidationTimeout] = setImmediate(() => { - socket[kIdleSocketValidationTimeout] = null; - socket[kIdleSocketValidation] = 2; - if (client[kSocket] === socket && !socket.destroyed) { - client[kResume](); - } - }); - } function resumeH1(client) { const socket = client[kSocket]; if (socket && !socket.destroyed) { @@ -6412,29 +6268,6 @@ var require_client_h1 = __commonJS({ socket.ref(); socket[kNoRef] = false; } - if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) { - if (socket[kIdleSocketValidation] === 0) { - scheduleIdleSocketValidation(client, socket); - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - if (socket[kIdleSocketValidation] === 1) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - } - if (client[kRunning] === 0) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - } if (client[kSize] === 0) { if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) { socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE); @@ -6465,16 +6298,8 @@ var require_client_h1 = __commonJS({ } body = bodyStream.stream; contentLength = bodyStream.length; - } else if (util.isBlobLike(body) && request2.contentType == null) { - const contentType = body.type; - if (contentType) { - const contentTypeValue = `${contentType}`; - if (!util.isValidHeaderValue(contentTypeValue)) { - util.errorRequest(client, request2, new InvalidArgumentError("invalid content-type header")); - return false; - } - headers.push("content-type", contentTypeValue); - } + } else if (util.isBlobLike(body) && request2.contentType == null && body.type) { + headers.push("content-type", body.type); } if (body && typeof body.read === "function") { body.read(0); @@ -6495,18 +6320,11 @@ var require_client_h1 = __commonJS({ process.emitWarning(new RequestContentLengthMismatchError()); } const socket = client[kSocket]; - clearIdleSocketValidation(socket); - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (request2.upgrade || request2.method === "CONNECT") { - util.destroy(socket, new InformationalError("aborted")); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - util.errorRequest(client, request2, error2 || new RequestAbortedError()); + util.errorRequest(client, request2, err || new RequestAbortedError()); util.destroy(body); util.destroy(socket, new InformationalError("aborted")); }; @@ -6862,7 +6680,6 @@ var require_client_h2 = __commonJS({ "node_modules/undici/lib/dispatcher/client-h2.js"(exports, module) { "use strict"; var assert = __require("node:assert"); - var { errorMonitor } = __require("node:events"); var { pipeline } = __require("node:stream"); var util = require_util(); var { @@ -6923,10 +6740,6 @@ var require_client_h2 = __commonJS({ } return result; } - function parseH2ResponseHeaders(headers) { - const { [HTTP2_HEADER_STATUS]: _statusCode, ...realHeaders } = headers; - return parseH2Headers(realHeaders); - } async function connectH2(client, socket) { client[kSocket] = socket; if (!h2ExperimentalWarned) { @@ -7090,22 +6903,16 @@ var require_client_h2 = __commonJS({ const { hostname, port } = client[kUrl]; headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ""}`; headers[HTTP2_HEADER_METHOD] = method; - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (method === "CONNECT" && stream != null) { - util.destroy(stream, error2 || new RequestAbortedError()); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - error2 = error2 || new RequestAbortedError(); - util.errorRequest(client, request2, error2); + err = err || new RequestAbortedError(); + util.errorRequest(client, request2, err); if (stream != null) { - util.destroy(stream, error2); + util.destroy(stream, err); } - util.destroy(body, error2); + util.destroy(body, err); client[kQueue][client[kRunningIdx]++] = null; client[kResume](); }; @@ -7120,42 +6927,18 @@ var require_client_h2 = __commonJS({ if (method === "CONNECT") { session.ref(); stream = session.request(headers, { endStream: false, signal }); - let upgradeResponseFinished = false; - const onResponse = (headers2) => { - upgradeResponseFinished = true; - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeResponse(Number(headers2[HTTP2_HEADER_STATUS]), headers2, parseH2ResponseHeaders); - }; - const onUpgradeError = (error2) => { - upgradeResponseFinished = true; - stream.off("response", onResponse); - request2.onUpgradeError(error2); - }; - const onReady = () => { - try { - request2.onUpgrade(null, null, stream); - } catch (error2) { - stream.off("response", onResponse); - abort(error2); - return; - } - if (request2.aborted) { - return; - } - stream.off("error", abort); - stream.once(errorMonitor, onUpgradeError); + if (stream.id && !stream.pending) { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; client[kQueue][client[kRunningIdx]++] = null; - }; - stream.once("response", onResponse); - stream.once("error", abort); - ++session[kOpenStreams]; - onReady(); + } else { + stream.once("ready", () => { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; + client[kQueue][client[kRunningIdx]++] = null; + }); + } stream.once("close", () => { - if (!upgradeResponseFinished && request2.completed) { - stream.off("response", onResponse); - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeError(new InformationalError(`HTTP/2: "stream error" received - code ${stream.rstCode}`)); - } session[kOpenStreams] -= 1; if (session[kOpenStreams] === 0) session.unref(); }); @@ -7716,10 +7499,9 @@ var require_client = __commonJS({ autoSelectFamilyAttemptTimeout, // h2 maxConcurrentStreams, - allowH2, - webSocket + allowH2 } = {}) { - super({ webSocket }); + super(); if (keepAlive !== void 0) { throw new InvalidArgumentError("unsupported keepAlive, use pipelining=0 instead"); } @@ -8225,8 +8007,8 @@ var require_pool_base = __commonJS({ var kRemoveClient = /* @__PURE__ */ Symbol("remove client"); var kStats = /* @__PURE__ */ Symbol("stats"); var PoolBase = class extends DispatcherBase { - constructor(opts) { - super(opts); + constructor() { + super(); this[kQueue] = new FixedQueue(); this[kClients] = []; this[kQueued] = 0; @@ -8397,6 +8179,7 @@ var require_pool = __commonJS({ allowH2, ...options } = {}) { + super(); if (connections != null && (!Number.isFinite(connections) || connections < 0)) { throw new InvalidArgumentError("invalid connections"); } @@ -8417,7 +8200,6 @@ var require_pool = __commonJS({ ...connect }); } - super(options); this[kInterceptors] = options.interceptors?.Pool && Array.isArray(options.interceptors.Pool) ? options.interceptors.Pool : []; this[kConnections] = connections || null; this[kUrl] = util.parseOrigin(origin); @@ -8617,6 +8399,7 @@ var require_agent = __commonJS({ } var Agent = class extends DispatcherBase { constructor({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { + super(); if (typeof factory !== "function") { throw new InvalidArgumentError("factory must be a function."); } @@ -8626,7 +8409,6 @@ var require_agent = __commonJS({ if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { throw new InvalidArgumentError("maxRedirections must be a positive number"); } - super(options); if (connect && typeof connect !== "function") { connect = { ...connect }; } @@ -9067,24 +8849,6 @@ var require_retry_handler = __commonJS({ const current = Date.now(); return new Date(retryAfter).getTime() - current; } - function validatePartialResponseContentLength(headers, range, statusCode, retryCount) { - const contentLength = headers["content-length"]; - if (contentLength == null) { - return null; - } - if (!Number.isFinite(range.start) || !Number.isFinite(range.end)) { - return null; - } - const length = Number(contentLength); - const expectedLength = range.end - range.start + 1; - if (!Number.isFinite(length) || length !== expectedLength) { - return new RequestRetryError("Content-Length mismatch", statusCode, { - headers, - data: { count: retryCount } - }); - } - return null; - } var RetryHandler = class _RetryHandler { constructor(opts, handlers) { const { retryOptions, ...dispatchOpts } = opts; @@ -9138,7 +8902,6 @@ var require_retry_handler = __commonJS({ this.end = null; this.etag = null; this.resume = null; - this.headersSent = false; this.handler.onConnect((reason) => { this.aborted = true; if (this.abort) { @@ -9148,17 +8911,6 @@ var require_retry_handler = __commonJS({ } }); } - 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(); @@ -9220,9 +8972,7 @@ var require_retry_handler = __commonJS({ const headers = parseHeaders(rawHeaders); this.retryCount += 1; if (statusCode >= 300) { - if (!this.headersSent && this.retryOpts.statusCodes.includes(statusCode) === false) { - this.headersSent = true; - this.checkpointResponseEnd(headers, resume); + if (this.retryOpts.statusCodes.includes(statusCode) === false) { return this.handler.onHeaders( statusCode, rawHeaders, @@ -9271,21 +9021,9 @@ var require_retry_handler = __commonJS({ ); return false; } - const contentLengthError = validatePartialResponseContentLength(headers, contentRange, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = contentRange; - 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; - } + assert(this.start === start, "content-range mismatch"); + assert(this.end == null || this.end === end, "content-range mismatch"); this.resume = resume; return true; } @@ -9293,7 +9031,6 @@ var require_retry_handler = __commonJS({ if (statusCode === 206) { const range = parseRangeHeader(headers["content-range"]); if (range == null) { - this.headersSent = true; return this.handler.onHeaders( statusCode, rawHeaders, @@ -9301,11 +9038,6 @@ var require_retry_handler = __commonJS({ statusMessage ); } - const contentLengthError = validatePartialResponseContentLength(headers, range, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = range; assert( start != null && Number.isFinite(start), @@ -9325,7 +9057,6 @@ var require_retry_handler = __commonJS({ "invalid content-length" ); this.resume = resume; - this.headersSent = true; this.etag = headers.etag != null ? headers.etag : null; if (this.etag != null && this.etag.startsWith("W/")) { this.etag = null; @@ -9353,7 +9084,7 @@ var require_retry_handler = __commonJS({ return this.handler.onComplete(rawTrailers); } onError(err) { - if (this.aborted || isDisturbed(this.opts.body) || this.headersSent && this.resume == null) { + if (this.aborted || isDisturbed(this.opts.body)) { return this.handler.onError(err); } if (this.retryCount - this.retryCountCheckpoint > 0) { @@ -16152,48 +15883,14 @@ var require_util6 = __commonJS({ for (let i = 0; i < path.length; ++i) { const code = path.charCodeAt(i); if (code < 32 || // exclude CTLs (0-31) - code > 126 || // exclude DEL and non-ascii + code === 127 || // DEL code === 59) { throw new Error("Invalid cookie path"); } } } - function isLetterOrDigit(code) { - return code >= 48 && code <= 57 || // 0-9 - code >= 65 && code <= 90 || // A-Z - code >= 97 && code <= 122; - } function validateCookieDomain(domain) { - if (domain === " ") { - return; - } - if (domain.length > 255) { - throw new Error("Invalid cookie domain"); - } - let labelLength = 0; - for (let i = 0; i < domain.length; ++i) { - const code = domain.charCodeAt(i); - if (code === 46) { - if (labelLength === 0) { - throw new Error("Invalid cookie domain"); - } - if (domain.charCodeAt(i - 1) === 45) { - throw new Error("Invalid cookie domain"); - } - labelLength = 0; - continue; - } - if (labelLength === 0 && !isLetterOrDigit(code)) { - throw new Error("Invalid cookie domain"); - } - if (!isLetterOrDigit(code) && code !== 45) { - throw new Error("Invalid cookie domain"); - } - if (++labelLength > 63) { - throw new Error("Invalid cookie domain"); - } - } - if (labelLength === 0 || domain.charCodeAt(domain.length - 1) === 45) { + if (domain.startsWith("-") || domain.endsWith(".") || domain.endsWith("-")) { throw new Error("Invalid cookie domain"); } } @@ -16276,11 +15973,7 @@ var require_util6 = __commonJS({ throw new Error("Invalid unparsed"); } const [key, ...value] = part.split("="); - const trimmedKey = key.trim(); - const joinedValue = value.join("="); - validateCookieName(trimmedKey); - validateCookieValue(joinedValue); - out.push(`${trimmedKey}=${joinedValue}`); + out.push(`${key.trim()}=${value.join("=")}`); } return out.join("; "); } @@ -16410,14 +16103,18 @@ var require_parse = __commonJS({ } else if (attributeNameLowercase === "httponly") { cookieAttributeList.httpOnly = true; } else if (attributeNameLowercase === "samesite") { + let enforcement = "Default"; const attributeValueLowercase = attributeValue.toLowerCase(); - if (attributeValueLowercase === "none") { - cookieAttributeList.sameSite = "None"; - } else if (attributeValueLowercase === "strict") { - cookieAttributeList.sameSite = "Strict"; - } else if (attributeValueLowercase === "lax") { - cookieAttributeList.sameSite = "Lax"; + if (attributeValueLowercase.includes("none")) { + enforcement = "None"; + } + if (attributeValueLowercase.includes("strict")) { + enforcement = "Strict"; + } + if (attributeValueLowercase.includes("lax")) { + enforcement = "Lax"; } + cookieAttributeList.sameSite = enforcement; } else { cookieAttributeList.unparsed ??= []; cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`); @@ -17239,7 +16936,7 @@ var require_connection = __commonJS({ const secProtocol = response.headersList.get("Sec-WebSocket-Protocol"); if (secProtocol !== null) { const requestProtocols = getDecodeSplit("sec-websocket-protocol", request2.headersList); - if (requestProtocols === null || !requestProtocols.includes(secProtocol)) { + if (!requestProtocols.includes(secProtocol)) { failWebsocketConnection(ws, "Protocol was not set in the opening handshake."); return; } @@ -17345,26 +17042,31 @@ var require_permessage_deflate = __commonJS({ var tail = Buffer.from([0, 0, 255, 255]); var kBuffer = /* @__PURE__ */ Symbol("kBuffer"); var kLength = /* @__PURE__ */ Symbol("kLength"); + var kDefaultMaxDecompressedSize = 4 * 1024 * 1024; var PerMessageDeflate = class { /** @type {import('node:zlib').InflateRaw} */ #inflate; #options = {}; - #maxPayloadSize = 0; + /** @type {number} */ + #maxDecompressedSize; + /** @type {boolean} */ + #aborted = false; + /** @type {Function|null} */ + #currentCallback = null; /** * @param {Map} extensions + * @param {{ maxDecompressedMessageSize?: number }} [options] */ - constructor(extensions, options) { + constructor(extensions, options = {}) { this.#options.serverNoContextTakeover = extensions.has("server_no_context_takeover"); this.#options.serverMaxWindowBits = extensions.get("server_max_window_bits"); - this.#maxPayloadSize = options.maxPayloadSize; + this.#maxDecompressedSize = options.maxDecompressedMessageSize ?? kDefaultMaxDecompressedSize; } - /** - * Decompress a compressed payload. - * @param {Buffer} chunk Compressed data - * @param {boolean} fin Final fragment flag - * @param {Function} callback Callback function - */ decompress(chunk, fin, callback) { + if (this.#aborted) { + callback(new MessageSizeExceededError()); + return; + } if (!this.#inflate) { let windowBits = Z_DEFAULT_WINDOWBITS; if (this.#options.serverMaxWindowBits) { @@ -17383,12 +17085,20 @@ var require_permessage_deflate = __commonJS({ this.#inflate[kBuffer] = []; this.#inflate[kLength] = 0; this.#inflate.on("data", (data) => { + if (this.#aborted) { + return; + } this.#inflate[kLength] += data.length; - if (this.#maxPayloadSize > 0 && this.#inflate[kLength] > this.#maxPayloadSize) { - callback(new MessageSizeExceededError()); + if (this.#inflate[kLength] > this.#maxDecompressedSize) { + this.#aborted = true; this.#inflate.removeAllListeners(); this.#inflate.destroy(); this.#inflate = null; + if (this.#currentCallback) { + const cb = this.#currentCallback; + this.#currentCallback = null; + cb(new MessageSizeExceededError()); + } return; } this.#inflate[kBuffer].push(data); @@ -17398,17 +17108,19 @@ var require_permessage_deflate = __commonJS({ callback(err); }); } + this.#currentCallback = callback; this.#inflate.write(chunk); if (fin) { this.#inflate.write(tail); } this.#inflate.flush(() => { - if (!this.#inflate) { + if (this.#aborted || !this.#inflate) { return; } const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]); this.#inflate[kBuffer].length = 0; this.#inflate[kLength] = 0; + this.#currentCallback = null; callback(null, full); }); } @@ -17439,14 +17151,8 @@ var require_receiver = __commonJS({ var { WebsocketFrameSend } = require_frame(); var { closeWebSocketConnection } = require_connection(); var { PerMessageDeflate } = require_permessage_deflate(); - var { MessageSizeExceededError } = require_errors(); - function failWebsocketConnectionWithCode(ws, code, reason) { - closeWebSocketConnection(ws, code, reason, Buffer.byteLength(reason)); - failWebsocketConnection(ws, reason); - } var ByteParser = class extends Writable { #buffers = []; - #fragmentsBytes = 0; #byteOffset = 0; #loop = false; #state = parserStates.INFO; @@ -17454,21 +17160,18 @@ var require_receiver = __commonJS({ #fragments = []; /** @type {Map} */ #extensions; - /** @type {number} */ - #maxFragments; - /** @type {number} */ - #maxPayloadSize; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {import('./websocket').WebSocket} ws * @param {Map|null} extensions - * @param {{ maxFragments?: number, maxPayloadSize?: number }} [options] + * @param {{ maxDecompressedMessageSize?: number }} [options] */ constructor(ws, extensions, options = {}) { super(); this.ws = ws; this.#extensions = extensions == null ? /* @__PURE__ */ new Map() : extensions; - this.#maxFragments = options.maxFragments ?? 0; - this.#maxPayloadSize = options.maxPayloadSize ?? 0; + this.#options = options; if (this.#extensions.has("permessage-deflate")) { this.#extensions.set("permessage-deflate", new PerMessageDeflate(extensions, options)); } @@ -17483,13 +17186,6 @@ var require_receiver = __commonJS({ this.#loop = true; this.run(callback); } - #validatePayloadLength() { - if (this.#maxPayloadSize > 0 && !isControlFrame(this.#info.opcode) && this.#info.payloadLength + this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, "Payload size exceeds maximum allowed size"); - return false; - } - return true; - } /** * Runs whenever a new chunk is received. * Callback is called whenever there are no more chunks buffering, @@ -17549,9 +17245,6 @@ var require_receiver = __commonJS({ if (payloadLength <= 125) { this.#info.payloadLength = payloadLength; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (payloadLength === 126) { this.#state = parserStates.PAYLOADLENGTH_16; } else if (payloadLength === 127) { @@ -17572,9 +17265,6 @@ var require_receiver = __commonJS({ const buffer = this.consume(2); this.#info.payloadLength = buffer.readUInt16BE(0); this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.PAYLOADLENGTH_64) { if (this.#byteOffset < 8) { return callback(); @@ -17588,9 +17278,6 @@ var require_receiver = __commonJS({ } this.#info.payloadLength = lower; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.READ_DATA) { if (this.#byteOffset < this.#info.payloadLength) { return callback(); @@ -17601,46 +17288,32 @@ var require_receiver = __commonJS({ this.#state = parserStates.INFO; } else { if (!this.#info.compressed) { - if (!this.writeFragments(body)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } + this.#fragments.push(body); if (!this.#info.fragmented && this.#info.fin) { - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); + const fullMessage = Buffer.concat(this.#fragments); + websocketMessageReceived(this.ws, this.#info.binaryType, fullMessage); + this.#fragments.length = 0; } this.#state = parserStates.INFO; } else { - this.#extensions.get("permessage-deflate").decompress( - body, - this.#info.fin, - (error2, data) => { - if (error2) { - const code = error2 instanceof MessageSizeExceededError ? 1009 : 1007; - failWebsocketConnectionWithCode(this.ws, code, error2.message); - return; - } - if (!this.writeFragments(data)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } - if (!this.#info.fin) { - this.#state = parserStates.INFO; - this.#loop = true; - this.run(callback); - return; - } - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); - this.#loop = true; + this.#extensions.get("permessage-deflate").decompress(body, this.#info.fin, (error2, data) => { + if (error2) { + failWebsocketConnection(this.ws, error2.message); + return; + } + this.#fragments.push(data); + if (!this.#info.fin) { this.#state = parserStates.INFO; + this.#loop = true; this.run(callback); + return; } - ); + websocketMessageReceived(this.ws, this.#info.binaryType, Buffer.concat(this.#fragments)); + this.#loop = true; + this.#state = parserStates.INFO; + this.#fragments.length = 0; + this.run(callback); + }); this.#loop = false; break; } @@ -17683,26 +17356,6 @@ var require_receiver = __commonJS({ this.#byteOffset -= n; return buffer; } - writeFragments(fragment) { - if (this.#maxFragments > 0 && this.#fragments.length === this.#maxFragments) { - failWebsocketConnectionWithCode(this.ws, 1008, "Too many message fragments"); - return false; - } - this.#fragmentsBytes += fragment.length; - this.#fragments.push(fragment); - return true; - } - consumeFragments() { - const fragments = this.#fragments; - if (fragments.length === 1) { - this.#fragmentsBytes = 0; - return fragments.shift(); - } - const output = Buffer.concat(fragments, this.#fragmentsBytes); - this.#fragments = []; - this.#fragmentsBytes = 0; - return output; - } parseCloseBody(data) { assert(data.length !== 1); let code; @@ -17914,6 +17567,8 @@ var require_websocket = __commonJS({ #extensions = ""; /** @type {SendQueue} */ #sendQueue; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {string} url * @param {string|string[]} protocols @@ -17957,6 +17612,9 @@ var require_websocket = __commonJS({ throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError"); } this[kWebSocketURL] = new URL(urlRecord.href); + this.#options = { + maxDecompressedMessageSize: options.maxDecompressedMessageSize + }; const client = environmentSettingsObject.settingsObject; this[kController] = establishWebSocketConnection( urlRecord, @@ -18140,13 +17798,7 @@ var require_websocket = __commonJS({ */ #onConnectionEstablished(response, parsedExtensions) { this[kResponse] = response; - const webSocketOptions = this[kController]?.dispatcher?.webSocketOptions; - const maxFragments = webSocketOptions?.maxFragments; - const maxPayloadSize = webSocketOptions?.maxPayloadSize; - const parser = new ByteParser(this, parsedExtensions, { - maxFragments, - maxPayloadSize - }); + const parser = new ByteParser(this, parsedExtensions, this.#options); parser.on("drain", onParserDrain); parser.on("error", onParserError.bind(this)); response.socket.ws = this; @@ -18221,6 +17873,19 @@ var require_websocket = __commonJS({ { key: "headers", converter: webidl.nullableConverter(webidl.converters.HeadersInit) + }, + { + key: "maxDecompressedMessageSize", + converter: webidl.nullableConverter((V) => { + V = webidl.converters["unsigned long long"](V); + if (V <= 0) { + throw webidl.errors.exception({ + header: "WebSocket constructor", + message: "maxDecompressedMessageSize must be greater than 0" + }); + } + return V; + }) } ]); webidl.converters["DOMString or sequence or WebSocketInit"] = function(V) { @@ -18299,40 +17964,6 @@ 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; - } - function isValidLastEventIdBytes(buffer, start) { - for (let i = start; i < buffer.length; i++) { - if (buffer[i] === 0) { - 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; - } var EventSourceStream = class extends Transform { /** * @type {eventSourceSettings} @@ -18352,13 +17983,10 @@ var require_eventsource_stream = __commonJS({ */ eventEndCheck = false; /** - * @type {Buffer[]} + * @type {Buffer} */ - chunks = []; - chunkIndex = 0; + buffer = null; pos = 0; - lineChunkIndex = 0; - linePos = 0; event = { data: void 0, event: void 0, @@ -18389,30 +18017,63 @@ var require_eventsource_stream = __commonJS({ callback(); return; } - this.chunks.push(chunk); + if (this.buffer) { + this.buffer = Buffer.concat([this.buffer, chunk]); + } else { + this.buffer = chunk; + } if (this.checkBOM) { - if (this.handleBOM()) { - callback(); - return; + 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; } } - while (this.hasCurrentByte()) { - const byte = this.currentByte(); + while (this.pos < this.buffer.length) { if (this.eventEndCheck) { if (this.crlfCheck) { - if (byte === LF) { + if (this.buffer[this.pos] === LF) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.crlfCheck = false; - this.consumeCurrentByte(); continue; } this.crlfCheck = false; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.consumeCurrentByte(); - if (this.hasPendingEvent()) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; + if (this.event.data !== void 0 || this.event.event || this.event.id || this.event.retry) { this.processEvent(this.event); } this.clearEvent(); @@ -18421,16 +18082,17 @@ var require_eventsource_stream = __commonJS({ this.eventEndCheck = false; continue; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.parseLine(this.readLine(), this.event); - this.consumeCurrentByte(); + this.parseLine(this.buffer.subarray(0, this.pos), this.event); + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.eventEndCheck = true; continue; } - this.advanceCursor(); + this.pos++; } callback(); } @@ -18446,42 +18108,43 @@ var require_eventsource_stream = __commonJS({ if (colonPosition === 0) { return; } - let fieldLength = line.length; - let valueStart = line.length; + let field = ""; + let value = ""; if (colonPosition !== -1) { - fieldLength = colonPosition; - valueStart = colonPosition + 1; + field = line.subarray(0, colonPosition).toString("utf8"); + let valueStart = colonPosition + 1; if (line[valueStart] === SPACE) { ++valueStart; } + value = line.subarray(valueStart).toString("utf8"); + } else { + field = line.toString("utf8"); + value = ""; } - if (isFieldName(line, fieldLength, DATA)) { - const value = line.toString("utf8", valueStart); - if (event.data === void 0) { - event.data = value; - } else { - event.data += ` + switch (field) { + case "data": + if (event[field] === void 0) { + event[field] = value; + } else { + event[field] += ` ${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; - } + } + 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; } } /** @@ -18506,120 +18169,12 @@ ${value}`; } } clearEvent() { - 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(); + this.event = { + data: void 0, + event: void 0, + id: void 0, + retry: void 0 + }; } }; module.exports = { diff --git a/.github/actions/javascript/bumpVersion/index.js b/.github/actions/javascript/bumpVersion/index.js index c2258fb0a82d..479e50a322da 100644 --- a/.github/actions/javascript/bumpVersion/index.js +++ b/.github/actions/javascript/bumpVersion/index.js @@ -2312,66 +2312,10 @@ var require_request = __commonJS({ return false; } } - /** - * @param {number|null} statusCode - * @param {Buffer[]|null} headers - * @param {import('node:stream').Duplex} socket - * @param {string} [statusText] - */ - onUpgrade(statusCode, headers, socket, statusText = "") { - this.onFinally(); + onUpgrade(statusCode, headers, socket) { assert(!this.aborted); assert(!this.completed); - 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(error2) { - assert(!this.aborted); - assert(this.completed); - if (channels.error.hasSubscribers) { - channels.error.publish({ request: this, error: error2 }); - } - } - /** - * @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: [] }); - } + return this[kHandler].onUpgrade(statusCode, headers, socket); } onComplete(trailers) { this.onFinally(); @@ -2438,11 +2382,7 @@ var require_request = __commonJS({ } else if (typeof val[i] === "object") { throw new InvalidArgumentError(`invalid ${key} header`); } else { - const str = `${val[i]}`; - if (!isValidHeaderValue(str)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } - arr.push(str); + arr.push(`${val[i]}`); } } val = arr; @@ -2454,9 +2394,6 @@ var require_request = __commonJS({ val = ""; } else { val = `${val}`; - if (!isValidHeaderValue(val)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } } if (headerName === "host") { if (request.host !== null) { @@ -2566,21 +2503,13 @@ var require_dispatcher_base = __commonJS({ var kOnDestroyed = /* @__PURE__ */ Symbol("onDestroyed"); var kOnClosed = /* @__PURE__ */ Symbol("onClosed"); var kInterceptedDispatch = /* @__PURE__ */ Symbol("Intercepted Dispatch"); - var kWebSocketOptions = /* @__PURE__ */ Symbol("webSocketOptions"); var DispatcherBase = class extends Dispatcher { - constructor(opts) { + constructor() { super(); this[kDestroyed] = false; this[kOnDestroyed] = null; this[kClosed] = false; this[kOnClosed] = []; - this[kWebSocketOptions] = opts?.webSocket ?? {}; - } - get webSocketOptions() { - return { - maxFragments: this[kWebSocketOptions].maxFragments ?? 131072, - maxPayloadSize: this[kWebSocketOptions].maxPayloadSize ?? 128 * 1024 * 1024 - }; } get destroyed() { return this[kDestroyed]; @@ -6187,7 +6116,6 @@ var require_client_h1 = __commonJS({ RequestContentLengthMismatchError, ResponseContentLengthMismatchError, RequestAbortedError, - InvalidArgumentError, HeadersTimeoutError, HeadersOverflowError, SocketError, @@ -6234,9 +6162,6 @@ var require_client_h1 = __commonJS({ var FastBuffer = Buffer[Symbol.species]; var addListener = util.addListener; var removeAllListeners = util.removeAllListeners; - var kIdleSocketValidation = /* @__PURE__ */ Symbol("kIdleSocketValidation"); - var kIdleSocketValidationTimeout = /* @__PURE__ */ Symbol("kIdleSocketValidationTimeout"); - var kSocketUsed = /* @__PURE__ */ Symbol("kSocketUsed"); var extractBody; async function lazyllhttp() { const llhttpWasmData = process.env.JEST_WORKER_ID ? require_llhttp_wasm() : void 0; @@ -6399,55 +6324,24 @@ var require_client_h1 = __commonJS({ currentBufferRef = null; } const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr; - if (ret !== constants3.ERROR.OK) { - const body = data.subarray(offset); - if (ret === constants3.ERROR.PAUSED_UPGRADE) { - this.onUpgrade(body); - } else if (ret === constants3.ERROR.PAUSED) { - this.paused = true; - socket.unshift(body); - } else { - throw this.createError(ret, body); + if (ret === constants3.ERROR.PAUSED_UPGRADE) { + this.onUpgrade(data.slice(offset)); + } else if (ret === constants3.ERROR.PAUSED) { + this.paused = true; + socket.unshift(data.slice(offset)); + } else if (ret !== constants3.ERROR.OK) { + const ptr = llhttp.llhttp_get_error_reason(this.ptr); + let message = ""; + if (ptr) { + const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); + message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; } + throw new HTTPParserError(message, constants3.ERROR[ret], data.slice(offset)); } } catch (err) { util.destroy(socket, err); } } - finish() { - assert(currentParser === null); - assert(this.ptr != null); - assert(!this.paused); - const { llhttp } = this; - let ret; - try { - currentParser = this; - ret = llhttp.llhttp_finish(this.ptr); - } finally { - currentParser = null; - } - if (ret === constants3.ERROR.OK) { - return null; - } - if (ret === constants3.ERROR.PAUSED || ret === constants3.ERROR.PAUSED_UPGRADE) { - this.paused = true; - return null; - } - return this.createError(ret, EMPTY_BUF); - } - createError(ret, data) { - const { llhttp, contentLength, bytesRead } = this; - if (contentLength && bytesRead !== parseInt(contentLength, 10)) { - return new ResponseContentLengthMismatchError(); - } - const ptr = llhttp.llhttp_get_error_reason(this.ptr); - let message = ""; - if (ptr) { - const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); - message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; - } - return new HTTPParserError(message, constants3.ERROR[ret], data); - } destroy() { assert(this.ptr != null); assert(currentParser == null); @@ -6467,10 +6361,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request = client[kQueue][client[kRunningIdx]]; if (!request) { return -1; @@ -6514,7 +6404,7 @@ var require_client_h1 = __commonJS({ } } onUpgrade(head) { - const { upgrade, client, socket, headers, statusCode, statusText } = this; + const { upgrade, client, socket, headers, statusCode } = this; assert(upgrade); assert(client[kSocket] === socket); assert(!socket.destroyed); @@ -6539,10 +6429,9 @@ var require_client_h1 = __commonJS({ client[kQueue][client[kRunningIdx]++] = null; client.emit("disconnect", client[kUrl], [client], new InformationalError("upgrade")); try { - request.onUpgrade(statusCode, headers, socket, statusText); - } catch (error2) { - util.errorRequest(client, request, error2); - util.destroy(socket, error2); + request.onUpgrade(statusCode, headers, socket); + } catch (err) { + util.destroy(socket, err); } client[kResume](); } @@ -6551,10 +6440,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request = client[kQueue][client[kRunningIdx]]; if (!request) { return -1; @@ -6680,7 +6565,6 @@ var require_client_h1 = __commonJS({ } request.onComplete(headers); client[kQueue][client[kRunningIdx]++] = null; - socket[kSocketUsed] = true; if (socket[kWriting]) { assert(client[kRunning] === 0); util.destroy(socket, new InformationalError("reset")); @@ -6724,19 +6608,12 @@ var require_client_h1 = __commonJS({ socket[kWriting] = false; socket[kReset] = false; socket[kBlocking] = false; - socket[kIdleSocketValidation] = 0; - socket[kIdleSocketValidationTimeout] = null; - socket[kSocketUsed] = false; socket[kParser] = new Parser(client, socket, llhttpInstance); addListener(socket, "error", function(err) { assert(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID"); const parser = this[kParser]; if (err.code === "ECONNRESET" && parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - this[kError] = parserErr; - this[kClient][kOnError](parserErr); - } + parser.onMessageComplete(); return; } this[kError] = err; @@ -6751,10 +6628,7 @@ var require_client_h1 = __commonJS({ addListener(socket, "end", function() { const parser = this[kParser]; if (parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - util.destroy(this, parserErr); - } + parser.onMessageComplete(); return; } util.destroy(this, new SocketError("other side closed", util.getSocketInfo(this))); @@ -6762,10 +6636,9 @@ var require_client_h1 = __commonJS({ addListener(socket, "close", function() { const client2 = this[kClient]; const parser = this[kParser]; - clearIdleSocketValidation(this); if (parser) { if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { - this[kError] = parser.finish() || this[kError]; + parser.onMessageComplete(); } this[kParser].destroy(); this[kParser] = null; @@ -6814,7 +6687,7 @@ var require_client_h1 = __commonJS({ return socket.destroyed; }, busy(request) { - if (socket[kWriting] || socket[kReset] || socket[kBlocking] || socket[kIdleSocketValidation] === 1) { + if (socket[kWriting] || socket[kReset] || socket[kBlocking]) { return true; } if (request) { @@ -6832,23 +6705,6 @@ var require_client_h1 = __commonJS({ } }; } - function clearIdleSocketValidation(socket) { - if (socket[kIdleSocketValidationTimeout]) { - clearImmediate(socket[kIdleSocketValidationTimeout]); - socket[kIdleSocketValidationTimeout] = null; - } - socket[kIdleSocketValidation] = 0; - } - function scheduleIdleSocketValidation(client, socket) { - socket[kIdleSocketValidation] = 1; - socket[kIdleSocketValidationTimeout] = setImmediate(() => { - socket[kIdleSocketValidationTimeout] = null; - socket[kIdleSocketValidation] = 2; - if (client[kSocket] === socket && !socket.destroyed) { - client[kResume](); - } - }); - } function resumeH1(client) { const socket = client[kSocket]; if (socket && !socket.destroyed) { @@ -6861,29 +6717,6 @@ var require_client_h1 = __commonJS({ socket.ref(); socket[kNoRef] = false; } - if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) { - if (socket[kIdleSocketValidation] === 0) { - scheduleIdleSocketValidation(client, socket); - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - if (socket[kIdleSocketValidation] === 1) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - } - if (client[kRunning] === 0) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - } if (client[kSize] === 0) { if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) { socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE); @@ -6914,16 +6747,8 @@ var require_client_h1 = __commonJS({ } body = bodyStream.stream; contentLength = bodyStream.length; - } else if (util.isBlobLike(body) && request.contentType == null) { - const contentType = body.type; - if (contentType) { - const contentTypeValue = `${contentType}`; - if (!util.isValidHeaderValue(contentTypeValue)) { - util.errorRequest(client, request, new InvalidArgumentError("invalid content-type header")); - return false; - } - headers.push("content-type", contentTypeValue); - } + } else if (util.isBlobLike(body) && request.contentType == null && body.type) { + headers.push("content-type", body.type); } if (body && typeof body.read === "function") { body.read(0); @@ -6944,18 +6769,11 @@ var require_client_h1 = __commonJS({ process.emitWarning(new RequestContentLengthMismatchError()); } const socket = client[kSocket]; - clearIdleSocketValidation(socket); - const abort = (error2) => { - if (request.aborted) { + const abort = (err) => { + if (request.aborted || request.completed) { return; } - if (request.completed) { - if (request.upgrade || request.method === "CONNECT") { - util.destroy(socket, new InformationalError("aborted")); - } - return; - } - util.errorRequest(client, request, error2 || new RequestAbortedError()); + util.errorRequest(client, request, err || new RequestAbortedError()); util.destroy(body); util.destroy(socket, new InformationalError("aborted")); }; @@ -7311,7 +7129,6 @@ var require_client_h2 = __commonJS({ "node_modules/undici/lib/dispatcher/client-h2.js"(exports, module) { "use strict"; var assert = __require("node:assert"); - var { errorMonitor } = __require("node:events"); var { pipeline } = __require("node:stream"); var util = require_util(); var { @@ -7372,10 +7189,6 @@ var require_client_h2 = __commonJS({ } return result; } - function parseH2ResponseHeaders(headers) { - const { [HTTP2_HEADER_STATUS]: _statusCode, ...realHeaders } = headers; - return parseH2Headers(realHeaders); - } async function connectH2(client, socket) { client[kSocket] = socket; if (!h2ExperimentalWarned) { @@ -7539,22 +7352,16 @@ var require_client_h2 = __commonJS({ const { hostname, port } = client[kUrl]; headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ""}`; headers[HTTP2_HEADER_METHOD] = method; - const abort = (error2) => { - if (request.aborted) { + const abort = (err) => { + if (request.aborted || request.completed) { return; } - if (request.completed) { - if (method === "CONNECT" && stream != null) { - util.destroy(stream, error2 || new RequestAbortedError()); - } - return; - } - error2 = error2 || new RequestAbortedError(); - util.errorRequest(client, request, error2); + err = err || new RequestAbortedError(); + util.errorRequest(client, request, err); if (stream != null) { - util.destroy(stream, error2); + util.destroy(stream, err); } - util.destroy(body, error2); + util.destroy(body, err); client[kQueue][client[kRunningIdx]++] = null; client[kResume](); }; @@ -7569,42 +7376,18 @@ var require_client_h2 = __commonJS({ if (method === "CONNECT") { session.ref(); stream = session.request(headers, { endStream: false, signal }); - let upgradeResponseFinished = false; - const onResponse = (headers2) => { - upgradeResponseFinished = true; - stream.off(errorMonitor, onUpgradeError); - request.onUpgradeResponse(Number(headers2[HTTP2_HEADER_STATUS]), headers2, parseH2ResponseHeaders); - }; - const onUpgradeError = (error2) => { - upgradeResponseFinished = true; - stream.off("response", onResponse); - request.onUpgradeError(error2); - }; - const onReady = () => { - try { - request.onUpgrade(null, null, stream); - } catch (error2) { - stream.off("response", onResponse); - abort(error2); - return; - } - if (request.aborted) { - return; - } - stream.off("error", abort); - stream.once(errorMonitor, onUpgradeError); + if (stream.id && !stream.pending) { + request.onUpgrade(null, null, stream); + ++session[kOpenStreams]; client[kQueue][client[kRunningIdx]++] = null; - }; - stream.once("response", onResponse); - stream.once("error", abort); - ++session[kOpenStreams]; - onReady(); + } else { + stream.once("ready", () => { + request.onUpgrade(null, null, stream); + ++session[kOpenStreams]; + client[kQueue][client[kRunningIdx]++] = null; + }); + } 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(); }); @@ -8165,10 +7948,9 @@ var require_client = __commonJS({ autoSelectFamilyAttemptTimeout, // h2 maxConcurrentStreams, - allowH2, - webSocket + allowH2 } = {}) { - super({ webSocket }); + super(); if (keepAlive !== void 0) { throw new InvalidArgumentError("unsupported keepAlive, use pipelining=0 instead"); } @@ -8674,8 +8456,8 @@ var require_pool_base = __commonJS({ var kRemoveClient = /* @__PURE__ */ Symbol("remove client"); var kStats = /* @__PURE__ */ Symbol("stats"); var PoolBase = class extends DispatcherBase { - constructor(opts) { - super(opts); + constructor() { + super(); this[kQueue] = new FixedQueue(); this[kClients] = []; this[kQueued] = 0; @@ -8846,6 +8628,7 @@ var require_pool = __commonJS({ allowH2, ...options } = {}) { + super(); if (connections != null && (!Number.isFinite(connections) || connections < 0)) { throw new InvalidArgumentError("invalid connections"); } @@ -8866,7 +8649,6 @@ var require_pool = __commonJS({ ...connect }); } - super(options); this[kInterceptors] = options.interceptors?.Pool && Array.isArray(options.interceptors.Pool) ? options.interceptors.Pool : []; this[kConnections] = connections || null; this[kUrl] = util.parseOrigin(origin); @@ -9066,6 +8848,7 @@ var require_agent = __commonJS({ } var Agent = class extends DispatcherBase { constructor({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { + super(); if (typeof factory !== "function") { throw new InvalidArgumentError("factory must be a function."); } @@ -9075,7 +8858,6 @@ var require_agent = __commonJS({ if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { throw new InvalidArgumentError("maxRedirections must be a positive number"); } - super(options); if (connect && typeof connect !== "function") { connect = { ...connect }; } @@ -9516,24 +9298,6 @@ var require_retry_handler = __commonJS({ const current = Date.now(); return new Date(retryAfter).getTime() - current; } - function validatePartialResponseContentLength(headers, range, statusCode, retryCount) { - const contentLength = headers["content-length"]; - if (contentLength == null) { - return null; - } - if (!Number.isFinite(range.start) || !Number.isFinite(range.end)) { - return null; - } - const length = Number(contentLength); - const expectedLength = range.end - range.start + 1; - if (!Number.isFinite(length) || length !== expectedLength) { - return new RequestRetryError("Content-Length mismatch", statusCode, { - headers, - data: { count: retryCount } - }); - } - return null; - } var RetryHandler = class _RetryHandler { constructor(opts, handlers) { const { retryOptions, ...dispatchOpts } = opts; @@ -9587,7 +9351,6 @@ var require_retry_handler = __commonJS({ this.end = null; this.etag = null; this.resume = null; - this.headersSent = false; this.handler.onConnect((reason) => { this.aborted = true; if (this.abort) { @@ -9597,17 +9360,6 @@ var require_retry_handler = __commonJS({ } }); } - 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(); @@ -9669,9 +9421,7 @@ var require_retry_handler = __commonJS({ const headers = parseHeaders(rawHeaders); this.retryCount += 1; if (statusCode >= 300) { - if (!this.headersSent && this.retryOpts.statusCodes.includes(statusCode) === false) { - this.headersSent = true; - this.checkpointResponseEnd(headers, resume); + if (this.retryOpts.statusCodes.includes(statusCode) === false) { return this.handler.onHeaders( statusCode, rawHeaders, @@ -9720,21 +9470,9 @@ var require_retry_handler = __commonJS({ ); return false; } - const contentLengthError = validatePartialResponseContentLength(headers, contentRange, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = contentRange; - 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; - } + assert(this.start === start, "content-range mismatch"); + assert(this.end == null || this.end === end, "content-range mismatch"); this.resume = resume; return true; } @@ -9742,7 +9480,6 @@ var require_retry_handler = __commonJS({ if (statusCode === 206) { const range = parseRangeHeader(headers["content-range"]); if (range == null) { - this.headersSent = true; return this.handler.onHeaders( statusCode, rawHeaders, @@ -9750,11 +9487,6 @@ var require_retry_handler = __commonJS({ statusMessage ); } - const contentLengthError = validatePartialResponseContentLength(headers, range, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = range; assert( start != null && Number.isFinite(start), @@ -9774,7 +9506,6 @@ var require_retry_handler = __commonJS({ "invalid content-length" ); this.resume = resume; - this.headersSent = true; this.etag = headers.etag != null ? headers.etag : null; if (this.etag != null && this.etag.startsWith("W/")) { this.etag = null; @@ -9802,7 +9533,7 @@ var require_retry_handler = __commonJS({ return this.handler.onComplete(rawTrailers); } onError(err) { - if (this.aborted || isDisturbed(this.opts.body) || this.headersSent && this.resume == null) { + if (this.aborted || isDisturbed(this.opts.body)) { return this.handler.onError(err); } if (this.retryCount - this.retryCountCheckpoint > 0) { @@ -16601,48 +16332,14 @@ var require_util6 = __commonJS({ for (let i = 0; i < path2.length; ++i) { const code = path2.charCodeAt(i); if (code < 32 || // exclude CTLs (0-31) - code > 126 || // exclude DEL and non-ascii + code === 127 || // DEL code === 59) { throw new Error("Invalid cookie path"); } } } - function isLetterOrDigit(code) { - return code >= 48 && code <= 57 || // 0-9 - code >= 65 && code <= 90 || // A-Z - code >= 97 && code <= 122; - } function validateCookieDomain(domain) { - if (domain === " ") { - return; - } - if (domain.length > 255) { - throw new Error("Invalid cookie domain"); - } - let labelLength = 0; - for (let i = 0; i < domain.length; ++i) { - const code = domain.charCodeAt(i); - if (code === 46) { - if (labelLength === 0) { - throw new Error("Invalid cookie domain"); - } - if (domain.charCodeAt(i - 1) === 45) { - throw new Error("Invalid cookie domain"); - } - labelLength = 0; - continue; - } - if (labelLength === 0 && !isLetterOrDigit(code)) { - throw new Error("Invalid cookie domain"); - } - if (!isLetterOrDigit(code) && code !== 45) { - throw new Error("Invalid cookie domain"); - } - if (++labelLength > 63) { - throw new Error("Invalid cookie domain"); - } - } - if (labelLength === 0 || domain.charCodeAt(domain.length - 1) === 45) { + if (domain.startsWith("-") || domain.endsWith(".") || domain.endsWith("-")) { throw new Error("Invalid cookie domain"); } } @@ -16725,11 +16422,7 @@ var require_util6 = __commonJS({ throw new Error("Invalid unparsed"); } const [key, ...value] = part.split("="); - const trimmedKey = key.trim(); - const joinedValue = value.join("="); - validateCookieName(trimmedKey); - validateCookieValue(joinedValue); - out.push(`${trimmedKey}=${joinedValue}`); + out.push(`${key.trim()}=${value.join("=")}`); } return out.join("; "); } @@ -16859,14 +16552,18 @@ var require_parse2 = __commonJS({ } else if (attributeNameLowercase === "httponly") { cookieAttributeList.httpOnly = true; } else if (attributeNameLowercase === "samesite") { + let enforcement = "Default"; const attributeValueLowercase = attributeValue.toLowerCase(); - if (attributeValueLowercase === "none") { - cookieAttributeList.sameSite = "None"; - } else if (attributeValueLowercase === "strict") { - cookieAttributeList.sameSite = "Strict"; - } else if (attributeValueLowercase === "lax") { - cookieAttributeList.sameSite = "Lax"; + if (attributeValueLowercase.includes("none")) { + enforcement = "None"; + } + if (attributeValueLowercase.includes("strict")) { + enforcement = "Strict"; + } + if (attributeValueLowercase.includes("lax")) { + enforcement = "Lax"; } + cookieAttributeList.sameSite = enforcement; } else { cookieAttributeList.unparsed ??= []; cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`); @@ -17688,7 +17385,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 === null || !requestProtocols.includes(secProtocol)) { + if (!requestProtocols.includes(secProtocol)) { failWebsocketConnection(ws, "Protocol was not set in the opening handshake."); return; } @@ -17794,26 +17491,31 @@ var require_permessage_deflate = __commonJS({ var tail = Buffer.from([0, 0, 255, 255]); var kBuffer = /* @__PURE__ */ Symbol("kBuffer"); var kLength = /* @__PURE__ */ Symbol("kLength"); + var kDefaultMaxDecompressedSize = 4 * 1024 * 1024; var PerMessageDeflate = class { /** @type {import('node:zlib').InflateRaw} */ #inflate; #options = {}; - #maxPayloadSize = 0; + /** @type {number} */ + #maxDecompressedSize; + /** @type {boolean} */ + #aborted = false; + /** @type {Function|null} */ + #currentCallback = null; /** * @param {Map} extensions + * @param {{ maxDecompressedMessageSize?: number }} [options] */ - constructor(extensions, options) { + constructor(extensions, options = {}) { this.#options.serverNoContextTakeover = extensions.has("server_no_context_takeover"); this.#options.serverMaxWindowBits = extensions.get("server_max_window_bits"); - this.#maxPayloadSize = options.maxPayloadSize; + this.#maxDecompressedSize = options.maxDecompressedMessageSize ?? kDefaultMaxDecompressedSize; } - /** - * Decompress a compressed payload. - * @param {Buffer} chunk Compressed data - * @param {boolean} fin Final fragment flag - * @param {Function} callback Callback function - */ decompress(chunk, fin, callback) { + if (this.#aborted) { + callback(new MessageSizeExceededError()); + return; + } if (!this.#inflate) { let windowBits = Z_DEFAULT_WINDOWBITS; if (this.#options.serverMaxWindowBits) { @@ -17832,12 +17534,20 @@ var require_permessage_deflate = __commonJS({ this.#inflate[kBuffer] = []; this.#inflate[kLength] = 0; this.#inflate.on("data", (data) => { + if (this.#aborted) { + return; + } this.#inflate[kLength] += data.length; - if (this.#maxPayloadSize > 0 && this.#inflate[kLength] > this.#maxPayloadSize) { - callback(new MessageSizeExceededError()); + if (this.#inflate[kLength] > this.#maxDecompressedSize) { + this.#aborted = true; this.#inflate.removeAllListeners(); this.#inflate.destroy(); this.#inflate = null; + if (this.#currentCallback) { + const cb = this.#currentCallback; + this.#currentCallback = null; + cb(new MessageSizeExceededError()); + } return; } this.#inflate[kBuffer].push(data); @@ -17847,17 +17557,19 @@ var require_permessage_deflate = __commonJS({ callback(err); }); } + this.#currentCallback = callback; this.#inflate.write(chunk); if (fin) { this.#inflate.write(tail); } this.#inflate.flush(() => { - if (!this.#inflate) { + if (this.#aborted || !this.#inflate) { return; } const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]); this.#inflate[kBuffer].length = 0; this.#inflate[kLength] = 0; + this.#currentCallback = null; callback(null, full); }); } @@ -17888,14 +17600,8 @@ var require_receiver = __commonJS({ var { WebsocketFrameSend } = require_frame(); var { closeWebSocketConnection } = require_connection(); var { PerMessageDeflate } = require_permessage_deflate(); - var { MessageSizeExceededError } = require_errors(); - function failWebsocketConnectionWithCode(ws, code, reason) { - closeWebSocketConnection(ws, code, reason, Buffer.byteLength(reason)); - failWebsocketConnection(ws, reason); - } var ByteParser = class extends Writable { #buffers = []; - #fragmentsBytes = 0; #byteOffset = 0; #loop = false; #state = parserStates.INFO; @@ -17903,21 +17609,18 @@ var require_receiver = __commonJS({ #fragments = []; /** @type {Map} */ #extensions; - /** @type {number} */ - #maxFragments; - /** @type {number} */ - #maxPayloadSize; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {import('./websocket').WebSocket} ws * @param {Map|null} extensions - * @param {{ maxFragments?: number, maxPayloadSize?: number }} [options] + * @param {{ maxDecompressedMessageSize?: number }} [options] */ constructor(ws, extensions, options = {}) { super(); this.ws = ws; this.#extensions = extensions == null ? /* @__PURE__ */ new Map() : extensions; - this.#maxFragments = options.maxFragments ?? 0; - this.#maxPayloadSize = options.maxPayloadSize ?? 0; + this.#options = options; if (this.#extensions.has("permessage-deflate")) { this.#extensions.set("permessage-deflate", new PerMessageDeflate(extensions, options)); } @@ -17932,13 +17635,6 @@ var require_receiver = __commonJS({ this.#loop = true; this.run(callback); } - #validatePayloadLength() { - if (this.#maxPayloadSize > 0 && !isControlFrame(this.#info.opcode) && this.#info.payloadLength + this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, "Payload size exceeds maximum allowed size"); - return false; - } - return true; - } /** * Runs whenever a new chunk is received. * Callback is called whenever there are no more chunks buffering, @@ -17998,9 +17694,6 @@ var require_receiver = __commonJS({ if (payloadLength <= 125) { this.#info.payloadLength = payloadLength; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (payloadLength === 126) { this.#state = parserStates.PAYLOADLENGTH_16; } else if (payloadLength === 127) { @@ -18021,9 +17714,6 @@ var require_receiver = __commonJS({ const buffer = this.consume(2); this.#info.payloadLength = buffer.readUInt16BE(0); this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.PAYLOADLENGTH_64) { if (this.#byteOffset < 8) { return callback(); @@ -18037,9 +17727,6 @@ var require_receiver = __commonJS({ } this.#info.payloadLength = lower; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.READ_DATA) { if (this.#byteOffset < this.#info.payloadLength) { return callback(); @@ -18050,46 +17737,32 @@ var require_receiver = __commonJS({ this.#state = parserStates.INFO; } else { if (!this.#info.compressed) { - if (!this.writeFragments(body)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } + this.#fragments.push(body); if (!this.#info.fragmented && this.#info.fin) { - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); + const fullMessage = Buffer.concat(this.#fragments); + websocketMessageReceived(this.ws, this.#info.binaryType, fullMessage); + this.#fragments.length = 0; } this.#state = parserStates.INFO; } else { - this.#extensions.get("permessage-deflate").decompress( - body, - this.#info.fin, - (error2, data) => { - if (error2) { - const code = error2 instanceof MessageSizeExceededError ? 1009 : 1007; - failWebsocketConnectionWithCode(this.ws, code, error2.message); - return; - } - if (!this.writeFragments(data)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } - if (!this.#info.fin) { - this.#state = parserStates.INFO; - this.#loop = true; - this.run(callback); - return; - } - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); - this.#loop = true; + this.#extensions.get("permessage-deflate").decompress(body, this.#info.fin, (error2, data) => { + if (error2) { + failWebsocketConnection(this.ws, error2.message); + return; + } + this.#fragments.push(data); + if (!this.#info.fin) { this.#state = parserStates.INFO; + this.#loop = true; this.run(callback); + return; } - ); + websocketMessageReceived(this.ws, this.#info.binaryType, Buffer.concat(this.#fragments)); + this.#loop = true; + this.#state = parserStates.INFO; + this.#fragments.length = 0; + this.run(callback); + }); this.#loop = false; break; } @@ -18132,26 +17805,6 @@ var require_receiver = __commonJS({ this.#byteOffset -= n; return buffer; } - writeFragments(fragment) { - if (this.#maxFragments > 0 && this.#fragments.length === this.#maxFragments) { - failWebsocketConnectionWithCode(this.ws, 1008, "Too many message fragments"); - return false; - } - this.#fragmentsBytes += fragment.length; - this.#fragments.push(fragment); - return true; - } - consumeFragments() { - const fragments = this.#fragments; - if (fragments.length === 1) { - this.#fragmentsBytes = 0; - return fragments.shift(); - } - const output = Buffer.concat(fragments, this.#fragmentsBytes); - this.#fragments = []; - this.#fragmentsBytes = 0; - return output; - } parseCloseBody(data) { assert(data.length !== 1); let code; @@ -18363,6 +18016,8 @@ var require_websocket = __commonJS({ #extensions = ""; /** @type {SendQueue} */ #sendQueue; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {string} url * @param {string|string[]} protocols @@ -18406,6 +18061,9 @@ var require_websocket = __commonJS({ throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError"); } this[kWebSocketURL] = new URL(urlRecord.href); + this.#options = { + maxDecompressedMessageSize: options.maxDecompressedMessageSize + }; const client = environmentSettingsObject.settingsObject; this[kController] = establishWebSocketConnection( urlRecord, @@ -18589,13 +18247,7 @@ var require_websocket = __commonJS({ */ #onConnectionEstablished(response, parsedExtensions) { this[kResponse] = response; - const webSocketOptions = this[kController]?.dispatcher?.webSocketOptions; - const maxFragments = webSocketOptions?.maxFragments; - const maxPayloadSize = webSocketOptions?.maxPayloadSize; - const parser = new ByteParser(this, parsedExtensions, { - maxFragments, - maxPayloadSize - }); + const parser = new ByteParser(this, parsedExtensions, this.#options); parser.on("drain", onParserDrain); parser.on("error", onParserError.bind(this)); response.socket.ws = this; @@ -18670,6 +18322,19 @@ var require_websocket = __commonJS({ { key: "headers", converter: webidl.nullableConverter(webidl.converters.HeadersInit) + }, + { + key: "maxDecompressedMessageSize", + converter: webidl.nullableConverter((V) => { + V = webidl.converters["unsigned long long"](V); + if (V <= 0) { + throw webidl.errors.exception({ + header: "WebSocket constructor", + message: "maxDecompressedMessageSize must be greater than 0" + }); + } + return V; + }) } ]); webidl.converters["DOMString or sequence or WebSocketInit"] = function(V) { @@ -18748,40 +18413,6 @@ 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; - } - function isValidLastEventIdBytes(buffer, start) { - for (let i = start; i < buffer.length; i++) { - if (buffer[i] === 0) { - 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; - } var EventSourceStream = class extends Transform { /** * @type {eventSourceSettings} @@ -18801,13 +18432,10 @@ var require_eventsource_stream = __commonJS({ */ eventEndCheck = false; /** - * @type {Buffer[]} + * @type {Buffer} */ - chunks = []; - chunkIndex = 0; + buffer = null; pos = 0; - lineChunkIndex = 0; - linePos = 0; event = { data: void 0, event: void 0, @@ -18838,30 +18466,63 @@ var require_eventsource_stream = __commonJS({ callback(); return; } - this.chunks.push(chunk); + if (this.buffer) { + this.buffer = Buffer.concat([this.buffer, chunk]); + } else { + this.buffer = chunk; + } if (this.checkBOM) { - if (this.handleBOM()) { - callback(); - return; + 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; } } - while (this.hasCurrentByte()) { - const byte = this.currentByte(); + while (this.pos < this.buffer.length) { if (this.eventEndCheck) { if (this.crlfCheck) { - if (byte === LF) { + if (this.buffer[this.pos] === LF) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.crlfCheck = false; - this.consumeCurrentByte(); continue; } this.crlfCheck = false; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.consumeCurrentByte(); - if (this.hasPendingEvent()) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; + if (this.event.data !== void 0 || this.event.event || this.event.id || this.event.retry) { this.processEvent(this.event); } this.clearEvent(); @@ -18870,16 +18531,17 @@ var require_eventsource_stream = __commonJS({ this.eventEndCheck = false; continue; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.parseLine(this.readLine(), this.event); - this.consumeCurrentByte(); + this.parseLine(this.buffer.subarray(0, this.pos), this.event); + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.eventEndCheck = true; continue; } - this.advanceCursor(); + this.pos++; } callback(); } @@ -18895,42 +18557,43 @@ var require_eventsource_stream = __commonJS({ if (colonPosition === 0) { return; } - let fieldLength = line.length; - let valueStart = line.length; + let field = ""; + let value = ""; if (colonPosition !== -1) { - fieldLength = colonPosition; - valueStart = colonPosition + 1; + field = line.subarray(0, colonPosition).toString("utf8"); + let valueStart = colonPosition + 1; if (line[valueStart] === SPACE) { ++valueStart; } + value = line.subarray(valueStart).toString("utf8"); + } else { + field = line.toString("utf8"); + value = ""; } - if (isFieldName(line, fieldLength, DATA)) { - const value = line.toString("utf8", valueStart); - if (event.data === void 0) { - event.data = value; - } else { - event.data += ` + switch (field) { + case "data": + if (event[field] === void 0) { + event[field] = value; + } else { + event[field] += ` ${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; - } + } + 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; } } /** @@ -18955,120 +18618,12 @@ ${value}`; } } clearEvent() { - 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(); + this.event = { + data: void 0, + event: void 0, + id: void 0, + retry: void 0 + }; } }; module.exports = { diff --git a/.github/actions/javascript/checkAndroidStatus/index.js b/.github/actions/javascript/checkAndroidStatus/index.js index de9e0e53ebc4..cf13138d08ce 100644 --- a/.github/actions/javascript/checkAndroidStatus/index.js +++ b/.github/actions/javascript/checkAndroidStatus/index.js @@ -1875,66 +1875,10 @@ var require_request = __commonJS({ return false; } } - /** - * @param {number|null} statusCode - * @param {Buffer[]|null} headers - * @param {import('node:stream').Duplex} socket - * @param {string} [statusText] - */ - onUpgrade(statusCode, headers, socket, statusText = "") { - this.onFinally(); + onUpgrade(statusCode, headers, socket) { assert(!this.aborted); assert(!this.completed); - 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(error2) { - assert(!this.aborted); - assert(this.completed); - if (channels.error.hasSubscribers) { - channels.error.publish({ request: this, error: error2 }); - } - } - /** - * @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: [] }); - } + return this[kHandler].onUpgrade(statusCode, headers, socket); } onComplete(trailers) { this.onFinally(); @@ -2001,11 +1945,7 @@ var require_request = __commonJS({ } else if (typeof val[i2] === "object") { throw new InvalidArgumentError(`invalid ${key} header`); } else { - const str = `${val[i2]}`; - if (!isValidHeaderValue(str)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } - arr.push(str); + arr.push(`${val[i2]}`); } } val = arr; @@ -2017,9 +1957,6 @@ var require_request = __commonJS({ val = ""; } else { val = `${val}`; - if (!isValidHeaderValue(val)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } } if (headerName === "host") { if (request2.host !== null) { @@ -2129,21 +2066,13 @@ var require_dispatcher_base = __commonJS({ var kOnDestroyed = /* @__PURE__ */ Symbol("onDestroyed"); var kOnClosed = /* @__PURE__ */ Symbol("onClosed"); var kInterceptedDispatch = /* @__PURE__ */ Symbol("Intercepted Dispatch"); - var kWebSocketOptions = /* @__PURE__ */ Symbol("webSocketOptions"); var DispatcherBase = class extends Dispatcher { - constructor(opts) { + constructor() { super(); this[kDestroyed] = false; this[kOnDestroyed] = null; this[kClosed] = false; this[kOnClosed] = []; - this[kWebSocketOptions] = opts?.webSocket ?? {}; - } - get webSocketOptions() { - return { - maxFragments: this[kWebSocketOptions].maxFragments ?? 131072, - maxPayloadSize: this[kWebSocketOptions].maxPayloadSize ?? 128 * 1024 * 1024 - }; } get destroyed() { return this[kDestroyed]; @@ -5750,7 +5679,6 @@ var require_client_h1 = __commonJS({ RequestContentLengthMismatchError, ResponseContentLengthMismatchError, RequestAbortedError, - InvalidArgumentError, HeadersTimeoutError, HeadersOverflowError, SocketError, @@ -5797,9 +5725,6 @@ var require_client_h1 = __commonJS({ var FastBuffer = Buffer[Symbol.species]; var addListener = util.addListener; var removeAllListeners = util.removeAllListeners; - var kIdleSocketValidation = /* @__PURE__ */ Symbol("kIdleSocketValidation"); - var kIdleSocketValidationTimeout = /* @__PURE__ */ Symbol("kIdleSocketValidationTimeout"); - var kSocketUsed = /* @__PURE__ */ Symbol("kSocketUsed"); var extractBody; async function lazyllhttp() { const llhttpWasmData = process.env.JEST_WORKER_ID ? require_llhttp_wasm() : void 0; @@ -5962,55 +5887,24 @@ var require_client_h1 = __commonJS({ currentBufferRef = null; } const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr; - if (ret !== constants3.ERROR.OK) { - const body = data.subarray(offset); - if (ret === constants3.ERROR.PAUSED_UPGRADE) { - this.onUpgrade(body); - } else if (ret === constants3.ERROR.PAUSED) { - this.paused = true; - socket.unshift(body); - } else { - throw this.createError(ret, body); - } + if (ret === constants3.ERROR.PAUSED_UPGRADE) { + this.onUpgrade(data.slice(offset)); + } else if (ret === constants3.ERROR.PAUSED) { + this.paused = true; + socket.unshift(data.slice(offset)); + } else if (ret !== constants3.ERROR.OK) { + const ptr = llhttp.llhttp_get_error_reason(this.ptr); + let message = ""; + if (ptr) { + const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); + message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; + } + throw new HTTPParserError(message, constants3.ERROR[ret], data.slice(offset)); } } catch (err) { util.destroy(socket, err); } } - finish() { - assert(currentParser === null); - assert(this.ptr != null); - assert(!this.paused); - const { llhttp } = this; - let ret; - try { - currentParser = this; - ret = llhttp.llhttp_finish(this.ptr); - } finally { - currentParser = null; - } - if (ret === constants3.ERROR.OK) { - return null; - } - if (ret === constants3.ERROR.PAUSED || ret === constants3.ERROR.PAUSED_UPGRADE) { - this.paused = true; - return null; - } - return this.createError(ret, EMPTY_BUF); - } - createError(ret, data) { - const { llhttp, contentLength, bytesRead } = this; - if (contentLength && bytesRead !== parseInt(contentLength, 10)) { - return new ResponseContentLengthMismatchError(); - } - const ptr = llhttp.llhttp_get_error_reason(this.ptr); - let message = ""; - if (ptr) { - const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); - message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; - } - return new HTTPParserError(message, constants3.ERROR[ret], data); - } destroy() { assert(this.ptr != null); assert(currentParser == null); @@ -6030,10 +5924,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6077,7 +5967,7 @@ var require_client_h1 = __commonJS({ } } onUpgrade(head) { - const { upgrade, client, socket, headers, statusCode, statusText } = this; + const { upgrade, client, socket, headers, statusCode } = this; assert(upgrade); assert(client[kSocket] === socket); assert(!socket.destroyed); @@ -6102,10 +5992,9 @@ var require_client_h1 = __commonJS({ client[kQueue][client[kRunningIdx]++] = null; client.emit("disconnect", client[kUrl], [client], new InformationalError("upgrade")); try { - request2.onUpgrade(statusCode, headers, socket, statusText); - } catch (error2) { - util.errorRequest(client, request2, error2); - util.destroy(socket, error2); + request2.onUpgrade(statusCode, headers, socket); + } catch (err) { + util.destroy(socket, err); } client[kResume](); } @@ -6114,10 +6003,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6243,7 +6128,6 @@ var require_client_h1 = __commonJS({ } request2.onComplete(headers); client[kQueue][client[kRunningIdx]++] = null; - socket[kSocketUsed] = true; if (socket[kWriting]) { assert(client[kRunning] === 0); util.destroy(socket, new InformationalError("reset")); @@ -6287,19 +6171,12 @@ var require_client_h1 = __commonJS({ socket[kWriting] = false; socket[kReset] = false; socket[kBlocking] = false; - socket[kIdleSocketValidation] = 0; - socket[kIdleSocketValidationTimeout] = null; - socket[kSocketUsed] = false; socket[kParser] = new Parser(client, socket, llhttpInstance); addListener(socket, "error", function(err) { assert(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID"); const parser = this[kParser]; if (err.code === "ECONNRESET" && parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - this[kError] = parserErr; - this[kClient][kOnError](parserErr); - } + parser.onMessageComplete(); return; } this[kError] = err; @@ -6314,10 +6191,7 @@ var require_client_h1 = __commonJS({ addListener(socket, "end", function() { const parser = this[kParser]; if (parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - util.destroy(this, parserErr); - } + parser.onMessageComplete(); return; } util.destroy(this, new SocketError("other side closed", util.getSocketInfo(this))); @@ -6325,10 +6199,9 @@ var require_client_h1 = __commonJS({ addListener(socket, "close", function() { const client2 = this[kClient]; const parser = this[kParser]; - clearIdleSocketValidation(this); if (parser) { if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { - this[kError] = parser.finish() || this[kError]; + parser.onMessageComplete(); } this[kParser].destroy(); this[kParser] = null; @@ -6377,7 +6250,7 @@ var require_client_h1 = __commonJS({ return socket.destroyed; }, busy(request2) { - if (socket[kWriting] || socket[kReset] || socket[kBlocking] || socket[kIdleSocketValidation] === 1) { + if (socket[kWriting] || socket[kReset] || socket[kBlocking]) { return true; } if (request2) { @@ -6395,23 +6268,6 @@ var require_client_h1 = __commonJS({ } }; } - function clearIdleSocketValidation(socket) { - if (socket[kIdleSocketValidationTimeout]) { - clearImmediate(socket[kIdleSocketValidationTimeout]); - socket[kIdleSocketValidationTimeout] = null; - } - socket[kIdleSocketValidation] = 0; - } - function scheduleIdleSocketValidation(client, socket) { - socket[kIdleSocketValidation] = 1; - socket[kIdleSocketValidationTimeout] = setImmediate(() => { - socket[kIdleSocketValidationTimeout] = null; - socket[kIdleSocketValidation] = 2; - if (client[kSocket] === socket && !socket.destroyed) { - client[kResume](); - } - }); - } function resumeH1(client) { const socket = client[kSocket]; if (socket && !socket.destroyed) { @@ -6424,29 +6280,6 @@ var require_client_h1 = __commonJS({ socket.ref(); socket[kNoRef] = false; } - if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) { - if (socket[kIdleSocketValidation] === 0) { - scheduleIdleSocketValidation(client, socket); - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - if (socket[kIdleSocketValidation] === 1) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - } - if (client[kRunning] === 0) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - } if (client[kSize] === 0) { if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) { socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE); @@ -6477,16 +6310,8 @@ var require_client_h1 = __commonJS({ } body = bodyStream.stream; contentLength = bodyStream.length; - } else if (util.isBlobLike(body) && request2.contentType == null) { - const contentType = body.type; - if (contentType) { - const contentTypeValue = `${contentType}`; - if (!util.isValidHeaderValue(contentTypeValue)) { - util.errorRequest(client, request2, new InvalidArgumentError("invalid content-type header")); - return false; - } - headers.push("content-type", contentTypeValue); - } + } else if (util.isBlobLike(body) && request2.contentType == null && body.type) { + headers.push("content-type", body.type); } if (body && typeof body.read === "function") { body.read(0); @@ -6507,18 +6332,11 @@ var require_client_h1 = __commonJS({ process.emitWarning(new RequestContentLengthMismatchError()); } const socket = client[kSocket]; - clearIdleSocketValidation(socket); - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (request2.upgrade || request2.method === "CONNECT") { - util.destroy(socket, new InformationalError("aborted")); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - util.errorRequest(client, request2, error2 || new RequestAbortedError()); + util.errorRequest(client, request2, err || new RequestAbortedError()); util.destroy(body); util.destroy(socket, new InformationalError("aborted")); }; @@ -6874,7 +6692,6 @@ var require_client_h2 = __commonJS({ "node_modules/undici/lib/dispatcher/client-h2.js"(exports, module) { "use strict"; var assert = __require("node:assert"); - var { errorMonitor } = __require("node:events"); var { pipeline: pipeline2 } = __require("node:stream"); var util = require_util(); var { @@ -6935,10 +6752,6 @@ var require_client_h2 = __commonJS({ } return result; } - function parseH2ResponseHeaders(headers) { - const { [HTTP2_HEADER_STATUS]: _statusCode, ...realHeaders } = headers; - return parseH2Headers(realHeaders); - } async function connectH2(client, socket) { client[kSocket] = socket; if (!h2ExperimentalWarned) { @@ -7102,22 +6915,16 @@ var require_client_h2 = __commonJS({ const { hostname, port } = client[kUrl]; headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ""}`; headers[HTTP2_HEADER_METHOD] = method; - const abort = (error2) => { - if (request2.aborted) { + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - if (request2.completed) { - if (method === "CONNECT" && stream != null) { - util.destroy(stream, error2 || new RequestAbortedError()); - } - return; - } - error2 = error2 || new RequestAbortedError(); - util.errorRequest(client, request2, error2); + err = err || new RequestAbortedError(); + util.errorRequest(client, request2, err); if (stream != null) { - util.destroy(stream, error2); + util.destroy(stream, err); } - util.destroy(body, error2); + util.destroy(body, err); client[kQueue][client[kRunningIdx]++] = null; client[kResume](); }; @@ -7132,42 +6939,18 @@ var require_client_h2 = __commonJS({ if (method === "CONNECT") { session.ref(); stream = session.request(headers, { endStream: false, signal }); - let upgradeResponseFinished = false; - const onResponse = (headers2) => { - upgradeResponseFinished = true; - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeResponse(Number(headers2[HTTP2_HEADER_STATUS]), headers2, parseH2ResponseHeaders); - }; - const onUpgradeError = (error2) => { - upgradeResponseFinished = true; - stream.off("response", onResponse); - request2.onUpgradeError(error2); - }; - const onReady = () => { - try { - request2.onUpgrade(null, null, stream); - } catch (error2) { - stream.off("response", onResponse); - abort(error2); - return; - } - if (request2.aborted) { - return; - } - stream.off("error", abort); - stream.once(errorMonitor, onUpgradeError); + if (stream.id && !stream.pending) { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; client[kQueue][client[kRunningIdx]++] = null; - }; - stream.once("response", onResponse); - stream.once("error", abort); - ++session[kOpenStreams]; - onReady(); + } else { + stream.once("ready", () => { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; + client[kQueue][client[kRunningIdx]++] = null; + }); + } stream.once("close", () => { - if (!upgradeResponseFinished && request2.completed) { - stream.off("response", onResponse); - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeError(new InformationalError(`HTTP/2: "stream error" received - code ${stream.rstCode}`)); - } session[kOpenStreams] -= 1; if (session[kOpenStreams] === 0) session.unref(); }); @@ -7728,10 +7511,9 @@ var require_client = __commonJS({ autoSelectFamilyAttemptTimeout, // h2 maxConcurrentStreams, - allowH2, - webSocket + allowH2 } = {}) { - super({ webSocket }); + super(); if (keepAlive !== void 0) { throw new InvalidArgumentError("unsupported keepAlive, use pipelining=0 instead"); } @@ -8237,8 +8019,8 @@ var require_pool_base = __commonJS({ var kRemoveClient = /* @__PURE__ */ Symbol("remove client"); var kStats = /* @__PURE__ */ Symbol("stats"); var PoolBase = class extends DispatcherBase { - constructor(opts) { - super(opts); + constructor() { + super(); this[kQueue] = new FixedQueue(); this[kClients] = []; this[kQueued] = 0; @@ -8409,6 +8191,7 @@ var require_pool = __commonJS({ allowH2, ...options } = {}) { + super(); if (connections != null && (!Number.isFinite(connections) || connections < 0)) { throw new InvalidArgumentError("invalid connections"); } @@ -8429,7 +8212,6 @@ var require_pool = __commonJS({ ...connect }); } - super(options); this[kInterceptors] = options.interceptors?.Pool && Array.isArray(options.interceptors.Pool) ? options.interceptors.Pool : []; this[kConnections] = connections || null; this[kUrl] = util.parseOrigin(origin); @@ -8629,6 +8411,7 @@ var require_agent = __commonJS({ } var Agent = class extends DispatcherBase { constructor({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { + super(); if (typeof factory !== "function") { throw new InvalidArgumentError("factory must be a function."); } @@ -8638,7 +8421,6 @@ var require_agent = __commonJS({ if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { throw new InvalidArgumentError("maxRedirections must be a positive number"); } - super(options); if (connect && typeof connect !== "function") { connect = { ...connect }; } @@ -9079,24 +8861,6 @@ var require_retry_handler = __commonJS({ const current = Date.now(); return new Date(retryAfter).getTime() - current; } - function validatePartialResponseContentLength(headers, range, statusCode, retryCount) { - const contentLength = headers["content-length"]; - if (contentLength == null) { - return null; - } - if (!Number.isFinite(range.start) || !Number.isFinite(range.end)) { - return null; - } - const length = Number(contentLength); - const expectedLength = range.end - range.start + 1; - if (!Number.isFinite(length) || length !== expectedLength) { - return new RequestRetryError("Content-Length mismatch", statusCode, { - headers, - data: { count: retryCount } - }); - } - return null; - } var RetryHandler = class _RetryHandler { constructor(opts, handlers) { const { retryOptions, ...dispatchOpts } = opts; @@ -9150,7 +8914,6 @@ var require_retry_handler = __commonJS({ this.end = null; this.etag = null; this.resume = null; - this.headersSent = false; this.handler.onConnect((reason) => { this.aborted = true; if (this.abort) { @@ -9160,17 +8923,6 @@ var require_retry_handler = __commonJS({ } }); } - 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(); @@ -9232,9 +8984,7 @@ var require_retry_handler = __commonJS({ const headers = parseHeaders(rawHeaders); this.retryCount += 1; if (statusCode >= 300) { - if (!this.headersSent && this.retryOpts.statusCodes.includes(statusCode) === false) { - this.headersSent = true; - this.checkpointResponseEnd(headers, resume); + if (this.retryOpts.statusCodes.includes(statusCode) === false) { return this.handler.onHeaders( statusCode, rawHeaders, @@ -9283,21 +9033,9 @@ var require_retry_handler = __commonJS({ ); return false; } - const contentLengthError = validatePartialResponseContentLength(headers, contentRange, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = contentRange; - 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; - } + assert(this.start === start, "content-range mismatch"); + assert(this.end == null || this.end === end, "content-range mismatch"); this.resume = resume; return true; } @@ -9305,7 +9043,6 @@ var require_retry_handler = __commonJS({ if (statusCode === 206) { const range = parseRangeHeader(headers["content-range"]); if (range == null) { - this.headersSent = true; return this.handler.onHeaders( statusCode, rawHeaders, @@ -9313,11 +9050,6 @@ var require_retry_handler = __commonJS({ statusMessage ); } - const contentLengthError = validatePartialResponseContentLength(headers, range, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = range; assert( start != null && Number.isFinite(start), @@ -9337,7 +9069,6 @@ var require_retry_handler = __commonJS({ "invalid content-length" ); this.resume = resume; - this.headersSent = true; this.etag = headers.etag != null ? headers.etag : null; if (this.etag != null && this.etag.startsWith("W/")) { this.etag = null; @@ -9365,7 +9096,7 @@ var require_retry_handler = __commonJS({ return this.handler.onComplete(rawTrailers); } onError(err) { - if (this.aborted || isDisturbed(this.opts.body) || this.headersSent && this.resume == null) { + if (this.aborted || isDisturbed(this.opts.body)) { return this.handler.onError(err); } if (this.retryCount - this.retryCountCheckpoint > 0) { @@ -16164,48 +15895,14 @@ var require_util6 = __commonJS({ for (let i2 = 0; i2 < path.length; ++i2) { const code = path.charCodeAt(i2); if (code < 32 || // exclude CTLs (0-31) - code > 126 || // exclude DEL and non-ascii + code === 127 || // DEL code === 59) { throw new Error("Invalid cookie path"); } } } - function isLetterOrDigit(code) { - return code >= 48 && code <= 57 || // 0-9 - code >= 65 && code <= 90 || // A-Z - code >= 97 && code <= 122; - } function validateCookieDomain(domain) { - if (domain === " ") { - return; - } - if (domain.length > 255) { - throw new Error("Invalid cookie domain"); - } - let labelLength = 0; - for (let i2 = 0; i2 < domain.length; ++i2) { - const code = domain.charCodeAt(i2); - if (code === 46) { - if (labelLength === 0) { - throw new Error("Invalid cookie domain"); - } - if (domain.charCodeAt(i2 - 1) === 45) { - throw new Error("Invalid cookie domain"); - } - labelLength = 0; - continue; - } - if (labelLength === 0 && !isLetterOrDigit(code)) { - throw new Error("Invalid cookie domain"); - } - if (!isLetterOrDigit(code) && code !== 45) { - throw new Error("Invalid cookie domain"); - } - if (++labelLength > 63) { - throw new Error("Invalid cookie domain"); - } - } - if (labelLength === 0 || domain.charCodeAt(domain.length - 1) === 45) { + if (domain.startsWith("-") || domain.endsWith(".") || domain.endsWith("-")) { throw new Error("Invalid cookie domain"); } } @@ -16288,11 +15985,7 @@ var require_util6 = __commonJS({ throw new Error("Invalid unparsed"); } const [key, ...value] = part.split("="); - const trimmedKey = key.trim(); - const joinedValue = value.join("="); - validateCookieName(trimmedKey); - validateCookieValue(joinedValue); - out.push(`${trimmedKey}=${joinedValue}`); + out.push(`${key.trim()}=${value.join("=")}`); } return out.join("; "); } @@ -16422,14 +16115,18 @@ var require_parse = __commonJS({ } else if (attributeNameLowercase === "httponly") { cookieAttributeList.httpOnly = true; } else if (attributeNameLowercase === "samesite") { + let enforcement = "Default"; const attributeValueLowercase = attributeValue.toLowerCase(); - if (attributeValueLowercase === "none") { - cookieAttributeList.sameSite = "None"; - } else if (attributeValueLowercase === "strict") { - cookieAttributeList.sameSite = "Strict"; - } else if (attributeValueLowercase === "lax") { - cookieAttributeList.sameSite = "Lax"; + if (attributeValueLowercase.includes("none")) { + enforcement = "None"; + } + if (attributeValueLowercase.includes("strict")) { + enforcement = "Strict"; + } + if (attributeValueLowercase.includes("lax")) { + enforcement = "Lax"; } + cookieAttributeList.sameSite = enforcement; } else { cookieAttributeList.unparsed ??= []; cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`); @@ -17251,7 +16948,7 @@ var require_connection = __commonJS({ const secProtocol = response.headersList.get("Sec-WebSocket-Protocol"); if (secProtocol !== null) { const requestProtocols = getDecodeSplit("sec-websocket-protocol", request2.headersList); - if (requestProtocols === null || !requestProtocols.includes(secProtocol)) { + if (!requestProtocols.includes(secProtocol)) { failWebsocketConnection(ws, "Protocol was not set in the opening handshake."); return; } @@ -17357,26 +17054,31 @@ var require_permessage_deflate = __commonJS({ var tail = Buffer.from([0, 0, 255, 255]); var kBuffer = /* @__PURE__ */ Symbol("kBuffer"); var kLength = /* @__PURE__ */ Symbol("kLength"); + var kDefaultMaxDecompressedSize = 4 * 1024 * 1024; var PerMessageDeflate = class { /** @type {import('node:zlib').InflateRaw} */ #inflate; #options = {}; - #maxPayloadSize = 0; + /** @type {number} */ + #maxDecompressedSize; + /** @type {boolean} */ + #aborted = false; + /** @type {Function|null} */ + #currentCallback = null; /** * @param {Map} extensions + * @param {{ maxDecompressedMessageSize?: number }} [options] */ - constructor(extensions, options) { + constructor(extensions, options = {}) { this.#options.serverNoContextTakeover = extensions.has("server_no_context_takeover"); this.#options.serverMaxWindowBits = extensions.get("server_max_window_bits"); - this.#maxPayloadSize = options.maxPayloadSize; + this.#maxDecompressedSize = options.maxDecompressedMessageSize ?? kDefaultMaxDecompressedSize; } - /** - * Decompress a compressed payload. - * @param {Buffer} chunk Compressed data - * @param {boolean} fin Final fragment flag - * @param {Function} callback Callback function - */ decompress(chunk, fin, callback) { + if (this.#aborted) { + callback(new MessageSizeExceededError()); + return; + } if (!this.#inflate) { let windowBits = Z_DEFAULT_WINDOWBITS; if (this.#options.serverMaxWindowBits) { @@ -17395,12 +17097,20 @@ var require_permessage_deflate = __commonJS({ this.#inflate[kBuffer] = []; this.#inflate[kLength] = 0; this.#inflate.on("data", (data) => { + if (this.#aborted) { + return; + } this.#inflate[kLength] += data.length; - if (this.#maxPayloadSize > 0 && this.#inflate[kLength] > this.#maxPayloadSize) { - callback(new MessageSizeExceededError()); + if (this.#inflate[kLength] > this.#maxDecompressedSize) { + this.#aborted = true; this.#inflate.removeAllListeners(); this.#inflate.destroy(); this.#inflate = null; + if (this.#currentCallback) { + const cb = this.#currentCallback; + this.#currentCallback = null; + cb(new MessageSizeExceededError()); + } return; } this.#inflate[kBuffer].push(data); @@ -17410,17 +17120,19 @@ var require_permessage_deflate = __commonJS({ callback(err); }); } + this.#currentCallback = callback; this.#inflate.write(chunk); if (fin) { this.#inflate.write(tail); } this.#inflate.flush(() => { - if (!this.#inflate) { + if (this.#aborted || !this.#inflate) { return; } const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]); this.#inflate[kBuffer].length = 0; this.#inflate[kLength] = 0; + this.#currentCallback = null; callback(null, full); }); } @@ -17451,14 +17163,8 @@ var require_receiver = __commonJS({ var { WebsocketFrameSend } = require_frame(); var { closeWebSocketConnection } = require_connection(); var { PerMessageDeflate } = require_permessage_deflate(); - var { MessageSizeExceededError } = require_errors(); - function failWebsocketConnectionWithCode(ws, code, reason) { - closeWebSocketConnection(ws, code, reason, Buffer.byteLength(reason)); - failWebsocketConnection(ws, reason); - } var ByteParser = class extends Writable { #buffers = []; - #fragmentsBytes = 0; #byteOffset = 0; #loop = false; #state = parserStates.INFO; @@ -17466,21 +17172,18 @@ var require_receiver = __commonJS({ #fragments = []; /** @type {Map} */ #extensions; - /** @type {number} */ - #maxFragments; - /** @type {number} */ - #maxPayloadSize; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {import('./websocket').WebSocket} ws * @param {Map|null} extensions - * @param {{ maxFragments?: number, maxPayloadSize?: number }} [options] + * @param {{ maxDecompressedMessageSize?: number }} [options] */ constructor(ws, extensions, options = {}) { super(); this.ws = ws; this.#extensions = extensions == null ? /* @__PURE__ */ new Map() : extensions; - this.#maxFragments = options.maxFragments ?? 0; - this.#maxPayloadSize = options.maxPayloadSize ?? 0; + this.#options = options; if (this.#extensions.has("permessage-deflate")) { this.#extensions.set("permessage-deflate", new PerMessageDeflate(extensions, options)); } @@ -17495,13 +17198,6 @@ var require_receiver = __commonJS({ this.#loop = true; this.run(callback); } - #validatePayloadLength() { - if (this.#maxPayloadSize > 0 && !isControlFrame(this.#info.opcode) && this.#info.payloadLength + this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, "Payload size exceeds maximum allowed size"); - return false; - } - return true; - } /** * Runs whenever a new chunk is received. * Callback is called whenever there are no more chunks buffering, @@ -17561,9 +17257,6 @@ var require_receiver = __commonJS({ if (payloadLength <= 125) { this.#info.payloadLength = payloadLength; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (payloadLength === 126) { this.#state = parserStates.PAYLOADLENGTH_16; } else if (payloadLength === 127) { @@ -17584,9 +17277,6 @@ var require_receiver = __commonJS({ const buffer = this.consume(2); this.#info.payloadLength = buffer.readUInt16BE(0); this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.PAYLOADLENGTH_64) { if (this.#byteOffset < 8) { return callback(); @@ -17600,9 +17290,6 @@ var require_receiver = __commonJS({ } this.#info.payloadLength = lower2; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.READ_DATA) { if (this.#byteOffset < this.#info.payloadLength) { return callback(); @@ -17613,46 +17300,32 @@ var require_receiver = __commonJS({ this.#state = parserStates.INFO; } else { if (!this.#info.compressed) { - if (!this.writeFragments(body)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } + this.#fragments.push(body); if (!this.#info.fragmented && this.#info.fin) { - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); + const fullMessage = Buffer.concat(this.#fragments); + websocketMessageReceived(this.ws, this.#info.binaryType, fullMessage); + this.#fragments.length = 0; } this.#state = parserStates.INFO; } else { - this.#extensions.get("permessage-deflate").decompress( - body, - this.#info.fin, - (error2, data) => { - if (error2) { - const code = error2 instanceof MessageSizeExceededError ? 1009 : 1007; - failWebsocketConnectionWithCode(this.ws, code, error2.message); - return; - } - if (!this.writeFragments(data)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } - if (!this.#info.fin) { - this.#state = parserStates.INFO; - this.#loop = true; - this.run(callback); - return; - } - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); - this.#loop = true; + this.#extensions.get("permessage-deflate").decompress(body, this.#info.fin, (error2, data) => { + if (error2) { + failWebsocketConnection(this.ws, error2.message); + return; + } + this.#fragments.push(data); + if (!this.#info.fin) { this.#state = parserStates.INFO; + this.#loop = true; this.run(callback); + return; } - ); + websocketMessageReceived(this.ws, this.#info.binaryType, Buffer.concat(this.#fragments)); + this.#loop = true; + this.#state = parserStates.INFO; + this.#fragments.length = 0; + this.run(callback); + }); this.#loop = false; break; } @@ -17695,26 +17368,6 @@ var require_receiver = __commonJS({ this.#byteOffset -= n; return buffer; } - writeFragments(fragment) { - if (this.#maxFragments > 0 && this.#fragments.length === this.#maxFragments) { - failWebsocketConnectionWithCode(this.ws, 1008, "Too many message fragments"); - return false; - } - this.#fragmentsBytes += fragment.length; - this.#fragments.push(fragment); - return true; - } - consumeFragments() { - const fragments = this.#fragments; - if (fragments.length === 1) { - this.#fragmentsBytes = 0; - return fragments.shift(); - } - const output = Buffer.concat(fragments, this.#fragmentsBytes); - this.#fragments = []; - this.#fragmentsBytes = 0; - return output; - } parseCloseBody(data) { assert(data.length !== 1); let code; @@ -17926,6 +17579,8 @@ var require_websocket = __commonJS({ #extensions = ""; /** @type {SendQueue} */ #sendQueue; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {string} url * @param {string|string[]} protocols @@ -17969,6 +17624,9 @@ var require_websocket = __commonJS({ throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError"); } this[kWebSocketURL] = new URL(urlRecord.href); + this.#options = { + maxDecompressedMessageSize: options.maxDecompressedMessageSize + }; const client = environmentSettingsObject.settingsObject; this[kController] = establishWebSocketConnection( urlRecord, @@ -18152,13 +17810,7 @@ var require_websocket = __commonJS({ */ #onConnectionEstablished(response, parsedExtensions) { this[kResponse] = response; - const webSocketOptions = this[kController]?.dispatcher?.webSocketOptions; - const maxFragments = webSocketOptions?.maxFragments; - const maxPayloadSize = webSocketOptions?.maxPayloadSize; - const parser = new ByteParser(this, parsedExtensions, { - maxFragments, - maxPayloadSize - }); + const parser = new ByteParser(this, parsedExtensions, this.#options); parser.on("drain", onParserDrain); parser.on("error", onParserError.bind(this)); response.socket.ws = this; @@ -18233,6 +17885,19 @@ var require_websocket = __commonJS({ { key: "headers", converter: webidl.nullableConverter(webidl.converters.HeadersInit) + }, + { + key: "maxDecompressedMessageSize", + converter: webidl.nullableConverter((V) => { + V = webidl.converters["unsigned long long"](V); + if (V <= 0) { + throw webidl.errors.exception({ + header: "WebSocket constructor", + message: "maxDecompressedMessageSize must be greater than 0" + }); + } + return V; + }) } ]); webidl.converters["DOMString or sequence or WebSocketInit"] = function(V) { @@ -18311,40 +17976,6 @@ var require_eventsource_stream = __commonJS({ var CR2 = 13; var COLON2 = 58; var SPACE2 = 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 i2 = start; i2 < buffer.length; i2++) { - if (buffer[i2] < 48 || buffer[i2] > 57) { - return false; - } - } - return true; - } - function isValidLastEventIdBytes(buffer, start) { - for (let i2 = start; i2 < buffer.length; i2++) { - if (buffer[i2] === 0) { - return false; - } - } - return true; - } - function isFieldName(line, length, field) { - if (length !== field.length) { - return false; - } - for (let i2 = 0; i2 < length; i2++) { - if (line[i2] !== field[i2]) { - return false; - } - } - return true; - } var EventSourceStream = class extends Transform { /** * @type {eventSourceSettings} @@ -18364,13 +17995,10 @@ var require_eventsource_stream = __commonJS({ */ eventEndCheck = false; /** - * @type {Buffer[]} + * @type {Buffer} */ - chunks = []; - chunkIndex = 0; + buffer = null; pos = 0; - lineChunkIndex = 0; - linePos = 0; event = { data: void 0, event: void 0, @@ -18401,30 +18029,63 @@ var require_eventsource_stream = __commonJS({ callback(); return; } - this.chunks.push(chunk); + if (this.buffer) { + this.buffer = Buffer.concat([this.buffer, chunk]); + } else { + this.buffer = chunk; + } if (this.checkBOM) { - if (this.handleBOM()) { - callback(); - return; + 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; } } - while (this.hasCurrentByte()) { - const byte = this.currentByte(); + while (this.pos < this.buffer.length) { if (this.eventEndCheck) { if (this.crlfCheck) { - if (byte === LF2) { + if (this.buffer[this.pos] === LF2) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.crlfCheck = false; - this.consumeCurrentByte(); continue; } this.crlfCheck = false; } - if (byte === LF2 || byte === CR2) { - if (byte === CR2) { + if (this.buffer[this.pos] === LF2 || this.buffer[this.pos] === CR2) { + if (this.buffer[this.pos] === CR2) { this.crlfCheck = true; } - this.consumeCurrentByte(); - if (this.hasPendingEvent()) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; + if (this.event.data !== void 0 || this.event.event || this.event.id || this.event.retry) { this.processEvent(this.event); } this.clearEvent(); @@ -18433,16 +18094,17 @@ var require_eventsource_stream = __commonJS({ this.eventEndCheck = false; continue; } - if (byte === LF2 || byte === CR2) { - if (byte === CR2) { + if (this.buffer[this.pos] === LF2 || this.buffer[this.pos] === CR2) { + if (this.buffer[this.pos] === CR2) { this.crlfCheck = true; } - this.parseLine(this.readLine(), this.event); - this.consumeCurrentByte(); + this.parseLine(this.buffer.subarray(0, this.pos), this.event); + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.eventEndCheck = true; continue; } - this.advanceCursor(); + this.pos++; } callback(); } @@ -18458,42 +18120,43 @@ var require_eventsource_stream = __commonJS({ if (colonPosition === 0) { return; } - let fieldLength = line.length; - let valueStart = line.length; + let field = ""; + let value = ""; if (colonPosition !== -1) { - fieldLength = colonPosition; - valueStart = colonPosition + 1; + field = line.subarray(0, colonPosition).toString("utf8"); + let valueStart = colonPosition + 1; if (line[valueStart] === SPACE2) { ++valueStart; } + value = line.subarray(valueStart).toString("utf8"); + } else { + field = line.toString("utf8"); + value = ""; } - if (isFieldName(line, fieldLength, DATA)) { - const value = line.toString("utf8", valueStart); - if (event.data === void 0) { - event.data = value; - } else { - event.data += ` + switch (field) { + case "data": + if (event[field] === void 0) { + event[field] = value; + } else { + event[field] += ` ${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; - } + } + 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; } } /** @@ -18518,120 +18181,12 @@ ${value}`; } } clearEvent() { - 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 i2 = this.lineChunkIndex; i2 <= this.chunkIndex; i2++) { - const chunk = this.chunks[i2]; - const start = i2 === this.lineChunkIndex ? this.linePos : 0; - const end = i2 === 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(); + this.event = { + data: void 0, + event: void 0, + id: void 0, + retry: void 0 + }; } }; module.exports = { diff --git a/.github/actions/javascript/checkDeployBlockers/index.js b/.github/actions/javascript/checkDeployBlockers/index.js index c59c854097c1..2ca391c52c00 100644 --- a/.github/actions/javascript/checkDeployBlockers/index.js +++ b/.github/actions/javascript/checkDeployBlockers/index.js @@ -1863,66 +1863,10 @@ var require_request = __commonJS({ return false; } } - /** - * @param {number|null} statusCode - * @param {Buffer[]|null} headers - * @param {import('node:stream').Duplex} socket - * @param {string} [statusText] - */ - onUpgrade(statusCode, headers, socket, statusText = "") { - this.onFinally(); + onUpgrade(statusCode, headers, socket) { assert(!this.aborted); assert(!this.completed); - 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(error2) { - assert(!this.aborted); - assert(this.completed); - if (channels.error.hasSubscribers) { - channels.error.publish({ request: this, error: error2 }); - } - } - /** - * @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: [] }); - } + return this[kHandler].onUpgrade(statusCode, headers, socket); } onComplete(trailers) { this.onFinally(); @@ -1989,11 +1933,7 @@ var require_request = __commonJS({ } else if (typeof val[i] === "object") { throw new InvalidArgumentError(`invalid ${key} header`); } else { - const str = `${val[i]}`; - if (!isValidHeaderValue(str)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } - arr.push(str); + arr.push(`${val[i]}`); } } val = arr; @@ -2005,9 +1945,6 @@ var require_request = __commonJS({ val = ""; } else { val = `${val}`; - if (!isValidHeaderValue(val)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } } if (headerName === "host") { if (request2.host !== null) { @@ -2117,21 +2054,13 @@ var require_dispatcher_base = __commonJS({ var kOnDestroyed = /* @__PURE__ */ Symbol("onDestroyed"); var kOnClosed = /* @__PURE__ */ Symbol("onClosed"); var kInterceptedDispatch = /* @__PURE__ */ Symbol("Intercepted Dispatch"); - var kWebSocketOptions = /* @__PURE__ */ Symbol("webSocketOptions"); var DispatcherBase = class extends Dispatcher { - constructor(opts) { + constructor() { super(); this[kDestroyed] = false; this[kOnDestroyed] = null; this[kClosed] = false; this[kOnClosed] = []; - this[kWebSocketOptions] = opts?.webSocket ?? {}; - } - get webSocketOptions() { - return { - maxFragments: this[kWebSocketOptions].maxFragments ?? 131072, - maxPayloadSize: this[kWebSocketOptions].maxPayloadSize ?? 128 * 1024 * 1024 - }; } get destroyed() { return this[kDestroyed]; @@ -5738,7 +5667,6 @@ var require_client_h1 = __commonJS({ RequestContentLengthMismatchError, ResponseContentLengthMismatchError, RequestAbortedError, - InvalidArgumentError, HeadersTimeoutError, HeadersOverflowError, SocketError, @@ -5785,9 +5713,6 @@ var require_client_h1 = __commonJS({ var FastBuffer = Buffer[Symbol.species]; var addListener = util.addListener; var removeAllListeners = util.removeAllListeners; - var kIdleSocketValidation = /* @__PURE__ */ Symbol("kIdleSocketValidation"); - var kIdleSocketValidationTimeout = /* @__PURE__ */ Symbol("kIdleSocketValidationTimeout"); - var kSocketUsed = /* @__PURE__ */ Symbol("kSocketUsed"); var extractBody; async function lazyllhttp() { const llhttpWasmData = process.env.JEST_WORKER_ID ? require_llhttp_wasm() : void 0; @@ -5950,55 +5875,24 @@ var require_client_h1 = __commonJS({ currentBufferRef = null; } const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr; - if (ret !== constants3.ERROR.OK) { - const body = data.subarray(offset); - if (ret === constants3.ERROR.PAUSED_UPGRADE) { - this.onUpgrade(body); - } else if (ret === constants3.ERROR.PAUSED) { - this.paused = true; - socket.unshift(body); - } else { - throw this.createError(ret, body); + if (ret === constants3.ERROR.PAUSED_UPGRADE) { + this.onUpgrade(data.slice(offset)); + } else if (ret === constants3.ERROR.PAUSED) { + this.paused = true; + socket.unshift(data.slice(offset)); + } else if (ret !== constants3.ERROR.OK) { + const ptr = llhttp.llhttp_get_error_reason(this.ptr); + let message = ""; + if (ptr) { + const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); + message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; } + throw new HTTPParserError(message, constants3.ERROR[ret], data.slice(offset)); } } catch (err) { util.destroy(socket, err); } } - finish() { - assert(currentParser === null); - assert(this.ptr != null); - assert(!this.paused); - const { llhttp } = this; - let ret; - try { - currentParser = this; - ret = llhttp.llhttp_finish(this.ptr); - } finally { - currentParser = null; - } - if (ret === constants3.ERROR.OK) { - return null; - } - if (ret === constants3.ERROR.PAUSED || ret === constants3.ERROR.PAUSED_UPGRADE) { - this.paused = true; - return null; - } - return this.createError(ret, EMPTY_BUF); - } - createError(ret, data) { - const { llhttp, contentLength, bytesRead } = this; - if (contentLength && bytesRead !== parseInt(contentLength, 10)) { - return new ResponseContentLengthMismatchError(); - } - const ptr = llhttp.llhttp_get_error_reason(this.ptr); - let message = ""; - if (ptr) { - const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); - message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; - } - return new HTTPParserError(message, constants3.ERROR[ret], data); - } destroy() { assert(this.ptr != null); assert(currentParser == null); @@ -6018,10 +5912,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6065,7 +5955,7 @@ var require_client_h1 = __commonJS({ } } onUpgrade(head) { - const { upgrade, client, socket, headers, statusCode, statusText } = this; + const { upgrade, client, socket, headers, statusCode } = this; assert(upgrade); assert(client[kSocket] === socket); assert(!socket.destroyed); @@ -6090,10 +5980,9 @@ var require_client_h1 = __commonJS({ client[kQueue][client[kRunningIdx]++] = null; client.emit("disconnect", client[kUrl], [client], new InformationalError("upgrade")); try { - request2.onUpgrade(statusCode, headers, socket, statusText); - } catch (error2) { - util.errorRequest(client, request2, error2); - util.destroy(socket, error2); + request2.onUpgrade(statusCode, headers, socket); + } catch (err) { + util.destroy(socket, err); } client[kResume](); } @@ -6102,10 +5991,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6231,7 +6116,6 @@ var require_client_h1 = __commonJS({ } request2.onComplete(headers); client[kQueue][client[kRunningIdx]++] = null; - socket[kSocketUsed] = true; if (socket[kWriting]) { assert(client[kRunning] === 0); util.destroy(socket, new InformationalError("reset")); @@ -6275,19 +6159,12 @@ var require_client_h1 = __commonJS({ socket[kWriting] = false; socket[kReset] = false; socket[kBlocking] = false; - socket[kIdleSocketValidation] = 0; - socket[kIdleSocketValidationTimeout] = null; - socket[kSocketUsed] = false; socket[kParser] = new Parser(client, socket, llhttpInstance); addListener(socket, "error", function(err) { assert(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID"); const parser = this[kParser]; if (err.code === "ECONNRESET" && parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - this[kError] = parserErr; - this[kClient][kOnError](parserErr); - } + parser.onMessageComplete(); return; } this[kError] = err; @@ -6302,10 +6179,7 @@ var require_client_h1 = __commonJS({ addListener(socket, "end", function() { const parser = this[kParser]; if (parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - util.destroy(this, parserErr); - } + parser.onMessageComplete(); return; } util.destroy(this, new SocketError("other side closed", util.getSocketInfo(this))); @@ -6313,10 +6187,9 @@ var require_client_h1 = __commonJS({ addListener(socket, "close", function() { const client2 = this[kClient]; const parser = this[kParser]; - clearIdleSocketValidation(this); if (parser) { if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { - this[kError] = parser.finish() || this[kError]; + parser.onMessageComplete(); } this[kParser].destroy(); this[kParser] = null; @@ -6365,7 +6238,7 @@ var require_client_h1 = __commonJS({ return socket.destroyed; }, busy(request2) { - if (socket[kWriting] || socket[kReset] || socket[kBlocking] || socket[kIdleSocketValidation] === 1) { + if (socket[kWriting] || socket[kReset] || socket[kBlocking]) { return true; } if (request2) { @@ -6383,23 +6256,6 @@ var require_client_h1 = __commonJS({ } }; } - function clearIdleSocketValidation(socket) { - if (socket[kIdleSocketValidationTimeout]) { - clearImmediate(socket[kIdleSocketValidationTimeout]); - socket[kIdleSocketValidationTimeout] = null; - } - socket[kIdleSocketValidation] = 0; - } - function scheduleIdleSocketValidation(client, socket) { - socket[kIdleSocketValidation] = 1; - socket[kIdleSocketValidationTimeout] = setImmediate(() => { - socket[kIdleSocketValidationTimeout] = null; - socket[kIdleSocketValidation] = 2; - if (client[kSocket] === socket && !socket.destroyed) { - client[kResume](); - } - }); - } function resumeH1(client) { const socket = client[kSocket]; if (socket && !socket.destroyed) { @@ -6412,29 +6268,6 @@ var require_client_h1 = __commonJS({ socket.ref(); socket[kNoRef] = false; } - if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) { - if (socket[kIdleSocketValidation] === 0) { - scheduleIdleSocketValidation(client, socket); - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - if (socket[kIdleSocketValidation] === 1) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - } - if (client[kRunning] === 0) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - } if (client[kSize] === 0) { if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) { socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE); @@ -6465,16 +6298,8 @@ var require_client_h1 = __commonJS({ } body = bodyStream.stream; contentLength = bodyStream.length; - } else if (util.isBlobLike(body) && request2.contentType == null) { - const contentType = body.type; - if (contentType) { - const contentTypeValue = `${contentType}`; - if (!util.isValidHeaderValue(contentTypeValue)) { - util.errorRequest(client, request2, new InvalidArgumentError("invalid content-type header")); - return false; - } - headers.push("content-type", contentTypeValue); - } + } else if (util.isBlobLike(body) && request2.contentType == null && body.type) { + headers.push("content-type", body.type); } if (body && typeof body.read === "function") { body.read(0); @@ -6495,18 +6320,11 @@ var require_client_h1 = __commonJS({ process.emitWarning(new RequestContentLengthMismatchError()); } const socket = client[kSocket]; - clearIdleSocketValidation(socket); - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (request2.upgrade || request2.method === "CONNECT") { - util.destroy(socket, new InformationalError("aborted")); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - util.errorRequest(client, request2, error2 || new RequestAbortedError()); + util.errorRequest(client, request2, err || new RequestAbortedError()); util.destroy(body); util.destroy(socket, new InformationalError("aborted")); }; @@ -6862,7 +6680,6 @@ var require_client_h2 = __commonJS({ "node_modules/undici/lib/dispatcher/client-h2.js"(exports, module) { "use strict"; var assert = __require("node:assert"); - var { errorMonitor } = __require("node:events"); var { pipeline } = __require("node:stream"); var util = require_util(); var { @@ -6923,10 +6740,6 @@ var require_client_h2 = __commonJS({ } return result; } - function parseH2ResponseHeaders(headers) { - const { [HTTP2_HEADER_STATUS]: _statusCode, ...realHeaders } = headers; - return parseH2Headers(realHeaders); - } async function connectH2(client, socket) { client[kSocket] = socket; if (!h2ExperimentalWarned) { @@ -7090,22 +6903,16 @@ var require_client_h2 = __commonJS({ const { hostname, port } = client[kUrl]; headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ""}`; headers[HTTP2_HEADER_METHOD] = method; - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (method === "CONNECT" && stream != null) { - util.destroy(stream, error2 || new RequestAbortedError()); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - error2 = error2 || new RequestAbortedError(); - util.errorRequest(client, request2, error2); + err = err || new RequestAbortedError(); + util.errorRequest(client, request2, err); if (stream != null) { - util.destroy(stream, error2); + util.destroy(stream, err); } - util.destroy(body, error2); + util.destroy(body, err); client[kQueue][client[kRunningIdx]++] = null; client[kResume](); }; @@ -7120,42 +6927,18 @@ var require_client_h2 = __commonJS({ if (method === "CONNECT") { session.ref(); stream = session.request(headers, { endStream: false, signal }); - let upgradeResponseFinished = false; - const onResponse = (headers2) => { - upgradeResponseFinished = true; - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeResponse(Number(headers2[HTTP2_HEADER_STATUS]), headers2, parseH2ResponseHeaders); - }; - const onUpgradeError = (error2) => { - upgradeResponseFinished = true; - stream.off("response", onResponse); - request2.onUpgradeError(error2); - }; - const onReady = () => { - try { - request2.onUpgrade(null, null, stream); - } catch (error2) { - stream.off("response", onResponse); - abort(error2); - return; - } - if (request2.aborted) { - return; - } - stream.off("error", abort); - stream.once(errorMonitor, onUpgradeError); + if (stream.id && !stream.pending) { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; client[kQueue][client[kRunningIdx]++] = null; - }; - stream.once("response", onResponse); - stream.once("error", abort); - ++session[kOpenStreams]; - onReady(); + } else { + stream.once("ready", () => { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; + client[kQueue][client[kRunningIdx]++] = null; + }); + } stream.once("close", () => { - if (!upgradeResponseFinished && request2.completed) { - stream.off("response", onResponse); - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeError(new InformationalError(`HTTP/2: "stream error" received - code ${stream.rstCode}`)); - } session[kOpenStreams] -= 1; if (session[kOpenStreams] === 0) session.unref(); }); @@ -7716,10 +7499,9 @@ var require_client = __commonJS({ autoSelectFamilyAttemptTimeout, // h2 maxConcurrentStreams, - allowH2, - webSocket + allowH2 } = {}) { - super({ webSocket }); + super(); if (keepAlive !== void 0) { throw new InvalidArgumentError("unsupported keepAlive, use pipelining=0 instead"); } @@ -8225,8 +8007,8 @@ var require_pool_base = __commonJS({ var kRemoveClient = /* @__PURE__ */ Symbol("remove client"); var kStats = /* @__PURE__ */ Symbol("stats"); var PoolBase = class extends DispatcherBase { - constructor(opts) { - super(opts); + constructor() { + super(); this[kQueue] = new FixedQueue(); this[kClients] = []; this[kQueued] = 0; @@ -8397,6 +8179,7 @@ var require_pool = __commonJS({ allowH2, ...options } = {}) { + super(); if (connections != null && (!Number.isFinite(connections) || connections < 0)) { throw new InvalidArgumentError("invalid connections"); } @@ -8417,7 +8200,6 @@ var require_pool = __commonJS({ ...connect }); } - super(options); this[kInterceptors] = options.interceptors?.Pool && Array.isArray(options.interceptors.Pool) ? options.interceptors.Pool : []; this[kConnections] = connections || null; this[kUrl] = util.parseOrigin(origin); @@ -8617,6 +8399,7 @@ var require_agent = __commonJS({ } var Agent = class extends DispatcherBase { constructor({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { + super(); if (typeof factory !== "function") { throw new InvalidArgumentError("factory must be a function."); } @@ -8626,7 +8409,6 @@ var require_agent = __commonJS({ if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { throw new InvalidArgumentError("maxRedirections must be a positive number"); } - super(options); if (connect && typeof connect !== "function") { connect = { ...connect }; } @@ -9067,24 +8849,6 @@ var require_retry_handler = __commonJS({ const current = Date.now(); return new Date(retryAfter).getTime() - current; } - function validatePartialResponseContentLength(headers, range, statusCode, retryCount) { - const contentLength = headers["content-length"]; - if (contentLength == null) { - return null; - } - if (!Number.isFinite(range.start) || !Number.isFinite(range.end)) { - return null; - } - const length = Number(contentLength); - const expectedLength = range.end - range.start + 1; - if (!Number.isFinite(length) || length !== expectedLength) { - return new RequestRetryError("Content-Length mismatch", statusCode, { - headers, - data: { count: retryCount } - }); - } - return null; - } var RetryHandler = class _RetryHandler { constructor(opts, handlers) { const { retryOptions, ...dispatchOpts } = opts; @@ -9138,7 +8902,6 @@ var require_retry_handler = __commonJS({ this.end = null; this.etag = null; this.resume = null; - this.headersSent = false; this.handler.onConnect((reason) => { this.aborted = true; if (this.abort) { @@ -9148,17 +8911,6 @@ var require_retry_handler = __commonJS({ } }); } - 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(); @@ -9220,9 +8972,7 @@ var require_retry_handler = __commonJS({ const headers = parseHeaders(rawHeaders); this.retryCount += 1; if (statusCode >= 300) { - if (!this.headersSent && this.retryOpts.statusCodes.includes(statusCode) === false) { - this.headersSent = true; - this.checkpointResponseEnd(headers, resume); + if (this.retryOpts.statusCodes.includes(statusCode) === false) { return this.handler.onHeaders( statusCode, rawHeaders, @@ -9271,21 +9021,9 @@ var require_retry_handler = __commonJS({ ); return false; } - const contentLengthError = validatePartialResponseContentLength(headers, contentRange, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = contentRange; - 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; - } + assert(this.start === start, "content-range mismatch"); + assert(this.end == null || this.end === end, "content-range mismatch"); this.resume = resume; return true; } @@ -9293,7 +9031,6 @@ var require_retry_handler = __commonJS({ if (statusCode === 206) { const range = parseRangeHeader(headers["content-range"]); if (range == null) { - this.headersSent = true; return this.handler.onHeaders( statusCode, rawHeaders, @@ -9301,11 +9038,6 @@ var require_retry_handler = __commonJS({ statusMessage ); } - const contentLengthError = validatePartialResponseContentLength(headers, range, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = range; assert( start != null && Number.isFinite(start), @@ -9325,7 +9057,6 @@ var require_retry_handler = __commonJS({ "invalid content-length" ); this.resume = resume; - this.headersSent = true; this.etag = headers.etag != null ? headers.etag : null; if (this.etag != null && this.etag.startsWith("W/")) { this.etag = null; @@ -9353,7 +9084,7 @@ var require_retry_handler = __commonJS({ return this.handler.onComplete(rawTrailers); } onError(err) { - if (this.aborted || isDisturbed(this.opts.body) || this.headersSent && this.resume == null) { + if (this.aborted || isDisturbed(this.opts.body)) { return this.handler.onError(err); } if (this.retryCount - this.retryCountCheckpoint > 0) { @@ -16152,48 +15883,14 @@ var require_util6 = __commonJS({ for (let i = 0; i < path.length; ++i) { const code = path.charCodeAt(i); if (code < 32 || // exclude CTLs (0-31) - code > 126 || // exclude DEL and non-ascii + code === 127 || // DEL code === 59) { throw new Error("Invalid cookie path"); } } } - function isLetterOrDigit(code) { - return code >= 48 && code <= 57 || // 0-9 - code >= 65 && code <= 90 || // A-Z - code >= 97 && code <= 122; - } function validateCookieDomain(domain) { - if (domain === " ") { - return; - } - if (domain.length > 255) { - throw new Error("Invalid cookie domain"); - } - let labelLength = 0; - for (let i = 0; i < domain.length; ++i) { - const code = domain.charCodeAt(i); - if (code === 46) { - if (labelLength === 0) { - throw new Error("Invalid cookie domain"); - } - if (domain.charCodeAt(i - 1) === 45) { - throw new Error("Invalid cookie domain"); - } - labelLength = 0; - continue; - } - if (labelLength === 0 && !isLetterOrDigit(code)) { - throw new Error("Invalid cookie domain"); - } - if (!isLetterOrDigit(code) && code !== 45) { - throw new Error("Invalid cookie domain"); - } - if (++labelLength > 63) { - throw new Error("Invalid cookie domain"); - } - } - if (labelLength === 0 || domain.charCodeAt(domain.length - 1) === 45) { + if (domain.startsWith("-") || domain.endsWith(".") || domain.endsWith("-")) { throw new Error("Invalid cookie domain"); } } @@ -16276,11 +15973,7 @@ var require_util6 = __commonJS({ throw new Error("Invalid unparsed"); } const [key, ...value] = part.split("="); - const trimmedKey = key.trim(); - const joinedValue = value.join("="); - validateCookieName(trimmedKey); - validateCookieValue(joinedValue); - out.push(`${trimmedKey}=${joinedValue}`); + out.push(`${key.trim()}=${value.join("=")}`); } return out.join("; "); } @@ -16410,14 +16103,18 @@ var require_parse = __commonJS({ } else if (attributeNameLowercase === "httponly") { cookieAttributeList.httpOnly = true; } else if (attributeNameLowercase === "samesite") { + let enforcement = "Default"; const attributeValueLowercase = attributeValue.toLowerCase(); - if (attributeValueLowercase === "none") { - cookieAttributeList.sameSite = "None"; - } else if (attributeValueLowercase === "strict") { - cookieAttributeList.sameSite = "Strict"; - } else if (attributeValueLowercase === "lax") { - cookieAttributeList.sameSite = "Lax"; + if (attributeValueLowercase.includes("none")) { + enforcement = "None"; + } + if (attributeValueLowercase.includes("strict")) { + enforcement = "Strict"; + } + if (attributeValueLowercase.includes("lax")) { + enforcement = "Lax"; } + cookieAttributeList.sameSite = enforcement; } else { cookieAttributeList.unparsed ??= []; cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`); @@ -17239,7 +16936,7 @@ var require_connection = __commonJS({ const secProtocol = response.headersList.get("Sec-WebSocket-Protocol"); if (secProtocol !== null) { const requestProtocols = getDecodeSplit("sec-websocket-protocol", request2.headersList); - if (requestProtocols === null || !requestProtocols.includes(secProtocol)) { + if (!requestProtocols.includes(secProtocol)) { failWebsocketConnection(ws, "Protocol was not set in the opening handshake."); return; } @@ -17345,26 +17042,31 @@ var require_permessage_deflate = __commonJS({ var tail = Buffer.from([0, 0, 255, 255]); var kBuffer = /* @__PURE__ */ Symbol("kBuffer"); var kLength = /* @__PURE__ */ Symbol("kLength"); + var kDefaultMaxDecompressedSize = 4 * 1024 * 1024; var PerMessageDeflate = class { /** @type {import('node:zlib').InflateRaw} */ #inflate; #options = {}; - #maxPayloadSize = 0; + /** @type {number} */ + #maxDecompressedSize; + /** @type {boolean} */ + #aborted = false; + /** @type {Function|null} */ + #currentCallback = null; /** * @param {Map} extensions + * @param {{ maxDecompressedMessageSize?: number }} [options] */ - constructor(extensions, options) { + constructor(extensions, options = {}) { this.#options.serverNoContextTakeover = extensions.has("server_no_context_takeover"); this.#options.serverMaxWindowBits = extensions.get("server_max_window_bits"); - this.#maxPayloadSize = options.maxPayloadSize; + this.#maxDecompressedSize = options.maxDecompressedMessageSize ?? kDefaultMaxDecompressedSize; } - /** - * Decompress a compressed payload. - * @param {Buffer} chunk Compressed data - * @param {boolean} fin Final fragment flag - * @param {Function} callback Callback function - */ decompress(chunk, fin, callback) { + if (this.#aborted) { + callback(new MessageSizeExceededError()); + return; + } if (!this.#inflate) { let windowBits = Z_DEFAULT_WINDOWBITS; if (this.#options.serverMaxWindowBits) { @@ -17383,12 +17085,20 @@ var require_permessage_deflate = __commonJS({ this.#inflate[kBuffer] = []; this.#inflate[kLength] = 0; this.#inflate.on("data", (data) => { + if (this.#aborted) { + return; + } this.#inflate[kLength] += data.length; - if (this.#maxPayloadSize > 0 && this.#inflate[kLength] > this.#maxPayloadSize) { - callback(new MessageSizeExceededError()); + if (this.#inflate[kLength] > this.#maxDecompressedSize) { + this.#aborted = true; this.#inflate.removeAllListeners(); this.#inflate.destroy(); this.#inflate = null; + if (this.#currentCallback) { + const cb = this.#currentCallback; + this.#currentCallback = null; + cb(new MessageSizeExceededError()); + } return; } this.#inflate[kBuffer].push(data); @@ -17398,17 +17108,19 @@ var require_permessage_deflate = __commonJS({ callback(err); }); } + this.#currentCallback = callback; this.#inflate.write(chunk); if (fin) { this.#inflate.write(tail); } this.#inflate.flush(() => { - if (!this.#inflate) { + if (this.#aborted || !this.#inflate) { return; } const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]); this.#inflate[kBuffer].length = 0; this.#inflate[kLength] = 0; + this.#currentCallback = null; callback(null, full); }); } @@ -17439,14 +17151,8 @@ var require_receiver = __commonJS({ var { WebsocketFrameSend } = require_frame(); var { closeWebSocketConnection } = require_connection(); var { PerMessageDeflate } = require_permessage_deflate(); - var { MessageSizeExceededError } = require_errors(); - function failWebsocketConnectionWithCode(ws, code, reason) { - closeWebSocketConnection(ws, code, reason, Buffer.byteLength(reason)); - failWebsocketConnection(ws, reason); - } var ByteParser = class extends Writable { #buffers = []; - #fragmentsBytes = 0; #byteOffset = 0; #loop = false; #state = parserStates.INFO; @@ -17454,21 +17160,18 @@ var require_receiver = __commonJS({ #fragments = []; /** @type {Map} */ #extensions; - /** @type {number} */ - #maxFragments; - /** @type {number} */ - #maxPayloadSize; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {import('./websocket').WebSocket} ws * @param {Map|null} extensions - * @param {{ maxFragments?: number, maxPayloadSize?: number }} [options] + * @param {{ maxDecompressedMessageSize?: number }} [options] */ constructor(ws, extensions, options = {}) { super(); this.ws = ws; this.#extensions = extensions == null ? /* @__PURE__ */ new Map() : extensions; - this.#maxFragments = options.maxFragments ?? 0; - this.#maxPayloadSize = options.maxPayloadSize ?? 0; + this.#options = options; if (this.#extensions.has("permessage-deflate")) { this.#extensions.set("permessage-deflate", new PerMessageDeflate(extensions, options)); } @@ -17483,13 +17186,6 @@ var require_receiver = __commonJS({ this.#loop = true; this.run(callback); } - #validatePayloadLength() { - if (this.#maxPayloadSize > 0 && !isControlFrame(this.#info.opcode) && this.#info.payloadLength + this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, "Payload size exceeds maximum allowed size"); - return false; - } - return true; - } /** * Runs whenever a new chunk is received. * Callback is called whenever there are no more chunks buffering, @@ -17549,9 +17245,6 @@ var require_receiver = __commonJS({ if (payloadLength <= 125) { this.#info.payloadLength = payloadLength; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (payloadLength === 126) { this.#state = parserStates.PAYLOADLENGTH_16; } else if (payloadLength === 127) { @@ -17572,9 +17265,6 @@ var require_receiver = __commonJS({ const buffer = this.consume(2); this.#info.payloadLength = buffer.readUInt16BE(0); this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.PAYLOADLENGTH_64) { if (this.#byteOffset < 8) { return callback(); @@ -17588,9 +17278,6 @@ var require_receiver = __commonJS({ } this.#info.payloadLength = lower; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.READ_DATA) { if (this.#byteOffset < this.#info.payloadLength) { return callback(); @@ -17601,46 +17288,32 @@ var require_receiver = __commonJS({ this.#state = parserStates.INFO; } else { if (!this.#info.compressed) { - if (!this.writeFragments(body)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } + this.#fragments.push(body); if (!this.#info.fragmented && this.#info.fin) { - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); + const fullMessage = Buffer.concat(this.#fragments); + websocketMessageReceived(this.ws, this.#info.binaryType, fullMessage); + this.#fragments.length = 0; } this.#state = parserStates.INFO; } else { - this.#extensions.get("permessage-deflate").decompress( - body, - this.#info.fin, - (error2, data) => { - if (error2) { - const code = error2 instanceof MessageSizeExceededError ? 1009 : 1007; - failWebsocketConnectionWithCode(this.ws, code, error2.message); - return; - } - if (!this.writeFragments(data)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } - if (!this.#info.fin) { - this.#state = parserStates.INFO; - this.#loop = true; - this.run(callback); - return; - } - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); - this.#loop = true; + this.#extensions.get("permessage-deflate").decompress(body, this.#info.fin, (error2, data) => { + if (error2) { + failWebsocketConnection(this.ws, error2.message); + return; + } + this.#fragments.push(data); + if (!this.#info.fin) { this.#state = parserStates.INFO; + this.#loop = true; this.run(callback); + return; } - ); + websocketMessageReceived(this.ws, this.#info.binaryType, Buffer.concat(this.#fragments)); + this.#loop = true; + this.#state = parserStates.INFO; + this.#fragments.length = 0; + this.run(callback); + }); this.#loop = false; break; } @@ -17683,26 +17356,6 @@ var require_receiver = __commonJS({ this.#byteOffset -= n; return buffer; } - writeFragments(fragment) { - if (this.#maxFragments > 0 && this.#fragments.length === this.#maxFragments) { - failWebsocketConnectionWithCode(this.ws, 1008, "Too many message fragments"); - return false; - } - this.#fragmentsBytes += fragment.length; - this.#fragments.push(fragment); - return true; - } - consumeFragments() { - const fragments = this.#fragments; - if (fragments.length === 1) { - this.#fragmentsBytes = 0; - return fragments.shift(); - } - const output = Buffer.concat(fragments, this.#fragmentsBytes); - this.#fragments = []; - this.#fragmentsBytes = 0; - return output; - } parseCloseBody(data) { assert(data.length !== 1); let code; @@ -17914,6 +17567,8 @@ var require_websocket = __commonJS({ #extensions = ""; /** @type {SendQueue} */ #sendQueue; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {string} url * @param {string|string[]} protocols @@ -17957,6 +17612,9 @@ var require_websocket = __commonJS({ throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError"); } this[kWebSocketURL] = new URL(urlRecord.href); + this.#options = { + maxDecompressedMessageSize: options.maxDecompressedMessageSize + }; const client = environmentSettingsObject.settingsObject; this[kController] = establishWebSocketConnection( urlRecord, @@ -18140,13 +17798,7 @@ var require_websocket = __commonJS({ */ #onConnectionEstablished(response, parsedExtensions) { this[kResponse] = response; - const webSocketOptions = this[kController]?.dispatcher?.webSocketOptions; - const maxFragments = webSocketOptions?.maxFragments; - const maxPayloadSize = webSocketOptions?.maxPayloadSize; - const parser = new ByteParser(this, parsedExtensions, { - maxFragments, - maxPayloadSize - }); + const parser = new ByteParser(this, parsedExtensions, this.#options); parser.on("drain", onParserDrain); parser.on("error", onParserError.bind(this)); response.socket.ws = this; @@ -18221,6 +17873,19 @@ var require_websocket = __commonJS({ { key: "headers", converter: webidl.nullableConverter(webidl.converters.HeadersInit) + }, + { + key: "maxDecompressedMessageSize", + converter: webidl.nullableConverter((V) => { + V = webidl.converters["unsigned long long"](V); + if (V <= 0) { + throw webidl.errors.exception({ + header: "WebSocket constructor", + message: "maxDecompressedMessageSize must be greater than 0" + }); + } + return V; + }) } ]); webidl.converters["DOMString or sequence or WebSocketInit"] = function(V) { @@ -18299,40 +17964,6 @@ 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; - } - function isValidLastEventIdBytes(buffer, start) { - for (let i = start; i < buffer.length; i++) { - if (buffer[i] === 0) { - 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; - } var EventSourceStream = class extends Transform { /** * @type {eventSourceSettings} @@ -18352,13 +17983,10 @@ var require_eventsource_stream = __commonJS({ */ eventEndCheck = false; /** - * @type {Buffer[]} + * @type {Buffer} */ - chunks = []; - chunkIndex = 0; + buffer = null; pos = 0; - lineChunkIndex = 0; - linePos = 0; event = { data: void 0, event: void 0, @@ -18389,30 +18017,63 @@ var require_eventsource_stream = __commonJS({ callback(); return; } - this.chunks.push(chunk); + if (this.buffer) { + this.buffer = Buffer.concat([this.buffer, chunk]); + } else { + this.buffer = chunk; + } if (this.checkBOM) { - if (this.handleBOM()) { - callback(); - return; + 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; } } - while (this.hasCurrentByte()) { - const byte = this.currentByte(); + while (this.pos < this.buffer.length) { if (this.eventEndCheck) { if (this.crlfCheck) { - if (byte === LF) { + if (this.buffer[this.pos] === LF) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.crlfCheck = false; - this.consumeCurrentByte(); continue; } this.crlfCheck = false; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.consumeCurrentByte(); - if (this.hasPendingEvent()) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; + if (this.event.data !== void 0 || this.event.event || this.event.id || this.event.retry) { this.processEvent(this.event); } this.clearEvent(); @@ -18421,16 +18082,17 @@ var require_eventsource_stream = __commonJS({ this.eventEndCheck = false; continue; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.parseLine(this.readLine(), this.event); - this.consumeCurrentByte(); + this.parseLine(this.buffer.subarray(0, this.pos), this.event); + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.eventEndCheck = true; continue; } - this.advanceCursor(); + this.pos++; } callback(); } @@ -18446,42 +18108,43 @@ var require_eventsource_stream = __commonJS({ if (colonPosition === 0) { return; } - let fieldLength = line.length; - let valueStart = line.length; + let field = ""; + let value = ""; if (colonPosition !== -1) { - fieldLength = colonPosition; - valueStart = colonPosition + 1; + field = line.subarray(0, colonPosition).toString("utf8"); + let valueStart = colonPosition + 1; if (line[valueStart] === SPACE) { ++valueStart; } + value = line.subarray(valueStart).toString("utf8"); + } else { + field = line.toString("utf8"); + value = ""; } - if (isFieldName(line, fieldLength, DATA)) { - const value = line.toString("utf8", valueStart); - if (event.data === void 0) { - event.data = value; - } else { - event.data += ` + switch (field) { + case "data": + if (event[field] === void 0) { + event[field] = value; + } else { + event[field] += ` ${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; - } + } + 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; } } /** @@ -18506,120 +18169,12 @@ ${value}`; } } clearEvent() { - 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(); + this.event = { + data: void 0, + event: void 0, + id: void 0, + retry: void 0 + }; } }; module.exports = { diff --git a/.github/actions/javascript/checkSVGCompression/index.js b/.github/actions/javascript/checkSVGCompression/index.js index cad1560febba..1bd2d9dfd701 100644 --- a/.github/actions/javascript/checkSVGCompression/index.js +++ b/.github/actions/javascript/checkSVGCompression/index.js @@ -1863,66 +1863,10 @@ var require_request = __commonJS({ return false; } } - /** - * @param {number|null} statusCode - * @param {Buffer[]|null} headers - * @param {import('node:stream').Duplex} socket - * @param {string} [statusText] - */ - onUpgrade(statusCode, headers, socket, statusText = "") { - this.onFinally(); + onUpgrade(statusCode, headers, socket) { assert(!this.aborted); assert(!this.completed); - 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(error2) { - assert(!this.aborted); - assert(this.completed); - if (channels.error.hasSubscribers) { - channels.error.publish({ request: this, error: error2 }); - } - } - /** - * @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: [] }); - } + return this[kHandler].onUpgrade(statusCode, headers, socket); } onComplete(trailers) { this.onFinally(); @@ -1989,11 +1933,7 @@ var require_request = __commonJS({ } else if (typeof val[i] === "object") { throw new InvalidArgumentError(`invalid ${key} header`); } else { - const str = `${val[i]}`; - if (!isValidHeaderValue(str)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } - arr.push(str); + arr.push(`${val[i]}`); } } val = arr; @@ -2005,9 +1945,6 @@ var require_request = __commonJS({ val = ""; } else { val = `${val}`; - if (!isValidHeaderValue(val)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } } if (headerName === "host") { if (request2.host !== null) { @@ -2117,21 +2054,13 @@ var require_dispatcher_base = __commonJS({ var kOnDestroyed = /* @__PURE__ */ Symbol("onDestroyed"); var kOnClosed = /* @__PURE__ */ Symbol("onClosed"); var kInterceptedDispatch = /* @__PURE__ */ Symbol("Intercepted Dispatch"); - var kWebSocketOptions = /* @__PURE__ */ Symbol("webSocketOptions"); var DispatcherBase = class extends Dispatcher { - constructor(opts) { + constructor() { super(); this[kDestroyed] = false; this[kOnDestroyed] = null; this[kClosed] = false; this[kOnClosed] = []; - this[kWebSocketOptions] = opts?.webSocket ?? {}; - } - get webSocketOptions() { - return { - maxFragments: this[kWebSocketOptions].maxFragments ?? 131072, - maxPayloadSize: this[kWebSocketOptions].maxPayloadSize ?? 128 * 1024 * 1024 - }; } get destroyed() { return this[kDestroyed]; @@ -5738,7 +5667,6 @@ var require_client_h1 = __commonJS({ RequestContentLengthMismatchError, ResponseContentLengthMismatchError, RequestAbortedError, - InvalidArgumentError, HeadersTimeoutError, HeadersOverflowError, SocketError, @@ -5785,9 +5713,6 @@ var require_client_h1 = __commonJS({ var FastBuffer = Buffer[Symbol.species]; var addListener = util.addListener; var removeAllListeners = util.removeAllListeners; - var kIdleSocketValidation = /* @__PURE__ */ Symbol("kIdleSocketValidation"); - var kIdleSocketValidationTimeout = /* @__PURE__ */ Symbol("kIdleSocketValidationTimeout"); - var kSocketUsed = /* @__PURE__ */ Symbol("kSocketUsed"); var extractBody; async function lazyllhttp() { const llhttpWasmData = process.env.JEST_WORKER_ID ? require_llhttp_wasm() : void 0; @@ -5950,55 +5875,24 @@ var require_client_h1 = __commonJS({ currentBufferRef = null; } const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr; - if (ret !== constants3.ERROR.OK) { - const body = data.subarray(offset); - if (ret === constants3.ERROR.PAUSED_UPGRADE) { - this.onUpgrade(body); - } else if (ret === constants3.ERROR.PAUSED) { - this.paused = true; - socket.unshift(body); - } else { - throw this.createError(ret, body); + if (ret === constants3.ERROR.PAUSED_UPGRADE) { + this.onUpgrade(data.slice(offset)); + } else if (ret === constants3.ERROR.PAUSED) { + this.paused = true; + socket.unshift(data.slice(offset)); + } else if (ret !== constants3.ERROR.OK) { + const ptr = llhttp.llhttp_get_error_reason(this.ptr); + let message = ""; + if (ptr) { + const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); + message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; } + throw new HTTPParserError(message, constants3.ERROR[ret], data.slice(offset)); } } catch (err) { util.destroy(socket, err); } } - finish() { - assert(currentParser === null); - assert(this.ptr != null); - assert(!this.paused); - const { llhttp } = this; - let ret; - try { - currentParser = this; - ret = llhttp.llhttp_finish(this.ptr); - } finally { - currentParser = null; - } - if (ret === constants3.ERROR.OK) { - return null; - } - if (ret === constants3.ERROR.PAUSED || ret === constants3.ERROR.PAUSED_UPGRADE) { - this.paused = true; - return null; - } - return this.createError(ret, EMPTY_BUF); - } - createError(ret, data) { - const { llhttp, contentLength, bytesRead } = this; - if (contentLength && bytesRead !== parseInt(contentLength, 10)) { - return new ResponseContentLengthMismatchError(); - } - const ptr = llhttp.llhttp_get_error_reason(this.ptr); - let message = ""; - if (ptr) { - const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); - message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; - } - return new HTTPParserError(message, constants3.ERROR[ret], data); - } destroy() { assert(this.ptr != null); assert(currentParser == null); @@ -6018,10 +5912,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6065,7 +5955,7 @@ var require_client_h1 = __commonJS({ } } onUpgrade(head) { - const { upgrade, client, socket, headers, statusCode, statusText } = this; + const { upgrade, client, socket, headers, statusCode } = this; assert(upgrade); assert(client[kSocket] === socket); assert(!socket.destroyed); @@ -6090,10 +5980,9 @@ var require_client_h1 = __commonJS({ client[kQueue][client[kRunningIdx]++] = null; client.emit("disconnect", client[kUrl], [client], new InformationalError("upgrade")); try { - request2.onUpgrade(statusCode, headers, socket, statusText); - } catch (error2) { - util.errorRequest(client, request2, error2); - util.destroy(socket, error2); + request2.onUpgrade(statusCode, headers, socket); + } catch (err) { + util.destroy(socket, err); } client[kResume](); } @@ -6102,10 +5991,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6231,7 +6116,6 @@ var require_client_h1 = __commonJS({ } request2.onComplete(headers); client[kQueue][client[kRunningIdx]++] = null; - socket[kSocketUsed] = true; if (socket[kWriting]) { assert(client[kRunning] === 0); util.destroy(socket, new InformationalError("reset")); @@ -6275,19 +6159,12 @@ var require_client_h1 = __commonJS({ socket[kWriting] = false; socket[kReset] = false; socket[kBlocking] = false; - socket[kIdleSocketValidation] = 0; - socket[kIdleSocketValidationTimeout] = null; - socket[kSocketUsed] = false; socket[kParser] = new Parser(client, socket, llhttpInstance); addListener(socket, "error", function(err) { assert(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID"); const parser = this[kParser]; if (err.code === "ECONNRESET" && parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - this[kError] = parserErr; - this[kClient][kOnError](parserErr); - } + parser.onMessageComplete(); return; } this[kError] = err; @@ -6302,10 +6179,7 @@ var require_client_h1 = __commonJS({ addListener(socket, "end", function() { const parser = this[kParser]; if (parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - util.destroy(this, parserErr); - } + parser.onMessageComplete(); return; } util.destroy(this, new SocketError("other side closed", util.getSocketInfo(this))); @@ -6313,10 +6187,9 @@ var require_client_h1 = __commonJS({ addListener(socket, "close", function() { const client2 = this[kClient]; const parser = this[kParser]; - clearIdleSocketValidation(this); if (parser) { if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { - this[kError] = parser.finish() || this[kError]; + parser.onMessageComplete(); } this[kParser].destroy(); this[kParser] = null; @@ -6365,7 +6238,7 @@ var require_client_h1 = __commonJS({ return socket.destroyed; }, busy(request2) { - if (socket[kWriting] || socket[kReset] || socket[kBlocking] || socket[kIdleSocketValidation] === 1) { + if (socket[kWriting] || socket[kReset] || socket[kBlocking]) { return true; } if (request2) { @@ -6383,23 +6256,6 @@ var require_client_h1 = __commonJS({ } }; } - function clearIdleSocketValidation(socket) { - if (socket[kIdleSocketValidationTimeout]) { - clearImmediate(socket[kIdleSocketValidationTimeout]); - socket[kIdleSocketValidationTimeout] = null; - } - socket[kIdleSocketValidation] = 0; - } - function scheduleIdleSocketValidation(client, socket) { - socket[kIdleSocketValidation] = 1; - socket[kIdleSocketValidationTimeout] = setImmediate(() => { - socket[kIdleSocketValidationTimeout] = null; - socket[kIdleSocketValidation] = 2; - if (client[kSocket] === socket && !socket.destroyed) { - client[kResume](); - } - }); - } function resumeH1(client) { const socket = client[kSocket]; if (socket && !socket.destroyed) { @@ -6412,29 +6268,6 @@ var require_client_h1 = __commonJS({ socket.ref(); socket[kNoRef] = false; } - if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) { - if (socket[kIdleSocketValidation] === 0) { - scheduleIdleSocketValidation(client, socket); - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - if (socket[kIdleSocketValidation] === 1) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - } - if (client[kRunning] === 0) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - } if (client[kSize] === 0) { if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) { socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE); @@ -6465,16 +6298,8 @@ var require_client_h1 = __commonJS({ } body = bodyStream.stream; contentLength = bodyStream.length; - } else if (util.isBlobLike(body) && request2.contentType == null) { - const contentType = body.type; - if (contentType) { - const contentTypeValue = `${contentType}`; - if (!util.isValidHeaderValue(contentTypeValue)) { - util.errorRequest(client, request2, new InvalidArgumentError("invalid content-type header")); - return false; - } - headers.push("content-type", contentTypeValue); - } + } else if (util.isBlobLike(body) && request2.contentType == null && body.type) { + headers.push("content-type", body.type); } if (body && typeof body.read === "function") { body.read(0); @@ -6495,18 +6320,11 @@ var require_client_h1 = __commonJS({ process.emitWarning(new RequestContentLengthMismatchError()); } const socket = client[kSocket]; - clearIdleSocketValidation(socket); - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (request2.upgrade || request2.method === "CONNECT") { - util.destroy(socket, new InformationalError("aborted")); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - util.errorRequest(client, request2, error2 || new RequestAbortedError()); + util.errorRequest(client, request2, err || new RequestAbortedError()); util.destroy(body); util.destroy(socket, new InformationalError("aborted")); }; @@ -6862,7 +6680,6 @@ var require_client_h2 = __commonJS({ "node_modules/undici/lib/dispatcher/client-h2.js"(exports, module) { "use strict"; var assert = __require("node:assert"); - var { errorMonitor } = __require("node:events"); var { pipeline } = __require("node:stream"); var util = require_util(); var { @@ -6923,10 +6740,6 @@ var require_client_h2 = __commonJS({ } return result; } - function parseH2ResponseHeaders(headers) { - const { [HTTP2_HEADER_STATUS]: _statusCode, ...realHeaders } = headers; - return parseH2Headers(realHeaders); - } async function connectH2(client, socket) { client[kSocket] = socket; if (!h2ExperimentalWarned) { @@ -7090,22 +6903,16 @@ var require_client_h2 = __commonJS({ const { hostname, port } = client[kUrl]; headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ""}`; headers[HTTP2_HEADER_METHOD] = method; - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (method === "CONNECT" && stream != null) { - util.destroy(stream, error2 || new RequestAbortedError()); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - error2 = error2 || new RequestAbortedError(); - util.errorRequest(client, request2, error2); + err = err || new RequestAbortedError(); + util.errorRequest(client, request2, err); if (stream != null) { - util.destroy(stream, error2); + util.destroy(stream, err); } - util.destroy(body, error2); + util.destroy(body, err); client[kQueue][client[kRunningIdx]++] = null; client[kResume](); }; @@ -7120,42 +6927,18 @@ var require_client_h2 = __commonJS({ if (method === "CONNECT") { session.ref(); stream = session.request(headers, { endStream: false, signal }); - let upgradeResponseFinished = false; - const onResponse = (headers2) => { - upgradeResponseFinished = true; - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeResponse(Number(headers2[HTTP2_HEADER_STATUS]), headers2, parseH2ResponseHeaders); - }; - const onUpgradeError = (error2) => { - upgradeResponseFinished = true; - stream.off("response", onResponse); - request2.onUpgradeError(error2); - }; - const onReady = () => { - try { - request2.onUpgrade(null, null, stream); - } catch (error2) { - stream.off("response", onResponse); - abort(error2); - return; - } - if (request2.aborted) { - return; - } - stream.off("error", abort); - stream.once(errorMonitor, onUpgradeError); + if (stream.id && !stream.pending) { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; client[kQueue][client[kRunningIdx]++] = null; - }; - stream.once("response", onResponse); - stream.once("error", abort); - ++session[kOpenStreams]; - onReady(); + } else { + stream.once("ready", () => { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; + client[kQueue][client[kRunningIdx]++] = null; + }); + } stream.once("close", () => { - if (!upgradeResponseFinished && request2.completed) { - stream.off("response", onResponse); - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeError(new InformationalError(`HTTP/2: "stream error" received - code ${stream.rstCode}`)); - } session[kOpenStreams] -= 1; if (session[kOpenStreams] === 0) session.unref(); }); @@ -7716,10 +7499,9 @@ var require_client = __commonJS({ autoSelectFamilyAttemptTimeout, // h2 maxConcurrentStreams, - allowH2, - webSocket + allowH2 } = {}) { - super({ webSocket }); + super(); if (keepAlive !== void 0) { throw new InvalidArgumentError("unsupported keepAlive, use pipelining=0 instead"); } @@ -8225,8 +8007,8 @@ var require_pool_base = __commonJS({ var kRemoveClient = /* @__PURE__ */ Symbol("remove client"); var kStats = /* @__PURE__ */ Symbol("stats"); var PoolBase = class extends DispatcherBase { - constructor(opts) { - super(opts); + constructor() { + super(); this[kQueue] = new FixedQueue(); this[kClients] = []; this[kQueued] = 0; @@ -8397,6 +8179,7 @@ var require_pool = __commonJS({ allowH2, ...options } = {}) { + super(); if (connections != null && (!Number.isFinite(connections) || connections < 0)) { throw new InvalidArgumentError("invalid connections"); } @@ -8417,7 +8200,6 @@ var require_pool = __commonJS({ ...connect }); } - super(options); this[kInterceptors] = options.interceptors?.Pool && Array.isArray(options.interceptors.Pool) ? options.interceptors.Pool : []; this[kConnections] = connections || null; this[kUrl] = util.parseOrigin(origin); @@ -8617,6 +8399,7 @@ var require_agent = __commonJS({ } var Agent = class extends DispatcherBase { constructor({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { + super(); if (typeof factory !== "function") { throw new InvalidArgumentError("factory must be a function."); } @@ -8626,7 +8409,6 @@ var require_agent = __commonJS({ if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { throw new InvalidArgumentError("maxRedirections must be a positive number"); } - super(options); if (connect && typeof connect !== "function") { connect = { ...connect }; } @@ -9067,24 +8849,6 @@ var require_retry_handler = __commonJS({ const current = Date.now(); return new Date(retryAfter).getTime() - current; } - function validatePartialResponseContentLength(headers, range, statusCode, retryCount) { - const contentLength = headers["content-length"]; - if (contentLength == null) { - return null; - } - if (!Number.isFinite(range.start) || !Number.isFinite(range.end)) { - return null; - } - const length = Number(contentLength); - const expectedLength = range.end - range.start + 1; - if (!Number.isFinite(length) || length !== expectedLength) { - return new RequestRetryError("Content-Length mismatch", statusCode, { - headers, - data: { count: retryCount } - }); - } - return null; - } var RetryHandler = class _RetryHandler { constructor(opts, handlers) { const { retryOptions, ...dispatchOpts } = opts; @@ -9138,7 +8902,6 @@ var require_retry_handler = __commonJS({ this.end = null; this.etag = null; this.resume = null; - this.headersSent = false; this.handler.onConnect((reason) => { this.aborted = true; if (this.abort) { @@ -9148,17 +8911,6 @@ var require_retry_handler = __commonJS({ } }); } - 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(); @@ -9220,9 +8972,7 @@ var require_retry_handler = __commonJS({ const headers = parseHeaders(rawHeaders); this.retryCount += 1; if (statusCode >= 300) { - if (!this.headersSent && this.retryOpts.statusCodes.includes(statusCode) === false) { - this.headersSent = true; - this.checkpointResponseEnd(headers, resume); + if (this.retryOpts.statusCodes.includes(statusCode) === false) { return this.handler.onHeaders( statusCode, rawHeaders, @@ -9271,21 +9021,9 @@ var require_retry_handler = __commonJS({ ); return false; } - const contentLengthError = validatePartialResponseContentLength(headers, contentRange, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = contentRange; - 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; - } + assert(this.start === start, "content-range mismatch"); + assert(this.end == null || this.end === end, "content-range mismatch"); this.resume = resume; return true; } @@ -9293,7 +9031,6 @@ var require_retry_handler = __commonJS({ if (statusCode === 206) { const range = parseRangeHeader(headers["content-range"]); if (range == null) { - this.headersSent = true; return this.handler.onHeaders( statusCode, rawHeaders, @@ -9301,11 +9038,6 @@ var require_retry_handler = __commonJS({ statusMessage ); } - const contentLengthError = validatePartialResponseContentLength(headers, range, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = range; assert( start != null && Number.isFinite(start), @@ -9325,7 +9057,6 @@ var require_retry_handler = __commonJS({ "invalid content-length" ); this.resume = resume; - this.headersSent = true; this.etag = headers.etag != null ? headers.etag : null; if (this.etag != null && this.etag.startsWith("W/")) { this.etag = null; @@ -9353,7 +9084,7 @@ var require_retry_handler = __commonJS({ return this.handler.onComplete(rawTrailers); } onError(err) { - if (this.aborted || isDisturbed(this.opts.body) || this.headersSent && this.resume == null) { + if (this.aborted || isDisturbed(this.opts.body)) { return this.handler.onError(err); } if (this.retryCount - this.retryCountCheckpoint > 0) { @@ -16152,48 +15883,14 @@ var require_util6 = __commonJS({ for (let i = 0; i < path2.length; ++i) { const code = path2.charCodeAt(i); if (code < 32 || // exclude CTLs (0-31) - code > 126 || // exclude DEL and non-ascii + code === 127 || // DEL code === 59) { throw new Error("Invalid cookie path"); } } } - function isLetterOrDigit(code) { - return code >= 48 && code <= 57 || // 0-9 - code >= 65 && code <= 90 || // A-Z - code >= 97 && code <= 122; - } function validateCookieDomain(domain) { - if (domain === " ") { - return; - } - if (domain.length > 255) { - throw new Error("Invalid cookie domain"); - } - let labelLength = 0; - for (let i = 0; i < domain.length; ++i) { - const code = domain.charCodeAt(i); - if (code === 46) { - if (labelLength === 0) { - throw new Error("Invalid cookie domain"); - } - if (domain.charCodeAt(i - 1) === 45) { - throw new Error("Invalid cookie domain"); - } - labelLength = 0; - continue; - } - if (labelLength === 0 && !isLetterOrDigit(code)) { - throw new Error("Invalid cookie domain"); - } - if (!isLetterOrDigit(code) && code !== 45) { - throw new Error("Invalid cookie domain"); - } - if (++labelLength > 63) { - throw new Error("Invalid cookie domain"); - } - } - if (labelLength === 0 || domain.charCodeAt(domain.length - 1) === 45) { + if (domain.startsWith("-") || domain.endsWith(".") || domain.endsWith("-")) { throw new Error("Invalid cookie domain"); } } @@ -16276,11 +15973,7 @@ var require_util6 = __commonJS({ throw new Error("Invalid unparsed"); } const [key, ...value] = part.split("="); - const trimmedKey = key.trim(); - const joinedValue = value.join("="); - validateCookieName(trimmedKey); - validateCookieValue(joinedValue); - out.push(`${trimmedKey}=${joinedValue}`); + out.push(`${key.trim()}=${value.join("=")}`); } return out.join("; "); } @@ -16410,14 +16103,18 @@ var require_parse = __commonJS({ } else if (attributeNameLowercase === "httponly") { cookieAttributeList.httpOnly = true; } else if (attributeNameLowercase === "samesite") { + let enforcement = "Default"; const attributeValueLowercase = attributeValue.toLowerCase(); - if (attributeValueLowercase === "none") { - cookieAttributeList.sameSite = "None"; - } else if (attributeValueLowercase === "strict") { - cookieAttributeList.sameSite = "Strict"; - } else if (attributeValueLowercase === "lax") { - cookieAttributeList.sameSite = "Lax"; + if (attributeValueLowercase.includes("none")) { + enforcement = "None"; + } + if (attributeValueLowercase.includes("strict")) { + enforcement = "Strict"; + } + if (attributeValueLowercase.includes("lax")) { + enforcement = "Lax"; } + cookieAttributeList.sameSite = enforcement; } else { cookieAttributeList.unparsed ??= []; cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`); @@ -17239,7 +16936,7 @@ var require_connection = __commonJS({ const secProtocol = response.headersList.get("Sec-WebSocket-Protocol"); if (secProtocol !== null) { const requestProtocols = getDecodeSplit("sec-websocket-protocol", request2.headersList); - if (requestProtocols === null || !requestProtocols.includes(secProtocol)) { + if (!requestProtocols.includes(secProtocol)) { failWebsocketConnection(ws, "Protocol was not set in the opening handshake."); return; } @@ -17345,26 +17042,31 @@ var require_permessage_deflate = __commonJS({ var tail = Buffer.from([0, 0, 255, 255]); var kBuffer = /* @__PURE__ */ Symbol("kBuffer"); var kLength = /* @__PURE__ */ Symbol("kLength"); + var kDefaultMaxDecompressedSize = 4 * 1024 * 1024; var PerMessageDeflate = class { /** @type {import('node:zlib').InflateRaw} */ #inflate; #options = {}; - #maxPayloadSize = 0; + /** @type {number} */ + #maxDecompressedSize; + /** @type {boolean} */ + #aborted = false; + /** @type {Function|null} */ + #currentCallback = null; /** * @param {Map} extensions + * @param {{ maxDecompressedMessageSize?: number }} [options] */ - constructor(extensions, options) { + constructor(extensions, options = {}) { this.#options.serverNoContextTakeover = extensions.has("server_no_context_takeover"); this.#options.serverMaxWindowBits = extensions.get("server_max_window_bits"); - this.#maxPayloadSize = options.maxPayloadSize; + this.#maxDecompressedSize = options.maxDecompressedMessageSize ?? kDefaultMaxDecompressedSize; } - /** - * Decompress a compressed payload. - * @param {Buffer} chunk Compressed data - * @param {boolean} fin Final fragment flag - * @param {Function} callback Callback function - */ decompress(chunk, fin, callback) { + if (this.#aborted) { + callback(new MessageSizeExceededError()); + return; + } if (!this.#inflate) { let windowBits = Z_DEFAULT_WINDOWBITS; if (this.#options.serverMaxWindowBits) { @@ -17383,12 +17085,20 @@ var require_permessage_deflate = __commonJS({ this.#inflate[kBuffer] = []; this.#inflate[kLength] = 0; this.#inflate.on("data", (data) => { + if (this.#aborted) { + return; + } this.#inflate[kLength] += data.length; - if (this.#maxPayloadSize > 0 && this.#inflate[kLength] > this.#maxPayloadSize) { - callback(new MessageSizeExceededError()); + if (this.#inflate[kLength] > this.#maxDecompressedSize) { + this.#aborted = true; this.#inflate.removeAllListeners(); this.#inflate.destroy(); this.#inflate = null; + if (this.#currentCallback) { + const cb = this.#currentCallback; + this.#currentCallback = null; + cb(new MessageSizeExceededError()); + } return; } this.#inflate[kBuffer].push(data); @@ -17398,17 +17108,19 @@ var require_permessage_deflate = __commonJS({ callback(err); }); } + this.#currentCallback = callback; this.#inflate.write(chunk); if (fin) { this.#inflate.write(tail); } this.#inflate.flush(() => { - if (!this.#inflate) { + if (this.#aborted || !this.#inflate) { return; } const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]); this.#inflate[kBuffer].length = 0; this.#inflate[kLength] = 0; + this.#currentCallback = null; callback(null, full); }); } @@ -17439,14 +17151,8 @@ var require_receiver = __commonJS({ var { WebsocketFrameSend } = require_frame(); var { closeWebSocketConnection } = require_connection(); var { PerMessageDeflate } = require_permessage_deflate(); - var { MessageSizeExceededError } = require_errors(); - function failWebsocketConnectionWithCode(ws, code, reason) { - closeWebSocketConnection(ws, code, reason, Buffer.byteLength(reason)); - failWebsocketConnection(ws, reason); - } var ByteParser = class extends Writable { #buffers = []; - #fragmentsBytes = 0; #byteOffset = 0; #loop = false; #state = parserStates.INFO; @@ -17454,21 +17160,18 @@ var require_receiver = __commonJS({ #fragments = []; /** @type {Map} */ #extensions; - /** @type {number} */ - #maxFragments; - /** @type {number} */ - #maxPayloadSize; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {import('./websocket').WebSocket} ws * @param {Map|null} extensions - * @param {{ maxFragments?: number, maxPayloadSize?: number }} [options] + * @param {{ maxDecompressedMessageSize?: number }} [options] */ constructor(ws, extensions, options = {}) { super(); this.ws = ws; this.#extensions = extensions == null ? /* @__PURE__ */ new Map() : extensions; - this.#maxFragments = options.maxFragments ?? 0; - this.#maxPayloadSize = options.maxPayloadSize ?? 0; + this.#options = options; if (this.#extensions.has("permessage-deflate")) { this.#extensions.set("permessage-deflate", new PerMessageDeflate(extensions, options)); } @@ -17483,13 +17186,6 @@ var require_receiver = __commonJS({ this.#loop = true; this.run(callback); } - #validatePayloadLength() { - if (this.#maxPayloadSize > 0 && !isControlFrame(this.#info.opcode) && this.#info.payloadLength + this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, "Payload size exceeds maximum allowed size"); - return false; - } - return true; - } /** * Runs whenever a new chunk is received. * Callback is called whenever there are no more chunks buffering, @@ -17549,9 +17245,6 @@ var require_receiver = __commonJS({ if (payloadLength <= 125) { this.#info.payloadLength = payloadLength; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (payloadLength === 126) { this.#state = parserStates.PAYLOADLENGTH_16; } else if (payloadLength === 127) { @@ -17572,9 +17265,6 @@ var require_receiver = __commonJS({ const buffer = this.consume(2); this.#info.payloadLength = buffer.readUInt16BE(0); this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.PAYLOADLENGTH_64) { if (this.#byteOffset < 8) { return callback(); @@ -17588,9 +17278,6 @@ var require_receiver = __commonJS({ } this.#info.payloadLength = lower; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.READ_DATA) { if (this.#byteOffset < this.#info.payloadLength) { return callback(); @@ -17601,46 +17288,32 @@ var require_receiver = __commonJS({ this.#state = parserStates.INFO; } else { if (!this.#info.compressed) { - if (!this.writeFragments(body)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } + this.#fragments.push(body); if (!this.#info.fragmented && this.#info.fin) { - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); + const fullMessage = Buffer.concat(this.#fragments); + websocketMessageReceived(this.ws, this.#info.binaryType, fullMessage); + this.#fragments.length = 0; } this.#state = parserStates.INFO; } else { - this.#extensions.get("permessage-deflate").decompress( - body, - this.#info.fin, - (error2, data) => { - if (error2) { - const code = error2 instanceof MessageSizeExceededError ? 1009 : 1007; - failWebsocketConnectionWithCode(this.ws, code, error2.message); - return; - } - if (!this.writeFragments(data)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } - if (!this.#info.fin) { - this.#state = parserStates.INFO; - this.#loop = true; - this.run(callback); - return; - } - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); - this.#loop = true; + this.#extensions.get("permessage-deflate").decompress(body, this.#info.fin, (error2, data) => { + if (error2) { + failWebsocketConnection(this.ws, error2.message); + return; + } + this.#fragments.push(data); + if (!this.#info.fin) { this.#state = parserStates.INFO; + this.#loop = true; this.run(callback); + return; } - ); + websocketMessageReceived(this.ws, this.#info.binaryType, Buffer.concat(this.#fragments)); + this.#loop = true; + this.#state = parserStates.INFO; + this.#fragments.length = 0; + this.run(callback); + }); this.#loop = false; break; } @@ -17683,26 +17356,6 @@ var require_receiver = __commonJS({ this.#byteOffset -= n; return buffer; } - writeFragments(fragment) { - if (this.#maxFragments > 0 && this.#fragments.length === this.#maxFragments) { - failWebsocketConnectionWithCode(this.ws, 1008, "Too many message fragments"); - return false; - } - this.#fragmentsBytes += fragment.length; - this.#fragments.push(fragment); - return true; - } - consumeFragments() { - const fragments = this.#fragments; - if (fragments.length === 1) { - this.#fragmentsBytes = 0; - return fragments.shift(); - } - const output = Buffer.concat(fragments, this.#fragmentsBytes); - this.#fragments = []; - this.#fragmentsBytes = 0; - return output; - } parseCloseBody(data) { assert(data.length !== 1); let code; @@ -17914,6 +17567,8 @@ var require_websocket = __commonJS({ #extensions = ""; /** @type {SendQueue} */ #sendQueue; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {string} url * @param {string|string[]} protocols @@ -17957,6 +17612,9 @@ var require_websocket = __commonJS({ throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError"); } this[kWebSocketURL] = new URL(urlRecord.href); + this.#options = { + maxDecompressedMessageSize: options.maxDecompressedMessageSize + }; const client = environmentSettingsObject.settingsObject; this[kController] = establishWebSocketConnection( urlRecord, @@ -18140,13 +17798,7 @@ var require_websocket = __commonJS({ */ #onConnectionEstablished(response, parsedExtensions) { this[kResponse] = response; - const webSocketOptions = this[kController]?.dispatcher?.webSocketOptions; - const maxFragments = webSocketOptions?.maxFragments; - const maxPayloadSize = webSocketOptions?.maxPayloadSize; - const parser = new ByteParser(this, parsedExtensions, { - maxFragments, - maxPayloadSize - }); + const parser = new ByteParser(this, parsedExtensions, this.#options); parser.on("drain", onParserDrain); parser.on("error", onParserError.bind(this)); response.socket.ws = this; @@ -18221,6 +17873,19 @@ var require_websocket = __commonJS({ { key: "headers", converter: webidl.nullableConverter(webidl.converters.HeadersInit) + }, + { + key: "maxDecompressedMessageSize", + converter: webidl.nullableConverter((V) => { + V = webidl.converters["unsigned long long"](V); + if (V <= 0) { + throw webidl.errors.exception({ + header: "WebSocket constructor", + message: "maxDecompressedMessageSize must be greater than 0" + }); + } + return V; + }) } ]); webidl.converters["DOMString or sequence or WebSocketInit"] = function(V) { @@ -18299,40 +17964,6 @@ 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; - } - function isValidLastEventIdBytes(buffer, start) { - for (let i = start; i < buffer.length; i++) { - if (buffer[i] === 0) { - 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; - } var EventSourceStream = class extends Transform { /** * @type {eventSourceSettings} @@ -18352,13 +17983,10 @@ var require_eventsource_stream = __commonJS({ */ eventEndCheck = false; /** - * @type {Buffer[]} + * @type {Buffer} */ - chunks = []; - chunkIndex = 0; + buffer = null; pos = 0; - lineChunkIndex = 0; - linePos = 0; event = { data: void 0, event: void 0, @@ -18389,30 +18017,63 @@ var require_eventsource_stream = __commonJS({ callback(); return; } - this.chunks.push(chunk); + if (this.buffer) { + this.buffer = Buffer.concat([this.buffer, chunk]); + } else { + this.buffer = chunk; + } if (this.checkBOM) { - if (this.handleBOM()) { - callback(); - return; + 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; } } - while (this.hasCurrentByte()) { - const byte = this.currentByte(); + while (this.pos < this.buffer.length) { if (this.eventEndCheck) { if (this.crlfCheck) { - if (byte === LF) { + if (this.buffer[this.pos] === LF) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.crlfCheck = false; - this.consumeCurrentByte(); continue; } this.crlfCheck = false; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.consumeCurrentByte(); - if (this.hasPendingEvent()) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; + if (this.event.data !== void 0 || this.event.event || this.event.id || this.event.retry) { this.processEvent(this.event); } this.clearEvent(); @@ -18421,16 +18082,17 @@ var require_eventsource_stream = __commonJS({ this.eventEndCheck = false; continue; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.parseLine(this.readLine(), this.event); - this.consumeCurrentByte(); + this.parseLine(this.buffer.subarray(0, this.pos), this.event); + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.eventEndCheck = true; continue; } - this.advanceCursor(); + this.pos++; } callback(); } @@ -18446,42 +18108,43 @@ var require_eventsource_stream = __commonJS({ if (colonPosition === 0) { return; } - let fieldLength = line.length; - let valueStart = line.length; + let field = ""; + let value = ""; if (colonPosition !== -1) { - fieldLength = colonPosition; - valueStart = colonPosition + 1; + field = line.subarray(0, colonPosition).toString("utf8"); + let valueStart = colonPosition + 1; if (line[valueStart] === SPACE) { ++valueStart; } + value = line.subarray(valueStart).toString("utf8"); + } else { + field = line.toString("utf8"); + value = ""; } - if (isFieldName(line, fieldLength, DATA)) { - const value = line.toString("utf8", valueStart); - if (event.data === void 0) { - event.data = value; - } else { - event.data += ` + switch (field) { + case "data": + if (event[field] === void 0) { + event[field] = value; + } else { + event[field] += ` ${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; - } + } + 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; } } /** @@ -18506,120 +18169,12 @@ ${value}`; } } clearEvent() { - 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(); + this.event = { + data: void 0, + event: void 0, + id: void 0, + retry: void 0 + }; } }; module.exports = { diff --git a/.github/actions/javascript/failureNotifier/index.js b/.github/actions/javascript/failureNotifier/index.js index 208e6286e656..7eedc830062e 100644 --- a/.github/actions/javascript/failureNotifier/index.js +++ b/.github/actions/javascript/failureNotifier/index.js @@ -1863,66 +1863,10 @@ var require_request = __commonJS({ return false; } } - /** - * @param {number|null} statusCode - * @param {Buffer[]|null} headers - * @param {import('node:stream').Duplex} socket - * @param {string} [statusText] - */ - onUpgrade(statusCode, headers, socket, statusText = "") { - this.onFinally(); + onUpgrade(statusCode, headers, socket) { assert(!this.aborted); assert(!this.completed); - 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(error2) { - assert(!this.aborted); - assert(this.completed); - if (channels.error.hasSubscribers) { - channels.error.publish({ request: this, error: error2 }); - } - } - /** - * @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: [] }); - } + return this[kHandler].onUpgrade(statusCode, headers, socket); } onComplete(trailers) { this.onFinally(); @@ -1989,11 +1933,7 @@ var require_request = __commonJS({ } else if (typeof val[i] === "object") { throw new InvalidArgumentError(`invalid ${key} header`); } else { - const str = `${val[i]}`; - if (!isValidHeaderValue(str)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } - arr.push(str); + arr.push(`${val[i]}`); } } val = arr; @@ -2005,9 +1945,6 @@ var require_request = __commonJS({ val = ""; } else { val = `${val}`; - if (!isValidHeaderValue(val)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } } if (headerName === "host") { if (request2.host !== null) { @@ -2117,21 +2054,13 @@ var require_dispatcher_base = __commonJS({ var kOnDestroyed = /* @__PURE__ */ Symbol("onDestroyed"); var kOnClosed = /* @__PURE__ */ Symbol("onClosed"); var kInterceptedDispatch = /* @__PURE__ */ Symbol("Intercepted Dispatch"); - var kWebSocketOptions = /* @__PURE__ */ Symbol("webSocketOptions"); var DispatcherBase = class extends Dispatcher { - constructor(opts) { + constructor() { super(); this[kDestroyed] = false; this[kOnDestroyed] = null; this[kClosed] = false; this[kOnClosed] = []; - this[kWebSocketOptions] = opts?.webSocket ?? {}; - } - get webSocketOptions() { - return { - maxFragments: this[kWebSocketOptions].maxFragments ?? 131072, - maxPayloadSize: this[kWebSocketOptions].maxPayloadSize ?? 128 * 1024 * 1024 - }; } get destroyed() { return this[kDestroyed]; @@ -5738,7 +5667,6 @@ var require_client_h1 = __commonJS({ RequestContentLengthMismatchError, ResponseContentLengthMismatchError, RequestAbortedError, - InvalidArgumentError, HeadersTimeoutError, HeadersOverflowError, SocketError, @@ -5785,9 +5713,6 @@ var require_client_h1 = __commonJS({ var FastBuffer = Buffer[Symbol.species]; var addListener = util.addListener; var removeAllListeners = util.removeAllListeners; - var kIdleSocketValidation = /* @__PURE__ */ Symbol("kIdleSocketValidation"); - var kIdleSocketValidationTimeout = /* @__PURE__ */ Symbol("kIdleSocketValidationTimeout"); - var kSocketUsed = /* @__PURE__ */ Symbol("kSocketUsed"); var extractBody; async function lazyllhttp() { const llhttpWasmData = process.env.JEST_WORKER_ID ? require_llhttp_wasm() : void 0; @@ -5950,55 +5875,24 @@ var require_client_h1 = __commonJS({ currentBufferRef = null; } const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr; - if (ret !== constants3.ERROR.OK) { - const body = data.subarray(offset); - if (ret === constants3.ERROR.PAUSED_UPGRADE) { - this.onUpgrade(body); - } else if (ret === constants3.ERROR.PAUSED) { - this.paused = true; - socket.unshift(body); - } else { - throw this.createError(ret, body); + if (ret === constants3.ERROR.PAUSED_UPGRADE) { + this.onUpgrade(data.slice(offset)); + } else if (ret === constants3.ERROR.PAUSED) { + this.paused = true; + socket.unshift(data.slice(offset)); + } else if (ret !== constants3.ERROR.OK) { + const ptr = llhttp.llhttp_get_error_reason(this.ptr); + let message = ""; + if (ptr) { + const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); + message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; } + throw new HTTPParserError(message, constants3.ERROR[ret], data.slice(offset)); } } catch (err) { util.destroy(socket, err); } } - finish() { - assert(currentParser === null); - assert(this.ptr != null); - assert(!this.paused); - const { llhttp } = this; - let ret; - try { - currentParser = this; - ret = llhttp.llhttp_finish(this.ptr); - } finally { - currentParser = null; - } - if (ret === constants3.ERROR.OK) { - return null; - } - if (ret === constants3.ERROR.PAUSED || ret === constants3.ERROR.PAUSED_UPGRADE) { - this.paused = true; - return null; - } - return this.createError(ret, EMPTY_BUF); - } - createError(ret, data) { - const { llhttp, contentLength, bytesRead } = this; - if (contentLength && bytesRead !== parseInt(contentLength, 10)) { - return new ResponseContentLengthMismatchError(); - } - const ptr = llhttp.llhttp_get_error_reason(this.ptr); - let message = ""; - if (ptr) { - const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); - message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; - } - return new HTTPParserError(message, constants3.ERROR[ret], data); - } destroy() { assert(this.ptr != null); assert(currentParser == null); @@ -6018,10 +5912,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6065,7 +5955,7 @@ var require_client_h1 = __commonJS({ } } onUpgrade(head) { - const { upgrade, client, socket, headers, statusCode, statusText } = this; + const { upgrade, client, socket, headers, statusCode } = this; assert(upgrade); assert(client[kSocket] === socket); assert(!socket.destroyed); @@ -6090,10 +5980,9 @@ var require_client_h1 = __commonJS({ client[kQueue][client[kRunningIdx]++] = null; client.emit("disconnect", client[kUrl], [client], new InformationalError("upgrade")); try { - request2.onUpgrade(statusCode, headers, socket, statusText); - } catch (error2) { - util.errorRequest(client, request2, error2); - util.destroy(socket, error2); + request2.onUpgrade(statusCode, headers, socket); + } catch (err) { + util.destroy(socket, err); } client[kResume](); } @@ -6102,10 +5991,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6231,7 +6116,6 @@ var require_client_h1 = __commonJS({ } request2.onComplete(headers); client[kQueue][client[kRunningIdx]++] = null; - socket[kSocketUsed] = true; if (socket[kWriting]) { assert(client[kRunning] === 0); util.destroy(socket, new InformationalError("reset")); @@ -6275,19 +6159,12 @@ var require_client_h1 = __commonJS({ socket[kWriting] = false; socket[kReset] = false; socket[kBlocking] = false; - socket[kIdleSocketValidation] = 0; - socket[kIdleSocketValidationTimeout] = null; - socket[kSocketUsed] = false; socket[kParser] = new Parser(client, socket, llhttpInstance); addListener(socket, "error", function(err) { assert(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID"); const parser = this[kParser]; if (err.code === "ECONNRESET" && parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - this[kError] = parserErr; - this[kClient][kOnError](parserErr); - } + parser.onMessageComplete(); return; } this[kError] = err; @@ -6302,10 +6179,7 @@ var require_client_h1 = __commonJS({ addListener(socket, "end", function() { const parser = this[kParser]; if (parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - util.destroy(this, parserErr); - } + parser.onMessageComplete(); return; } util.destroy(this, new SocketError("other side closed", util.getSocketInfo(this))); @@ -6313,10 +6187,9 @@ var require_client_h1 = __commonJS({ addListener(socket, "close", function() { const client2 = this[kClient]; const parser = this[kParser]; - clearIdleSocketValidation(this); if (parser) { if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { - this[kError] = parser.finish() || this[kError]; + parser.onMessageComplete(); } this[kParser].destroy(); this[kParser] = null; @@ -6365,7 +6238,7 @@ var require_client_h1 = __commonJS({ return socket.destroyed; }, busy(request2) { - if (socket[kWriting] || socket[kReset] || socket[kBlocking] || socket[kIdleSocketValidation] === 1) { + if (socket[kWriting] || socket[kReset] || socket[kBlocking]) { return true; } if (request2) { @@ -6383,23 +6256,6 @@ var require_client_h1 = __commonJS({ } }; } - function clearIdleSocketValidation(socket) { - if (socket[kIdleSocketValidationTimeout]) { - clearImmediate(socket[kIdleSocketValidationTimeout]); - socket[kIdleSocketValidationTimeout] = null; - } - socket[kIdleSocketValidation] = 0; - } - function scheduleIdleSocketValidation(client, socket) { - socket[kIdleSocketValidation] = 1; - socket[kIdleSocketValidationTimeout] = setImmediate(() => { - socket[kIdleSocketValidationTimeout] = null; - socket[kIdleSocketValidation] = 2; - if (client[kSocket] === socket && !socket.destroyed) { - client[kResume](); - } - }); - } function resumeH1(client) { const socket = client[kSocket]; if (socket && !socket.destroyed) { @@ -6412,29 +6268,6 @@ var require_client_h1 = __commonJS({ socket.ref(); socket[kNoRef] = false; } - if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) { - if (socket[kIdleSocketValidation] === 0) { - scheduleIdleSocketValidation(client, socket); - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - if (socket[kIdleSocketValidation] === 1) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - } - if (client[kRunning] === 0) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - } if (client[kSize] === 0) { if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) { socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE); @@ -6465,16 +6298,8 @@ var require_client_h1 = __commonJS({ } body = bodyStream.stream; contentLength = bodyStream.length; - } else if (util.isBlobLike(body) && request2.contentType == null) { - const contentType = body.type; - if (contentType) { - const contentTypeValue = `${contentType}`; - if (!util.isValidHeaderValue(contentTypeValue)) { - util.errorRequest(client, request2, new InvalidArgumentError("invalid content-type header")); - return false; - } - headers.push("content-type", contentTypeValue); - } + } else if (util.isBlobLike(body) && request2.contentType == null && body.type) { + headers.push("content-type", body.type); } if (body && typeof body.read === "function") { body.read(0); @@ -6495,18 +6320,11 @@ var require_client_h1 = __commonJS({ process.emitWarning(new RequestContentLengthMismatchError()); } const socket = client[kSocket]; - clearIdleSocketValidation(socket); - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (request2.upgrade || request2.method === "CONNECT") { - util.destroy(socket, new InformationalError("aborted")); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - util.errorRequest(client, request2, error2 || new RequestAbortedError()); + util.errorRequest(client, request2, err || new RequestAbortedError()); util.destroy(body); util.destroy(socket, new InformationalError("aborted")); }; @@ -6862,7 +6680,6 @@ var require_client_h2 = __commonJS({ "node_modules/undici/lib/dispatcher/client-h2.js"(exports, module) { "use strict"; var assert = __require("node:assert"); - var { errorMonitor } = __require("node:events"); var { pipeline } = __require("node:stream"); var util = require_util(); var { @@ -6923,10 +6740,6 @@ var require_client_h2 = __commonJS({ } return result; } - function parseH2ResponseHeaders(headers) { - const { [HTTP2_HEADER_STATUS]: _statusCode, ...realHeaders } = headers; - return parseH2Headers(realHeaders); - } async function connectH2(client, socket) { client[kSocket] = socket; if (!h2ExperimentalWarned) { @@ -7090,22 +6903,16 @@ var require_client_h2 = __commonJS({ const { hostname, port } = client[kUrl]; headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ""}`; headers[HTTP2_HEADER_METHOD] = method; - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (method === "CONNECT" && stream != null) { - util.destroy(stream, error2 || new RequestAbortedError()); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - error2 = error2 || new RequestAbortedError(); - util.errorRequest(client, request2, error2); + err = err || new RequestAbortedError(); + util.errorRequest(client, request2, err); if (stream != null) { - util.destroy(stream, error2); + util.destroy(stream, err); } - util.destroy(body, error2); + util.destroy(body, err); client[kQueue][client[kRunningIdx]++] = null; client[kResume](); }; @@ -7120,42 +6927,18 @@ var require_client_h2 = __commonJS({ if (method === "CONNECT") { session.ref(); stream = session.request(headers, { endStream: false, signal }); - let upgradeResponseFinished = false; - const onResponse = (headers2) => { - upgradeResponseFinished = true; - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeResponse(Number(headers2[HTTP2_HEADER_STATUS]), headers2, parseH2ResponseHeaders); - }; - const onUpgradeError = (error2) => { - upgradeResponseFinished = true; - stream.off("response", onResponse); - request2.onUpgradeError(error2); - }; - const onReady = () => { - try { - request2.onUpgrade(null, null, stream); - } catch (error2) { - stream.off("response", onResponse); - abort(error2); - return; - } - if (request2.aborted) { - return; - } - stream.off("error", abort); - stream.once(errorMonitor, onUpgradeError); + if (stream.id && !stream.pending) { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; client[kQueue][client[kRunningIdx]++] = null; - }; - stream.once("response", onResponse); - stream.once("error", abort); - ++session[kOpenStreams]; - onReady(); + } else { + stream.once("ready", () => { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; + client[kQueue][client[kRunningIdx]++] = null; + }); + } stream.once("close", () => { - if (!upgradeResponseFinished && request2.completed) { - stream.off("response", onResponse); - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeError(new InformationalError(`HTTP/2: "stream error" received - code ${stream.rstCode}`)); - } session[kOpenStreams] -= 1; if (session[kOpenStreams] === 0) session.unref(); }); @@ -7716,10 +7499,9 @@ var require_client = __commonJS({ autoSelectFamilyAttemptTimeout, // h2 maxConcurrentStreams, - allowH2, - webSocket + allowH2 } = {}) { - super({ webSocket }); + super(); if (keepAlive !== void 0) { throw new InvalidArgumentError("unsupported keepAlive, use pipelining=0 instead"); } @@ -8225,8 +8007,8 @@ var require_pool_base = __commonJS({ var kRemoveClient = /* @__PURE__ */ Symbol("remove client"); var kStats = /* @__PURE__ */ Symbol("stats"); var PoolBase = class extends DispatcherBase { - constructor(opts) { - super(opts); + constructor() { + super(); this[kQueue] = new FixedQueue(); this[kClients] = []; this[kQueued] = 0; @@ -8397,6 +8179,7 @@ var require_pool = __commonJS({ allowH2, ...options } = {}) { + super(); if (connections != null && (!Number.isFinite(connections) || connections < 0)) { throw new InvalidArgumentError("invalid connections"); } @@ -8417,7 +8200,6 @@ var require_pool = __commonJS({ ...connect }); } - super(options); this[kInterceptors] = options.interceptors?.Pool && Array.isArray(options.interceptors.Pool) ? options.interceptors.Pool : []; this[kConnections] = connections || null; this[kUrl] = util.parseOrigin(origin); @@ -8617,6 +8399,7 @@ var require_agent = __commonJS({ } var Agent = class extends DispatcherBase { constructor({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { + super(); if (typeof factory !== "function") { throw new InvalidArgumentError("factory must be a function."); } @@ -8626,7 +8409,6 @@ var require_agent = __commonJS({ if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { throw new InvalidArgumentError("maxRedirections must be a positive number"); } - super(options); if (connect && typeof connect !== "function") { connect = { ...connect }; } @@ -9067,24 +8849,6 @@ var require_retry_handler = __commonJS({ const current = Date.now(); return new Date(retryAfter).getTime() - current; } - function validatePartialResponseContentLength(headers, range, statusCode, retryCount) { - const contentLength = headers["content-length"]; - if (contentLength == null) { - return null; - } - if (!Number.isFinite(range.start) || !Number.isFinite(range.end)) { - return null; - } - const length = Number(contentLength); - const expectedLength = range.end - range.start + 1; - if (!Number.isFinite(length) || length !== expectedLength) { - return new RequestRetryError("Content-Length mismatch", statusCode, { - headers, - data: { count: retryCount } - }); - } - return null; - } var RetryHandler = class _RetryHandler { constructor(opts, handlers) { const { retryOptions, ...dispatchOpts } = opts; @@ -9138,7 +8902,6 @@ var require_retry_handler = __commonJS({ this.end = null; this.etag = null; this.resume = null; - this.headersSent = false; this.handler.onConnect((reason) => { this.aborted = true; if (this.abort) { @@ -9148,17 +8911,6 @@ var require_retry_handler = __commonJS({ } }); } - 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(); @@ -9220,9 +8972,7 @@ var require_retry_handler = __commonJS({ const headers = parseHeaders(rawHeaders); this.retryCount += 1; if (statusCode >= 300) { - if (!this.headersSent && this.retryOpts.statusCodes.includes(statusCode) === false) { - this.headersSent = true; - this.checkpointResponseEnd(headers, resume); + if (this.retryOpts.statusCodes.includes(statusCode) === false) { return this.handler.onHeaders( statusCode, rawHeaders, @@ -9271,21 +9021,9 @@ var require_retry_handler = __commonJS({ ); return false; } - const contentLengthError = validatePartialResponseContentLength(headers, contentRange, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = contentRange; - 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; - } + assert(this.start === start, "content-range mismatch"); + assert(this.end == null || this.end === end, "content-range mismatch"); this.resume = resume; return true; } @@ -9293,7 +9031,6 @@ var require_retry_handler = __commonJS({ if (statusCode === 206) { const range = parseRangeHeader(headers["content-range"]); if (range == null) { - this.headersSent = true; return this.handler.onHeaders( statusCode, rawHeaders, @@ -9301,11 +9038,6 @@ var require_retry_handler = __commonJS({ statusMessage ); } - const contentLengthError = validatePartialResponseContentLength(headers, range, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = range; assert( start != null && Number.isFinite(start), @@ -9325,7 +9057,6 @@ var require_retry_handler = __commonJS({ "invalid content-length" ); this.resume = resume; - this.headersSent = true; this.etag = headers.etag != null ? headers.etag : null; if (this.etag != null && this.etag.startsWith("W/")) { this.etag = null; @@ -9353,7 +9084,7 @@ var require_retry_handler = __commonJS({ return this.handler.onComplete(rawTrailers); } onError(err) { - if (this.aborted || isDisturbed(this.opts.body) || this.headersSent && this.resume == null) { + if (this.aborted || isDisturbed(this.opts.body)) { return this.handler.onError(err); } if (this.retryCount - this.retryCountCheckpoint > 0) { @@ -16152,48 +15883,14 @@ var require_util6 = __commonJS({ for (let i = 0; i < path.length; ++i) { const code = path.charCodeAt(i); if (code < 32 || // exclude CTLs (0-31) - code > 126 || // exclude DEL and non-ascii + code === 127 || // DEL code === 59) { throw new Error("Invalid cookie path"); } } } - function isLetterOrDigit(code) { - return code >= 48 && code <= 57 || // 0-9 - code >= 65 && code <= 90 || // A-Z - code >= 97 && code <= 122; - } function validateCookieDomain(domain) { - if (domain === " ") { - return; - } - if (domain.length > 255) { - throw new Error("Invalid cookie domain"); - } - let labelLength = 0; - for (let i = 0; i < domain.length; ++i) { - const code = domain.charCodeAt(i); - if (code === 46) { - if (labelLength === 0) { - throw new Error("Invalid cookie domain"); - } - if (domain.charCodeAt(i - 1) === 45) { - throw new Error("Invalid cookie domain"); - } - labelLength = 0; - continue; - } - if (labelLength === 0 && !isLetterOrDigit(code)) { - throw new Error("Invalid cookie domain"); - } - if (!isLetterOrDigit(code) && code !== 45) { - throw new Error("Invalid cookie domain"); - } - if (++labelLength > 63) { - throw new Error("Invalid cookie domain"); - } - } - if (labelLength === 0 || domain.charCodeAt(domain.length - 1) === 45) { + if (domain.startsWith("-") || domain.endsWith(".") || domain.endsWith("-")) { throw new Error("Invalid cookie domain"); } } @@ -16276,11 +15973,7 @@ var require_util6 = __commonJS({ throw new Error("Invalid unparsed"); } const [key, ...value] = part.split("="); - const trimmedKey = key.trim(); - const joinedValue = value.join("="); - validateCookieName(trimmedKey); - validateCookieValue(joinedValue); - out.push(`${trimmedKey}=${joinedValue}`); + out.push(`${key.trim()}=${value.join("=")}`); } return out.join("; "); } @@ -16410,14 +16103,18 @@ var require_parse = __commonJS({ } else if (attributeNameLowercase === "httponly") { cookieAttributeList.httpOnly = true; } else if (attributeNameLowercase === "samesite") { + let enforcement = "Default"; const attributeValueLowercase = attributeValue.toLowerCase(); - if (attributeValueLowercase === "none") { - cookieAttributeList.sameSite = "None"; - } else if (attributeValueLowercase === "strict") { - cookieAttributeList.sameSite = "Strict"; - } else if (attributeValueLowercase === "lax") { - cookieAttributeList.sameSite = "Lax"; + if (attributeValueLowercase.includes("none")) { + enforcement = "None"; + } + if (attributeValueLowercase.includes("strict")) { + enforcement = "Strict"; + } + if (attributeValueLowercase.includes("lax")) { + enforcement = "Lax"; } + cookieAttributeList.sameSite = enforcement; } else { cookieAttributeList.unparsed ??= []; cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`); @@ -17239,7 +16936,7 @@ var require_connection = __commonJS({ const secProtocol = response.headersList.get("Sec-WebSocket-Protocol"); if (secProtocol !== null) { const requestProtocols = getDecodeSplit("sec-websocket-protocol", request2.headersList); - if (requestProtocols === null || !requestProtocols.includes(secProtocol)) { + if (!requestProtocols.includes(secProtocol)) { failWebsocketConnection(ws, "Protocol was not set in the opening handshake."); return; } @@ -17345,26 +17042,31 @@ var require_permessage_deflate = __commonJS({ var tail = Buffer.from([0, 0, 255, 255]); var kBuffer = /* @__PURE__ */ Symbol("kBuffer"); var kLength = /* @__PURE__ */ Symbol("kLength"); + var kDefaultMaxDecompressedSize = 4 * 1024 * 1024; var PerMessageDeflate = class { /** @type {import('node:zlib').InflateRaw} */ #inflate; #options = {}; - #maxPayloadSize = 0; + /** @type {number} */ + #maxDecompressedSize; + /** @type {boolean} */ + #aborted = false; + /** @type {Function|null} */ + #currentCallback = null; /** * @param {Map} extensions + * @param {{ maxDecompressedMessageSize?: number }} [options] */ - constructor(extensions, options) { + constructor(extensions, options = {}) { this.#options.serverNoContextTakeover = extensions.has("server_no_context_takeover"); this.#options.serverMaxWindowBits = extensions.get("server_max_window_bits"); - this.#maxPayloadSize = options.maxPayloadSize; + this.#maxDecompressedSize = options.maxDecompressedMessageSize ?? kDefaultMaxDecompressedSize; } - /** - * Decompress a compressed payload. - * @param {Buffer} chunk Compressed data - * @param {boolean} fin Final fragment flag - * @param {Function} callback Callback function - */ decompress(chunk, fin, callback) { + if (this.#aborted) { + callback(new MessageSizeExceededError()); + return; + } if (!this.#inflate) { let windowBits = Z_DEFAULT_WINDOWBITS; if (this.#options.serverMaxWindowBits) { @@ -17383,12 +17085,20 @@ var require_permessage_deflate = __commonJS({ this.#inflate[kBuffer] = []; this.#inflate[kLength] = 0; this.#inflate.on("data", (data) => { + if (this.#aborted) { + return; + } this.#inflate[kLength] += data.length; - if (this.#maxPayloadSize > 0 && this.#inflate[kLength] > this.#maxPayloadSize) { - callback(new MessageSizeExceededError()); + if (this.#inflate[kLength] > this.#maxDecompressedSize) { + this.#aborted = true; this.#inflate.removeAllListeners(); this.#inflate.destroy(); this.#inflate = null; + if (this.#currentCallback) { + const cb = this.#currentCallback; + this.#currentCallback = null; + cb(new MessageSizeExceededError()); + } return; } this.#inflate[kBuffer].push(data); @@ -17398,17 +17108,19 @@ var require_permessage_deflate = __commonJS({ callback(err); }); } + this.#currentCallback = callback; this.#inflate.write(chunk); if (fin) { this.#inflate.write(tail); } this.#inflate.flush(() => { - if (!this.#inflate) { + if (this.#aborted || !this.#inflate) { return; } const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]); this.#inflate[kBuffer].length = 0; this.#inflate[kLength] = 0; + this.#currentCallback = null; callback(null, full); }); } @@ -17439,14 +17151,8 @@ var require_receiver = __commonJS({ var { WebsocketFrameSend } = require_frame(); var { closeWebSocketConnection } = require_connection(); var { PerMessageDeflate } = require_permessage_deflate(); - var { MessageSizeExceededError } = require_errors(); - function failWebsocketConnectionWithCode(ws, code, reason) { - closeWebSocketConnection(ws, code, reason, Buffer.byteLength(reason)); - failWebsocketConnection(ws, reason); - } var ByteParser = class extends Writable { #buffers = []; - #fragmentsBytes = 0; #byteOffset = 0; #loop = false; #state = parserStates.INFO; @@ -17454,21 +17160,18 @@ var require_receiver = __commonJS({ #fragments = []; /** @type {Map} */ #extensions; - /** @type {number} */ - #maxFragments; - /** @type {number} */ - #maxPayloadSize; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {import('./websocket').WebSocket} ws * @param {Map|null} extensions - * @param {{ maxFragments?: number, maxPayloadSize?: number }} [options] + * @param {{ maxDecompressedMessageSize?: number }} [options] */ constructor(ws, extensions, options = {}) { super(); this.ws = ws; this.#extensions = extensions == null ? /* @__PURE__ */ new Map() : extensions; - this.#maxFragments = options.maxFragments ?? 0; - this.#maxPayloadSize = options.maxPayloadSize ?? 0; + this.#options = options; if (this.#extensions.has("permessage-deflate")) { this.#extensions.set("permessage-deflate", new PerMessageDeflate(extensions, options)); } @@ -17483,13 +17186,6 @@ var require_receiver = __commonJS({ this.#loop = true; this.run(callback); } - #validatePayloadLength() { - if (this.#maxPayloadSize > 0 && !isControlFrame(this.#info.opcode) && this.#info.payloadLength + this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, "Payload size exceeds maximum allowed size"); - return false; - } - return true; - } /** * Runs whenever a new chunk is received. * Callback is called whenever there are no more chunks buffering, @@ -17549,9 +17245,6 @@ var require_receiver = __commonJS({ if (payloadLength <= 125) { this.#info.payloadLength = payloadLength; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (payloadLength === 126) { this.#state = parserStates.PAYLOADLENGTH_16; } else if (payloadLength === 127) { @@ -17572,9 +17265,6 @@ var require_receiver = __commonJS({ const buffer = this.consume(2); this.#info.payloadLength = buffer.readUInt16BE(0); this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.PAYLOADLENGTH_64) { if (this.#byteOffset < 8) { return callback(); @@ -17588,9 +17278,6 @@ var require_receiver = __commonJS({ } this.#info.payloadLength = lower; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.READ_DATA) { if (this.#byteOffset < this.#info.payloadLength) { return callback(); @@ -17601,46 +17288,32 @@ var require_receiver = __commonJS({ this.#state = parserStates.INFO; } else { if (!this.#info.compressed) { - if (!this.writeFragments(body)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } + this.#fragments.push(body); if (!this.#info.fragmented && this.#info.fin) { - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); + const fullMessage = Buffer.concat(this.#fragments); + websocketMessageReceived(this.ws, this.#info.binaryType, fullMessage); + this.#fragments.length = 0; } this.#state = parserStates.INFO; } else { - this.#extensions.get("permessage-deflate").decompress( - body, - this.#info.fin, - (error2, data) => { - if (error2) { - const code = error2 instanceof MessageSizeExceededError ? 1009 : 1007; - failWebsocketConnectionWithCode(this.ws, code, error2.message); - return; - } - if (!this.writeFragments(data)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } - if (!this.#info.fin) { - this.#state = parserStates.INFO; - this.#loop = true; - this.run(callback); - return; - } - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); - this.#loop = true; + this.#extensions.get("permessage-deflate").decompress(body, this.#info.fin, (error2, data) => { + if (error2) { + failWebsocketConnection(this.ws, error2.message); + return; + } + this.#fragments.push(data); + if (!this.#info.fin) { this.#state = parserStates.INFO; + this.#loop = true; this.run(callback); + return; } - ); + websocketMessageReceived(this.ws, this.#info.binaryType, Buffer.concat(this.#fragments)); + this.#loop = true; + this.#state = parserStates.INFO; + this.#fragments.length = 0; + this.run(callback); + }); this.#loop = false; break; } @@ -17683,26 +17356,6 @@ var require_receiver = __commonJS({ this.#byteOffset -= n; return buffer; } - writeFragments(fragment) { - if (this.#maxFragments > 0 && this.#fragments.length === this.#maxFragments) { - failWebsocketConnectionWithCode(this.ws, 1008, "Too many message fragments"); - return false; - } - this.#fragmentsBytes += fragment.length; - this.#fragments.push(fragment); - return true; - } - consumeFragments() { - const fragments = this.#fragments; - if (fragments.length === 1) { - this.#fragmentsBytes = 0; - return fragments.shift(); - } - const output = Buffer.concat(fragments, this.#fragmentsBytes); - this.#fragments = []; - this.#fragmentsBytes = 0; - return output; - } parseCloseBody(data) { assert(data.length !== 1); let code; @@ -17914,6 +17567,8 @@ var require_websocket = __commonJS({ #extensions = ""; /** @type {SendQueue} */ #sendQueue; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {string} url * @param {string|string[]} protocols @@ -17957,6 +17612,9 @@ var require_websocket = __commonJS({ throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError"); } this[kWebSocketURL] = new URL(urlRecord.href); + this.#options = { + maxDecompressedMessageSize: options.maxDecompressedMessageSize + }; const client = environmentSettingsObject.settingsObject; this[kController] = establishWebSocketConnection( urlRecord, @@ -18140,13 +17798,7 @@ var require_websocket = __commonJS({ */ #onConnectionEstablished(response, parsedExtensions) { this[kResponse] = response; - const webSocketOptions = this[kController]?.dispatcher?.webSocketOptions; - const maxFragments = webSocketOptions?.maxFragments; - const maxPayloadSize = webSocketOptions?.maxPayloadSize; - const parser = new ByteParser(this, parsedExtensions, { - maxFragments, - maxPayloadSize - }); + const parser = new ByteParser(this, parsedExtensions, this.#options); parser.on("drain", onParserDrain); parser.on("error", onParserError.bind(this)); response.socket.ws = this; @@ -18221,6 +17873,19 @@ var require_websocket = __commonJS({ { key: "headers", converter: webidl.nullableConverter(webidl.converters.HeadersInit) + }, + { + key: "maxDecompressedMessageSize", + converter: webidl.nullableConverter((V) => { + V = webidl.converters["unsigned long long"](V); + if (V <= 0) { + throw webidl.errors.exception({ + header: "WebSocket constructor", + message: "maxDecompressedMessageSize must be greater than 0" + }); + } + return V; + }) } ]); webidl.converters["DOMString or sequence or WebSocketInit"] = function(V) { @@ -18299,40 +17964,6 @@ 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; - } - function isValidLastEventIdBytes(buffer, start) { - for (let i = start; i < buffer.length; i++) { - if (buffer[i] === 0) { - 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; - } var EventSourceStream = class extends Transform { /** * @type {eventSourceSettings} @@ -18352,13 +17983,10 @@ var require_eventsource_stream = __commonJS({ */ eventEndCheck = false; /** - * @type {Buffer[]} + * @type {Buffer} */ - chunks = []; - chunkIndex = 0; + buffer = null; pos = 0; - lineChunkIndex = 0; - linePos = 0; event = { data: void 0, event: void 0, @@ -18389,30 +18017,63 @@ var require_eventsource_stream = __commonJS({ callback(); return; } - this.chunks.push(chunk); + if (this.buffer) { + this.buffer = Buffer.concat([this.buffer, chunk]); + } else { + this.buffer = chunk; + } if (this.checkBOM) { - if (this.handleBOM()) { - callback(); - return; + 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; } } - while (this.hasCurrentByte()) { - const byte = this.currentByte(); + while (this.pos < this.buffer.length) { if (this.eventEndCheck) { if (this.crlfCheck) { - if (byte === LF) { + if (this.buffer[this.pos] === LF) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.crlfCheck = false; - this.consumeCurrentByte(); continue; } this.crlfCheck = false; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.consumeCurrentByte(); - if (this.hasPendingEvent()) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; + if (this.event.data !== void 0 || this.event.event || this.event.id || this.event.retry) { this.processEvent(this.event); } this.clearEvent(); @@ -18421,16 +18082,17 @@ var require_eventsource_stream = __commonJS({ this.eventEndCheck = false; continue; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.parseLine(this.readLine(), this.event); - this.consumeCurrentByte(); + this.parseLine(this.buffer.subarray(0, this.pos), this.event); + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.eventEndCheck = true; continue; } - this.advanceCursor(); + this.pos++; } callback(); } @@ -18446,42 +18108,43 @@ var require_eventsource_stream = __commonJS({ if (colonPosition === 0) { return; } - let fieldLength = line.length; - let valueStart = line.length; + let field = ""; + let value = ""; if (colonPosition !== -1) { - fieldLength = colonPosition; - valueStart = colonPosition + 1; + field = line.subarray(0, colonPosition).toString("utf8"); + let valueStart = colonPosition + 1; if (line[valueStart] === SPACE) { ++valueStart; } + value = line.subarray(valueStart).toString("utf8"); + } else { + field = line.toString("utf8"); + value = ""; } - if (isFieldName(line, fieldLength, DATA)) { - const value = line.toString("utf8", valueStart); - if (event.data === void 0) { - event.data = value; - } else { - event.data += ` + switch (field) { + case "data": + if (event[field] === void 0) { + event[field] = value; + } else { + event[field] += ` ${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; - } + } + 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; } } /** @@ -18506,120 +18169,12 @@ ${value}`; } } clearEvent() { - 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(); + this.event = { + data: void 0, + event: void 0, + id: void 0, + retry: void 0 + }; } }; module.exports = { diff --git a/.github/actions/javascript/formatCodeCovComment/index.js b/.github/actions/javascript/formatCodeCovComment/index.js index 9aac21e43b56..133b8de4b0d2 100644 --- a/.github/actions/javascript/formatCodeCovComment/index.js +++ b/.github/actions/javascript/formatCodeCovComment/index.js @@ -1863,66 +1863,10 @@ var require_request = __commonJS({ return false; } } - /** - * @param {number|null} statusCode - * @param {Buffer[]|null} headers - * @param {import('node:stream').Duplex} socket - * @param {string} [statusText] - */ - onUpgrade(statusCode, headers, socket, statusText = "") { - this.onFinally(); + onUpgrade(statusCode, headers, socket) { assert(!this.aborted); assert(!this.completed); - 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(error2) { - assert(!this.aborted); - assert(this.completed); - if (channels.error.hasSubscribers) { - channels.error.publish({ request: this, error: error2 }); - } - } - /** - * @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: [] }); - } + return this[kHandler].onUpgrade(statusCode, headers, socket); } onComplete(trailers) { this.onFinally(); @@ -1989,11 +1933,7 @@ var require_request = __commonJS({ } else if (typeof val[i] === "object") { throw new InvalidArgumentError(`invalid ${key} header`); } else { - const str = `${val[i]}`; - if (!isValidHeaderValue(str)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } - arr.push(str); + arr.push(`${val[i]}`); } } val = arr; @@ -2005,9 +1945,6 @@ var require_request = __commonJS({ val = ""; } else { val = `${val}`; - if (!isValidHeaderValue(val)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } } if (headerName === "host") { if (request2.host !== null) { @@ -2117,21 +2054,13 @@ var require_dispatcher_base = __commonJS({ var kOnDestroyed = /* @__PURE__ */ Symbol("onDestroyed"); var kOnClosed = /* @__PURE__ */ Symbol("onClosed"); var kInterceptedDispatch = /* @__PURE__ */ Symbol("Intercepted Dispatch"); - var kWebSocketOptions = /* @__PURE__ */ Symbol("webSocketOptions"); var DispatcherBase = class extends Dispatcher { - constructor(opts) { + constructor() { super(); this[kDestroyed] = false; this[kOnDestroyed] = null; this[kClosed] = false; this[kOnClosed] = []; - this[kWebSocketOptions] = opts?.webSocket ?? {}; - } - get webSocketOptions() { - return { - maxFragments: this[kWebSocketOptions].maxFragments ?? 131072, - maxPayloadSize: this[kWebSocketOptions].maxPayloadSize ?? 128 * 1024 * 1024 - }; } get destroyed() { return this[kDestroyed]; @@ -5738,7 +5667,6 @@ var require_client_h1 = __commonJS({ RequestContentLengthMismatchError, ResponseContentLengthMismatchError, RequestAbortedError, - InvalidArgumentError, HeadersTimeoutError, HeadersOverflowError, SocketError, @@ -5785,9 +5713,6 @@ var require_client_h1 = __commonJS({ var FastBuffer = Buffer[Symbol.species]; var addListener = util.addListener; var removeAllListeners = util.removeAllListeners; - var kIdleSocketValidation = /* @__PURE__ */ Symbol("kIdleSocketValidation"); - var kIdleSocketValidationTimeout = /* @__PURE__ */ Symbol("kIdleSocketValidationTimeout"); - var kSocketUsed = /* @__PURE__ */ Symbol("kSocketUsed"); var extractBody; async function lazyllhttp() { const llhttpWasmData = process.env.JEST_WORKER_ID ? require_llhttp_wasm() : void 0; @@ -5950,55 +5875,24 @@ var require_client_h1 = __commonJS({ currentBufferRef = null; } const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr; - if (ret !== constants3.ERROR.OK) { - const body = data.subarray(offset); - if (ret === constants3.ERROR.PAUSED_UPGRADE) { - this.onUpgrade(body); - } else if (ret === constants3.ERROR.PAUSED) { - this.paused = true; - socket.unshift(body); - } else { - throw this.createError(ret, body); + if (ret === constants3.ERROR.PAUSED_UPGRADE) { + this.onUpgrade(data.slice(offset)); + } else if (ret === constants3.ERROR.PAUSED) { + this.paused = true; + socket.unshift(data.slice(offset)); + } else if (ret !== constants3.ERROR.OK) { + const ptr = llhttp.llhttp_get_error_reason(this.ptr); + let message = ""; + if (ptr) { + const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); + message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; } + throw new HTTPParserError(message, constants3.ERROR[ret], data.slice(offset)); } } catch (err) { util.destroy(socket, err); } } - finish() { - assert(currentParser === null); - assert(this.ptr != null); - assert(!this.paused); - const { llhttp } = this; - let ret; - try { - currentParser = this; - ret = llhttp.llhttp_finish(this.ptr); - } finally { - currentParser = null; - } - if (ret === constants3.ERROR.OK) { - return null; - } - if (ret === constants3.ERROR.PAUSED || ret === constants3.ERROR.PAUSED_UPGRADE) { - this.paused = true; - return null; - } - return this.createError(ret, EMPTY_BUF); - } - createError(ret, data) { - const { llhttp, contentLength, bytesRead } = this; - if (contentLength && bytesRead !== parseInt(contentLength, 10)) { - return new ResponseContentLengthMismatchError(); - } - const ptr = llhttp.llhttp_get_error_reason(this.ptr); - let message = ""; - if (ptr) { - const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); - message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; - } - return new HTTPParserError(message, constants3.ERROR[ret], data); - } destroy() { assert(this.ptr != null); assert(currentParser == null); @@ -6018,10 +5912,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6065,7 +5955,7 @@ var require_client_h1 = __commonJS({ } } onUpgrade(head) { - const { upgrade, client, socket, headers, statusCode, statusText } = this; + const { upgrade, client, socket, headers, statusCode } = this; assert(upgrade); assert(client[kSocket] === socket); assert(!socket.destroyed); @@ -6090,10 +5980,9 @@ var require_client_h1 = __commonJS({ client[kQueue][client[kRunningIdx]++] = null; client.emit("disconnect", client[kUrl], [client], new InformationalError("upgrade")); try { - request2.onUpgrade(statusCode, headers, socket, statusText); - } catch (error2) { - util.errorRequest(client, request2, error2); - util.destroy(socket, error2); + request2.onUpgrade(statusCode, headers, socket); + } catch (err) { + util.destroy(socket, err); } client[kResume](); } @@ -6102,10 +5991,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6231,7 +6116,6 @@ var require_client_h1 = __commonJS({ } request2.onComplete(headers); client[kQueue][client[kRunningIdx]++] = null; - socket[kSocketUsed] = true; if (socket[kWriting]) { assert(client[kRunning] === 0); util.destroy(socket, new InformationalError("reset")); @@ -6275,19 +6159,12 @@ var require_client_h1 = __commonJS({ socket[kWriting] = false; socket[kReset] = false; socket[kBlocking] = false; - socket[kIdleSocketValidation] = 0; - socket[kIdleSocketValidationTimeout] = null; - socket[kSocketUsed] = false; socket[kParser] = new Parser(client, socket, llhttpInstance); addListener(socket, "error", function(err) { assert(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID"); const parser = this[kParser]; if (err.code === "ECONNRESET" && parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - this[kError] = parserErr; - this[kClient][kOnError](parserErr); - } + parser.onMessageComplete(); return; } this[kError] = err; @@ -6302,10 +6179,7 @@ var require_client_h1 = __commonJS({ addListener(socket, "end", function() { const parser = this[kParser]; if (parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - util.destroy(this, parserErr); - } + parser.onMessageComplete(); return; } util.destroy(this, new SocketError("other side closed", util.getSocketInfo(this))); @@ -6313,10 +6187,9 @@ var require_client_h1 = __commonJS({ addListener(socket, "close", function() { const client2 = this[kClient]; const parser = this[kParser]; - clearIdleSocketValidation(this); if (parser) { if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { - this[kError] = parser.finish() || this[kError]; + parser.onMessageComplete(); } this[kParser].destroy(); this[kParser] = null; @@ -6365,7 +6238,7 @@ var require_client_h1 = __commonJS({ return socket.destroyed; }, busy(request2) { - if (socket[kWriting] || socket[kReset] || socket[kBlocking] || socket[kIdleSocketValidation] === 1) { + if (socket[kWriting] || socket[kReset] || socket[kBlocking]) { return true; } if (request2) { @@ -6383,23 +6256,6 @@ var require_client_h1 = __commonJS({ } }; } - function clearIdleSocketValidation(socket) { - if (socket[kIdleSocketValidationTimeout]) { - clearImmediate(socket[kIdleSocketValidationTimeout]); - socket[kIdleSocketValidationTimeout] = null; - } - socket[kIdleSocketValidation] = 0; - } - function scheduleIdleSocketValidation(client, socket) { - socket[kIdleSocketValidation] = 1; - socket[kIdleSocketValidationTimeout] = setImmediate(() => { - socket[kIdleSocketValidationTimeout] = null; - socket[kIdleSocketValidation] = 2; - if (client[kSocket] === socket && !socket.destroyed) { - client[kResume](); - } - }); - } function resumeH1(client) { const socket = client[kSocket]; if (socket && !socket.destroyed) { @@ -6412,29 +6268,6 @@ var require_client_h1 = __commonJS({ socket.ref(); socket[kNoRef] = false; } - if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) { - if (socket[kIdleSocketValidation] === 0) { - scheduleIdleSocketValidation(client, socket); - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - if (socket[kIdleSocketValidation] === 1) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - } - if (client[kRunning] === 0) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - } if (client[kSize] === 0) { if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) { socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE); @@ -6465,16 +6298,8 @@ var require_client_h1 = __commonJS({ } body = bodyStream.stream; contentLength = bodyStream.length; - } else if (util.isBlobLike(body) && request2.contentType == null) { - const contentType = body.type; - if (contentType) { - const contentTypeValue = `${contentType}`; - if (!util.isValidHeaderValue(contentTypeValue)) { - util.errorRequest(client, request2, new InvalidArgumentError("invalid content-type header")); - return false; - } - headers.push("content-type", contentTypeValue); - } + } else if (util.isBlobLike(body) && request2.contentType == null && body.type) { + headers.push("content-type", body.type); } if (body && typeof body.read === "function") { body.read(0); @@ -6495,18 +6320,11 @@ var require_client_h1 = __commonJS({ process.emitWarning(new RequestContentLengthMismatchError()); } const socket = client[kSocket]; - clearIdleSocketValidation(socket); - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (request2.upgrade || request2.method === "CONNECT") { - util.destroy(socket, new InformationalError("aborted")); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - util.errorRequest(client, request2, error2 || new RequestAbortedError()); + util.errorRequest(client, request2, err || new RequestAbortedError()); util.destroy(body); util.destroy(socket, new InformationalError("aborted")); }; @@ -6862,7 +6680,6 @@ var require_client_h2 = __commonJS({ "node_modules/undici/lib/dispatcher/client-h2.js"(exports, module) { "use strict"; var assert = __require("node:assert"); - var { errorMonitor } = __require("node:events"); var { pipeline } = __require("node:stream"); var util = require_util(); var { @@ -6923,10 +6740,6 @@ var require_client_h2 = __commonJS({ } return result; } - function parseH2ResponseHeaders(headers) { - const { [HTTP2_HEADER_STATUS]: _statusCode, ...realHeaders } = headers; - return parseH2Headers(realHeaders); - } async function connectH2(client, socket) { client[kSocket] = socket; if (!h2ExperimentalWarned) { @@ -7090,22 +6903,16 @@ var require_client_h2 = __commonJS({ const { hostname, port } = client[kUrl]; headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ""}`; headers[HTTP2_HEADER_METHOD] = method; - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (method === "CONNECT" && stream != null) { - util.destroy(stream, error2 || new RequestAbortedError()); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - error2 = error2 || new RequestAbortedError(); - util.errorRequest(client, request2, error2); + err = err || new RequestAbortedError(); + util.errorRequest(client, request2, err); if (stream != null) { - util.destroy(stream, error2); + util.destroy(stream, err); } - util.destroy(body, error2); + util.destroy(body, err); client[kQueue][client[kRunningIdx]++] = null; client[kResume](); }; @@ -7120,42 +6927,18 @@ var require_client_h2 = __commonJS({ if (method === "CONNECT") { session.ref(); stream = session.request(headers, { endStream: false, signal }); - let upgradeResponseFinished = false; - const onResponse = (headers2) => { - upgradeResponseFinished = true; - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeResponse(Number(headers2[HTTP2_HEADER_STATUS]), headers2, parseH2ResponseHeaders); - }; - const onUpgradeError = (error2) => { - upgradeResponseFinished = true; - stream.off("response", onResponse); - request2.onUpgradeError(error2); - }; - const onReady = () => { - try { - request2.onUpgrade(null, null, stream); - } catch (error2) { - stream.off("response", onResponse); - abort(error2); - return; - } - if (request2.aborted) { - return; - } - stream.off("error", abort); - stream.once(errorMonitor, onUpgradeError); + if (stream.id && !stream.pending) { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; client[kQueue][client[kRunningIdx]++] = null; - }; - stream.once("response", onResponse); - stream.once("error", abort); - ++session[kOpenStreams]; - onReady(); + } else { + stream.once("ready", () => { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; + client[kQueue][client[kRunningIdx]++] = null; + }); + } stream.once("close", () => { - if (!upgradeResponseFinished && request2.completed) { - stream.off("response", onResponse); - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeError(new InformationalError(`HTTP/2: "stream error" received - code ${stream.rstCode}`)); - } session[kOpenStreams] -= 1; if (session[kOpenStreams] === 0) session.unref(); }); @@ -7716,10 +7499,9 @@ var require_client = __commonJS({ autoSelectFamilyAttemptTimeout, // h2 maxConcurrentStreams, - allowH2, - webSocket + allowH2 } = {}) { - super({ webSocket }); + super(); if (keepAlive !== void 0) { throw new InvalidArgumentError("unsupported keepAlive, use pipelining=0 instead"); } @@ -8225,8 +8007,8 @@ var require_pool_base = __commonJS({ var kRemoveClient = /* @__PURE__ */ Symbol("remove client"); var kStats = /* @__PURE__ */ Symbol("stats"); var PoolBase = class extends DispatcherBase { - constructor(opts) { - super(opts); + constructor() { + super(); this[kQueue] = new FixedQueue(); this[kClients] = []; this[kQueued] = 0; @@ -8397,6 +8179,7 @@ var require_pool = __commonJS({ allowH2, ...options } = {}) { + super(); if (connections != null && (!Number.isFinite(connections) || connections < 0)) { throw new InvalidArgumentError("invalid connections"); } @@ -8417,7 +8200,6 @@ var require_pool = __commonJS({ ...connect }); } - super(options); this[kInterceptors] = options.interceptors?.Pool && Array.isArray(options.interceptors.Pool) ? options.interceptors.Pool : []; this[kConnections] = connections || null; this[kUrl] = util.parseOrigin(origin); @@ -8617,6 +8399,7 @@ var require_agent = __commonJS({ } var Agent = class extends DispatcherBase { constructor({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { + super(); if (typeof factory !== "function") { throw new InvalidArgumentError("factory must be a function."); } @@ -8626,7 +8409,6 @@ var require_agent = __commonJS({ if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { throw new InvalidArgumentError("maxRedirections must be a positive number"); } - super(options); if (connect && typeof connect !== "function") { connect = { ...connect }; } @@ -9067,24 +8849,6 @@ var require_retry_handler = __commonJS({ const current = Date.now(); return new Date(retryAfter).getTime() - current; } - function validatePartialResponseContentLength(headers, range, statusCode, retryCount) { - const contentLength = headers["content-length"]; - if (contentLength == null) { - return null; - } - if (!Number.isFinite(range.start) || !Number.isFinite(range.end)) { - return null; - } - const length = Number(contentLength); - const expectedLength = range.end - range.start + 1; - if (!Number.isFinite(length) || length !== expectedLength) { - return new RequestRetryError("Content-Length mismatch", statusCode, { - headers, - data: { count: retryCount } - }); - } - return null; - } var RetryHandler = class _RetryHandler { constructor(opts, handlers) { const { retryOptions, ...dispatchOpts } = opts; @@ -9138,7 +8902,6 @@ var require_retry_handler = __commonJS({ this.end = null; this.etag = null; this.resume = null; - this.headersSent = false; this.handler.onConnect((reason) => { this.aborted = true; if (this.abort) { @@ -9148,17 +8911,6 @@ var require_retry_handler = __commonJS({ } }); } - 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(); @@ -9220,9 +8972,7 @@ var require_retry_handler = __commonJS({ const headers = parseHeaders(rawHeaders); this.retryCount += 1; if (statusCode >= 300) { - if (!this.headersSent && this.retryOpts.statusCodes.includes(statusCode) === false) { - this.headersSent = true; - this.checkpointResponseEnd(headers, resume); + if (this.retryOpts.statusCodes.includes(statusCode) === false) { return this.handler.onHeaders( statusCode, rawHeaders, @@ -9271,21 +9021,9 @@ var require_retry_handler = __commonJS({ ); return false; } - const contentLengthError = validatePartialResponseContentLength(headers, contentRange, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = contentRange; - 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; - } + assert(this.start === start, "content-range mismatch"); + assert(this.end == null || this.end === end, "content-range mismatch"); this.resume = resume; return true; } @@ -9293,7 +9031,6 @@ var require_retry_handler = __commonJS({ if (statusCode === 206) { const range = parseRangeHeader(headers["content-range"]); if (range == null) { - this.headersSent = true; return this.handler.onHeaders( statusCode, rawHeaders, @@ -9301,11 +9038,6 @@ var require_retry_handler = __commonJS({ statusMessage ); } - const contentLengthError = validatePartialResponseContentLength(headers, range, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = range; assert( start != null && Number.isFinite(start), @@ -9325,7 +9057,6 @@ var require_retry_handler = __commonJS({ "invalid content-length" ); this.resume = resume; - this.headersSent = true; this.etag = headers.etag != null ? headers.etag : null; if (this.etag != null && this.etag.startsWith("W/")) { this.etag = null; @@ -9353,7 +9084,7 @@ var require_retry_handler = __commonJS({ return this.handler.onComplete(rawTrailers); } onError(err) { - if (this.aborted || isDisturbed(this.opts.body) || this.headersSent && this.resume == null) { + if (this.aborted || isDisturbed(this.opts.body)) { return this.handler.onError(err); } if (this.retryCount - this.retryCountCheckpoint > 0) { @@ -16152,48 +15883,14 @@ var require_util6 = __commonJS({ for (let i = 0; i < path.length; ++i) { const code = path.charCodeAt(i); if (code < 32 || // exclude CTLs (0-31) - code > 126 || // exclude DEL and non-ascii + code === 127 || // DEL code === 59) { throw new Error("Invalid cookie path"); } } } - function isLetterOrDigit(code) { - return code >= 48 && code <= 57 || // 0-9 - code >= 65 && code <= 90 || // A-Z - code >= 97 && code <= 122; - } function validateCookieDomain(domain) { - if (domain === " ") { - return; - } - if (domain.length > 255) { - throw new Error("Invalid cookie domain"); - } - let labelLength = 0; - for (let i = 0; i < domain.length; ++i) { - const code = domain.charCodeAt(i); - if (code === 46) { - if (labelLength === 0) { - throw new Error("Invalid cookie domain"); - } - if (domain.charCodeAt(i - 1) === 45) { - throw new Error("Invalid cookie domain"); - } - labelLength = 0; - continue; - } - if (labelLength === 0 && !isLetterOrDigit(code)) { - throw new Error("Invalid cookie domain"); - } - if (!isLetterOrDigit(code) && code !== 45) { - throw new Error("Invalid cookie domain"); - } - if (++labelLength > 63) { - throw new Error("Invalid cookie domain"); - } - } - if (labelLength === 0 || domain.charCodeAt(domain.length - 1) === 45) { + if (domain.startsWith("-") || domain.endsWith(".") || domain.endsWith("-")) { throw new Error("Invalid cookie domain"); } } @@ -16276,11 +15973,7 @@ var require_util6 = __commonJS({ throw new Error("Invalid unparsed"); } const [key, ...value] = part.split("="); - const trimmedKey = key.trim(); - const joinedValue = value.join("="); - validateCookieName(trimmedKey); - validateCookieValue(joinedValue); - out.push(`${trimmedKey}=${joinedValue}`); + out.push(`${key.trim()}=${value.join("=")}`); } return out.join("; "); } @@ -16410,14 +16103,18 @@ var require_parse = __commonJS({ } else if (attributeNameLowercase === "httponly") { cookieAttributeList.httpOnly = true; } else if (attributeNameLowercase === "samesite") { + let enforcement = "Default"; const attributeValueLowercase = attributeValue.toLowerCase(); - if (attributeValueLowercase === "none") { - cookieAttributeList.sameSite = "None"; - } else if (attributeValueLowercase === "strict") { - cookieAttributeList.sameSite = "Strict"; - } else if (attributeValueLowercase === "lax") { - cookieAttributeList.sameSite = "Lax"; + if (attributeValueLowercase.includes("none")) { + enforcement = "None"; + } + if (attributeValueLowercase.includes("strict")) { + enforcement = "Strict"; + } + if (attributeValueLowercase.includes("lax")) { + enforcement = "Lax"; } + cookieAttributeList.sameSite = enforcement; } else { cookieAttributeList.unparsed ??= []; cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`); @@ -17239,7 +16936,7 @@ var require_connection = __commonJS({ const secProtocol = response.headersList.get("Sec-WebSocket-Protocol"); if (secProtocol !== null) { const requestProtocols = getDecodeSplit("sec-websocket-protocol", request2.headersList); - if (requestProtocols === null || !requestProtocols.includes(secProtocol)) { + if (!requestProtocols.includes(secProtocol)) { failWebsocketConnection(ws, "Protocol was not set in the opening handshake."); return; } @@ -17345,26 +17042,31 @@ var require_permessage_deflate = __commonJS({ var tail = Buffer.from([0, 0, 255, 255]); var kBuffer = /* @__PURE__ */ Symbol("kBuffer"); var kLength = /* @__PURE__ */ Symbol("kLength"); + var kDefaultMaxDecompressedSize = 4 * 1024 * 1024; var PerMessageDeflate = class { /** @type {import('node:zlib').InflateRaw} */ #inflate; #options = {}; - #maxPayloadSize = 0; + /** @type {number} */ + #maxDecompressedSize; + /** @type {boolean} */ + #aborted = false; + /** @type {Function|null} */ + #currentCallback = null; /** * @param {Map} extensions + * @param {{ maxDecompressedMessageSize?: number }} [options] */ - constructor(extensions, options) { + constructor(extensions, options = {}) { this.#options.serverNoContextTakeover = extensions.has("server_no_context_takeover"); this.#options.serverMaxWindowBits = extensions.get("server_max_window_bits"); - this.#maxPayloadSize = options.maxPayloadSize; + this.#maxDecompressedSize = options.maxDecompressedMessageSize ?? kDefaultMaxDecompressedSize; } - /** - * Decompress a compressed payload. - * @param {Buffer} chunk Compressed data - * @param {boolean} fin Final fragment flag - * @param {Function} callback Callback function - */ decompress(chunk, fin, callback) { + if (this.#aborted) { + callback(new MessageSizeExceededError()); + return; + } if (!this.#inflate) { let windowBits = Z_DEFAULT_WINDOWBITS; if (this.#options.serverMaxWindowBits) { @@ -17383,12 +17085,20 @@ var require_permessage_deflate = __commonJS({ this.#inflate[kBuffer] = []; this.#inflate[kLength] = 0; this.#inflate.on("data", (data) => { + if (this.#aborted) { + return; + } this.#inflate[kLength] += data.length; - if (this.#maxPayloadSize > 0 && this.#inflate[kLength] > this.#maxPayloadSize) { - callback(new MessageSizeExceededError()); + if (this.#inflate[kLength] > this.#maxDecompressedSize) { + this.#aborted = true; this.#inflate.removeAllListeners(); this.#inflate.destroy(); this.#inflate = null; + if (this.#currentCallback) { + const cb = this.#currentCallback; + this.#currentCallback = null; + cb(new MessageSizeExceededError()); + } return; } this.#inflate[kBuffer].push(data); @@ -17398,17 +17108,19 @@ var require_permessage_deflate = __commonJS({ callback(err); }); } + this.#currentCallback = callback; this.#inflate.write(chunk); if (fin) { this.#inflate.write(tail); } this.#inflate.flush(() => { - if (!this.#inflate) { + if (this.#aborted || !this.#inflate) { return; } const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]); this.#inflate[kBuffer].length = 0; this.#inflate[kLength] = 0; + this.#currentCallback = null; callback(null, full); }); } @@ -17439,14 +17151,8 @@ var require_receiver = __commonJS({ var { WebsocketFrameSend } = require_frame(); var { closeWebSocketConnection } = require_connection(); var { PerMessageDeflate } = require_permessage_deflate(); - var { MessageSizeExceededError } = require_errors(); - function failWebsocketConnectionWithCode(ws, code, reason) { - closeWebSocketConnection(ws, code, reason, Buffer.byteLength(reason)); - failWebsocketConnection(ws, reason); - } var ByteParser = class extends Writable { #buffers = []; - #fragmentsBytes = 0; #byteOffset = 0; #loop = false; #state = parserStates.INFO; @@ -17454,21 +17160,18 @@ var require_receiver = __commonJS({ #fragments = []; /** @type {Map} */ #extensions; - /** @type {number} */ - #maxFragments; - /** @type {number} */ - #maxPayloadSize; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {import('./websocket').WebSocket} ws * @param {Map|null} extensions - * @param {{ maxFragments?: number, maxPayloadSize?: number }} [options] + * @param {{ maxDecompressedMessageSize?: number }} [options] */ constructor(ws, extensions, options = {}) { super(); this.ws = ws; this.#extensions = extensions == null ? /* @__PURE__ */ new Map() : extensions; - this.#maxFragments = options.maxFragments ?? 0; - this.#maxPayloadSize = options.maxPayloadSize ?? 0; + this.#options = options; if (this.#extensions.has("permessage-deflate")) { this.#extensions.set("permessage-deflate", new PerMessageDeflate(extensions, options)); } @@ -17483,13 +17186,6 @@ var require_receiver = __commonJS({ this.#loop = true; this.run(callback); } - #validatePayloadLength() { - if (this.#maxPayloadSize > 0 && !isControlFrame(this.#info.opcode) && this.#info.payloadLength + this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, "Payload size exceeds maximum allowed size"); - return false; - } - return true; - } /** * Runs whenever a new chunk is received. * Callback is called whenever there are no more chunks buffering, @@ -17549,9 +17245,6 @@ var require_receiver = __commonJS({ if (payloadLength <= 125) { this.#info.payloadLength = payloadLength; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (payloadLength === 126) { this.#state = parserStates.PAYLOADLENGTH_16; } else if (payloadLength === 127) { @@ -17572,9 +17265,6 @@ var require_receiver = __commonJS({ const buffer = this.consume(2); this.#info.payloadLength = buffer.readUInt16BE(0); this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.PAYLOADLENGTH_64) { if (this.#byteOffset < 8) { return callback(); @@ -17588,9 +17278,6 @@ var require_receiver = __commonJS({ } this.#info.payloadLength = lower; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.READ_DATA) { if (this.#byteOffset < this.#info.payloadLength) { return callback(); @@ -17601,46 +17288,32 @@ var require_receiver = __commonJS({ this.#state = parserStates.INFO; } else { if (!this.#info.compressed) { - if (!this.writeFragments(body)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } + this.#fragments.push(body); if (!this.#info.fragmented && this.#info.fin) { - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); + const fullMessage = Buffer.concat(this.#fragments); + websocketMessageReceived(this.ws, this.#info.binaryType, fullMessage); + this.#fragments.length = 0; } this.#state = parserStates.INFO; } else { - this.#extensions.get("permessage-deflate").decompress( - body, - this.#info.fin, - (error2, data) => { - if (error2) { - const code = error2 instanceof MessageSizeExceededError ? 1009 : 1007; - failWebsocketConnectionWithCode(this.ws, code, error2.message); - return; - } - if (!this.writeFragments(data)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } - if (!this.#info.fin) { - this.#state = parserStates.INFO; - this.#loop = true; - this.run(callback); - return; - } - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); - this.#loop = true; + this.#extensions.get("permessage-deflate").decompress(body, this.#info.fin, (error2, data) => { + if (error2) { + failWebsocketConnection(this.ws, error2.message); + return; + } + this.#fragments.push(data); + if (!this.#info.fin) { this.#state = parserStates.INFO; + this.#loop = true; this.run(callback); + return; } - ); + websocketMessageReceived(this.ws, this.#info.binaryType, Buffer.concat(this.#fragments)); + this.#loop = true; + this.#state = parserStates.INFO; + this.#fragments.length = 0; + this.run(callback); + }); this.#loop = false; break; } @@ -17683,26 +17356,6 @@ var require_receiver = __commonJS({ this.#byteOffset -= n; return buffer; } - writeFragments(fragment) { - if (this.#maxFragments > 0 && this.#fragments.length === this.#maxFragments) { - failWebsocketConnectionWithCode(this.ws, 1008, "Too many message fragments"); - return false; - } - this.#fragmentsBytes += fragment.length; - this.#fragments.push(fragment); - return true; - } - consumeFragments() { - const fragments = this.#fragments; - if (fragments.length === 1) { - this.#fragmentsBytes = 0; - return fragments.shift(); - } - const output = Buffer.concat(fragments, this.#fragmentsBytes); - this.#fragments = []; - this.#fragmentsBytes = 0; - return output; - } parseCloseBody(data) { assert(data.length !== 1); let code; @@ -17914,6 +17567,8 @@ var require_websocket = __commonJS({ #extensions = ""; /** @type {SendQueue} */ #sendQueue; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {string} url * @param {string|string[]} protocols @@ -17957,6 +17612,9 @@ var require_websocket = __commonJS({ throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError"); } this[kWebSocketURL] = new URL(urlRecord.href); + this.#options = { + maxDecompressedMessageSize: options.maxDecompressedMessageSize + }; const client = environmentSettingsObject.settingsObject; this[kController] = establishWebSocketConnection( urlRecord, @@ -18140,13 +17798,7 @@ var require_websocket = __commonJS({ */ #onConnectionEstablished(response, parsedExtensions) { this[kResponse] = response; - const webSocketOptions = this[kController]?.dispatcher?.webSocketOptions; - const maxFragments = webSocketOptions?.maxFragments; - const maxPayloadSize = webSocketOptions?.maxPayloadSize; - const parser = new ByteParser(this, parsedExtensions, { - maxFragments, - maxPayloadSize - }); + const parser = new ByteParser(this, parsedExtensions, this.#options); parser.on("drain", onParserDrain); parser.on("error", onParserError.bind(this)); response.socket.ws = this; @@ -18221,6 +17873,19 @@ var require_websocket = __commonJS({ { key: "headers", converter: webidl.nullableConverter(webidl.converters.HeadersInit) + }, + { + key: "maxDecompressedMessageSize", + converter: webidl.nullableConverter((V) => { + V = webidl.converters["unsigned long long"](V); + if (V <= 0) { + throw webidl.errors.exception({ + header: "WebSocket constructor", + message: "maxDecompressedMessageSize must be greater than 0" + }); + } + return V; + }) } ]); webidl.converters["DOMString or sequence or WebSocketInit"] = function(V) { @@ -18299,40 +17964,6 @@ 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; - } - function isValidLastEventIdBytes(buffer, start) { - for (let i = start; i < buffer.length; i++) { - if (buffer[i] === 0) { - 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; - } var EventSourceStream = class extends Transform { /** * @type {eventSourceSettings} @@ -18352,13 +17983,10 @@ var require_eventsource_stream = __commonJS({ */ eventEndCheck = false; /** - * @type {Buffer[]} + * @type {Buffer} */ - chunks = []; - chunkIndex = 0; + buffer = null; pos = 0; - lineChunkIndex = 0; - linePos = 0; event = { data: void 0, event: void 0, @@ -18389,30 +18017,63 @@ var require_eventsource_stream = __commonJS({ callback(); return; } - this.chunks.push(chunk); + if (this.buffer) { + this.buffer = Buffer.concat([this.buffer, chunk]); + } else { + this.buffer = chunk; + } if (this.checkBOM) { - if (this.handleBOM()) { - callback(); - return; + 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; } } - while (this.hasCurrentByte()) { - const byte = this.currentByte(); + while (this.pos < this.buffer.length) { if (this.eventEndCheck) { if (this.crlfCheck) { - if (byte === LF) { + if (this.buffer[this.pos] === LF) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.crlfCheck = false; - this.consumeCurrentByte(); continue; } this.crlfCheck = false; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.consumeCurrentByte(); - if (this.hasPendingEvent()) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; + if (this.event.data !== void 0 || this.event.event || this.event.id || this.event.retry) { this.processEvent(this.event); } this.clearEvent(); @@ -18421,16 +18082,17 @@ var require_eventsource_stream = __commonJS({ this.eventEndCheck = false; continue; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.parseLine(this.readLine(), this.event); - this.consumeCurrentByte(); + this.parseLine(this.buffer.subarray(0, this.pos), this.event); + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.eventEndCheck = true; continue; } - this.advanceCursor(); + this.pos++; } callback(); } @@ -18446,42 +18108,43 @@ var require_eventsource_stream = __commonJS({ if (colonPosition === 0) { return; } - let fieldLength = line.length; - let valueStart = line.length; + let field = ""; + let value = ""; if (colonPosition !== -1) { - fieldLength = colonPosition; - valueStart = colonPosition + 1; + field = line.subarray(0, colonPosition).toString("utf8"); + let valueStart = colonPosition + 1; if (line[valueStart] === SPACE) { ++valueStart; } + value = line.subarray(valueStart).toString("utf8"); + } else { + field = line.toString("utf8"); + value = ""; } - if (isFieldName(line, fieldLength, DATA)) { - const value = line.toString("utf8", valueStart); - if (event.data === void 0) { - event.data = value; - } else { - event.data += ` + switch (field) { + case "data": + if (event[field] === void 0) { + event[field] = value; + } else { + event[field] += ` ${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; - } + } + 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; } } /** @@ -18506,120 +18169,12 @@ ${value}`; } } clearEvent() { - 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(); + this.event = { + data: void 0, + event: void 0, + id: void 0, + retry: void 0 + }; } }; module.exports = { diff --git a/.github/actions/javascript/generateHelpPreviewComment/index.js b/.github/actions/javascript/generateHelpPreviewComment/index.js index 222ea227535c..4fffa145a897 100644 --- a/.github/actions/javascript/generateHelpPreviewComment/index.js +++ b/.github/actions/javascript/generateHelpPreviewComment/index.js @@ -1863,66 +1863,10 @@ var require_request = __commonJS({ return false; } } - /** - * @param {number|null} statusCode - * @param {Buffer[]|null} headers - * @param {import('node:stream').Duplex} socket - * @param {string} [statusText] - */ - onUpgrade(statusCode, headers, socket, statusText = "") { - this.onFinally(); + onUpgrade(statusCode, headers, socket) { assert(!this.aborted); assert(!this.completed); - 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: [] }); - } + return this[kHandler].onUpgrade(statusCode, headers, socket); } onComplete(trailers) { this.onFinally(); @@ -1989,11 +1933,7 @@ var require_request = __commonJS({ } else if (typeof val[i] === "object") { throw new InvalidArgumentError(`invalid ${key} header`); } else { - const str = `${val[i]}`; - if (!isValidHeaderValue(str)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } - arr.push(str); + arr.push(`${val[i]}`); } } val = arr; @@ -2005,9 +1945,6 @@ var require_request = __commonJS({ val = ""; } else { val = `${val}`; - if (!isValidHeaderValue(val)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } } if (headerName === "host") { if (request2.host !== null) { @@ -2117,21 +2054,13 @@ var require_dispatcher_base = __commonJS({ var kOnDestroyed = /* @__PURE__ */ Symbol("onDestroyed"); var kOnClosed = /* @__PURE__ */ Symbol("onClosed"); var kInterceptedDispatch = /* @__PURE__ */ Symbol("Intercepted Dispatch"); - var kWebSocketOptions = /* @__PURE__ */ Symbol("webSocketOptions"); var DispatcherBase = class extends Dispatcher { - constructor(opts) { + constructor() { super(); this[kDestroyed] = false; this[kOnDestroyed] = null; this[kClosed] = false; this[kOnClosed] = []; - this[kWebSocketOptions] = opts?.webSocket ?? {}; - } - get webSocketOptions() { - return { - maxFragments: this[kWebSocketOptions].maxFragments ?? 131072, - maxPayloadSize: this[kWebSocketOptions].maxPayloadSize ?? 128 * 1024 * 1024 - }; } get destroyed() { return this[kDestroyed]; @@ -5738,7 +5667,6 @@ var require_client_h1 = __commonJS({ RequestContentLengthMismatchError, ResponseContentLengthMismatchError, RequestAbortedError, - InvalidArgumentError, HeadersTimeoutError, HeadersOverflowError, SocketError, @@ -5785,9 +5713,6 @@ var require_client_h1 = __commonJS({ var FastBuffer = Buffer[Symbol.species]; var addListener = util.addListener; var removeAllListeners = util.removeAllListeners; - var kIdleSocketValidation = /* @__PURE__ */ Symbol("kIdleSocketValidation"); - var kIdleSocketValidationTimeout = /* @__PURE__ */ Symbol("kIdleSocketValidationTimeout"); - var kSocketUsed = /* @__PURE__ */ Symbol("kSocketUsed"); var extractBody; async function lazyllhttp() { const llhttpWasmData = process.env.JEST_WORKER_ID ? require_llhttp_wasm() : void 0; @@ -5950,55 +5875,24 @@ var require_client_h1 = __commonJS({ currentBufferRef = null; } const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr; - if (ret !== constants3.ERROR.OK) { - const body = data.subarray(offset); - if (ret === constants3.ERROR.PAUSED_UPGRADE) { - this.onUpgrade(body); - } else if (ret === constants3.ERROR.PAUSED) { - this.paused = true; - socket.unshift(body); - } else { - throw this.createError(ret, body); + if (ret === constants3.ERROR.PAUSED_UPGRADE) { + this.onUpgrade(data.slice(offset)); + } else if (ret === constants3.ERROR.PAUSED) { + this.paused = true; + socket.unshift(data.slice(offset)); + } else if (ret !== constants3.ERROR.OK) { + const ptr = llhttp.llhttp_get_error_reason(this.ptr); + let message = ""; + if (ptr) { + const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); + message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; } + throw new HTTPParserError(message, constants3.ERROR[ret], data.slice(offset)); } } catch (err) { util.destroy(socket, err); } } - finish() { - assert(currentParser === null); - assert(this.ptr != null); - assert(!this.paused); - const { llhttp } = this; - let ret; - try { - currentParser = this; - ret = llhttp.llhttp_finish(this.ptr); - } finally { - currentParser = null; - } - if (ret === constants3.ERROR.OK) { - return null; - } - if (ret === constants3.ERROR.PAUSED || ret === constants3.ERROR.PAUSED_UPGRADE) { - this.paused = true; - return null; - } - return this.createError(ret, EMPTY_BUF); - } - createError(ret, data) { - const { llhttp, contentLength, bytesRead } = this; - if (contentLength && bytesRead !== parseInt(contentLength, 10)) { - return new ResponseContentLengthMismatchError(); - } - const ptr = llhttp.llhttp_get_error_reason(this.ptr); - let message = ""; - if (ptr) { - const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); - message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; - } - return new HTTPParserError(message, constants3.ERROR[ret], data); - } destroy() { assert(this.ptr != null); assert(currentParser == null); @@ -6018,10 +5912,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6065,7 +5955,7 @@ var require_client_h1 = __commonJS({ } } onUpgrade(head) { - const { upgrade, client, socket, headers, statusCode, statusText } = this; + const { upgrade, client, socket, headers, statusCode } = this; assert(upgrade); assert(client[kSocket] === socket); assert(!socket.destroyed); @@ -6090,10 +5980,9 @@ var require_client_h1 = __commonJS({ client[kQueue][client[kRunningIdx]++] = null; client.emit("disconnect", client[kUrl], [client], new InformationalError("upgrade")); try { - request2.onUpgrade(statusCode, headers, socket, statusText); - } catch (error) { - util.errorRequest(client, request2, error); - util.destroy(socket, error); + request2.onUpgrade(statusCode, headers, socket); + } catch (err) { + util.destroy(socket, err); } client[kResume](); } @@ -6102,10 +5991,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6231,7 +6116,6 @@ var require_client_h1 = __commonJS({ } request2.onComplete(headers); client[kQueue][client[kRunningIdx]++] = null; - socket[kSocketUsed] = true; if (socket[kWriting]) { assert(client[kRunning] === 0); util.destroy(socket, new InformationalError("reset")); @@ -6275,19 +6159,12 @@ var require_client_h1 = __commonJS({ socket[kWriting] = false; socket[kReset] = false; socket[kBlocking] = false; - socket[kIdleSocketValidation] = 0; - socket[kIdleSocketValidationTimeout] = null; - socket[kSocketUsed] = false; socket[kParser] = new Parser(client, socket, llhttpInstance); addListener(socket, "error", function(err) { assert(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID"); const parser = this[kParser]; if (err.code === "ECONNRESET" && parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - this[kError] = parserErr; - this[kClient][kOnError](parserErr); - } + parser.onMessageComplete(); return; } this[kError] = err; @@ -6302,10 +6179,7 @@ var require_client_h1 = __commonJS({ addListener(socket, "end", function() { const parser = this[kParser]; if (parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - util.destroy(this, parserErr); - } + parser.onMessageComplete(); return; } util.destroy(this, new SocketError("other side closed", util.getSocketInfo(this))); @@ -6313,10 +6187,9 @@ var require_client_h1 = __commonJS({ addListener(socket, "close", function() { const client2 = this[kClient]; const parser = this[kParser]; - clearIdleSocketValidation(this); if (parser) { if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { - this[kError] = parser.finish() || this[kError]; + parser.onMessageComplete(); } this[kParser].destroy(); this[kParser] = null; @@ -6365,7 +6238,7 @@ var require_client_h1 = __commonJS({ return socket.destroyed; }, busy(request2) { - if (socket[kWriting] || socket[kReset] || socket[kBlocking] || socket[kIdleSocketValidation] === 1) { + if (socket[kWriting] || socket[kReset] || socket[kBlocking]) { return true; } if (request2) { @@ -6383,23 +6256,6 @@ var require_client_h1 = __commonJS({ } }; } - function clearIdleSocketValidation(socket) { - if (socket[kIdleSocketValidationTimeout]) { - clearImmediate(socket[kIdleSocketValidationTimeout]); - socket[kIdleSocketValidationTimeout] = null; - } - socket[kIdleSocketValidation] = 0; - } - function scheduleIdleSocketValidation(client, socket) { - socket[kIdleSocketValidation] = 1; - socket[kIdleSocketValidationTimeout] = setImmediate(() => { - socket[kIdleSocketValidationTimeout] = null; - socket[kIdleSocketValidation] = 2; - if (client[kSocket] === socket && !socket.destroyed) { - client[kResume](); - } - }); - } function resumeH1(client) { const socket = client[kSocket]; if (socket && !socket.destroyed) { @@ -6412,29 +6268,6 @@ var require_client_h1 = __commonJS({ socket.ref(); socket[kNoRef] = false; } - if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) { - if (socket[kIdleSocketValidation] === 0) { - scheduleIdleSocketValidation(client, socket); - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - if (socket[kIdleSocketValidation] === 1) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - } - if (client[kRunning] === 0) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - } if (client[kSize] === 0) { if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) { socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE); @@ -6465,16 +6298,8 @@ var require_client_h1 = __commonJS({ } body = bodyStream.stream; contentLength = bodyStream.length; - } else if (util.isBlobLike(body) && request2.contentType == null) { - const contentType = body.type; - if (contentType) { - const contentTypeValue = `${contentType}`; - if (!util.isValidHeaderValue(contentTypeValue)) { - util.errorRequest(client, request2, new InvalidArgumentError("invalid content-type header")); - return false; - } - headers.push("content-type", contentTypeValue); - } + } else if (util.isBlobLike(body) && request2.contentType == null && body.type) { + headers.push("content-type", body.type); } if (body && typeof body.read === "function") { body.read(0); @@ -6495,18 +6320,11 @@ var require_client_h1 = __commonJS({ process.emitWarning(new RequestContentLengthMismatchError()); } const socket = client[kSocket]; - clearIdleSocketValidation(socket); - const abort = (error) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (request2.upgrade || request2.method === "CONNECT") { - util.destroy(socket, new InformationalError("aborted")); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - util.errorRequest(client, request2, error || new RequestAbortedError()); + util.errorRequest(client, request2, err || new RequestAbortedError()); util.destroy(body); util.destroy(socket, new InformationalError("aborted")); }; @@ -6862,7 +6680,6 @@ var require_client_h2 = __commonJS({ "node_modules/undici/lib/dispatcher/client-h2.js"(exports, module) { "use strict"; var assert = __require("node:assert"); - var { errorMonitor } = __require("node:events"); var { pipeline } = __require("node:stream"); var util = require_util(); var { @@ -6923,10 +6740,6 @@ var require_client_h2 = __commonJS({ } return result; } - function parseH2ResponseHeaders(headers) { - const { [HTTP2_HEADER_STATUS]: _statusCode, ...realHeaders } = headers; - return parseH2Headers(realHeaders); - } async function connectH2(client, socket) { client[kSocket] = socket; if (!h2ExperimentalWarned) { @@ -7090,22 +6903,16 @@ var require_client_h2 = __commonJS({ const { hostname, port } = client[kUrl]; headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ""}`; headers[HTTP2_HEADER_METHOD] = method; - const abort = (error) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (method === "CONNECT" && stream != null) { - util.destroy(stream, error || new RequestAbortedError()); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - error = error || new RequestAbortedError(); - util.errorRequest(client, request2, error); + err = err || new RequestAbortedError(); + util.errorRequest(client, request2, err); if (stream != null) { - util.destroy(stream, error); + util.destroy(stream, err); } - util.destroy(body, error); + util.destroy(body, err); client[kQueue][client[kRunningIdx]++] = null; client[kResume](); }; @@ -7120,42 +6927,18 @@ var require_client_h2 = __commonJS({ if (method === "CONNECT") { session.ref(); stream = session.request(headers, { endStream: false, signal }); - let upgradeResponseFinished = false; - const onResponse = (headers2) => { - upgradeResponseFinished = true; - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeResponse(Number(headers2[HTTP2_HEADER_STATUS]), headers2, parseH2ResponseHeaders); - }; - const onUpgradeError = (error) => { - upgradeResponseFinished = true; - stream.off("response", onResponse); - request2.onUpgradeError(error); - }; - const onReady = () => { - try { - request2.onUpgrade(null, null, stream); - } catch (error) { - stream.off("response", onResponse); - abort(error); - return; - } - if (request2.aborted) { - return; - } - stream.off("error", abort); - stream.once(errorMonitor, onUpgradeError); + if (stream.id && !stream.pending) { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; client[kQueue][client[kRunningIdx]++] = null; - }; - stream.once("response", onResponse); - stream.once("error", abort); - ++session[kOpenStreams]; - onReady(); + } else { + stream.once("ready", () => { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; + client[kQueue][client[kRunningIdx]++] = null; + }); + } stream.once("close", () => { - if (!upgradeResponseFinished && request2.completed) { - stream.off("response", onResponse); - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeError(new InformationalError(`HTTP/2: "stream error" received - code ${stream.rstCode}`)); - } session[kOpenStreams] -= 1; if (session[kOpenStreams] === 0) session.unref(); }); @@ -7716,10 +7499,9 @@ var require_client = __commonJS({ autoSelectFamilyAttemptTimeout, // h2 maxConcurrentStreams, - allowH2, - webSocket + allowH2 } = {}) { - super({ webSocket }); + super(); if (keepAlive !== void 0) { throw new InvalidArgumentError("unsupported keepAlive, use pipelining=0 instead"); } @@ -8225,8 +8007,8 @@ var require_pool_base = __commonJS({ var kRemoveClient = /* @__PURE__ */ Symbol("remove client"); var kStats = /* @__PURE__ */ Symbol("stats"); var PoolBase = class extends DispatcherBase { - constructor(opts) { - super(opts); + constructor() { + super(); this[kQueue] = new FixedQueue(); this[kClients] = []; this[kQueued] = 0; @@ -8397,6 +8179,7 @@ var require_pool = __commonJS({ allowH2, ...options } = {}) { + super(); if (connections != null && (!Number.isFinite(connections) || connections < 0)) { throw new InvalidArgumentError("invalid connections"); } @@ -8417,7 +8200,6 @@ var require_pool = __commonJS({ ...connect }); } - super(options); this[kInterceptors] = options.interceptors?.Pool && Array.isArray(options.interceptors.Pool) ? options.interceptors.Pool : []; this[kConnections] = connections || null; this[kUrl] = util.parseOrigin(origin); @@ -8617,6 +8399,7 @@ var require_agent = __commonJS({ } var Agent = class extends DispatcherBase { constructor({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { + super(); if (typeof factory !== "function") { throw new InvalidArgumentError("factory must be a function."); } @@ -8626,7 +8409,6 @@ var require_agent = __commonJS({ if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { throw new InvalidArgumentError("maxRedirections must be a positive number"); } - super(options); if (connect && typeof connect !== "function") { connect = { ...connect }; } @@ -9067,24 +8849,6 @@ var require_retry_handler = __commonJS({ const current = Date.now(); return new Date(retryAfter).getTime() - current; } - function validatePartialResponseContentLength(headers, range, statusCode, retryCount) { - const contentLength = headers["content-length"]; - if (contentLength == null) { - return null; - } - if (!Number.isFinite(range.start) || !Number.isFinite(range.end)) { - return null; - } - const length = Number(contentLength); - const expectedLength = range.end - range.start + 1; - if (!Number.isFinite(length) || length !== expectedLength) { - return new RequestRetryError("Content-Length mismatch", statusCode, { - headers, - data: { count: retryCount } - }); - } - return null; - } var RetryHandler = class _RetryHandler { constructor(opts, handlers) { const { retryOptions, ...dispatchOpts } = opts; @@ -9138,7 +8902,6 @@ var require_retry_handler = __commonJS({ this.end = null; this.etag = null; this.resume = null; - this.headersSent = false; this.handler.onConnect((reason) => { this.aborted = true; if (this.abort) { @@ -9148,17 +8911,6 @@ var require_retry_handler = __commonJS({ } }); } - 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(); @@ -9220,9 +8972,7 @@ var require_retry_handler = __commonJS({ const headers = parseHeaders(rawHeaders); this.retryCount += 1; if (statusCode >= 300) { - if (!this.headersSent && this.retryOpts.statusCodes.includes(statusCode) === false) { - this.headersSent = true; - this.checkpointResponseEnd(headers, resume); + if (this.retryOpts.statusCodes.includes(statusCode) === false) { return this.handler.onHeaders( statusCode, rawHeaders, @@ -9271,21 +9021,9 @@ var require_retry_handler = __commonJS({ ); return false; } - const contentLengthError = validatePartialResponseContentLength(headers, contentRange, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = contentRange; - 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; - } + assert(this.start === start, "content-range mismatch"); + assert(this.end == null || this.end === end, "content-range mismatch"); this.resume = resume; return true; } @@ -9293,7 +9031,6 @@ var require_retry_handler = __commonJS({ if (statusCode === 206) { const range = parseRangeHeader(headers["content-range"]); if (range == null) { - this.headersSent = true; return this.handler.onHeaders( statusCode, rawHeaders, @@ -9301,11 +9038,6 @@ var require_retry_handler = __commonJS({ statusMessage ); } - const contentLengthError = validatePartialResponseContentLength(headers, range, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = range; assert( start != null && Number.isFinite(start), @@ -9325,7 +9057,6 @@ var require_retry_handler = __commonJS({ "invalid content-length" ); this.resume = resume; - this.headersSent = true; this.etag = headers.etag != null ? headers.etag : null; if (this.etag != null && this.etag.startsWith("W/")) { this.etag = null; @@ -9353,7 +9084,7 @@ var require_retry_handler = __commonJS({ return this.handler.onComplete(rawTrailers); } onError(err) { - if (this.aborted || isDisturbed(this.opts.body) || this.headersSent && this.resume == null) { + if (this.aborted || isDisturbed(this.opts.body)) { return this.handler.onError(err); } if (this.retryCount - this.retryCountCheckpoint > 0) { @@ -16152,48 +15883,14 @@ var require_util6 = __commonJS({ for (let i = 0; i < path.length; ++i) { const code = path.charCodeAt(i); if (code < 32 || // exclude CTLs (0-31) - code > 126 || // exclude DEL and non-ascii + code === 127 || // DEL code === 59) { throw new Error("Invalid cookie path"); } } } - function isLetterOrDigit(code) { - return code >= 48 && code <= 57 || // 0-9 - code >= 65 && code <= 90 || // A-Z - code >= 97 && code <= 122; - } function validateCookieDomain(domain) { - if (domain === " ") { - return; - } - if (domain.length > 255) { - throw new Error("Invalid cookie domain"); - } - let labelLength = 0; - for (let i = 0; i < domain.length; ++i) { - const code = domain.charCodeAt(i); - if (code === 46) { - if (labelLength === 0) { - throw new Error("Invalid cookie domain"); - } - if (domain.charCodeAt(i - 1) === 45) { - throw new Error("Invalid cookie domain"); - } - labelLength = 0; - continue; - } - if (labelLength === 0 && !isLetterOrDigit(code)) { - throw new Error("Invalid cookie domain"); - } - if (!isLetterOrDigit(code) && code !== 45) { - throw new Error("Invalid cookie domain"); - } - if (++labelLength > 63) { - throw new Error("Invalid cookie domain"); - } - } - if (labelLength === 0 || domain.charCodeAt(domain.length - 1) === 45) { + if (domain.startsWith("-") || domain.endsWith(".") || domain.endsWith("-")) { throw new Error("Invalid cookie domain"); } } @@ -16276,11 +15973,7 @@ var require_util6 = __commonJS({ throw new Error("Invalid unparsed"); } const [key, ...value] = part.split("="); - const trimmedKey = key.trim(); - const joinedValue = value.join("="); - validateCookieName(trimmedKey); - validateCookieValue(joinedValue); - out.push(`${trimmedKey}=${joinedValue}`); + out.push(`${key.trim()}=${value.join("=")}`); } return out.join("; "); } @@ -16410,14 +16103,18 @@ var require_parse = __commonJS({ } else if (attributeNameLowercase === "httponly") { cookieAttributeList.httpOnly = true; } else if (attributeNameLowercase === "samesite") { + let enforcement = "Default"; const attributeValueLowercase = attributeValue.toLowerCase(); - if (attributeValueLowercase === "none") { - cookieAttributeList.sameSite = "None"; - } else if (attributeValueLowercase === "strict") { - cookieAttributeList.sameSite = "Strict"; - } else if (attributeValueLowercase === "lax") { - cookieAttributeList.sameSite = "Lax"; + if (attributeValueLowercase.includes("none")) { + enforcement = "None"; + } + if (attributeValueLowercase.includes("strict")) { + enforcement = "Strict"; + } + if (attributeValueLowercase.includes("lax")) { + enforcement = "Lax"; } + cookieAttributeList.sameSite = enforcement; } else { cookieAttributeList.unparsed ??= []; cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`); @@ -17239,7 +16936,7 @@ var require_connection = __commonJS({ const secProtocol = response.headersList.get("Sec-WebSocket-Protocol"); if (secProtocol !== null) { const requestProtocols = getDecodeSplit("sec-websocket-protocol", request2.headersList); - if (requestProtocols === null || !requestProtocols.includes(secProtocol)) { + if (!requestProtocols.includes(secProtocol)) { failWebsocketConnection(ws, "Protocol was not set in the opening handshake."); return; } @@ -17345,26 +17042,31 @@ var require_permessage_deflate = __commonJS({ var tail = Buffer.from([0, 0, 255, 255]); var kBuffer = /* @__PURE__ */ Symbol("kBuffer"); var kLength = /* @__PURE__ */ Symbol("kLength"); + var kDefaultMaxDecompressedSize = 4 * 1024 * 1024; var PerMessageDeflate = class { /** @type {import('node:zlib').InflateRaw} */ #inflate; #options = {}; - #maxPayloadSize = 0; + /** @type {number} */ + #maxDecompressedSize; + /** @type {boolean} */ + #aborted = false; + /** @type {Function|null} */ + #currentCallback = null; /** * @param {Map} extensions + * @param {{ maxDecompressedMessageSize?: number }} [options] */ - constructor(extensions, options) { + constructor(extensions, options = {}) { this.#options.serverNoContextTakeover = extensions.has("server_no_context_takeover"); this.#options.serverMaxWindowBits = extensions.get("server_max_window_bits"); - this.#maxPayloadSize = options.maxPayloadSize; + this.#maxDecompressedSize = options.maxDecompressedMessageSize ?? kDefaultMaxDecompressedSize; } - /** - * Decompress a compressed payload. - * @param {Buffer} chunk Compressed data - * @param {boolean} fin Final fragment flag - * @param {Function} callback Callback function - */ decompress(chunk, fin, callback) { + if (this.#aborted) { + callback(new MessageSizeExceededError()); + return; + } if (!this.#inflate) { let windowBits = Z_DEFAULT_WINDOWBITS; if (this.#options.serverMaxWindowBits) { @@ -17383,12 +17085,20 @@ var require_permessage_deflate = __commonJS({ this.#inflate[kBuffer] = []; this.#inflate[kLength] = 0; this.#inflate.on("data", (data) => { + if (this.#aborted) { + return; + } this.#inflate[kLength] += data.length; - if (this.#maxPayloadSize > 0 && this.#inflate[kLength] > this.#maxPayloadSize) { - callback(new MessageSizeExceededError()); + if (this.#inflate[kLength] > this.#maxDecompressedSize) { + this.#aborted = true; this.#inflate.removeAllListeners(); this.#inflate.destroy(); this.#inflate = null; + if (this.#currentCallback) { + const cb = this.#currentCallback; + this.#currentCallback = null; + cb(new MessageSizeExceededError()); + } return; } this.#inflate[kBuffer].push(data); @@ -17398,17 +17108,19 @@ var require_permessage_deflate = __commonJS({ callback(err); }); } + this.#currentCallback = callback; this.#inflate.write(chunk); if (fin) { this.#inflate.write(tail); } this.#inflate.flush(() => { - if (!this.#inflate) { + if (this.#aborted || !this.#inflate) { return; } const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]); this.#inflate[kBuffer].length = 0; this.#inflate[kLength] = 0; + this.#currentCallback = null; callback(null, full); }); } @@ -17439,14 +17151,8 @@ var require_receiver = __commonJS({ var { WebsocketFrameSend } = require_frame(); var { closeWebSocketConnection } = require_connection(); var { PerMessageDeflate } = require_permessage_deflate(); - var { MessageSizeExceededError } = require_errors(); - function failWebsocketConnectionWithCode(ws, code, reason) { - closeWebSocketConnection(ws, code, reason, Buffer.byteLength(reason)); - failWebsocketConnection(ws, reason); - } var ByteParser = class extends Writable { #buffers = []; - #fragmentsBytes = 0; #byteOffset = 0; #loop = false; #state = parserStates.INFO; @@ -17454,21 +17160,18 @@ var require_receiver = __commonJS({ #fragments = []; /** @type {Map} */ #extensions; - /** @type {number} */ - #maxFragments; - /** @type {number} */ - #maxPayloadSize; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {import('./websocket').WebSocket} ws * @param {Map|null} extensions - * @param {{ maxFragments?: number, maxPayloadSize?: number }} [options] + * @param {{ maxDecompressedMessageSize?: number }} [options] */ constructor(ws, extensions, options = {}) { super(); this.ws = ws; this.#extensions = extensions == null ? /* @__PURE__ */ new Map() : extensions; - this.#maxFragments = options.maxFragments ?? 0; - this.#maxPayloadSize = options.maxPayloadSize ?? 0; + this.#options = options; if (this.#extensions.has("permessage-deflate")) { this.#extensions.set("permessage-deflate", new PerMessageDeflate(extensions, options)); } @@ -17483,13 +17186,6 @@ var require_receiver = __commonJS({ this.#loop = true; this.run(callback); } - #validatePayloadLength() { - if (this.#maxPayloadSize > 0 && !isControlFrame(this.#info.opcode) && this.#info.payloadLength + this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, "Payload size exceeds maximum allowed size"); - return false; - } - return true; - } /** * Runs whenever a new chunk is received. * Callback is called whenever there are no more chunks buffering, @@ -17549,9 +17245,6 @@ var require_receiver = __commonJS({ if (payloadLength <= 125) { this.#info.payloadLength = payloadLength; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (payloadLength === 126) { this.#state = parserStates.PAYLOADLENGTH_16; } else if (payloadLength === 127) { @@ -17572,9 +17265,6 @@ var require_receiver = __commonJS({ const buffer = this.consume(2); this.#info.payloadLength = buffer.readUInt16BE(0); this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.PAYLOADLENGTH_64) { if (this.#byteOffset < 8) { return callback(); @@ -17588,9 +17278,6 @@ var require_receiver = __commonJS({ } this.#info.payloadLength = lower; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.READ_DATA) { if (this.#byteOffset < this.#info.payloadLength) { return callback(); @@ -17601,46 +17288,32 @@ var require_receiver = __commonJS({ this.#state = parserStates.INFO; } else { if (!this.#info.compressed) { - if (!this.writeFragments(body)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } + this.#fragments.push(body); if (!this.#info.fragmented && this.#info.fin) { - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); + const fullMessage = Buffer.concat(this.#fragments); + websocketMessageReceived(this.ws, this.#info.binaryType, fullMessage); + this.#fragments.length = 0; } this.#state = parserStates.INFO; } else { - this.#extensions.get("permessage-deflate").decompress( - body, - this.#info.fin, - (error, data) => { - if (error) { - const code = error instanceof MessageSizeExceededError ? 1009 : 1007; - failWebsocketConnectionWithCode(this.ws, code, error.message); - return; - } - if (!this.writeFragments(data)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } - if (!this.#info.fin) { - this.#state = parserStates.INFO; - this.#loop = true; - this.run(callback); - return; - } - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); - this.#loop = true; + this.#extensions.get("permessage-deflate").decompress(body, this.#info.fin, (error, data) => { + if (error) { + failWebsocketConnection(this.ws, error.message); + return; + } + this.#fragments.push(data); + if (!this.#info.fin) { this.#state = parserStates.INFO; + this.#loop = true; this.run(callback); + return; } - ); + websocketMessageReceived(this.ws, this.#info.binaryType, Buffer.concat(this.#fragments)); + this.#loop = true; + this.#state = parserStates.INFO; + this.#fragments.length = 0; + this.run(callback); + }); this.#loop = false; break; } @@ -17683,26 +17356,6 @@ var require_receiver = __commonJS({ this.#byteOffset -= n; return buffer; } - writeFragments(fragment) { - if (this.#maxFragments > 0 && this.#fragments.length === this.#maxFragments) { - failWebsocketConnectionWithCode(this.ws, 1008, "Too many message fragments"); - return false; - } - this.#fragmentsBytes += fragment.length; - this.#fragments.push(fragment); - return true; - } - consumeFragments() { - const fragments = this.#fragments; - if (fragments.length === 1) { - this.#fragmentsBytes = 0; - return fragments.shift(); - } - const output = Buffer.concat(fragments, this.#fragmentsBytes); - this.#fragments = []; - this.#fragmentsBytes = 0; - return output; - } parseCloseBody(data) { assert(data.length !== 1); let code; @@ -17914,6 +17567,8 @@ var require_websocket = __commonJS({ #extensions = ""; /** @type {SendQueue} */ #sendQueue; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {string} url * @param {string|string[]} protocols @@ -17957,6 +17612,9 @@ var require_websocket = __commonJS({ throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError"); } this[kWebSocketURL] = new URL(urlRecord.href); + this.#options = { + maxDecompressedMessageSize: options.maxDecompressedMessageSize + }; const client = environmentSettingsObject.settingsObject; this[kController] = establishWebSocketConnection( urlRecord, @@ -18140,13 +17798,7 @@ var require_websocket = __commonJS({ */ #onConnectionEstablished(response, parsedExtensions) { this[kResponse] = response; - const webSocketOptions = this[kController]?.dispatcher?.webSocketOptions; - const maxFragments = webSocketOptions?.maxFragments; - const maxPayloadSize = webSocketOptions?.maxPayloadSize; - const parser = new ByteParser(this, parsedExtensions, { - maxFragments, - maxPayloadSize - }); + const parser = new ByteParser(this, parsedExtensions, this.#options); parser.on("drain", onParserDrain); parser.on("error", onParserError.bind(this)); response.socket.ws = this; @@ -18221,6 +17873,19 @@ var require_websocket = __commonJS({ { key: "headers", converter: webidl.nullableConverter(webidl.converters.HeadersInit) + }, + { + key: "maxDecompressedMessageSize", + converter: webidl.nullableConverter((V) => { + V = webidl.converters["unsigned long long"](V); + if (V <= 0) { + throw webidl.errors.exception({ + header: "WebSocket constructor", + message: "maxDecompressedMessageSize must be greater than 0" + }); + } + return V; + }) } ]); webidl.converters["DOMString or sequence or WebSocketInit"] = function(V) { @@ -18299,40 +17964,6 @@ 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; - } - function isValidLastEventIdBytes(buffer, start) { - for (let i = start; i < buffer.length; i++) { - if (buffer[i] === 0) { - 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; - } var EventSourceStream = class extends Transform { /** * @type {eventSourceSettings} @@ -18352,13 +17983,10 @@ var require_eventsource_stream = __commonJS({ */ eventEndCheck = false; /** - * @type {Buffer[]} + * @type {Buffer} */ - chunks = []; - chunkIndex = 0; + buffer = null; pos = 0; - lineChunkIndex = 0; - linePos = 0; event = { data: void 0, event: void 0, @@ -18389,30 +18017,63 @@ var require_eventsource_stream = __commonJS({ callback(); return; } - this.chunks.push(chunk); + if (this.buffer) { + this.buffer = Buffer.concat([this.buffer, chunk]); + } else { + this.buffer = chunk; + } if (this.checkBOM) { - if (this.handleBOM()) { - callback(); - return; + 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; } } - while (this.hasCurrentByte()) { - const byte = this.currentByte(); + while (this.pos < this.buffer.length) { if (this.eventEndCheck) { if (this.crlfCheck) { - if (byte === LF) { + if (this.buffer[this.pos] === LF) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.crlfCheck = false; - this.consumeCurrentByte(); continue; } this.crlfCheck = false; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.consumeCurrentByte(); - if (this.hasPendingEvent()) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; + if (this.event.data !== void 0 || this.event.event || this.event.id || this.event.retry) { this.processEvent(this.event); } this.clearEvent(); @@ -18421,16 +18082,17 @@ var require_eventsource_stream = __commonJS({ this.eventEndCheck = false; continue; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.parseLine(this.readLine(), this.event); - this.consumeCurrentByte(); + this.parseLine(this.buffer.subarray(0, this.pos), this.event); + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.eventEndCheck = true; continue; } - this.advanceCursor(); + this.pos++; } callback(); } @@ -18446,42 +18108,43 @@ var require_eventsource_stream = __commonJS({ if (colonPosition === 0) { return; } - let fieldLength = line.length; - let valueStart = line.length; + let field = ""; + let value = ""; if (colonPosition !== -1) { - fieldLength = colonPosition; - valueStart = colonPosition + 1; + field = line.subarray(0, colonPosition).toString("utf8"); + let valueStart = colonPosition + 1; if (line[valueStart] === SPACE) { ++valueStart; } + value = line.subarray(valueStart).toString("utf8"); + } else { + field = line.toString("utf8"); + value = ""; } - if (isFieldName(line, fieldLength, DATA)) { - const value = line.toString("utf8", valueStart); - if (event.data === void 0) { - event.data = value; - } else { - event.data += ` + switch (field) { + case "data": + if (event[field] === void 0) { + event[field] = value; + } else { + event[field] += ` ${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; - } + } + 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; } } /** @@ -18506,120 +18169,12 @@ ${value}`; } } clearEvent() { - 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(); + this.event = { + data: void 0, + event: void 0, + id: void 0, + retry: void 0 + }; } }; module.exports = { diff --git a/.github/actions/javascript/getAndroidRolloutPercentage/index.js b/.github/actions/javascript/getAndroidRolloutPercentage/index.js index 1abd092e27ea..e970b3649819 100644 --- a/.github/actions/javascript/getAndroidRolloutPercentage/index.js +++ b/.github/actions/javascript/getAndroidRolloutPercentage/index.js @@ -1875,66 +1875,10 @@ var require_request = __commonJS({ return false; } } - /** - * @param {number|null} statusCode - * @param {Buffer[]|null} headers - * @param {import('node:stream').Duplex} socket - * @param {string} [statusText] - */ - onUpgrade(statusCode, headers, socket, statusText = "") { - this.onFinally(); + onUpgrade(statusCode, headers, socket) { assert(!this.aborted); assert(!this.completed); - 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: [] }); - } + return this[kHandler].onUpgrade(statusCode, headers, socket); } onComplete(trailers) { this.onFinally(); @@ -2001,11 +1945,7 @@ var require_request = __commonJS({ } else if (typeof val[i2] === "object") { throw new InvalidArgumentError(`invalid ${key} header`); } else { - const str = `${val[i2]}`; - if (!isValidHeaderValue(str)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } - arr.push(str); + arr.push(`${val[i2]}`); } } val = arr; @@ -2017,9 +1957,6 @@ var require_request = __commonJS({ val = ""; } else { val = `${val}`; - if (!isValidHeaderValue(val)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } } if (headerName === "host") { if (request.host !== null) { @@ -2129,21 +2066,13 @@ var require_dispatcher_base = __commonJS({ var kOnDestroyed = /* @__PURE__ */ Symbol("onDestroyed"); var kOnClosed = /* @__PURE__ */ Symbol("onClosed"); var kInterceptedDispatch = /* @__PURE__ */ Symbol("Intercepted Dispatch"); - var kWebSocketOptions = /* @__PURE__ */ Symbol("webSocketOptions"); var DispatcherBase = class extends Dispatcher { - constructor(opts) { + constructor() { super(); this[kDestroyed] = false; this[kOnDestroyed] = null; this[kClosed] = false; this[kOnClosed] = []; - this[kWebSocketOptions] = opts?.webSocket ?? {}; - } - get webSocketOptions() { - return { - maxFragments: this[kWebSocketOptions].maxFragments ?? 131072, - maxPayloadSize: this[kWebSocketOptions].maxPayloadSize ?? 128 * 1024 * 1024 - }; } get destroyed() { return this[kDestroyed]; @@ -5750,7 +5679,6 @@ var require_client_h1 = __commonJS({ RequestContentLengthMismatchError, ResponseContentLengthMismatchError, RequestAbortedError, - InvalidArgumentError, HeadersTimeoutError, HeadersOverflowError, SocketError, @@ -5797,9 +5725,6 @@ var require_client_h1 = __commonJS({ var FastBuffer = Buffer[Symbol.species]; var addListener = util.addListener; var removeAllListeners = util.removeAllListeners; - var kIdleSocketValidation = /* @__PURE__ */ Symbol("kIdleSocketValidation"); - var kIdleSocketValidationTimeout = /* @__PURE__ */ Symbol("kIdleSocketValidationTimeout"); - var kSocketUsed = /* @__PURE__ */ Symbol("kSocketUsed"); var extractBody; async function lazyllhttp() { const llhttpWasmData = process.env.JEST_WORKER_ID ? require_llhttp_wasm() : void 0; @@ -5962,55 +5887,24 @@ var require_client_h1 = __commonJS({ currentBufferRef = null; } const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr; - if (ret !== constants3.ERROR.OK) { - const body = data.subarray(offset); - if (ret === constants3.ERROR.PAUSED_UPGRADE) { - this.onUpgrade(body); - } else if (ret === constants3.ERROR.PAUSED) { - this.paused = true; - socket.unshift(body); - } else { - throw this.createError(ret, body); - } + if (ret === constants3.ERROR.PAUSED_UPGRADE) { + this.onUpgrade(data.slice(offset)); + } else if (ret === constants3.ERROR.PAUSED) { + this.paused = true; + socket.unshift(data.slice(offset)); + } else if (ret !== constants3.ERROR.OK) { + const ptr = llhttp.llhttp_get_error_reason(this.ptr); + let message = ""; + if (ptr) { + const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); + message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; + } + throw new HTTPParserError(message, constants3.ERROR[ret], data.slice(offset)); } } catch (err) { util.destroy(socket, err); } } - finish() { - assert(currentParser === null); - assert(this.ptr != null); - assert(!this.paused); - const { llhttp } = this; - let ret; - try { - currentParser = this; - ret = llhttp.llhttp_finish(this.ptr); - } finally { - currentParser = null; - } - if (ret === constants3.ERROR.OK) { - return null; - } - if (ret === constants3.ERROR.PAUSED || ret === constants3.ERROR.PAUSED_UPGRADE) { - this.paused = true; - return null; - } - return this.createError(ret, EMPTY_BUF); - } - createError(ret, data) { - const { llhttp, contentLength, bytesRead } = this; - if (contentLength && bytesRead !== parseInt(contentLength, 10)) { - return new ResponseContentLengthMismatchError(); - } - const ptr = llhttp.llhttp_get_error_reason(this.ptr); - let message = ""; - if (ptr) { - const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); - message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; - } - return new HTTPParserError(message, constants3.ERROR[ret], data); - } destroy() { assert(this.ptr != null); assert(currentParser == null); @@ -6030,10 +5924,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request = client[kQueue][client[kRunningIdx]]; if (!request) { return -1; @@ -6077,7 +5967,7 @@ var require_client_h1 = __commonJS({ } } onUpgrade(head) { - const { upgrade, client, socket, headers, statusCode, statusText } = this; + const { upgrade, client, socket, headers, statusCode } = this; assert(upgrade); assert(client[kSocket] === socket); assert(!socket.destroyed); @@ -6102,10 +5992,9 @@ var require_client_h1 = __commonJS({ client[kQueue][client[kRunningIdx]++] = null; client.emit("disconnect", client[kUrl], [client], new InformationalError("upgrade")); try { - request.onUpgrade(statusCode, headers, socket, statusText); - } catch (error) { - util.errorRequest(client, request, error); - util.destroy(socket, error); + request.onUpgrade(statusCode, headers, socket); + } catch (err) { + util.destroy(socket, err); } client[kResume](); } @@ -6114,10 +6003,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request = client[kQueue][client[kRunningIdx]]; if (!request) { return -1; @@ -6243,7 +6128,6 @@ var require_client_h1 = __commonJS({ } request.onComplete(headers); client[kQueue][client[kRunningIdx]++] = null; - socket[kSocketUsed] = true; if (socket[kWriting]) { assert(client[kRunning] === 0); util.destroy(socket, new InformationalError("reset")); @@ -6287,19 +6171,12 @@ var require_client_h1 = __commonJS({ socket[kWriting] = false; socket[kReset] = false; socket[kBlocking] = false; - socket[kIdleSocketValidation] = 0; - socket[kIdleSocketValidationTimeout] = null; - socket[kSocketUsed] = false; socket[kParser] = new Parser(client, socket, llhttpInstance); addListener(socket, "error", function(err) { assert(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID"); const parser = this[kParser]; if (err.code === "ECONNRESET" && parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - this[kError] = parserErr; - this[kClient][kOnError](parserErr); - } + parser.onMessageComplete(); return; } this[kError] = err; @@ -6314,10 +6191,7 @@ var require_client_h1 = __commonJS({ addListener(socket, "end", function() { const parser = this[kParser]; if (parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - util.destroy(this, parserErr); - } + parser.onMessageComplete(); return; } util.destroy(this, new SocketError("other side closed", util.getSocketInfo(this))); @@ -6325,10 +6199,9 @@ var require_client_h1 = __commonJS({ addListener(socket, "close", function() { const client2 = this[kClient]; const parser = this[kParser]; - clearIdleSocketValidation(this); if (parser) { if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { - this[kError] = parser.finish() || this[kError]; + parser.onMessageComplete(); } this[kParser].destroy(); this[kParser] = null; @@ -6377,7 +6250,7 @@ var require_client_h1 = __commonJS({ return socket.destroyed; }, busy(request) { - if (socket[kWriting] || socket[kReset] || socket[kBlocking] || socket[kIdleSocketValidation] === 1) { + if (socket[kWriting] || socket[kReset] || socket[kBlocking]) { return true; } if (request) { @@ -6395,23 +6268,6 @@ var require_client_h1 = __commonJS({ } }; } - function clearIdleSocketValidation(socket) { - if (socket[kIdleSocketValidationTimeout]) { - clearImmediate(socket[kIdleSocketValidationTimeout]); - socket[kIdleSocketValidationTimeout] = null; - } - socket[kIdleSocketValidation] = 0; - } - function scheduleIdleSocketValidation(client, socket) { - socket[kIdleSocketValidation] = 1; - socket[kIdleSocketValidationTimeout] = setImmediate(() => { - socket[kIdleSocketValidationTimeout] = null; - socket[kIdleSocketValidation] = 2; - if (client[kSocket] === socket && !socket.destroyed) { - client[kResume](); - } - }); - } function resumeH1(client) { const socket = client[kSocket]; if (socket && !socket.destroyed) { @@ -6424,29 +6280,6 @@ var require_client_h1 = __commonJS({ socket.ref(); socket[kNoRef] = false; } - if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) { - if (socket[kIdleSocketValidation] === 0) { - scheduleIdleSocketValidation(client, socket); - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - if (socket[kIdleSocketValidation] === 1) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - } - if (client[kRunning] === 0) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - } if (client[kSize] === 0) { if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) { socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE); @@ -6477,16 +6310,8 @@ var require_client_h1 = __commonJS({ } body = bodyStream.stream; contentLength = bodyStream.length; - } else if (util.isBlobLike(body) && request.contentType == null) { - const contentType = body.type; - if (contentType) { - const contentTypeValue = `${contentType}`; - if (!util.isValidHeaderValue(contentTypeValue)) { - util.errorRequest(client, request, new InvalidArgumentError("invalid content-type header")); - return false; - } - headers.push("content-type", contentTypeValue); - } + } else if (util.isBlobLike(body) && request.contentType == null && body.type) { + headers.push("content-type", body.type); } if (body && typeof body.read === "function") { body.read(0); @@ -6507,18 +6332,11 @@ var require_client_h1 = __commonJS({ process.emitWarning(new RequestContentLengthMismatchError()); } const socket = client[kSocket]; - clearIdleSocketValidation(socket); - const abort = (error) => { - if (request.aborted) { - return; - } - if (request.completed) { - if (request.upgrade || request.method === "CONNECT") { - util.destroy(socket, new InformationalError("aborted")); - } + const abort = (err) => { + if (request.aborted || request.completed) { return; } - util.errorRequest(client, request, error || new RequestAbortedError()); + util.errorRequest(client, request, err || new RequestAbortedError()); util.destroy(body); util.destroy(socket, new InformationalError("aborted")); }; @@ -6874,7 +6692,6 @@ var require_client_h2 = __commonJS({ "node_modules/undici/lib/dispatcher/client-h2.js"(exports, module) { "use strict"; var assert = __require("node:assert"); - var { errorMonitor } = __require("node:events"); var { pipeline: pipeline2 } = __require("node:stream"); var util = require_util(); var { @@ -6935,10 +6752,6 @@ var require_client_h2 = __commonJS({ } return result; } - function parseH2ResponseHeaders(headers) { - const { [HTTP2_HEADER_STATUS]: _statusCode, ...realHeaders } = headers; - return parseH2Headers(realHeaders); - } async function connectH2(client, socket) { client[kSocket] = socket; if (!h2ExperimentalWarned) { @@ -7102,22 +6915,16 @@ var require_client_h2 = __commonJS({ const { hostname, port } = client[kUrl]; headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ""}`; headers[HTTP2_HEADER_METHOD] = method; - const abort = (error) => { - if (request.aborted) { - return; - } - if (request.completed) { - if (method === "CONNECT" && stream != null) { - util.destroy(stream, error || new RequestAbortedError()); - } + const abort = (err) => { + if (request.aborted || request.completed) { return; } - error = error || new RequestAbortedError(); - util.errorRequest(client, request, error); + err = err || new RequestAbortedError(); + util.errorRequest(client, request, err); if (stream != null) { - util.destroy(stream, error); + util.destroy(stream, err); } - util.destroy(body, error); + util.destroy(body, err); client[kQueue][client[kRunningIdx]++] = null; client[kResume](); }; @@ -7132,42 +6939,18 @@ var require_client_h2 = __commonJS({ if (method === "CONNECT") { session.ref(); stream = session.request(headers, { endStream: false, signal }); - let upgradeResponseFinished = false; - const onResponse = (headers2) => { - upgradeResponseFinished = true; - stream.off(errorMonitor, onUpgradeError); - request.onUpgradeResponse(Number(headers2[HTTP2_HEADER_STATUS]), headers2, parseH2ResponseHeaders); - }; - const onUpgradeError = (error) => { - upgradeResponseFinished = true; - stream.off("response", onResponse); - request.onUpgradeError(error); - }; - const onReady = () => { - try { - request.onUpgrade(null, null, stream); - } catch (error) { - stream.off("response", onResponse); - abort(error); - return; - } - if (request.aborted) { - return; - } - stream.off("error", abort); - stream.once(errorMonitor, onUpgradeError); + if (stream.id && !stream.pending) { + request.onUpgrade(null, null, stream); + ++session[kOpenStreams]; client[kQueue][client[kRunningIdx]++] = null; - }; - stream.once("response", onResponse); - stream.once("error", abort); - ++session[kOpenStreams]; - onReady(); + } else { + stream.once("ready", () => { + request.onUpgrade(null, null, stream); + ++session[kOpenStreams]; + client[kQueue][client[kRunningIdx]++] = null; + }); + } 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(); }); @@ -7728,10 +7511,9 @@ var require_client = __commonJS({ autoSelectFamilyAttemptTimeout, // h2 maxConcurrentStreams, - allowH2, - webSocket + allowH2 } = {}) { - super({ webSocket }); + super(); if (keepAlive !== void 0) { throw new InvalidArgumentError("unsupported keepAlive, use pipelining=0 instead"); } @@ -8237,8 +8019,8 @@ var require_pool_base = __commonJS({ var kRemoveClient = /* @__PURE__ */ Symbol("remove client"); var kStats = /* @__PURE__ */ Symbol("stats"); var PoolBase = class extends DispatcherBase { - constructor(opts) { - super(opts); + constructor() { + super(); this[kQueue] = new FixedQueue(); this[kClients] = []; this[kQueued] = 0; @@ -8409,6 +8191,7 @@ var require_pool = __commonJS({ allowH2, ...options } = {}) { + super(); if (connections != null && (!Number.isFinite(connections) || connections < 0)) { throw new InvalidArgumentError("invalid connections"); } @@ -8429,7 +8212,6 @@ var require_pool = __commonJS({ ...connect }); } - super(options); this[kInterceptors] = options.interceptors?.Pool && Array.isArray(options.interceptors.Pool) ? options.interceptors.Pool : []; this[kConnections] = connections || null; this[kUrl] = util.parseOrigin(origin); @@ -8629,6 +8411,7 @@ var require_agent = __commonJS({ } var Agent = class extends DispatcherBase { constructor({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { + super(); if (typeof factory !== "function") { throw new InvalidArgumentError("factory must be a function."); } @@ -8638,7 +8421,6 @@ var require_agent = __commonJS({ if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { throw new InvalidArgumentError("maxRedirections must be a positive number"); } - super(options); if (connect && typeof connect !== "function") { connect = { ...connect }; } @@ -9079,24 +8861,6 @@ var require_retry_handler = __commonJS({ const current = Date.now(); return new Date(retryAfter).getTime() - current; } - function validatePartialResponseContentLength(headers, range, statusCode, retryCount) { - const contentLength = headers["content-length"]; - if (contentLength == null) { - return null; - } - if (!Number.isFinite(range.start) || !Number.isFinite(range.end)) { - return null; - } - const length = Number(contentLength); - const expectedLength = range.end - range.start + 1; - if (!Number.isFinite(length) || length !== expectedLength) { - return new RequestRetryError("Content-Length mismatch", statusCode, { - headers, - data: { count: retryCount } - }); - } - return null; - } var RetryHandler = class _RetryHandler { constructor(opts, handlers) { const { retryOptions, ...dispatchOpts } = opts; @@ -9150,7 +8914,6 @@ var require_retry_handler = __commonJS({ this.end = null; this.etag = null; this.resume = null; - this.headersSent = false; this.handler.onConnect((reason) => { this.aborted = true; if (this.abort) { @@ -9160,17 +8923,6 @@ var require_retry_handler = __commonJS({ } }); } - 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(); @@ -9232,9 +8984,7 @@ var require_retry_handler = __commonJS({ const headers = parseHeaders(rawHeaders); this.retryCount += 1; if (statusCode >= 300) { - if (!this.headersSent && this.retryOpts.statusCodes.includes(statusCode) === false) { - this.headersSent = true; - this.checkpointResponseEnd(headers, resume); + if (this.retryOpts.statusCodes.includes(statusCode) === false) { return this.handler.onHeaders( statusCode, rawHeaders, @@ -9283,21 +9033,9 @@ var require_retry_handler = __commonJS({ ); return false; } - const contentLengthError = validatePartialResponseContentLength(headers, contentRange, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = contentRange; - 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; - } + assert(this.start === start, "content-range mismatch"); + assert(this.end == null || this.end === end, "content-range mismatch"); this.resume = resume; return true; } @@ -9305,7 +9043,6 @@ var require_retry_handler = __commonJS({ if (statusCode === 206) { const range = parseRangeHeader(headers["content-range"]); if (range == null) { - this.headersSent = true; return this.handler.onHeaders( statusCode, rawHeaders, @@ -9313,11 +9050,6 @@ var require_retry_handler = __commonJS({ statusMessage ); } - const contentLengthError = validatePartialResponseContentLength(headers, range, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = range; assert( start != null && Number.isFinite(start), @@ -9337,7 +9069,6 @@ var require_retry_handler = __commonJS({ "invalid content-length" ); this.resume = resume; - this.headersSent = true; this.etag = headers.etag != null ? headers.etag : null; if (this.etag != null && this.etag.startsWith("W/")) { this.etag = null; @@ -9365,7 +9096,7 @@ var require_retry_handler = __commonJS({ return this.handler.onComplete(rawTrailers); } onError(err) { - if (this.aborted || isDisturbed(this.opts.body) || this.headersSent && this.resume == null) { + if (this.aborted || isDisturbed(this.opts.body)) { return this.handler.onError(err); } if (this.retryCount - this.retryCountCheckpoint > 0) { @@ -16164,48 +15895,14 @@ var require_util6 = __commonJS({ for (let i2 = 0; i2 < path.length; ++i2) { const code = path.charCodeAt(i2); if (code < 32 || // exclude CTLs (0-31) - code > 126 || // exclude DEL and non-ascii + code === 127 || // DEL code === 59) { throw new Error("Invalid cookie path"); } } } - function isLetterOrDigit(code) { - return code >= 48 && code <= 57 || // 0-9 - code >= 65 && code <= 90 || // A-Z - code >= 97 && code <= 122; - } function validateCookieDomain(domain) { - if (domain === " ") { - return; - } - if (domain.length > 255) { - throw new Error("Invalid cookie domain"); - } - let labelLength = 0; - for (let i2 = 0; i2 < domain.length; ++i2) { - const code = domain.charCodeAt(i2); - if (code === 46) { - if (labelLength === 0) { - throw new Error("Invalid cookie domain"); - } - if (domain.charCodeAt(i2 - 1) === 45) { - throw new Error("Invalid cookie domain"); - } - labelLength = 0; - continue; - } - if (labelLength === 0 && !isLetterOrDigit(code)) { - throw new Error("Invalid cookie domain"); - } - if (!isLetterOrDigit(code) && code !== 45) { - throw new Error("Invalid cookie domain"); - } - if (++labelLength > 63) { - throw new Error("Invalid cookie domain"); - } - } - if (labelLength === 0 || domain.charCodeAt(domain.length - 1) === 45) { + if (domain.startsWith("-") || domain.endsWith(".") || domain.endsWith("-")) { throw new Error("Invalid cookie domain"); } } @@ -16288,11 +15985,7 @@ var require_util6 = __commonJS({ throw new Error("Invalid unparsed"); } const [key, ...value] = part.split("="); - const trimmedKey = key.trim(); - const joinedValue = value.join("="); - validateCookieName(trimmedKey); - validateCookieValue(joinedValue); - out.push(`${trimmedKey}=${joinedValue}`); + out.push(`${key.trim()}=${value.join("=")}`); } return out.join("; "); } @@ -16422,14 +16115,18 @@ var require_parse = __commonJS({ } else if (attributeNameLowercase === "httponly") { cookieAttributeList.httpOnly = true; } else if (attributeNameLowercase === "samesite") { + let enforcement = "Default"; const attributeValueLowercase = attributeValue.toLowerCase(); - if (attributeValueLowercase === "none") { - cookieAttributeList.sameSite = "None"; - } else if (attributeValueLowercase === "strict") { - cookieAttributeList.sameSite = "Strict"; - } else if (attributeValueLowercase === "lax") { - cookieAttributeList.sameSite = "Lax"; + if (attributeValueLowercase.includes("none")) { + enforcement = "None"; } + if (attributeValueLowercase.includes("strict")) { + enforcement = "Strict"; + } + if (attributeValueLowercase.includes("lax")) { + enforcement = "Lax"; + } + cookieAttributeList.sameSite = enforcement; } else { cookieAttributeList.unparsed ??= []; cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`); @@ -17251,7 +16948,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 === null || !requestProtocols.includes(secProtocol)) { + if (!requestProtocols.includes(secProtocol)) { failWebsocketConnection(ws, "Protocol was not set in the opening handshake."); return; } @@ -17357,26 +17054,31 @@ var require_permessage_deflate = __commonJS({ var tail = Buffer.from([0, 0, 255, 255]); var kBuffer = /* @__PURE__ */ Symbol("kBuffer"); var kLength = /* @__PURE__ */ Symbol("kLength"); + var kDefaultMaxDecompressedSize = 4 * 1024 * 1024; var PerMessageDeflate = class { /** @type {import('node:zlib').InflateRaw} */ #inflate; #options = {}; - #maxPayloadSize = 0; + /** @type {number} */ + #maxDecompressedSize; + /** @type {boolean} */ + #aborted = false; + /** @type {Function|null} */ + #currentCallback = null; /** * @param {Map} extensions + * @param {{ maxDecompressedMessageSize?: number }} [options] */ - constructor(extensions, options) { + constructor(extensions, options = {}) { this.#options.serverNoContextTakeover = extensions.has("server_no_context_takeover"); this.#options.serverMaxWindowBits = extensions.get("server_max_window_bits"); - this.#maxPayloadSize = options.maxPayloadSize; + this.#maxDecompressedSize = options.maxDecompressedMessageSize ?? kDefaultMaxDecompressedSize; } - /** - * Decompress a compressed payload. - * @param {Buffer} chunk Compressed data - * @param {boolean} fin Final fragment flag - * @param {Function} callback Callback function - */ decompress(chunk, fin, callback) { + if (this.#aborted) { + callback(new MessageSizeExceededError()); + return; + } if (!this.#inflate) { let windowBits = Z_DEFAULT_WINDOWBITS; if (this.#options.serverMaxWindowBits) { @@ -17395,12 +17097,20 @@ var require_permessage_deflate = __commonJS({ this.#inflate[kBuffer] = []; this.#inflate[kLength] = 0; this.#inflate.on("data", (data) => { + if (this.#aborted) { + return; + } this.#inflate[kLength] += data.length; - if (this.#maxPayloadSize > 0 && this.#inflate[kLength] > this.#maxPayloadSize) { - callback(new MessageSizeExceededError()); + if (this.#inflate[kLength] > this.#maxDecompressedSize) { + this.#aborted = true; this.#inflate.removeAllListeners(); this.#inflate.destroy(); this.#inflate = null; + if (this.#currentCallback) { + const cb = this.#currentCallback; + this.#currentCallback = null; + cb(new MessageSizeExceededError()); + } return; } this.#inflate[kBuffer].push(data); @@ -17410,17 +17120,19 @@ var require_permessage_deflate = __commonJS({ callback(err); }); } + this.#currentCallback = callback; this.#inflate.write(chunk); if (fin) { this.#inflate.write(tail); } this.#inflate.flush(() => { - if (!this.#inflate) { + if (this.#aborted || !this.#inflate) { return; } const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]); this.#inflate[kBuffer].length = 0; this.#inflate[kLength] = 0; + this.#currentCallback = null; callback(null, full); }); } @@ -17451,14 +17163,8 @@ var require_receiver = __commonJS({ var { WebsocketFrameSend } = require_frame(); var { closeWebSocketConnection } = require_connection(); var { PerMessageDeflate } = require_permessage_deflate(); - var { MessageSizeExceededError } = require_errors(); - function failWebsocketConnectionWithCode(ws, code, reason) { - closeWebSocketConnection(ws, code, reason, Buffer.byteLength(reason)); - failWebsocketConnection(ws, reason); - } var ByteParser = class extends Writable { #buffers = []; - #fragmentsBytes = 0; #byteOffset = 0; #loop = false; #state = parserStates.INFO; @@ -17466,21 +17172,18 @@ var require_receiver = __commonJS({ #fragments = []; /** @type {Map} */ #extensions; - /** @type {number} */ - #maxFragments; - /** @type {number} */ - #maxPayloadSize; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {import('./websocket').WebSocket} ws * @param {Map|null} extensions - * @param {{ maxFragments?: number, maxPayloadSize?: number }} [options] + * @param {{ maxDecompressedMessageSize?: number }} [options] */ constructor(ws, extensions, options = {}) { super(); this.ws = ws; this.#extensions = extensions == null ? /* @__PURE__ */ new Map() : extensions; - this.#maxFragments = options.maxFragments ?? 0; - this.#maxPayloadSize = options.maxPayloadSize ?? 0; + this.#options = options; if (this.#extensions.has("permessage-deflate")) { this.#extensions.set("permessage-deflate", new PerMessageDeflate(extensions, options)); } @@ -17495,13 +17198,6 @@ var require_receiver = __commonJS({ this.#loop = true; this.run(callback); } - #validatePayloadLength() { - if (this.#maxPayloadSize > 0 && !isControlFrame(this.#info.opcode) && this.#info.payloadLength + this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, "Payload size exceeds maximum allowed size"); - return false; - } - return true; - } /** * Runs whenever a new chunk is received. * Callback is called whenever there are no more chunks buffering, @@ -17561,9 +17257,6 @@ var require_receiver = __commonJS({ if (payloadLength <= 125) { this.#info.payloadLength = payloadLength; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (payloadLength === 126) { this.#state = parserStates.PAYLOADLENGTH_16; } else if (payloadLength === 127) { @@ -17584,9 +17277,6 @@ var require_receiver = __commonJS({ const buffer = this.consume(2); this.#info.payloadLength = buffer.readUInt16BE(0); this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.PAYLOADLENGTH_64) { if (this.#byteOffset < 8) { return callback(); @@ -17600,9 +17290,6 @@ var require_receiver = __commonJS({ } this.#info.payloadLength = lower2; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.READ_DATA) { if (this.#byteOffset < this.#info.payloadLength) { return callback(); @@ -17613,46 +17300,32 @@ var require_receiver = __commonJS({ this.#state = parserStates.INFO; } else { if (!this.#info.compressed) { - if (!this.writeFragments(body)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } + this.#fragments.push(body); if (!this.#info.fragmented && this.#info.fin) { - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); + const fullMessage = Buffer.concat(this.#fragments); + websocketMessageReceived(this.ws, this.#info.binaryType, fullMessage); + this.#fragments.length = 0; } this.#state = parserStates.INFO; } else { - this.#extensions.get("permessage-deflate").decompress( - body, - this.#info.fin, - (error, data) => { - if (error) { - const code = error instanceof MessageSizeExceededError ? 1009 : 1007; - failWebsocketConnectionWithCode(this.ws, code, error.message); - return; - } - if (!this.writeFragments(data)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } - if (!this.#info.fin) { - this.#state = parserStates.INFO; - this.#loop = true; - this.run(callback); - return; - } - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); - this.#loop = true; + this.#extensions.get("permessage-deflate").decompress(body, this.#info.fin, (error, data) => { + if (error) { + failWebsocketConnection(this.ws, error.message); + return; + } + this.#fragments.push(data); + if (!this.#info.fin) { this.#state = parserStates.INFO; + this.#loop = true; this.run(callback); + return; } - ); + websocketMessageReceived(this.ws, this.#info.binaryType, Buffer.concat(this.#fragments)); + this.#loop = true; + this.#state = parserStates.INFO; + this.#fragments.length = 0; + this.run(callback); + }); this.#loop = false; break; } @@ -17695,26 +17368,6 @@ var require_receiver = __commonJS({ this.#byteOffset -= n; return buffer; } - writeFragments(fragment) { - if (this.#maxFragments > 0 && this.#fragments.length === this.#maxFragments) { - failWebsocketConnectionWithCode(this.ws, 1008, "Too many message fragments"); - return false; - } - this.#fragmentsBytes += fragment.length; - this.#fragments.push(fragment); - return true; - } - consumeFragments() { - const fragments = this.#fragments; - if (fragments.length === 1) { - this.#fragmentsBytes = 0; - return fragments.shift(); - } - const output = Buffer.concat(fragments, this.#fragmentsBytes); - this.#fragments = []; - this.#fragmentsBytes = 0; - return output; - } parseCloseBody(data) { assert(data.length !== 1); let code; @@ -17926,6 +17579,8 @@ var require_websocket = __commonJS({ #extensions = ""; /** @type {SendQueue} */ #sendQueue; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {string} url * @param {string|string[]} protocols @@ -17969,6 +17624,9 @@ var require_websocket = __commonJS({ throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError"); } this[kWebSocketURL] = new URL(urlRecord.href); + this.#options = { + maxDecompressedMessageSize: options.maxDecompressedMessageSize + }; const client = environmentSettingsObject.settingsObject; this[kController] = establishWebSocketConnection( urlRecord, @@ -18152,13 +17810,7 @@ var require_websocket = __commonJS({ */ #onConnectionEstablished(response, parsedExtensions) { this[kResponse] = response; - const webSocketOptions = this[kController]?.dispatcher?.webSocketOptions; - const maxFragments = webSocketOptions?.maxFragments; - const maxPayloadSize = webSocketOptions?.maxPayloadSize; - const parser = new ByteParser(this, parsedExtensions, { - maxFragments, - maxPayloadSize - }); + const parser = new ByteParser(this, parsedExtensions, this.#options); parser.on("drain", onParserDrain); parser.on("error", onParserError.bind(this)); response.socket.ws = this; @@ -18233,6 +17885,19 @@ var require_websocket = __commonJS({ { key: "headers", converter: webidl.nullableConverter(webidl.converters.HeadersInit) + }, + { + key: "maxDecompressedMessageSize", + converter: webidl.nullableConverter((V) => { + V = webidl.converters["unsigned long long"](V); + if (V <= 0) { + throw webidl.errors.exception({ + header: "WebSocket constructor", + message: "maxDecompressedMessageSize must be greater than 0" + }); + } + return V; + }) } ]); webidl.converters["DOMString or sequence or WebSocketInit"] = function(V) { @@ -18311,40 +17976,6 @@ var require_eventsource_stream = __commonJS({ var CR2 = 13; var COLON2 = 58; var SPACE2 = 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 i2 = start; i2 < buffer.length; i2++) { - if (buffer[i2] < 48 || buffer[i2] > 57) { - return false; - } - } - return true; - } - function isValidLastEventIdBytes(buffer, start) { - for (let i2 = start; i2 < buffer.length; i2++) { - if (buffer[i2] === 0) { - return false; - } - } - return true; - } - function isFieldName(line, length, field) { - if (length !== field.length) { - return false; - } - for (let i2 = 0; i2 < length; i2++) { - if (line[i2] !== field[i2]) { - return false; - } - } - return true; - } var EventSourceStream = class extends Transform { /** * @type {eventSourceSettings} @@ -18364,13 +17995,10 @@ var require_eventsource_stream = __commonJS({ */ eventEndCheck = false; /** - * @type {Buffer[]} + * @type {Buffer} */ - chunks = []; - chunkIndex = 0; + buffer = null; pos = 0; - lineChunkIndex = 0; - linePos = 0; event = { data: void 0, event: void 0, @@ -18401,30 +18029,63 @@ var require_eventsource_stream = __commonJS({ callback(); return; } - this.chunks.push(chunk); + if (this.buffer) { + this.buffer = Buffer.concat([this.buffer, chunk]); + } else { + this.buffer = chunk; + } if (this.checkBOM) { - if (this.handleBOM()) { - callback(); - return; + 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; } } - while (this.hasCurrentByte()) { - const byte = this.currentByte(); + while (this.pos < this.buffer.length) { if (this.eventEndCheck) { if (this.crlfCheck) { - if (byte === LF2) { + if (this.buffer[this.pos] === LF2) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.crlfCheck = false; - this.consumeCurrentByte(); continue; } this.crlfCheck = false; } - if (byte === LF2 || byte === CR2) { - if (byte === CR2) { + if (this.buffer[this.pos] === LF2 || this.buffer[this.pos] === CR2) { + if (this.buffer[this.pos] === CR2) { this.crlfCheck = true; } - this.consumeCurrentByte(); - if (this.hasPendingEvent()) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; + if (this.event.data !== void 0 || this.event.event || this.event.id || this.event.retry) { this.processEvent(this.event); } this.clearEvent(); @@ -18433,16 +18094,17 @@ var require_eventsource_stream = __commonJS({ this.eventEndCheck = false; continue; } - if (byte === LF2 || byte === CR2) { - if (byte === CR2) { + if (this.buffer[this.pos] === LF2 || this.buffer[this.pos] === CR2) { + if (this.buffer[this.pos] === CR2) { this.crlfCheck = true; } - this.parseLine(this.readLine(), this.event); - this.consumeCurrentByte(); + this.parseLine(this.buffer.subarray(0, this.pos), this.event); + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.eventEndCheck = true; continue; } - this.advanceCursor(); + this.pos++; } callback(); } @@ -18458,42 +18120,43 @@ var require_eventsource_stream = __commonJS({ if (colonPosition === 0) { return; } - let fieldLength = line.length; - let valueStart = line.length; + let field = ""; + let value = ""; if (colonPosition !== -1) { - fieldLength = colonPosition; - valueStart = colonPosition + 1; + field = line.subarray(0, colonPosition).toString("utf8"); + let valueStart = colonPosition + 1; if (line[valueStart] === SPACE2) { ++valueStart; } + value = line.subarray(valueStart).toString("utf8"); + } else { + field = line.toString("utf8"); + value = ""; } - if (isFieldName(line, fieldLength, DATA)) { - const value = line.toString("utf8", valueStart); - if (event.data === void 0) { - event.data = value; - } else { - event.data += ` + switch (field) { + case "data": + if (event[field] === void 0) { + event[field] = value; + } else { + event[field] += ` ${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; - } + } + 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; } } /** @@ -18518,120 +18181,12 @@ ${value}`; } } clearEvent() { - 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 i2 = this.lineChunkIndex; i2 <= this.chunkIndex; i2++) { - const chunk = this.chunks[i2]; - const start = i2 === this.lineChunkIndex ? this.linePos : 0; - const end = i2 === 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(); + this.event = { + data: void 0, + event: void 0, + id: void 0, + retry: void 0 + }; } }; module.exports = { diff --git a/.github/actions/javascript/getArtifactInfo/index.js b/.github/actions/javascript/getArtifactInfo/index.js index b511ee174521..1d7315a4ae65 100644 --- a/.github/actions/javascript/getArtifactInfo/index.js +++ b/.github/actions/javascript/getArtifactInfo/index.js @@ -1863,66 +1863,10 @@ var require_request = __commonJS({ return false; } } - /** - * @param {number|null} statusCode - * @param {Buffer[]|null} headers - * @param {import('node:stream').Duplex} socket - * @param {string} [statusText] - */ - onUpgrade(statusCode, headers, socket, statusText = "") { - this.onFinally(); + onUpgrade(statusCode, headers, socket) { assert(!this.aborted); assert(!this.completed); - 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(error2) { - assert(!this.aborted); - assert(this.completed); - if (channels.error.hasSubscribers) { - channels.error.publish({ request: this, error: error2 }); - } - } - /** - * @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: [] }); - } + return this[kHandler].onUpgrade(statusCode, headers, socket); } onComplete(trailers) { this.onFinally(); @@ -1989,11 +1933,7 @@ var require_request = __commonJS({ } else if (typeof val[i] === "object") { throw new InvalidArgumentError(`invalid ${key} header`); } else { - const str = `${val[i]}`; - if (!isValidHeaderValue(str)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } - arr.push(str); + arr.push(`${val[i]}`); } } val = arr; @@ -2005,9 +1945,6 @@ var require_request = __commonJS({ val = ""; } else { val = `${val}`; - if (!isValidHeaderValue(val)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } } if (headerName === "host") { if (request2.host !== null) { @@ -2117,21 +2054,13 @@ var require_dispatcher_base = __commonJS({ var kOnDestroyed = /* @__PURE__ */ Symbol("onDestroyed"); var kOnClosed = /* @__PURE__ */ Symbol("onClosed"); var kInterceptedDispatch = /* @__PURE__ */ Symbol("Intercepted Dispatch"); - var kWebSocketOptions = /* @__PURE__ */ Symbol("webSocketOptions"); var DispatcherBase = class extends Dispatcher { - constructor(opts) { + constructor() { super(); this[kDestroyed] = false; this[kOnDestroyed] = null; this[kClosed] = false; this[kOnClosed] = []; - this[kWebSocketOptions] = opts?.webSocket ?? {}; - } - get webSocketOptions() { - return { - maxFragments: this[kWebSocketOptions].maxFragments ?? 131072, - maxPayloadSize: this[kWebSocketOptions].maxPayloadSize ?? 128 * 1024 * 1024 - }; } get destroyed() { return this[kDestroyed]; @@ -5738,7 +5667,6 @@ var require_client_h1 = __commonJS({ RequestContentLengthMismatchError, ResponseContentLengthMismatchError, RequestAbortedError, - InvalidArgumentError, HeadersTimeoutError, HeadersOverflowError, SocketError, @@ -5785,9 +5713,6 @@ var require_client_h1 = __commonJS({ var FastBuffer = Buffer[Symbol.species]; var addListener = util.addListener; var removeAllListeners = util.removeAllListeners; - var kIdleSocketValidation = /* @__PURE__ */ Symbol("kIdleSocketValidation"); - var kIdleSocketValidationTimeout = /* @__PURE__ */ Symbol("kIdleSocketValidationTimeout"); - var kSocketUsed = /* @__PURE__ */ Symbol("kSocketUsed"); var extractBody; async function lazyllhttp() { const llhttpWasmData = process.env.JEST_WORKER_ID ? require_llhttp_wasm() : void 0; @@ -5950,55 +5875,24 @@ var require_client_h1 = __commonJS({ currentBufferRef = null; } const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr; - if (ret !== constants3.ERROR.OK) { - const body = data.subarray(offset); - if (ret === constants3.ERROR.PAUSED_UPGRADE) { - this.onUpgrade(body); - } else if (ret === constants3.ERROR.PAUSED) { - this.paused = true; - socket.unshift(body); - } else { - throw this.createError(ret, body); + if (ret === constants3.ERROR.PAUSED_UPGRADE) { + this.onUpgrade(data.slice(offset)); + } else if (ret === constants3.ERROR.PAUSED) { + this.paused = true; + socket.unshift(data.slice(offset)); + } else if (ret !== constants3.ERROR.OK) { + const ptr = llhttp.llhttp_get_error_reason(this.ptr); + let message = ""; + if (ptr) { + const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); + message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; } + throw new HTTPParserError(message, constants3.ERROR[ret], data.slice(offset)); } } catch (err) { util.destroy(socket, err); } } - finish() { - assert(currentParser === null); - assert(this.ptr != null); - assert(!this.paused); - const { llhttp } = this; - let ret; - try { - currentParser = this; - ret = llhttp.llhttp_finish(this.ptr); - } finally { - currentParser = null; - } - if (ret === constants3.ERROR.OK) { - return null; - } - if (ret === constants3.ERROR.PAUSED || ret === constants3.ERROR.PAUSED_UPGRADE) { - this.paused = true; - return null; - } - return this.createError(ret, EMPTY_BUF); - } - createError(ret, data) { - const { llhttp, contentLength, bytesRead } = this; - if (contentLength && bytesRead !== parseInt(contentLength, 10)) { - return new ResponseContentLengthMismatchError(); - } - const ptr = llhttp.llhttp_get_error_reason(this.ptr); - let message = ""; - if (ptr) { - const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); - message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; - } - return new HTTPParserError(message, constants3.ERROR[ret], data); - } destroy() { assert(this.ptr != null); assert(currentParser == null); @@ -6018,10 +5912,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6065,7 +5955,7 @@ var require_client_h1 = __commonJS({ } } onUpgrade(head) { - const { upgrade, client, socket, headers, statusCode, statusText } = this; + const { upgrade, client, socket, headers, statusCode } = this; assert(upgrade); assert(client[kSocket] === socket); assert(!socket.destroyed); @@ -6090,10 +5980,9 @@ var require_client_h1 = __commonJS({ client[kQueue][client[kRunningIdx]++] = null; client.emit("disconnect", client[kUrl], [client], new InformationalError("upgrade")); try { - request2.onUpgrade(statusCode, headers, socket, statusText); - } catch (error2) { - util.errorRequest(client, request2, error2); - util.destroy(socket, error2); + request2.onUpgrade(statusCode, headers, socket); + } catch (err) { + util.destroy(socket, err); } client[kResume](); } @@ -6102,10 +5991,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6231,7 +6116,6 @@ var require_client_h1 = __commonJS({ } request2.onComplete(headers); client[kQueue][client[kRunningIdx]++] = null; - socket[kSocketUsed] = true; if (socket[kWriting]) { assert(client[kRunning] === 0); util.destroy(socket, new InformationalError("reset")); @@ -6275,19 +6159,12 @@ var require_client_h1 = __commonJS({ socket[kWriting] = false; socket[kReset] = false; socket[kBlocking] = false; - socket[kIdleSocketValidation] = 0; - socket[kIdleSocketValidationTimeout] = null; - socket[kSocketUsed] = false; socket[kParser] = new Parser(client, socket, llhttpInstance); addListener(socket, "error", function(err) { assert(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID"); const parser = this[kParser]; if (err.code === "ECONNRESET" && parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - this[kError] = parserErr; - this[kClient][kOnError](parserErr); - } + parser.onMessageComplete(); return; } this[kError] = err; @@ -6302,10 +6179,7 @@ var require_client_h1 = __commonJS({ addListener(socket, "end", function() { const parser = this[kParser]; if (parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - util.destroy(this, parserErr); - } + parser.onMessageComplete(); return; } util.destroy(this, new SocketError("other side closed", util.getSocketInfo(this))); @@ -6313,10 +6187,9 @@ var require_client_h1 = __commonJS({ addListener(socket, "close", function() { const client2 = this[kClient]; const parser = this[kParser]; - clearIdleSocketValidation(this); if (parser) { if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { - this[kError] = parser.finish() || this[kError]; + parser.onMessageComplete(); } this[kParser].destroy(); this[kParser] = null; @@ -6365,7 +6238,7 @@ var require_client_h1 = __commonJS({ return socket.destroyed; }, busy(request2) { - if (socket[kWriting] || socket[kReset] || socket[kBlocking] || socket[kIdleSocketValidation] === 1) { + if (socket[kWriting] || socket[kReset] || socket[kBlocking]) { return true; } if (request2) { @@ -6383,23 +6256,6 @@ var require_client_h1 = __commonJS({ } }; } - function clearIdleSocketValidation(socket) { - if (socket[kIdleSocketValidationTimeout]) { - clearImmediate(socket[kIdleSocketValidationTimeout]); - socket[kIdleSocketValidationTimeout] = null; - } - socket[kIdleSocketValidation] = 0; - } - function scheduleIdleSocketValidation(client, socket) { - socket[kIdleSocketValidation] = 1; - socket[kIdleSocketValidationTimeout] = setImmediate(() => { - socket[kIdleSocketValidationTimeout] = null; - socket[kIdleSocketValidation] = 2; - if (client[kSocket] === socket && !socket.destroyed) { - client[kResume](); - } - }); - } function resumeH1(client) { const socket = client[kSocket]; if (socket && !socket.destroyed) { @@ -6412,29 +6268,6 @@ var require_client_h1 = __commonJS({ socket.ref(); socket[kNoRef] = false; } - if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) { - if (socket[kIdleSocketValidation] === 0) { - scheduleIdleSocketValidation(client, socket); - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - if (socket[kIdleSocketValidation] === 1) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - } - if (client[kRunning] === 0) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - } if (client[kSize] === 0) { if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) { socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE); @@ -6465,16 +6298,8 @@ var require_client_h1 = __commonJS({ } body = bodyStream.stream; contentLength = bodyStream.length; - } else if (util.isBlobLike(body) && request2.contentType == null) { - const contentType = body.type; - if (contentType) { - const contentTypeValue = `${contentType}`; - if (!util.isValidHeaderValue(contentTypeValue)) { - util.errorRequest(client, request2, new InvalidArgumentError("invalid content-type header")); - return false; - } - headers.push("content-type", contentTypeValue); - } + } else if (util.isBlobLike(body) && request2.contentType == null && body.type) { + headers.push("content-type", body.type); } if (body && typeof body.read === "function") { body.read(0); @@ -6495,18 +6320,11 @@ var require_client_h1 = __commonJS({ process.emitWarning(new RequestContentLengthMismatchError()); } const socket = client[kSocket]; - clearIdleSocketValidation(socket); - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (request2.upgrade || request2.method === "CONNECT") { - util.destroy(socket, new InformationalError("aborted")); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - util.errorRequest(client, request2, error2 || new RequestAbortedError()); + util.errorRequest(client, request2, err || new RequestAbortedError()); util.destroy(body); util.destroy(socket, new InformationalError("aborted")); }; @@ -6862,7 +6680,6 @@ var require_client_h2 = __commonJS({ "node_modules/undici/lib/dispatcher/client-h2.js"(exports, module) { "use strict"; var assert = __require("node:assert"); - var { errorMonitor } = __require("node:events"); var { pipeline } = __require("node:stream"); var util = require_util(); var { @@ -6923,10 +6740,6 @@ var require_client_h2 = __commonJS({ } return result; } - function parseH2ResponseHeaders(headers) { - const { [HTTP2_HEADER_STATUS]: _statusCode, ...realHeaders } = headers; - return parseH2Headers(realHeaders); - } async function connectH2(client, socket) { client[kSocket] = socket; if (!h2ExperimentalWarned) { @@ -7090,22 +6903,16 @@ var require_client_h2 = __commonJS({ const { hostname, port } = client[kUrl]; headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ""}`; headers[HTTP2_HEADER_METHOD] = method; - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (method === "CONNECT" && stream != null) { - util.destroy(stream, error2 || new RequestAbortedError()); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - error2 = error2 || new RequestAbortedError(); - util.errorRequest(client, request2, error2); + err = err || new RequestAbortedError(); + util.errorRequest(client, request2, err); if (stream != null) { - util.destroy(stream, error2); + util.destroy(stream, err); } - util.destroy(body, error2); + util.destroy(body, err); client[kQueue][client[kRunningIdx]++] = null; client[kResume](); }; @@ -7120,42 +6927,18 @@ var require_client_h2 = __commonJS({ if (method === "CONNECT") { session.ref(); stream = session.request(headers, { endStream: false, signal }); - let upgradeResponseFinished = false; - const onResponse = (headers2) => { - upgradeResponseFinished = true; - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeResponse(Number(headers2[HTTP2_HEADER_STATUS]), headers2, parseH2ResponseHeaders); - }; - const onUpgradeError = (error2) => { - upgradeResponseFinished = true; - stream.off("response", onResponse); - request2.onUpgradeError(error2); - }; - const onReady = () => { - try { - request2.onUpgrade(null, null, stream); - } catch (error2) { - stream.off("response", onResponse); - abort(error2); - return; - } - if (request2.aborted) { - return; - } - stream.off("error", abort); - stream.once(errorMonitor, onUpgradeError); + if (stream.id && !stream.pending) { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; client[kQueue][client[kRunningIdx]++] = null; - }; - stream.once("response", onResponse); - stream.once("error", abort); - ++session[kOpenStreams]; - onReady(); + } else { + stream.once("ready", () => { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; + client[kQueue][client[kRunningIdx]++] = null; + }); + } stream.once("close", () => { - if (!upgradeResponseFinished && request2.completed) { - stream.off("response", onResponse); - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeError(new InformationalError(`HTTP/2: "stream error" received - code ${stream.rstCode}`)); - } session[kOpenStreams] -= 1; if (session[kOpenStreams] === 0) session.unref(); }); @@ -7716,10 +7499,9 @@ var require_client = __commonJS({ autoSelectFamilyAttemptTimeout, // h2 maxConcurrentStreams, - allowH2, - webSocket + allowH2 } = {}) { - super({ webSocket }); + super(); if (keepAlive !== void 0) { throw new InvalidArgumentError("unsupported keepAlive, use pipelining=0 instead"); } @@ -8225,8 +8007,8 @@ var require_pool_base = __commonJS({ var kRemoveClient = /* @__PURE__ */ Symbol("remove client"); var kStats = /* @__PURE__ */ Symbol("stats"); var PoolBase = class extends DispatcherBase { - constructor(opts) { - super(opts); + constructor() { + super(); this[kQueue] = new FixedQueue(); this[kClients] = []; this[kQueued] = 0; @@ -8397,6 +8179,7 @@ var require_pool = __commonJS({ allowH2, ...options } = {}) { + super(); if (connections != null && (!Number.isFinite(connections) || connections < 0)) { throw new InvalidArgumentError("invalid connections"); } @@ -8417,7 +8200,6 @@ var require_pool = __commonJS({ ...connect }); } - super(options); this[kInterceptors] = options.interceptors?.Pool && Array.isArray(options.interceptors.Pool) ? options.interceptors.Pool : []; this[kConnections] = connections || null; this[kUrl] = util.parseOrigin(origin); @@ -8617,6 +8399,7 @@ var require_agent = __commonJS({ } var Agent = class extends DispatcherBase { constructor({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { + super(); if (typeof factory !== "function") { throw new InvalidArgumentError("factory must be a function."); } @@ -8626,7 +8409,6 @@ var require_agent = __commonJS({ if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { throw new InvalidArgumentError("maxRedirections must be a positive number"); } - super(options); if (connect && typeof connect !== "function") { connect = { ...connect }; } @@ -9067,24 +8849,6 @@ var require_retry_handler = __commonJS({ const current = Date.now(); return new Date(retryAfter).getTime() - current; } - function validatePartialResponseContentLength(headers, range, statusCode, retryCount) { - const contentLength = headers["content-length"]; - if (contentLength == null) { - return null; - } - if (!Number.isFinite(range.start) || !Number.isFinite(range.end)) { - return null; - } - const length = Number(contentLength); - const expectedLength = range.end - range.start + 1; - if (!Number.isFinite(length) || length !== expectedLength) { - return new RequestRetryError("Content-Length mismatch", statusCode, { - headers, - data: { count: retryCount } - }); - } - return null; - } var RetryHandler = class _RetryHandler { constructor(opts, handlers) { const { retryOptions, ...dispatchOpts } = opts; @@ -9138,7 +8902,6 @@ var require_retry_handler = __commonJS({ this.end = null; this.etag = null; this.resume = null; - this.headersSent = false; this.handler.onConnect((reason) => { this.aborted = true; if (this.abort) { @@ -9148,17 +8911,6 @@ var require_retry_handler = __commonJS({ } }); } - 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(); @@ -9220,9 +8972,7 @@ var require_retry_handler = __commonJS({ const headers = parseHeaders(rawHeaders); this.retryCount += 1; if (statusCode >= 300) { - if (!this.headersSent && this.retryOpts.statusCodes.includes(statusCode) === false) { - this.headersSent = true; - this.checkpointResponseEnd(headers, resume); + if (this.retryOpts.statusCodes.includes(statusCode) === false) { return this.handler.onHeaders( statusCode, rawHeaders, @@ -9271,21 +9021,9 @@ var require_retry_handler = __commonJS({ ); return false; } - const contentLengthError = validatePartialResponseContentLength(headers, contentRange, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = contentRange; - 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; - } + assert(this.start === start, "content-range mismatch"); + assert(this.end == null || this.end === end, "content-range mismatch"); this.resume = resume; return true; } @@ -9293,7 +9031,6 @@ var require_retry_handler = __commonJS({ if (statusCode === 206) { const range = parseRangeHeader(headers["content-range"]); if (range == null) { - this.headersSent = true; return this.handler.onHeaders( statusCode, rawHeaders, @@ -9301,11 +9038,6 @@ var require_retry_handler = __commonJS({ statusMessage ); } - const contentLengthError = validatePartialResponseContentLength(headers, range, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = range; assert( start != null && Number.isFinite(start), @@ -9325,7 +9057,6 @@ var require_retry_handler = __commonJS({ "invalid content-length" ); this.resume = resume; - this.headersSent = true; this.etag = headers.etag != null ? headers.etag : null; if (this.etag != null && this.etag.startsWith("W/")) { this.etag = null; @@ -9353,7 +9084,7 @@ var require_retry_handler = __commonJS({ return this.handler.onComplete(rawTrailers); } onError(err) { - if (this.aborted || isDisturbed(this.opts.body) || this.headersSent && this.resume == null) { + if (this.aborted || isDisturbed(this.opts.body)) { return this.handler.onError(err); } if (this.retryCount - this.retryCountCheckpoint > 0) { @@ -16152,48 +15883,14 @@ var require_util6 = __commonJS({ for (let i = 0; i < path.length; ++i) { const code = path.charCodeAt(i); if (code < 32 || // exclude CTLs (0-31) - code > 126 || // exclude DEL and non-ascii + code === 127 || // DEL code === 59) { throw new Error("Invalid cookie path"); } } } - function isLetterOrDigit(code) { - return code >= 48 && code <= 57 || // 0-9 - code >= 65 && code <= 90 || // A-Z - code >= 97 && code <= 122; - } function validateCookieDomain(domain) { - if (domain === " ") { - return; - } - if (domain.length > 255) { - throw new Error("Invalid cookie domain"); - } - let labelLength = 0; - for (let i = 0; i < domain.length; ++i) { - const code = domain.charCodeAt(i); - if (code === 46) { - if (labelLength === 0) { - throw new Error("Invalid cookie domain"); - } - if (domain.charCodeAt(i - 1) === 45) { - throw new Error("Invalid cookie domain"); - } - labelLength = 0; - continue; - } - if (labelLength === 0 && !isLetterOrDigit(code)) { - throw new Error("Invalid cookie domain"); - } - if (!isLetterOrDigit(code) && code !== 45) { - throw new Error("Invalid cookie domain"); - } - if (++labelLength > 63) { - throw new Error("Invalid cookie domain"); - } - } - if (labelLength === 0 || domain.charCodeAt(domain.length - 1) === 45) { + if (domain.startsWith("-") || domain.endsWith(".") || domain.endsWith("-")) { throw new Error("Invalid cookie domain"); } } @@ -16276,11 +15973,7 @@ var require_util6 = __commonJS({ throw new Error("Invalid unparsed"); } const [key, ...value] = part.split("="); - const trimmedKey = key.trim(); - const joinedValue = value.join("="); - validateCookieName(trimmedKey); - validateCookieValue(joinedValue); - out.push(`${trimmedKey}=${joinedValue}`); + out.push(`${key.trim()}=${value.join("=")}`); } return out.join("; "); } @@ -16410,14 +16103,18 @@ var require_parse = __commonJS({ } else if (attributeNameLowercase === "httponly") { cookieAttributeList.httpOnly = true; } else if (attributeNameLowercase === "samesite") { + let enforcement = "Default"; const attributeValueLowercase = attributeValue.toLowerCase(); - if (attributeValueLowercase === "none") { - cookieAttributeList.sameSite = "None"; - } else if (attributeValueLowercase === "strict") { - cookieAttributeList.sameSite = "Strict"; - } else if (attributeValueLowercase === "lax") { - cookieAttributeList.sameSite = "Lax"; + if (attributeValueLowercase.includes("none")) { + enforcement = "None"; + } + if (attributeValueLowercase.includes("strict")) { + enforcement = "Strict"; + } + if (attributeValueLowercase.includes("lax")) { + enforcement = "Lax"; } + cookieAttributeList.sameSite = enforcement; } else { cookieAttributeList.unparsed ??= []; cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`); @@ -17239,7 +16936,7 @@ var require_connection = __commonJS({ const secProtocol = response.headersList.get("Sec-WebSocket-Protocol"); if (secProtocol !== null) { const requestProtocols = getDecodeSplit("sec-websocket-protocol", request2.headersList); - if (requestProtocols === null || !requestProtocols.includes(secProtocol)) { + if (!requestProtocols.includes(secProtocol)) { failWebsocketConnection(ws, "Protocol was not set in the opening handshake."); return; } @@ -17345,26 +17042,31 @@ var require_permessage_deflate = __commonJS({ var tail = Buffer.from([0, 0, 255, 255]); var kBuffer = /* @__PURE__ */ Symbol("kBuffer"); var kLength = /* @__PURE__ */ Symbol("kLength"); + var kDefaultMaxDecompressedSize = 4 * 1024 * 1024; var PerMessageDeflate = class { /** @type {import('node:zlib').InflateRaw} */ #inflate; #options = {}; - #maxPayloadSize = 0; + /** @type {number} */ + #maxDecompressedSize; + /** @type {boolean} */ + #aborted = false; + /** @type {Function|null} */ + #currentCallback = null; /** * @param {Map} extensions + * @param {{ maxDecompressedMessageSize?: number }} [options] */ - constructor(extensions, options) { + constructor(extensions, options = {}) { this.#options.serverNoContextTakeover = extensions.has("server_no_context_takeover"); this.#options.serverMaxWindowBits = extensions.get("server_max_window_bits"); - this.#maxPayloadSize = options.maxPayloadSize; + this.#maxDecompressedSize = options.maxDecompressedMessageSize ?? kDefaultMaxDecompressedSize; } - /** - * Decompress a compressed payload. - * @param {Buffer} chunk Compressed data - * @param {boolean} fin Final fragment flag - * @param {Function} callback Callback function - */ decompress(chunk, fin, callback) { + if (this.#aborted) { + callback(new MessageSizeExceededError()); + return; + } if (!this.#inflate) { let windowBits = Z_DEFAULT_WINDOWBITS; if (this.#options.serverMaxWindowBits) { @@ -17383,12 +17085,20 @@ var require_permessage_deflate = __commonJS({ this.#inflate[kBuffer] = []; this.#inflate[kLength] = 0; this.#inflate.on("data", (data) => { + if (this.#aborted) { + return; + } this.#inflate[kLength] += data.length; - if (this.#maxPayloadSize > 0 && this.#inflate[kLength] > this.#maxPayloadSize) { - callback(new MessageSizeExceededError()); + if (this.#inflate[kLength] > this.#maxDecompressedSize) { + this.#aborted = true; this.#inflate.removeAllListeners(); this.#inflate.destroy(); this.#inflate = null; + if (this.#currentCallback) { + const cb = this.#currentCallback; + this.#currentCallback = null; + cb(new MessageSizeExceededError()); + } return; } this.#inflate[kBuffer].push(data); @@ -17398,17 +17108,19 @@ var require_permessage_deflate = __commonJS({ callback(err); }); } + this.#currentCallback = callback; this.#inflate.write(chunk); if (fin) { this.#inflate.write(tail); } this.#inflate.flush(() => { - if (!this.#inflate) { + if (this.#aborted || !this.#inflate) { return; } const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]); this.#inflate[kBuffer].length = 0; this.#inflate[kLength] = 0; + this.#currentCallback = null; callback(null, full); }); } @@ -17439,14 +17151,8 @@ var require_receiver = __commonJS({ var { WebsocketFrameSend } = require_frame(); var { closeWebSocketConnection } = require_connection(); var { PerMessageDeflate } = require_permessage_deflate(); - var { MessageSizeExceededError } = require_errors(); - function failWebsocketConnectionWithCode(ws, code, reason) { - closeWebSocketConnection(ws, code, reason, Buffer.byteLength(reason)); - failWebsocketConnection(ws, reason); - } var ByteParser = class extends Writable { #buffers = []; - #fragmentsBytes = 0; #byteOffset = 0; #loop = false; #state = parserStates.INFO; @@ -17454,21 +17160,18 @@ var require_receiver = __commonJS({ #fragments = []; /** @type {Map} */ #extensions; - /** @type {number} */ - #maxFragments; - /** @type {number} */ - #maxPayloadSize; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {import('./websocket').WebSocket} ws * @param {Map|null} extensions - * @param {{ maxFragments?: number, maxPayloadSize?: number }} [options] + * @param {{ maxDecompressedMessageSize?: number }} [options] */ constructor(ws, extensions, options = {}) { super(); this.ws = ws; this.#extensions = extensions == null ? /* @__PURE__ */ new Map() : extensions; - this.#maxFragments = options.maxFragments ?? 0; - this.#maxPayloadSize = options.maxPayloadSize ?? 0; + this.#options = options; if (this.#extensions.has("permessage-deflate")) { this.#extensions.set("permessage-deflate", new PerMessageDeflate(extensions, options)); } @@ -17483,13 +17186,6 @@ var require_receiver = __commonJS({ this.#loop = true; this.run(callback); } - #validatePayloadLength() { - if (this.#maxPayloadSize > 0 && !isControlFrame(this.#info.opcode) && this.#info.payloadLength + this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, "Payload size exceeds maximum allowed size"); - return false; - } - return true; - } /** * Runs whenever a new chunk is received. * Callback is called whenever there are no more chunks buffering, @@ -17549,9 +17245,6 @@ var require_receiver = __commonJS({ if (payloadLength <= 125) { this.#info.payloadLength = payloadLength; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (payloadLength === 126) { this.#state = parserStates.PAYLOADLENGTH_16; } else if (payloadLength === 127) { @@ -17572,9 +17265,6 @@ var require_receiver = __commonJS({ const buffer = this.consume(2); this.#info.payloadLength = buffer.readUInt16BE(0); this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.PAYLOADLENGTH_64) { if (this.#byteOffset < 8) { return callback(); @@ -17588,9 +17278,6 @@ var require_receiver = __commonJS({ } this.#info.payloadLength = lower; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.READ_DATA) { if (this.#byteOffset < this.#info.payloadLength) { return callback(); @@ -17601,46 +17288,32 @@ var require_receiver = __commonJS({ this.#state = parserStates.INFO; } else { if (!this.#info.compressed) { - if (!this.writeFragments(body)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } + this.#fragments.push(body); if (!this.#info.fragmented && this.#info.fin) { - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); + const fullMessage = Buffer.concat(this.#fragments); + websocketMessageReceived(this.ws, this.#info.binaryType, fullMessage); + this.#fragments.length = 0; } this.#state = parserStates.INFO; } else { - this.#extensions.get("permessage-deflate").decompress( - body, - this.#info.fin, - (error2, data) => { - if (error2) { - const code = error2 instanceof MessageSizeExceededError ? 1009 : 1007; - failWebsocketConnectionWithCode(this.ws, code, error2.message); - return; - } - if (!this.writeFragments(data)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } - if (!this.#info.fin) { - this.#state = parserStates.INFO; - this.#loop = true; - this.run(callback); - return; - } - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); - this.#loop = true; + this.#extensions.get("permessage-deflate").decompress(body, this.#info.fin, (error2, data) => { + if (error2) { + failWebsocketConnection(this.ws, error2.message); + return; + } + this.#fragments.push(data); + if (!this.#info.fin) { this.#state = parserStates.INFO; + this.#loop = true; this.run(callback); + return; } - ); + websocketMessageReceived(this.ws, this.#info.binaryType, Buffer.concat(this.#fragments)); + this.#loop = true; + this.#state = parserStates.INFO; + this.#fragments.length = 0; + this.run(callback); + }); this.#loop = false; break; } @@ -17683,26 +17356,6 @@ var require_receiver = __commonJS({ this.#byteOffset -= n; return buffer; } - writeFragments(fragment) { - if (this.#maxFragments > 0 && this.#fragments.length === this.#maxFragments) { - failWebsocketConnectionWithCode(this.ws, 1008, "Too many message fragments"); - return false; - } - this.#fragmentsBytes += fragment.length; - this.#fragments.push(fragment); - return true; - } - consumeFragments() { - const fragments = this.#fragments; - if (fragments.length === 1) { - this.#fragmentsBytes = 0; - return fragments.shift(); - } - const output = Buffer.concat(fragments, this.#fragmentsBytes); - this.#fragments = []; - this.#fragmentsBytes = 0; - return output; - } parseCloseBody(data) { assert(data.length !== 1); let code; @@ -17914,6 +17567,8 @@ var require_websocket = __commonJS({ #extensions = ""; /** @type {SendQueue} */ #sendQueue; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {string} url * @param {string|string[]} protocols @@ -17957,6 +17612,9 @@ var require_websocket = __commonJS({ throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError"); } this[kWebSocketURL] = new URL(urlRecord.href); + this.#options = { + maxDecompressedMessageSize: options.maxDecompressedMessageSize + }; const client = environmentSettingsObject.settingsObject; this[kController] = establishWebSocketConnection( urlRecord, @@ -18140,13 +17798,7 @@ var require_websocket = __commonJS({ */ #onConnectionEstablished(response, parsedExtensions) { this[kResponse] = response; - const webSocketOptions = this[kController]?.dispatcher?.webSocketOptions; - const maxFragments = webSocketOptions?.maxFragments; - const maxPayloadSize = webSocketOptions?.maxPayloadSize; - const parser = new ByteParser(this, parsedExtensions, { - maxFragments, - maxPayloadSize - }); + const parser = new ByteParser(this, parsedExtensions, this.#options); parser.on("drain", onParserDrain); parser.on("error", onParserError.bind(this)); response.socket.ws = this; @@ -18221,6 +17873,19 @@ var require_websocket = __commonJS({ { key: "headers", converter: webidl.nullableConverter(webidl.converters.HeadersInit) + }, + { + key: "maxDecompressedMessageSize", + converter: webidl.nullableConverter((V) => { + V = webidl.converters["unsigned long long"](V); + if (V <= 0) { + throw webidl.errors.exception({ + header: "WebSocket constructor", + message: "maxDecompressedMessageSize must be greater than 0" + }); + } + return V; + }) } ]); webidl.converters["DOMString or sequence or WebSocketInit"] = function(V) { @@ -18299,40 +17964,6 @@ 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; - } - function isValidLastEventIdBytes(buffer, start) { - for (let i = start; i < buffer.length; i++) { - if (buffer[i] === 0) { - 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; - } var EventSourceStream = class extends Transform { /** * @type {eventSourceSettings} @@ -18352,13 +17983,10 @@ var require_eventsource_stream = __commonJS({ */ eventEndCheck = false; /** - * @type {Buffer[]} + * @type {Buffer} */ - chunks = []; - chunkIndex = 0; + buffer = null; pos = 0; - lineChunkIndex = 0; - linePos = 0; event = { data: void 0, event: void 0, @@ -18389,30 +18017,63 @@ var require_eventsource_stream = __commonJS({ callback(); return; } - this.chunks.push(chunk); + if (this.buffer) { + this.buffer = Buffer.concat([this.buffer, chunk]); + } else { + this.buffer = chunk; + } if (this.checkBOM) { - if (this.handleBOM()) { - callback(); - return; + 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; } } - while (this.hasCurrentByte()) { - const byte = this.currentByte(); + while (this.pos < this.buffer.length) { if (this.eventEndCheck) { if (this.crlfCheck) { - if (byte === LF) { + if (this.buffer[this.pos] === LF) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.crlfCheck = false; - this.consumeCurrentByte(); continue; } this.crlfCheck = false; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.consumeCurrentByte(); - if (this.hasPendingEvent()) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; + if (this.event.data !== void 0 || this.event.event || this.event.id || this.event.retry) { this.processEvent(this.event); } this.clearEvent(); @@ -18421,16 +18082,17 @@ var require_eventsource_stream = __commonJS({ this.eventEndCheck = false; continue; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.parseLine(this.readLine(), this.event); - this.consumeCurrentByte(); + this.parseLine(this.buffer.subarray(0, this.pos), this.event); + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.eventEndCheck = true; continue; } - this.advanceCursor(); + this.pos++; } callback(); } @@ -18446,42 +18108,43 @@ var require_eventsource_stream = __commonJS({ if (colonPosition === 0) { return; } - let fieldLength = line.length; - let valueStart = line.length; + let field = ""; + let value = ""; if (colonPosition !== -1) { - fieldLength = colonPosition; - valueStart = colonPosition + 1; + field = line.subarray(0, colonPosition).toString("utf8"); + let valueStart = colonPosition + 1; if (line[valueStart] === SPACE) { ++valueStart; } + value = line.subarray(valueStart).toString("utf8"); + } else { + field = line.toString("utf8"); + value = ""; } - if (isFieldName(line, fieldLength, DATA)) { - const value = line.toString("utf8", valueStart); - if (event.data === void 0) { - event.data = value; - } else { - event.data += ` + switch (field) { + case "data": + if (event[field] === void 0) { + event[field] = value; + } else { + event[field] += ` ${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; - } + } + 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; } } /** @@ -18506,120 +18169,12 @@ ${value}`; } } clearEvent() { - 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(); + this.event = { + data: void 0, + event: void 0, + id: void 0, + retry: void 0 + }; } }; module.exports = { diff --git a/.github/actions/javascript/getDeployPullRequestList/index.js b/.github/actions/javascript/getDeployPullRequestList/index.js index c6a083ec32cf..86ebf2b747d2 100644 --- a/.github/actions/javascript/getDeployPullRequestList/index.js +++ b/.github/actions/javascript/getDeployPullRequestList/index.js @@ -1863,66 +1863,10 @@ var require_request = __commonJS({ return false; } } - /** - * @param {number|null} statusCode - * @param {Buffer[]|null} headers - * @param {import('node:stream').Duplex} socket - * @param {string} [statusText] - */ - onUpgrade(statusCode, headers, socket, statusText = "") { - this.onFinally(); + onUpgrade(statusCode, headers, socket) { assert(!this.aborted); assert(!this.completed); - 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(error2) { - assert(!this.aborted); - assert(this.completed); - if (channels.error.hasSubscribers) { - channels.error.publish({ request: this, error: error2 }); - } - } - /** - * @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: [] }); - } + return this[kHandler].onUpgrade(statusCode, headers, socket); } onComplete(trailers) { this.onFinally(); @@ -1989,11 +1933,7 @@ var require_request = __commonJS({ } else if (typeof val[i] === "object") { throw new InvalidArgumentError(`invalid ${key} header`); } else { - const str = `${val[i]}`; - if (!isValidHeaderValue(str)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } - arr.push(str); + arr.push(`${val[i]}`); } } val = arr; @@ -2005,9 +1945,6 @@ var require_request = __commonJS({ val = ""; } else { val = `${val}`; - if (!isValidHeaderValue(val)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } } if (headerName === "host") { if (request2.host !== null) { @@ -2117,21 +2054,13 @@ var require_dispatcher_base = __commonJS({ var kOnDestroyed = /* @__PURE__ */ Symbol("onDestroyed"); var kOnClosed = /* @__PURE__ */ Symbol("onClosed"); var kInterceptedDispatch = /* @__PURE__ */ Symbol("Intercepted Dispatch"); - var kWebSocketOptions = /* @__PURE__ */ Symbol("webSocketOptions"); var DispatcherBase = class extends Dispatcher { - constructor(opts) { + constructor() { super(); this[kDestroyed] = false; this[kOnDestroyed] = null; this[kClosed] = false; this[kOnClosed] = []; - this[kWebSocketOptions] = opts?.webSocket ?? {}; - } - get webSocketOptions() { - return { - maxFragments: this[kWebSocketOptions].maxFragments ?? 131072, - maxPayloadSize: this[kWebSocketOptions].maxPayloadSize ?? 128 * 1024 * 1024 - }; } get destroyed() { return this[kDestroyed]; @@ -5738,7 +5667,6 @@ var require_client_h1 = __commonJS({ RequestContentLengthMismatchError, ResponseContentLengthMismatchError, RequestAbortedError, - InvalidArgumentError, HeadersTimeoutError, HeadersOverflowError, SocketError, @@ -5785,9 +5713,6 @@ var require_client_h1 = __commonJS({ var FastBuffer = Buffer[Symbol.species]; var addListener = util.addListener; var removeAllListeners = util.removeAllListeners; - var kIdleSocketValidation = /* @__PURE__ */ Symbol("kIdleSocketValidation"); - var kIdleSocketValidationTimeout = /* @__PURE__ */ Symbol("kIdleSocketValidationTimeout"); - var kSocketUsed = /* @__PURE__ */ Symbol("kSocketUsed"); var extractBody; async function lazyllhttp() { const llhttpWasmData = process.env.JEST_WORKER_ID ? require_llhttp_wasm() : void 0; @@ -5950,55 +5875,24 @@ var require_client_h1 = __commonJS({ currentBufferRef = null; } const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr; - if (ret !== constants3.ERROR.OK) { - const body = data.subarray(offset); - if (ret === constants3.ERROR.PAUSED_UPGRADE) { - this.onUpgrade(body); - } else if (ret === constants3.ERROR.PAUSED) { - this.paused = true; - socket.unshift(body); - } else { - throw this.createError(ret, body); + if (ret === constants3.ERROR.PAUSED_UPGRADE) { + this.onUpgrade(data.slice(offset)); + } else if (ret === constants3.ERROR.PAUSED) { + this.paused = true; + socket.unshift(data.slice(offset)); + } else if (ret !== constants3.ERROR.OK) { + const ptr = llhttp.llhttp_get_error_reason(this.ptr); + let message = ""; + if (ptr) { + const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); + message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; } + throw new HTTPParserError(message, constants3.ERROR[ret], data.slice(offset)); } } catch (err) { util.destroy(socket, err); } } - finish() { - assert(currentParser === null); - assert(this.ptr != null); - assert(!this.paused); - const { llhttp } = this; - let ret; - try { - currentParser = this; - ret = llhttp.llhttp_finish(this.ptr); - } finally { - currentParser = null; - } - if (ret === constants3.ERROR.OK) { - return null; - } - if (ret === constants3.ERROR.PAUSED || ret === constants3.ERROR.PAUSED_UPGRADE) { - this.paused = true; - return null; - } - return this.createError(ret, EMPTY_BUF); - } - createError(ret, data) { - const { llhttp, contentLength, bytesRead } = this; - if (contentLength && bytesRead !== parseInt(contentLength, 10)) { - return new ResponseContentLengthMismatchError(); - } - const ptr = llhttp.llhttp_get_error_reason(this.ptr); - let message = ""; - if (ptr) { - const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); - message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; - } - return new HTTPParserError(message, constants3.ERROR[ret], data); - } destroy() { assert(this.ptr != null); assert(currentParser == null); @@ -6018,10 +5912,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6065,7 +5955,7 @@ var require_client_h1 = __commonJS({ } } onUpgrade(head) { - const { upgrade, client, socket, headers, statusCode, statusText } = this; + const { upgrade, client, socket, headers, statusCode } = this; assert(upgrade); assert(client[kSocket] === socket); assert(!socket.destroyed); @@ -6090,10 +5980,9 @@ var require_client_h1 = __commonJS({ client[kQueue][client[kRunningIdx]++] = null; client.emit("disconnect", client[kUrl], [client], new InformationalError("upgrade")); try { - request2.onUpgrade(statusCode, headers, socket, statusText); - } catch (error2) { - util.errorRequest(client, request2, error2); - util.destroy(socket, error2); + request2.onUpgrade(statusCode, headers, socket); + } catch (err) { + util.destroy(socket, err); } client[kResume](); } @@ -6102,10 +5991,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6231,7 +6116,6 @@ var require_client_h1 = __commonJS({ } request2.onComplete(headers); client[kQueue][client[kRunningIdx]++] = null; - socket[kSocketUsed] = true; if (socket[kWriting]) { assert(client[kRunning] === 0); util.destroy(socket, new InformationalError("reset")); @@ -6275,19 +6159,12 @@ var require_client_h1 = __commonJS({ socket[kWriting] = false; socket[kReset] = false; socket[kBlocking] = false; - socket[kIdleSocketValidation] = 0; - socket[kIdleSocketValidationTimeout] = null; - socket[kSocketUsed] = false; socket[kParser] = new Parser(client, socket, llhttpInstance); addListener(socket, "error", function(err) { assert(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID"); const parser = this[kParser]; if (err.code === "ECONNRESET" && parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - this[kError] = parserErr; - this[kClient][kOnError](parserErr); - } + parser.onMessageComplete(); return; } this[kError] = err; @@ -6302,10 +6179,7 @@ var require_client_h1 = __commonJS({ addListener(socket, "end", function() { const parser = this[kParser]; if (parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - util.destroy(this, parserErr); - } + parser.onMessageComplete(); return; } util.destroy(this, new SocketError("other side closed", util.getSocketInfo(this))); @@ -6313,10 +6187,9 @@ var require_client_h1 = __commonJS({ addListener(socket, "close", function() { const client2 = this[kClient]; const parser = this[kParser]; - clearIdleSocketValidation(this); if (parser) { if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { - this[kError] = parser.finish() || this[kError]; + parser.onMessageComplete(); } this[kParser].destroy(); this[kParser] = null; @@ -6365,7 +6238,7 @@ var require_client_h1 = __commonJS({ return socket.destroyed; }, busy(request2) { - if (socket[kWriting] || socket[kReset] || socket[kBlocking] || socket[kIdleSocketValidation] === 1) { + if (socket[kWriting] || socket[kReset] || socket[kBlocking]) { return true; } if (request2) { @@ -6383,23 +6256,6 @@ var require_client_h1 = __commonJS({ } }; } - function clearIdleSocketValidation(socket) { - if (socket[kIdleSocketValidationTimeout]) { - clearImmediate(socket[kIdleSocketValidationTimeout]); - socket[kIdleSocketValidationTimeout] = null; - } - socket[kIdleSocketValidation] = 0; - } - function scheduleIdleSocketValidation(client, socket) { - socket[kIdleSocketValidation] = 1; - socket[kIdleSocketValidationTimeout] = setImmediate(() => { - socket[kIdleSocketValidationTimeout] = null; - socket[kIdleSocketValidation] = 2; - if (client[kSocket] === socket && !socket.destroyed) { - client[kResume](); - } - }); - } function resumeH1(client) { const socket = client[kSocket]; if (socket && !socket.destroyed) { @@ -6412,29 +6268,6 @@ var require_client_h1 = __commonJS({ socket.ref(); socket[kNoRef] = false; } - if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) { - if (socket[kIdleSocketValidation] === 0) { - scheduleIdleSocketValidation(client, socket); - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - if (socket[kIdleSocketValidation] === 1) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - } - if (client[kRunning] === 0) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - } if (client[kSize] === 0) { if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) { socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE); @@ -6465,16 +6298,8 @@ var require_client_h1 = __commonJS({ } body = bodyStream.stream; contentLength = bodyStream.length; - } else if (util.isBlobLike(body) && request2.contentType == null) { - const contentType = body.type; - if (contentType) { - const contentTypeValue = `${contentType}`; - if (!util.isValidHeaderValue(contentTypeValue)) { - util.errorRequest(client, request2, new InvalidArgumentError("invalid content-type header")); - return false; - } - headers.push("content-type", contentTypeValue); - } + } else if (util.isBlobLike(body) && request2.contentType == null && body.type) { + headers.push("content-type", body.type); } if (body && typeof body.read === "function") { body.read(0); @@ -6495,18 +6320,11 @@ var require_client_h1 = __commonJS({ process.emitWarning(new RequestContentLengthMismatchError()); } const socket = client[kSocket]; - clearIdleSocketValidation(socket); - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (request2.upgrade || request2.method === "CONNECT") { - util.destroy(socket, new InformationalError("aborted")); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - util.errorRequest(client, request2, error2 || new RequestAbortedError()); + util.errorRequest(client, request2, err || new RequestAbortedError()); util.destroy(body); util.destroy(socket, new InformationalError("aborted")); }; @@ -6862,7 +6680,6 @@ var require_client_h2 = __commonJS({ "node_modules/undici/lib/dispatcher/client-h2.js"(exports, module) { "use strict"; var assert = __require("node:assert"); - var { errorMonitor } = __require("node:events"); var { pipeline } = __require("node:stream"); var util = require_util(); var { @@ -6923,10 +6740,6 @@ var require_client_h2 = __commonJS({ } return result; } - function parseH2ResponseHeaders(headers) { - const { [HTTP2_HEADER_STATUS]: _statusCode, ...realHeaders } = headers; - return parseH2Headers(realHeaders); - } async function connectH2(client, socket) { client[kSocket] = socket; if (!h2ExperimentalWarned) { @@ -7090,22 +6903,16 @@ var require_client_h2 = __commonJS({ const { hostname, port } = client[kUrl]; headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ""}`; headers[HTTP2_HEADER_METHOD] = method; - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (method === "CONNECT" && stream != null) { - util.destroy(stream, error2 || new RequestAbortedError()); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - error2 = error2 || new RequestAbortedError(); - util.errorRequest(client, request2, error2); + err = err || new RequestAbortedError(); + util.errorRequest(client, request2, err); if (stream != null) { - util.destroy(stream, error2); + util.destroy(stream, err); } - util.destroy(body, error2); + util.destroy(body, err); client[kQueue][client[kRunningIdx]++] = null; client[kResume](); }; @@ -7120,42 +6927,18 @@ var require_client_h2 = __commonJS({ if (method === "CONNECT") { session.ref(); stream = session.request(headers, { endStream: false, signal }); - let upgradeResponseFinished = false; - const onResponse = (headers2) => { - upgradeResponseFinished = true; - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeResponse(Number(headers2[HTTP2_HEADER_STATUS]), headers2, parseH2ResponseHeaders); - }; - const onUpgradeError = (error2) => { - upgradeResponseFinished = true; - stream.off("response", onResponse); - request2.onUpgradeError(error2); - }; - const onReady = () => { - try { - request2.onUpgrade(null, null, stream); - } catch (error2) { - stream.off("response", onResponse); - abort(error2); - return; - } - if (request2.aborted) { - return; - } - stream.off("error", abort); - stream.once(errorMonitor, onUpgradeError); + if (stream.id && !stream.pending) { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; client[kQueue][client[kRunningIdx]++] = null; - }; - stream.once("response", onResponse); - stream.once("error", abort); - ++session[kOpenStreams]; - onReady(); + } else { + stream.once("ready", () => { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; + client[kQueue][client[kRunningIdx]++] = null; + }); + } stream.once("close", () => { - if (!upgradeResponseFinished && request2.completed) { - stream.off("response", onResponse); - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeError(new InformationalError(`HTTP/2: "stream error" received - code ${stream.rstCode}`)); - } session[kOpenStreams] -= 1; if (session[kOpenStreams] === 0) session.unref(); }); @@ -7716,10 +7499,9 @@ var require_client = __commonJS({ autoSelectFamilyAttemptTimeout, // h2 maxConcurrentStreams, - allowH2, - webSocket + allowH2 } = {}) { - super({ webSocket }); + super(); if (keepAlive !== void 0) { throw new InvalidArgumentError("unsupported keepAlive, use pipelining=0 instead"); } @@ -8225,8 +8007,8 @@ var require_pool_base = __commonJS({ var kRemoveClient = /* @__PURE__ */ Symbol("remove client"); var kStats = /* @__PURE__ */ Symbol("stats"); var PoolBase = class extends DispatcherBase { - constructor(opts) { - super(opts); + constructor() { + super(); this[kQueue] = new FixedQueue(); this[kClients] = []; this[kQueued] = 0; @@ -8397,6 +8179,7 @@ var require_pool = __commonJS({ allowH2, ...options } = {}) { + super(); if (connections != null && (!Number.isFinite(connections) || connections < 0)) { throw new InvalidArgumentError("invalid connections"); } @@ -8417,7 +8200,6 @@ var require_pool = __commonJS({ ...connect }); } - super(options); this[kInterceptors] = options.interceptors?.Pool && Array.isArray(options.interceptors.Pool) ? options.interceptors.Pool : []; this[kConnections] = connections || null; this[kUrl] = util.parseOrigin(origin); @@ -8617,6 +8399,7 @@ var require_agent = __commonJS({ } var Agent = class extends DispatcherBase { constructor({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { + super(); if (typeof factory !== "function") { throw new InvalidArgumentError("factory must be a function."); } @@ -8626,7 +8409,6 @@ var require_agent = __commonJS({ if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { throw new InvalidArgumentError("maxRedirections must be a positive number"); } - super(options); if (connect && typeof connect !== "function") { connect = { ...connect }; } @@ -9067,24 +8849,6 @@ var require_retry_handler = __commonJS({ const current = Date.now(); return new Date(retryAfter).getTime() - current; } - function validatePartialResponseContentLength(headers, range, statusCode, retryCount) { - const contentLength = headers["content-length"]; - if (contentLength == null) { - return null; - } - if (!Number.isFinite(range.start) || !Number.isFinite(range.end)) { - return null; - } - const length = Number(contentLength); - const expectedLength = range.end - range.start + 1; - if (!Number.isFinite(length) || length !== expectedLength) { - return new RequestRetryError("Content-Length mismatch", statusCode, { - headers, - data: { count: retryCount } - }); - } - return null; - } var RetryHandler = class _RetryHandler { constructor(opts, handlers) { const { retryOptions, ...dispatchOpts } = opts; @@ -9138,7 +8902,6 @@ var require_retry_handler = __commonJS({ this.end = null; this.etag = null; this.resume = null; - this.headersSent = false; this.handler.onConnect((reason) => { this.aborted = true; if (this.abort) { @@ -9148,17 +8911,6 @@ var require_retry_handler = __commonJS({ } }); } - 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(); @@ -9220,9 +8972,7 @@ var require_retry_handler = __commonJS({ const headers = parseHeaders(rawHeaders); this.retryCount += 1; if (statusCode >= 300) { - if (!this.headersSent && this.retryOpts.statusCodes.includes(statusCode) === false) { - this.headersSent = true; - this.checkpointResponseEnd(headers, resume); + if (this.retryOpts.statusCodes.includes(statusCode) === false) { return this.handler.onHeaders( statusCode, rawHeaders, @@ -9271,21 +9021,9 @@ var require_retry_handler = __commonJS({ ); return false; } - const contentLengthError = validatePartialResponseContentLength(headers, contentRange, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = contentRange; - 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; - } + assert(this.start === start, "content-range mismatch"); + assert(this.end == null || this.end === end, "content-range mismatch"); this.resume = resume; return true; } @@ -9293,7 +9031,6 @@ var require_retry_handler = __commonJS({ if (statusCode === 206) { const range = parseRangeHeader(headers["content-range"]); if (range == null) { - this.headersSent = true; return this.handler.onHeaders( statusCode, rawHeaders, @@ -9301,11 +9038,6 @@ var require_retry_handler = __commonJS({ statusMessage ); } - const contentLengthError = validatePartialResponseContentLength(headers, range, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = range; assert( start != null && Number.isFinite(start), @@ -9325,7 +9057,6 @@ var require_retry_handler = __commonJS({ "invalid content-length" ); this.resume = resume; - this.headersSent = true; this.etag = headers.etag != null ? headers.etag : null; if (this.etag != null && this.etag.startsWith("W/")) { this.etag = null; @@ -9353,7 +9084,7 @@ var require_retry_handler = __commonJS({ return this.handler.onComplete(rawTrailers); } onError(err) { - if (this.aborted || isDisturbed(this.opts.body) || this.headersSent && this.resume == null) { + if (this.aborted || isDisturbed(this.opts.body)) { return this.handler.onError(err); } if (this.retryCount - this.retryCountCheckpoint > 0) { @@ -16152,48 +15883,14 @@ var require_util6 = __commonJS({ for (let i = 0; i < path.length; ++i) { const code = path.charCodeAt(i); if (code < 32 || // exclude CTLs (0-31) - code > 126 || // exclude DEL and non-ascii + code === 127 || // DEL code === 59) { throw new Error("Invalid cookie path"); } } } - function isLetterOrDigit(code) { - return code >= 48 && code <= 57 || // 0-9 - code >= 65 && code <= 90 || // A-Z - code >= 97 && code <= 122; - } function validateCookieDomain(domain) { - if (domain === " ") { - return; - } - if (domain.length > 255) { - throw new Error("Invalid cookie domain"); - } - let labelLength = 0; - for (let i = 0; i < domain.length; ++i) { - const code = domain.charCodeAt(i); - if (code === 46) { - if (labelLength === 0) { - throw new Error("Invalid cookie domain"); - } - if (domain.charCodeAt(i - 1) === 45) { - throw new Error("Invalid cookie domain"); - } - labelLength = 0; - continue; - } - if (labelLength === 0 && !isLetterOrDigit(code)) { - throw new Error("Invalid cookie domain"); - } - if (!isLetterOrDigit(code) && code !== 45) { - throw new Error("Invalid cookie domain"); - } - if (++labelLength > 63) { - throw new Error("Invalid cookie domain"); - } - } - if (labelLength === 0 || domain.charCodeAt(domain.length - 1) === 45) { + if (domain.startsWith("-") || domain.endsWith(".") || domain.endsWith("-")) { throw new Error("Invalid cookie domain"); } } @@ -16276,11 +15973,7 @@ var require_util6 = __commonJS({ throw new Error("Invalid unparsed"); } const [key, ...value] = part.split("="); - const trimmedKey = key.trim(); - const joinedValue = value.join("="); - validateCookieName(trimmedKey); - validateCookieValue(joinedValue); - out.push(`${trimmedKey}=${joinedValue}`); + out.push(`${key.trim()}=${value.join("=")}`); } return out.join("; "); } @@ -16410,14 +16103,18 @@ var require_parse = __commonJS({ } else if (attributeNameLowercase === "httponly") { cookieAttributeList.httpOnly = true; } else if (attributeNameLowercase === "samesite") { + let enforcement = "Default"; const attributeValueLowercase = attributeValue.toLowerCase(); - if (attributeValueLowercase === "none") { - cookieAttributeList.sameSite = "None"; - } else if (attributeValueLowercase === "strict") { - cookieAttributeList.sameSite = "Strict"; - } else if (attributeValueLowercase === "lax") { - cookieAttributeList.sameSite = "Lax"; + if (attributeValueLowercase.includes("none")) { + enforcement = "None"; + } + if (attributeValueLowercase.includes("strict")) { + enforcement = "Strict"; + } + if (attributeValueLowercase.includes("lax")) { + enforcement = "Lax"; } + cookieAttributeList.sameSite = enforcement; } else { cookieAttributeList.unparsed ??= []; cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`); @@ -17239,7 +16936,7 @@ var require_connection = __commonJS({ const secProtocol = response.headersList.get("Sec-WebSocket-Protocol"); if (secProtocol !== null) { const requestProtocols = getDecodeSplit("sec-websocket-protocol", request2.headersList); - if (requestProtocols === null || !requestProtocols.includes(secProtocol)) { + if (!requestProtocols.includes(secProtocol)) { failWebsocketConnection(ws, "Protocol was not set in the opening handshake."); return; } @@ -17345,26 +17042,31 @@ var require_permessage_deflate = __commonJS({ var tail = Buffer.from([0, 0, 255, 255]); var kBuffer = /* @__PURE__ */ Symbol("kBuffer"); var kLength = /* @__PURE__ */ Symbol("kLength"); + var kDefaultMaxDecompressedSize = 4 * 1024 * 1024; var PerMessageDeflate = class { /** @type {import('node:zlib').InflateRaw} */ #inflate; #options = {}; - #maxPayloadSize = 0; + /** @type {number} */ + #maxDecompressedSize; + /** @type {boolean} */ + #aborted = false; + /** @type {Function|null} */ + #currentCallback = null; /** * @param {Map} extensions + * @param {{ maxDecompressedMessageSize?: number }} [options] */ - constructor(extensions, options) { + constructor(extensions, options = {}) { this.#options.serverNoContextTakeover = extensions.has("server_no_context_takeover"); this.#options.serverMaxWindowBits = extensions.get("server_max_window_bits"); - this.#maxPayloadSize = options.maxPayloadSize; + this.#maxDecompressedSize = options.maxDecompressedMessageSize ?? kDefaultMaxDecompressedSize; } - /** - * Decompress a compressed payload. - * @param {Buffer} chunk Compressed data - * @param {boolean} fin Final fragment flag - * @param {Function} callback Callback function - */ decompress(chunk, fin, callback) { + if (this.#aborted) { + callback(new MessageSizeExceededError()); + return; + } if (!this.#inflate) { let windowBits = Z_DEFAULT_WINDOWBITS; if (this.#options.serverMaxWindowBits) { @@ -17383,12 +17085,20 @@ var require_permessage_deflate = __commonJS({ this.#inflate[kBuffer] = []; this.#inflate[kLength] = 0; this.#inflate.on("data", (data) => { + if (this.#aborted) { + return; + } this.#inflate[kLength] += data.length; - if (this.#maxPayloadSize > 0 && this.#inflate[kLength] > this.#maxPayloadSize) { - callback(new MessageSizeExceededError()); + if (this.#inflate[kLength] > this.#maxDecompressedSize) { + this.#aborted = true; this.#inflate.removeAllListeners(); this.#inflate.destroy(); this.#inflate = null; + if (this.#currentCallback) { + const cb = this.#currentCallback; + this.#currentCallback = null; + cb(new MessageSizeExceededError()); + } return; } this.#inflate[kBuffer].push(data); @@ -17398,17 +17108,19 @@ var require_permessage_deflate = __commonJS({ callback(err); }); } + this.#currentCallback = callback; this.#inflate.write(chunk); if (fin) { this.#inflate.write(tail); } this.#inflate.flush(() => { - if (!this.#inflate) { + if (this.#aborted || !this.#inflate) { return; } const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]); this.#inflate[kBuffer].length = 0; this.#inflate[kLength] = 0; + this.#currentCallback = null; callback(null, full); }); } @@ -17439,14 +17151,8 @@ var require_receiver = __commonJS({ var { WebsocketFrameSend } = require_frame(); var { closeWebSocketConnection } = require_connection(); var { PerMessageDeflate } = require_permessage_deflate(); - var { MessageSizeExceededError } = require_errors(); - function failWebsocketConnectionWithCode(ws, code, reason) { - closeWebSocketConnection(ws, code, reason, Buffer.byteLength(reason)); - failWebsocketConnection(ws, reason); - } var ByteParser = class extends Writable { #buffers = []; - #fragmentsBytes = 0; #byteOffset = 0; #loop = false; #state = parserStates.INFO; @@ -17454,21 +17160,18 @@ var require_receiver = __commonJS({ #fragments = []; /** @type {Map} */ #extensions; - /** @type {number} */ - #maxFragments; - /** @type {number} */ - #maxPayloadSize; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {import('./websocket').WebSocket} ws * @param {Map|null} extensions - * @param {{ maxFragments?: number, maxPayloadSize?: number }} [options] + * @param {{ maxDecompressedMessageSize?: number }} [options] */ constructor(ws, extensions, options = {}) { super(); this.ws = ws; this.#extensions = extensions == null ? /* @__PURE__ */ new Map() : extensions; - this.#maxFragments = options.maxFragments ?? 0; - this.#maxPayloadSize = options.maxPayloadSize ?? 0; + this.#options = options; if (this.#extensions.has("permessage-deflate")) { this.#extensions.set("permessage-deflate", new PerMessageDeflate(extensions, options)); } @@ -17483,13 +17186,6 @@ var require_receiver = __commonJS({ this.#loop = true; this.run(callback); } - #validatePayloadLength() { - if (this.#maxPayloadSize > 0 && !isControlFrame(this.#info.opcode) && this.#info.payloadLength + this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, "Payload size exceeds maximum allowed size"); - return false; - } - return true; - } /** * Runs whenever a new chunk is received. * Callback is called whenever there are no more chunks buffering, @@ -17549,9 +17245,6 @@ var require_receiver = __commonJS({ if (payloadLength <= 125) { this.#info.payloadLength = payloadLength; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (payloadLength === 126) { this.#state = parserStates.PAYLOADLENGTH_16; } else if (payloadLength === 127) { @@ -17572,9 +17265,6 @@ var require_receiver = __commonJS({ const buffer = this.consume(2); this.#info.payloadLength = buffer.readUInt16BE(0); this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.PAYLOADLENGTH_64) { if (this.#byteOffset < 8) { return callback(); @@ -17588,9 +17278,6 @@ var require_receiver = __commonJS({ } this.#info.payloadLength = lower; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.READ_DATA) { if (this.#byteOffset < this.#info.payloadLength) { return callback(); @@ -17601,46 +17288,32 @@ var require_receiver = __commonJS({ this.#state = parserStates.INFO; } else { if (!this.#info.compressed) { - if (!this.writeFragments(body)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } + this.#fragments.push(body); if (!this.#info.fragmented && this.#info.fin) { - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); + const fullMessage = Buffer.concat(this.#fragments); + websocketMessageReceived(this.ws, this.#info.binaryType, fullMessage); + this.#fragments.length = 0; } this.#state = parserStates.INFO; } else { - this.#extensions.get("permessage-deflate").decompress( - body, - this.#info.fin, - (error2, data) => { - if (error2) { - const code = error2 instanceof MessageSizeExceededError ? 1009 : 1007; - failWebsocketConnectionWithCode(this.ws, code, error2.message); - return; - } - if (!this.writeFragments(data)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } - if (!this.#info.fin) { - this.#state = parserStates.INFO; - this.#loop = true; - this.run(callback); - return; - } - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); - this.#loop = true; + this.#extensions.get("permessage-deflate").decompress(body, this.#info.fin, (error2, data) => { + if (error2) { + failWebsocketConnection(this.ws, error2.message); + return; + } + this.#fragments.push(data); + if (!this.#info.fin) { this.#state = parserStates.INFO; + this.#loop = true; this.run(callback); + return; } - ); + websocketMessageReceived(this.ws, this.#info.binaryType, Buffer.concat(this.#fragments)); + this.#loop = true; + this.#state = parserStates.INFO; + this.#fragments.length = 0; + this.run(callback); + }); this.#loop = false; break; } @@ -17683,26 +17356,6 @@ var require_receiver = __commonJS({ this.#byteOffset -= n; return buffer; } - writeFragments(fragment) { - if (this.#maxFragments > 0 && this.#fragments.length === this.#maxFragments) { - failWebsocketConnectionWithCode(this.ws, 1008, "Too many message fragments"); - return false; - } - this.#fragmentsBytes += fragment.length; - this.#fragments.push(fragment); - return true; - } - consumeFragments() { - const fragments = this.#fragments; - if (fragments.length === 1) { - this.#fragmentsBytes = 0; - return fragments.shift(); - } - const output = Buffer.concat(fragments, this.#fragmentsBytes); - this.#fragments = []; - this.#fragmentsBytes = 0; - return output; - } parseCloseBody(data) { assert(data.length !== 1); let code; @@ -17914,6 +17567,8 @@ var require_websocket = __commonJS({ #extensions = ""; /** @type {SendQueue} */ #sendQueue; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {string} url * @param {string|string[]} protocols @@ -17957,6 +17612,9 @@ var require_websocket = __commonJS({ throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError"); } this[kWebSocketURL] = new URL(urlRecord.href); + this.#options = { + maxDecompressedMessageSize: options.maxDecompressedMessageSize + }; const client = environmentSettingsObject.settingsObject; this[kController] = establishWebSocketConnection( urlRecord, @@ -18140,13 +17798,7 @@ var require_websocket = __commonJS({ */ #onConnectionEstablished(response, parsedExtensions) { this[kResponse] = response; - const webSocketOptions = this[kController]?.dispatcher?.webSocketOptions; - const maxFragments = webSocketOptions?.maxFragments; - const maxPayloadSize = webSocketOptions?.maxPayloadSize; - const parser = new ByteParser(this, parsedExtensions, { - maxFragments, - maxPayloadSize - }); + const parser = new ByteParser(this, parsedExtensions, this.#options); parser.on("drain", onParserDrain); parser.on("error", onParserError.bind(this)); response.socket.ws = this; @@ -18221,6 +17873,19 @@ var require_websocket = __commonJS({ { key: "headers", converter: webidl.nullableConverter(webidl.converters.HeadersInit) + }, + { + key: "maxDecompressedMessageSize", + converter: webidl.nullableConverter((V) => { + V = webidl.converters["unsigned long long"](V); + if (V <= 0) { + throw webidl.errors.exception({ + header: "WebSocket constructor", + message: "maxDecompressedMessageSize must be greater than 0" + }); + } + return V; + }) } ]); webidl.converters["DOMString or sequence or WebSocketInit"] = function(V) { @@ -18299,40 +17964,6 @@ 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; - } - function isValidLastEventIdBytes(buffer, start) { - for (let i = start; i < buffer.length; i++) { - if (buffer[i] === 0) { - 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; - } var EventSourceStream = class extends Transform { /** * @type {eventSourceSettings} @@ -18352,13 +17983,10 @@ var require_eventsource_stream = __commonJS({ */ eventEndCheck = false; /** - * @type {Buffer[]} + * @type {Buffer} */ - chunks = []; - chunkIndex = 0; + buffer = null; pos = 0; - lineChunkIndex = 0; - linePos = 0; event = { data: void 0, event: void 0, @@ -18389,30 +18017,63 @@ var require_eventsource_stream = __commonJS({ callback(); return; } - this.chunks.push(chunk); + if (this.buffer) { + this.buffer = Buffer.concat([this.buffer, chunk]); + } else { + this.buffer = chunk; + } if (this.checkBOM) { - if (this.handleBOM()) { - callback(); - return; + 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; } } - while (this.hasCurrentByte()) { - const byte = this.currentByte(); + while (this.pos < this.buffer.length) { if (this.eventEndCheck) { if (this.crlfCheck) { - if (byte === LF) { + if (this.buffer[this.pos] === LF) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.crlfCheck = false; - this.consumeCurrentByte(); continue; } this.crlfCheck = false; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.consumeCurrentByte(); - if (this.hasPendingEvent()) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; + if (this.event.data !== void 0 || this.event.event || this.event.id || this.event.retry) { this.processEvent(this.event); } this.clearEvent(); @@ -18421,16 +18082,17 @@ var require_eventsource_stream = __commonJS({ this.eventEndCheck = false; continue; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.parseLine(this.readLine(), this.event); - this.consumeCurrentByte(); + this.parseLine(this.buffer.subarray(0, this.pos), this.event); + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.eventEndCheck = true; continue; } - this.advanceCursor(); + this.pos++; } callback(); } @@ -18446,42 +18108,43 @@ var require_eventsource_stream = __commonJS({ if (colonPosition === 0) { return; } - let fieldLength = line.length; - let valueStart = line.length; + let field = ""; + let value = ""; if (colonPosition !== -1) { - fieldLength = colonPosition; - valueStart = colonPosition + 1; + field = line.subarray(0, colonPosition).toString("utf8"); + let valueStart = colonPosition + 1; if (line[valueStart] === SPACE) { ++valueStart; } + value = line.subarray(valueStart).toString("utf8"); + } else { + field = line.toString("utf8"); + value = ""; } - if (isFieldName(line, fieldLength, DATA)) { - const value = line.toString("utf8", valueStart); - if (event.data === void 0) { - event.data = value; - } else { - event.data += ` + switch (field) { + case "data": + if (event[field] === void 0) { + event[field] = value; + } else { + event[field] += ` ${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; - } + } + 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; } } /** @@ -18506,120 +18169,12 @@ ${value}`; } } clearEvent() { - 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(); + this.event = { + data: void 0, + event: void 0, + id: void 0, + retry: void 0 + }; } }; module.exports = { diff --git a/.github/actions/javascript/getPreviousVersion/index.js b/.github/actions/javascript/getPreviousVersion/index.js index dc48a205f79b..0343158e5a02 100644 --- a/.github/actions/javascript/getPreviousVersion/index.js +++ b/.github/actions/javascript/getPreviousVersion/index.js @@ -1863,66 +1863,10 @@ var require_request = __commonJS({ return false; } } - /** - * @param {number|null} statusCode - * @param {Buffer[]|null} headers - * @param {import('node:stream').Duplex} socket - * @param {string} [statusText] - */ - onUpgrade(statusCode, headers, socket, statusText = "") { - this.onFinally(); + onUpgrade(statusCode, headers, socket) { assert(!this.aborted); assert(!this.completed); - 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(error2) { - assert(!this.aborted); - assert(this.completed); - if (channels.error.hasSubscribers) { - channels.error.publish({ request: this, error: error2 }); - } - } - /** - * @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: [] }); - } + return this[kHandler].onUpgrade(statusCode, headers, socket); } onComplete(trailers) { this.onFinally(); @@ -1989,11 +1933,7 @@ var require_request = __commonJS({ } else if (typeof val[i] === "object") { throw new InvalidArgumentError(`invalid ${key} header`); } else { - const str = `${val[i]}`; - if (!isValidHeaderValue(str)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } - arr.push(str); + arr.push(`${val[i]}`); } } val = arr; @@ -2005,9 +1945,6 @@ var require_request = __commonJS({ val = ""; } else { val = `${val}`; - if (!isValidHeaderValue(val)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } } if (headerName === "host") { if (request2.host !== null) { @@ -2117,21 +2054,13 @@ var require_dispatcher_base = __commonJS({ var kOnDestroyed = /* @__PURE__ */ Symbol("onDestroyed"); var kOnClosed = /* @__PURE__ */ Symbol("onClosed"); var kInterceptedDispatch = /* @__PURE__ */ Symbol("Intercepted Dispatch"); - var kWebSocketOptions = /* @__PURE__ */ Symbol("webSocketOptions"); var DispatcherBase = class extends Dispatcher { - constructor(opts) { + constructor() { super(); this[kDestroyed] = false; this[kOnDestroyed] = null; this[kClosed] = false; this[kOnClosed] = []; - this[kWebSocketOptions] = opts?.webSocket ?? {}; - } - get webSocketOptions() { - return { - maxFragments: this[kWebSocketOptions].maxFragments ?? 131072, - maxPayloadSize: this[kWebSocketOptions].maxPayloadSize ?? 128 * 1024 * 1024 - }; } get destroyed() { return this[kDestroyed]; @@ -5738,7 +5667,6 @@ var require_client_h1 = __commonJS({ RequestContentLengthMismatchError, ResponseContentLengthMismatchError, RequestAbortedError, - InvalidArgumentError, HeadersTimeoutError, HeadersOverflowError, SocketError, @@ -5785,9 +5713,6 @@ var require_client_h1 = __commonJS({ var FastBuffer = Buffer[Symbol.species]; var addListener = util.addListener; var removeAllListeners = util.removeAllListeners; - var kIdleSocketValidation = /* @__PURE__ */ Symbol("kIdleSocketValidation"); - var kIdleSocketValidationTimeout = /* @__PURE__ */ Symbol("kIdleSocketValidationTimeout"); - var kSocketUsed = /* @__PURE__ */ Symbol("kSocketUsed"); var extractBody; async function lazyllhttp() { const llhttpWasmData = process.env.JEST_WORKER_ID ? require_llhttp_wasm() : void 0; @@ -5950,55 +5875,24 @@ var require_client_h1 = __commonJS({ currentBufferRef = null; } const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr; - if (ret !== constants3.ERROR.OK) { - const body = data.subarray(offset); - if (ret === constants3.ERROR.PAUSED_UPGRADE) { - this.onUpgrade(body); - } else if (ret === constants3.ERROR.PAUSED) { - this.paused = true; - socket.unshift(body); - } else { - throw this.createError(ret, body); + if (ret === constants3.ERROR.PAUSED_UPGRADE) { + this.onUpgrade(data.slice(offset)); + } else if (ret === constants3.ERROR.PAUSED) { + this.paused = true; + socket.unshift(data.slice(offset)); + } else if (ret !== constants3.ERROR.OK) { + const ptr = llhttp.llhttp_get_error_reason(this.ptr); + let message = ""; + if (ptr) { + const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); + message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; } + throw new HTTPParserError(message, constants3.ERROR[ret], data.slice(offset)); } } catch (err) { util.destroy(socket, err); } } - finish() { - assert(currentParser === null); - assert(this.ptr != null); - assert(!this.paused); - const { llhttp } = this; - let ret; - try { - currentParser = this; - ret = llhttp.llhttp_finish(this.ptr); - } finally { - currentParser = null; - } - if (ret === constants3.ERROR.OK) { - return null; - } - if (ret === constants3.ERROR.PAUSED || ret === constants3.ERROR.PAUSED_UPGRADE) { - this.paused = true; - return null; - } - return this.createError(ret, EMPTY_BUF); - } - createError(ret, data) { - const { llhttp, contentLength, bytesRead } = this; - if (contentLength && bytesRead !== parseInt(contentLength, 10)) { - return new ResponseContentLengthMismatchError(); - } - const ptr = llhttp.llhttp_get_error_reason(this.ptr); - let message = ""; - if (ptr) { - const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); - message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; - } - return new HTTPParserError(message, constants3.ERROR[ret], data); - } destroy() { assert(this.ptr != null); assert(currentParser == null); @@ -6018,10 +5912,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6065,7 +5955,7 @@ var require_client_h1 = __commonJS({ } } onUpgrade(head) { - const { upgrade, client, socket, headers, statusCode, statusText } = this; + const { upgrade, client, socket, headers, statusCode } = this; assert(upgrade); assert(client[kSocket] === socket); assert(!socket.destroyed); @@ -6090,10 +5980,9 @@ var require_client_h1 = __commonJS({ client[kQueue][client[kRunningIdx]++] = null; client.emit("disconnect", client[kUrl], [client], new InformationalError("upgrade")); try { - request2.onUpgrade(statusCode, headers, socket, statusText); - } catch (error2) { - util.errorRequest(client, request2, error2); - util.destroy(socket, error2); + request2.onUpgrade(statusCode, headers, socket); + } catch (err) { + util.destroy(socket, err); } client[kResume](); } @@ -6102,10 +5991,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6231,7 +6116,6 @@ var require_client_h1 = __commonJS({ } request2.onComplete(headers); client[kQueue][client[kRunningIdx]++] = null; - socket[kSocketUsed] = true; if (socket[kWriting]) { assert(client[kRunning] === 0); util.destroy(socket, new InformationalError("reset")); @@ -6275,19 +6159,12 @@ var require_client_h1 = __commonJS({ socket[kWriting] = false; socket[kReset] = false; socket[kBlocking] = false; - socket[kIdleSocketValidation] = 0; - socket[kIdleSocketValidationTimeout] = null; - socket[kSocketUsed] = false; socket[kParser] = new Parser(client, socket, llhttpInstance); addListener(socket, "error", function(err) { assert(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID"); const parser = this[kParser]; if (err.code === "ECONNRESET" && parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - this[kError] = parserErr; - this[kClient][kOnError](parserErr); - } + parser.onMessageComplete(); return; } this[kError] = err; @@ -6302,10 +6179,7 @@ var require_client_h1 = __commonJS({ addListener(socket, "end", function() { const parser = this[kParser]; if (parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - util.destroy(this, parserErr); - } + parser.onMessageComplete(); return; } util.destroy(this, new SocketError("other side closed", util.getSocketInfo(this))); @@ -6313,10 +6187,9 @@ var require_client_h1 = __commonJS({ addListener(socket, "close", function() { const client2 = this[kClient]; const parser = this[kParser]; - clearIdleSocketValidation(this); if (parser) { if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { - this[kError] = parser.finish() || this[kError]; + parser.onMessageComplete(); } this[kParser].destroy(); this[kParser] = null; @@ -6365,7 +6238,7 @@ var require_client_h1 = __commonJS({ return socket.destroyed; }, busy(request2) { - if (socket[kWriting] || socket[kReset] || socket[kBlocking] || socket[kIdleSocketValidation] === 1) { + if (socket[kWriting] || socket[kReset] || socket[kBlocking]) { return true; } if (request2) { @@ -6383,23 +6256,6 @@ var require_client_h1 = __commonJS({ } }; } - function clearIdleSocketValidation(socket) { - if (socket[kIdleSocketValidationTimeout]) { - clearImmediate(socket[kIdleSocketValidationTimeout]); - socket[kIdleSocketValidationTimeout] = null; - } - socket[kIdleSocketValidation] = 0; - } - function scheduleIdleSocketValidation(client, socket) { - socket[kIdleSocketValidation] = 1; - socket[kIdleSocketValidationTimeout] = setImmediate(() => { - socket[kIdleSocketValidationTimeout] = null; - socket[kIdleSocketValidation] = 2; - if (client[kSocket] === socket && !socket.destroyed) { - client[kResume](); - } - }); - } function resumeH1(client) { const socket = client[kSocket]; if (socket && !socket.destroyed) { @@ -6412,29 +6268,6 @@ var require_client_h1 = __commonJS({ socket.ref(); socket[kNoRef] = false; } - if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) { - if (socket[kIdleSocketValidation] === 0) { - scheduleIdleSocketValidation(client, socket); - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - if (socket[kIdleSocketValidation] === 1) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - } - if (client[kRunning] === 0) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - } if (client[kSize] === 0) { if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) { socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE); @@ -6465,16 +6298,8 @@ var require_client_h1 = __commonJS({ } body = bodyStream.stream; contentLength = bodyStream.length; - } else if (util.isBlobLike(body) && request2.contentType == null) { - const contentType = body.type; - if (contentType) { - const contentTypeValue = `${contentType}`; - if (!util.isValidHeaderValue(contentTypeValue)) { - util.errorRequest(client, request2, new InvalidArgumentError("invalid content-type header")); - return false; - } - headers.push("content-type", contentTypeValue); - } + } else if (util.isBlobLike(body) && request2.contentType == null && body.type) { + headers.push("content-type", body.type); } if (body && typeof body.read === "function") { body.read(0); @@ -6495,18 +6320,11 @@ var require_client_h1 = __commonJS({ process.emitWarning(new RequestContentLengthMismatchError()); } const socket = client[kSocket]; - clearIdleSocketValidation(socket); - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (request2.upgrade || request2.method === "CONNECT") { - util.destroy(socket, new InformationalError("aborted")); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - util.errorRequest(client, request2, error2 || new RequestAbortedError()); + util.errorRequest(client, request2, err || new RequestAbortedError()); util.destroy(body); util.destroy(socket, new InformationalError("aborted")); }; @@ -6862,7 +6680,6 @@ var require_client_h2 = __commonJS({ "node_modules/undici/lib/dispatcher/client-h2.js"(exports, module) { "use strict"; var assert = __require("node:assert"); - var { errorMonitor } = __require("node:events"); var { pipeline } = __require("node:stream"); var util = require_util(); var { @@ -6923,10 +6740,6 @@ var require_client_h2 = __commonJS({ } return result; } - function parseH2ResponseHeaders(headers) { - const { [HTTP2_HEADER_STATUS]: _statusCode, ...realHeaders } = headers; - return parseH2Headers(realHeaders); - } async function connectH2(client, socket) { client[kSocket] = socket; if (!h2ExperimentalWarned) { @@ -7090,22 +6903,16 @@ var require_client_h2 = __commonJS({ const { hostname, port } = client[kUrl]; headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ""}`; headers[HTTP2_HEADER_METHOD] = method; - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (method === "CONNECT" && stream != null) { - util.destroy(stream, error2 || new RequestAbortedError()); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - error2 = error2 || new RequestAbortedError(); - util.errorRequest(client, request2, error2); + err = err || new RequestAbortedError(); + util.errorRequest(client, request2, err); if (stream != null) { - util.destroy(stream, error2); + util.destroy(stream, err); } - util.destroy(body, error2); + util.destroy(body, err); client[kQueue][client[kRunningIdx]++] = null; client[kResume](); }; @@ -7120,42 +6927,18 @@ var require_client_h2 = __commonJS({ if (method === "CONNECT") { session.ref(); stream = session.request(headers, { endStream: false, signal }); - let upgradeResponseFinished = false; - const onResponse = (headers2) => { - upgradeResponseFinished = true; - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeResponse(Number(headers2[HTTP2_HEADER_STATUS]), headers2, parseH2ResponseHeaders); - }; - const onUpgradeError = (error2) => { - upgradeResponseFinished = true; - stream.off("response", onResponse); - request2.onUpgradeError(error2); - }; - const onReady = () => { - try { - request2.onUpgrade(null, null, stream); - } catch (error2) { - stream.off("response", onResponse); - abort(error2); - return; - } - if (request2.aborted) { - return; - } - stream.off("error", abort); - stream.once(errorMonitor, onUpgradeError); + if (stream.id && !stream.pending) { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; client[kQueue][client[kRunningIdx]++] = null; - }; - stream.once("response", onResponse); - stream.once("error", abort); - ++session[kOpenStreams]; - onReady(); + } else { + stream.once("ready", () => { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; + client[kQueue][client[kRunningIdx]++] = null; + }); + } stream.once("close", () => { - if (!upgradeResponseFinished && request2.completed) { - stream.off("response", onResponse); - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeError(new InformationalError(`HTTP/2: "stream error" received - code ${stream.rstCode}`)); - } session[kOpenStreams] -= 1; if (session[kOpenStreams] === 0) session.unref(); }); @@ -7716,10 +7499,9 @@ var require_client = __commonJS({ autoSelectFamilyAttemptTimeout, // h2 maxConcurrentStreams, - allowH2, - webSocket + allowH2 } = {}) { - super({ webSocket }); + super(); if (keepAlive !== void 0) { throw new InvalidArgumentError("unsupported keepAlive, use pipelining=0 instead"); } @@ -8225,8 +8007,8 @@ var require_pool_base = __commonJS({ var kRemoveClient = /* @__PURE__ */ Symbol("remove client"); var kStats = /* @__PURE__ */ Symbol("stats"); var PoolBase = class extends DispatcherBase { - constructor(opts) { - super(opts); + constructor() { + super(); this[kQueue] = new FixedQueue(); this[kClients] = []; this[kQueued] = 0; @@ -8397,6 +8179,7 @@ var require_pool = __commonJS({ allowH2, ...options } = {}) { + super(); if (connections != null && (!Number.isFinite(connections) || connections < 0)) { throw new InvalidArgumentError("invalid connections"); } @@ -8417,7 +8200,6 @@ var require_pool = __commonJS({ ...connect }); } - super(options); this[kInterceptors] = options.interceptors?.Pool && Array.isArray(options.interceptors.Pool) ? options.interceptors.Pool : []; this[kConnections] = connections || null; this[kUrl] = util.parseOrigin(origin); @@ -8617,6 +8399,7 @@ var require_agent = __commonJS({ } var Agent = class extends DispatcherBase { constructor({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { + super(); if (typeof factory !== "function") { throw new InvalidArgumentError("factory must be a function."); } @@ -8626,7 +8409,6 @@ var require_agent = __commonJS({ if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { throw new InvalidArgumentError("maxRedirections must be a positive number"); } - super(options); if (connect && typeof connect !== "function") { connect = { ...connect }; } @@ -9067,24 +8849,6 @@ var require_retry_handler = __commonJS({ const current = Date.now(); return new Date(retryAfter).getTime() - current; } - function validatePartialResponseContentLength(headers, range, statusCode, retryCount) { - const contentLength = headers["content-length"]; - if (contentLength == null) { - return null; - } - if (!Number.isFinite(range.start) || !Number.isFinite(range.end)) { - return null; - } - const length = Number(contentLength); - const expectedLength = range.end - range.start + 1; - if (!Number.isFinite(length) || length !== expectedLength) { - return new RequestRetryError("Content-Length mismatch", statusCode, { - headers, - data: { count: retryCount } - }); - } - return null; - } var RetryHandler = class _RetryHandler { constructor(opts, handlers) { const { retryOptions, ...dispatchOpts } = opts; @@ -9138,7 +8902,6 @@ var require_retry_handler = __commonJS({ this.end = null; this.etag = null; this.resume = null; - this.headersSent = false; this.handler.onConnect((reason) => { this.aborted = true; if (this.abort) { @@ -9148,17 +8911,6 @@ var require_retry_handler = __commonJS({ } }); } - 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(); @@ -9220,9 +8972,7 @@ var require_retry_handler = __commonJS({ const headers = parseHeaders(rawHeaders); this.retryCount += 1; if (statusCode >= 300) { - if (!this.headersSent && this.retryOpts.statusCodes.includes(statusCode) === false) { - this.headersSent = true; - this.checkpointResponseEnd(headers, resume); + if (this.retryOpts.statusCodes.includes(statusCode) === false) { return this.handler.onHeaders( statusCode, rawHeaders, @@ -9271,21 +9021,9 @@ var require_retry_handler = __commonJS({ ); return false; } - const contentLengthError = validatePartialResponseContentLength(headers, contentRange, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = contentRange; - 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; - } + assert(this.start === start, "content-range mismatch"); + assert(this.end == null || this.end === end, "content-range mismatch"); this.resume = resume; return true; } @@ -9293,7 +9031,6 @@ var require_retry_handler = __commonJS({ if (statusCode === 206) { const range = parseRangeHeader(headers["content-range"]); if (range == null) { - this.headersSent = true; return this.handler.onHeaders( statusCode, rawHeaders, @@ -9301,11 +9038,6 @@ var require_retry_handler = __commonJS({ statusMessage ); } - const contentLengthError = validatePartialResponseContentLength(headers, range, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = range; assert( start != null && Number.isFinite(start), @@ -9325,7 +9057,6 @@ var require_retry_handler = __commonJS({ "invalid content-length" ); this.resume = resume; - this.headersSent = true; this.etag = headers.etag != null ? headers.etag : null; if (this.etag != null && this.etag.startsWith("W/")) { this.etag = null; @@ -9353,7 +9084,7 @@ var require_retry_handler = __commonJS({ return this.handler.onComplete(rawTrailers); } onError(err) { - if (this.aborted || isDisturbed(this.opts.body) || this.headersSent && this.resume == null) { + if (this.aborted || isDisturbed(this.opts.body)) { return this.handler.onError(err); } if (this.retryCount - this.retryCountCheckpoint > 0) { @@ -16152,48 +15883,14 @@ var require_util6 = __commonJS({ for (let i = 0; i < path.length; ++i) { const code = path.charCodeAt(i); if (code < 32 || // exclude CTLs (0-31) - code > 126 || // exclude DEL and non-ascii + code === 127 || // DEL code === 59) { throw new Error("Invalid cookie path"); } } } - function isLetterOrDigit(code) { - return code >= 48 && code <= 57 || // 0-9 - code >= 65 && code <= 90 || // A-Z - code >= 97 && code <= 122; - } function validateCookieDomain(domain) { - if (domain === " ") { - return; - } - if (domain.length > 255) { - throw new Error("Invalid cookie domain"); - } - let labelLength = 0; - for (let i = 0; i < domain.length; ++i) { - const code = domain.charCodeAt(i); - if (code === 46) { - if (labelLength === 0) { - throw new Error("Invalid cookie domain"); - } - if (domain.charCodeAt(i - 1) === 45) { - throw new Error("Invalid cookie domain"); - } - labelLength = 0; - continue; - } - if (labelLength === 0 && !isLetterOrDigit(code)) { - throw new Error("Invalid cookie domain"); - } - if (!isLetterOrDigit(code) && code !== 45) { - throw new Error("Invalid cookie domain"); - } - if (++labelLength > 63) { - throw new Error("Invalid cookie domain"); - } - } - if (labelLength === 0 || domain.charCodeAt(domain.length - 1) === 45) { + if (domain.startsWith("-") || domain.endsWith(".") || domain.endsWith("-")) { throw new Error("Invalid cookie domain"); } } @@ -16276,11 +15973,7 @@ var require_util6 = __commonJS({ throw new Error("Invalid unparsed"); } const [key, ...value] = part.split("="); - const trimmedKey = key.trim(); - const joinedValue = value.join("="); - validateCookieName(trimmedKey); - validateCookieValue(joinedValue); - out.push(`${trimmedKey}=${joinedValue}`); + out.push(`${key.trim()}=${value.join("=")}`); } return out.join("; "); } @@ -16410,14 +16103,18 @@ var require_parse = __commonJS({ } else if (attributeNameLowercase === "httponly") { cookieAttributeList.httpOnly = true; } else if (attributeNameLowercase === "samesite") { + let enforcement = "Default"; const attributeValueLowercase = attributeValue.toLowerCase(); - if (attributeValueLowercase === "none") { - cookieAttributeList.sameSite = "None"; - } else if (attributeValueLowercase === "strict") { - cookieAttributeList.sameSite = "Strict"; - } else if (attributeValueLowercase === "lax") { - cookieAttributeList.sameSite = "Lax"; + if (attributeValueLowercase.includes("none")) { + enforcement = "None"; + } + if (attributeValueLowercase.includes("strict")) { + enforcement = "Strict"; + } + if (attributeValueLowercase.includes("lax")) { + enforcement = "Lax"; } + cookieAttributeList.sameSite = enforcement; } else { cookieAttributeList.unparsed ??= []; cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`); @@ -17239,7 +16936,7 @@ var require_connection = __commonJS({ const secProtocol = response.headersList.get("Sec-WebSocket-Protocol"); if (secProtocol !== null) { const requestProtocols = getDecodeSplit("sec-websocket-protocol", request2.headersList); - if (requestProtocols === null || !requestProtocols.includes(secProtocol)) { + if (!requestProtocols.includes(secProtocol)) { failWebsocketConnection(ws, "Protocol was not set in the opening handshake."); return; } @@ -17345,26 +17042,31 @@ var require_permessage_deflate = __commonJS({ var tail = Buffer.from([0, 0, 255, 255]); var kBuffer = /* @__PURE__ */ Symbol("kBuffer"); var kLength = /* @__PURE__ */ Symbol("kLength"); + var kDefaultMaxDecompressedSize = 4 * 1024 * 1024; var PerMessageDeflate = class { /** @type {import('node:zlib').InflateRaw} */ #inflate; #options = {}; - #maxPayloadSize = 0; + /** @type {number} */ + #maxDecompressedSize; + /** @type {boolean} */ + #aborted = false; + /** @type {Function|null} */ + #currentCallback = null; /** * @param {Map} extensions + * @param {{ maxDecompressedMessageSize?: number }} [options] */ - constructor(extensions, options) { + constructor(extensions, options = {}) { this.#options.serverNoContextTakeover = extensions.has("server_no_context_takeover"); this.#options.serverMaxWindowBits = extensions.get("server_max_window_bits"); - this.#maxPayloadSize = options.maxPayloadSize; + this.#maxDecompressedSize = options.maxDecompressedMessageSize ?? kDefaultMaxDecompressedSize; } - /** - * Decompress a compressed payload. - * @param {Buffer} chunk Compressed data - * @param {boolean} fin Final fragment flag - * @param {Function} callback Callback function - */ decompress(chunk, fin, callback) { + if (this.#aborted) { + callback(new MessageSizeExceededError()); + return; + } if (!this.#inflate) { let windowBits = Z_DEFAULT_WINDOWBITS; if (this.#options.serverMaxWindowBits) { @@ -17383,12 +17085,20 @@ var require_permessage_deflate = __commonJS({ this.#inflate[kBuffer] = []; this.#inflate[kLength] = 0; this.#inflate.on("data", (data) => { + if (this.#aborted) { + return; + } this.#inflate[kLength] += data.length; - if (this.#maxPayloadSize > 0 && this.#inflate[kLength] > this.#maxPayloadSize) { - callback(new MessageSizeExceededError()); + if (this.#inflate[kLength] > this.#maxDecompressedSize) { + this.#aborted = true; this.#inflate.removeAllListeners(); this.#inflate.destroy(); this.#inflate = null; + if (this.#currentCallback) { + const cb = this.#currentCallback; + this.#currentCallback = null; + cb(new MessageSizeExceededError()); + } return; } this.#inflate[kBuffer].push(data); @@ -17398,17 +17108,19 @@ var require_permessage_deflate = __commonJS({ callback(err); }); } + this.#currentCallback = callback; this.#inflate.write(chunk); if (fin) { this.#inflate.write(tail); } this.#inflate.flush(() => { - if (!this.#inflate) { + if (this.#aborted || !this.#inflate) { return; } const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]); this.#inflate[kBuffer].length = 0; this.#inflate[kLength] = 0; + this.#currentCallback = null; callback(null, full); }); } @@ -17439,14 +17151,8 @@ var require_receiver = __commonJS({ var { WebsocketFrameSend } = require_frame(); var { closeWebSocketConnection } = require_connection(); var { PerMessageDeflate } = require_permessage_deflate(); - var { MessageSizeExceededError } = require_errors(); - function failWebsocketConnectionWithCode(ws, code, reason) { - closeWebSocketConnection(ws, code, reason, Buffer.byteLength(reason)); - failWebsocketConnection(ws, reason); - } var ByteParser = class extends Writable { #buffers = []; - #fragmentsBytes = 0; #byteOffset = 0; #loop = false; #state = parserStates.INFO; @@ -17454,21 +17160,18 @@ var require_receiver = __commonJS({ #fragments = []; /** @type {Map} */ #extensions; - /** @type {number} */ - #maxFragments; - /** @type {number} */ - #maxPayloadSize; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {import('./websocket').WebSocket} ws * @param {Map|null} extensions - * @param {{ maxFragments?: number, maxPayloadSize?: number }} [options] + * @param {{ maxDecompressedMessageSize?: number }} [options] */ constructor(ws, extensions, options = {}) { super(); this.ws = ws; this.#extensions = extensions == null ? /* @__PURE__ */ new Map() : extensions; - this.#maxFragments = options.maxFragments ?? 0; - this.#maxPayloadSize = options.maxPayloadSize ?? 0; + this.#options = options; if (this.#extensions.has("permessage-deflate")) { this.#extensions.set("permessage-deflate", new PerMessageDeflate(extensions, options)); } @@ -17483,13 +17186,6 @@ var require_receiver = __commonJS({ this.#loop = true; this.run(callback); } - #validatePayloadLength() { - if (this.#maxPayloadSize > 0 && !isControlFrame(this.#info.opcode) && this.#info.payloadLength + this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, "Payload size exceeds maximum allowed size"); - return false; - } - return true; - } /** * Runs whenever a new chunk is received. * Callback is called whenever there are no more chunks buffering, @@ -17549,9 +17245,6 @@ var require_receiver = __commonJS({ if (payloadLength <= 125) { this.#info.payloadLength = payloadLength; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (payloadLength === 126) { this.#state = parserStates.PAYLOADLENGTH_16; } else if (payloadLength === 127) { @@ -17572,9 +17265,6 @@ var require_receiver = __commonJS({ const buffer = this.consume(2); this.#info.payloadLength = buffer.readUInt16BE(0); this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.PAYLOADLENGTH_64) { if (this.#byteOffset < 8) { return callback(); @@ -17588,9 +17278,6 @@ var require_receiver = __commonJS({ } this.#info.payloadLength = lower; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.READ_DATA) { if (this.#byteOffset < this.#info.payloadLength) { return callback(); @@ -17601,46 +17288,32 @@ var require_receiver = __commonJS({ this.#state = parserStates.INFO; } else { if (!this.#info.compressed) { - if (!this.writeFragments(body)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } + this.#fragments.push(body); if (!this.#info.fragmented && this.#info.fin) { - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); + const fullMessage = Buffer.concat(this.#fragments); + websocketMessageReceived(this.ws, this.#info.binaryType, fullMessage); + this.#fragments.length = 0; } this.#state = parserStates.INFO; } else { - this.#extensions.get("permessage-deflate").decompress( - body, - this.#info.fin, - (error2, data) => { - if (error2) { - const code = error2 instanceof MessageSizeExceededError ? 1009 : 1007; - failWebsocketConnectionWithCode(this.ws, code, error2.message); - return; - } - if (!this.writeFragments(data)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } - if (!this.#info.fin) { - this.#state = parserStates.INFO; - this.#loop = true; - this.run(callback); - return; - } - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); - this.#loop = true; + this.#extensions.get("permessage-deflate").decompress(body, this.#info.fin, (error2, data) => { + if (error2) { + failWebsocketConnection(this.ws, error2.message); + return; + } + this.#fragments.push(data); + if (!this.#info.fin) { this.#state = parserStates.INFO; + this.#loop = true; this.run(callback); + return; } - ); + websocketMessageReceived(this.ws, this.#info.binaryType, Buffer.concat(this.#fragments)); + this.#loop = true; + this.#state = parserStates.INFO; + this.#fragments.length = 0; + this.run(callback); + }); this.#loop = false; break; } @@ -17683,26 +17356,6 @@ var require_receiver = __commonJS({ this.#byteOffset -= n; return buffer; } - writeFragments(fragment) { - if (this.#maxFragments > 0 && this.#fragments.length === this.#maxFragments) { - failWebsocketConnectionWithCode(this.ws, 1008, "Too many message fragments"); - return false; - } - this.#fragmentsBytes += fragment.length; - this.#fragments.push(fragment); - return true; - } - consumeFragments() { - const fragments = this.#fragments; - if (fragments.length === 1) { - this.#fragmentsBytes = 0; - return fragments.shift(); - } - const output = Buffer.concat(fragments, this.#fragmentsBytes); - this.#fragments = []; - this.#fragmentsBytes = 0; - return output; - } parseCloseBody(data) { assert(data.length !== 1); let code; @@ -17914,6 +17567,8 @@ var require_websocket = __commonJS({ #extensions = ""; /** @type {SendQueue} */ #sendQueue; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {string} url * @param {string|string[]} protocols @@ -17957,6 +17612,9 @@ var require_websocket = __commonJS({ throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError"); } this[kWebSocketURL] = new URL(urlRecord.href); + this.#options = { + maxDecompressedMessageSize: options.maxDecompressedMessageSize + }; const client = environmentSettingsObject.settingsObject; this[kController] = establishWebSocketConnection( urlRecord, @@ -18140,13 +17798,7 @@ var require_websocket = __commonJS({ */ #onConnectionEstablished(response, parsedExtensions) { this[kResponse] = response; - const webSocketOptions = this[kController]?.dispatcher?.webSocketOptions; - const maxFragments = webSocketOptions?.maxFragments; - const maxPayloadSize = webSocketOptions?.maxPayloadSize; - const parser = new ByteParser(this, parsedExtensions, { - maxFragments, - maxPayloadSize - }); + const parser = new ByteParser(this, parsedExtensions, this.#options); parser.on("drain", onParserDrain); parser.on("error", onParserError.bind(this)); response.socket.ws = this; @@ -18221,6 +17873,19 @@ var require_websocket = __commonJS({ { key: "headers", converter: webidl.nullableConverter(webidl.converters.HeadersInit) + }, + { + key: "maxDecompressedMessageSize", + converter: webidl.nullableConverter((V) => { + V = webidl.converters["unsigned long long"](V); + if (V <= 0) { + throw webidl.errors.exception({ + header: "WebSocket constructor", + message: "maxDecompressedMessageSize must be greater than 0" + }); + } + return V; + }) } ]); webidl.converters["DOMString or sequence or WebSocketInit"] = function(V) { @@ -18299,40 +17964,6 @@ 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; - } - function isValidLastEventIdBytes(buffer, start) { - for (let i = start; i < buffer.length; i++) { - if (buffer[i] === 0) { - 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; - } var EventSourceStream = class extends Transform { /** * @type {eventSourceSettings} @@ -18352,13 +17983,10 @@ var require_eventsource_stream = __commonJS({ */ eventEndCheck = false; /** - * @type {Buffer[]} + * @type {Buffer} */ - chunks = []; - chunkIndex = 0; + buffer = null; pos = 0; - lineChunkIndex = 0; - linePos = 0; event = { data: void 0, event: void 0, @@ -18389,30 +18017,63 @@ var require_eventsource_stream = __commonJS({ callback(); return; } - this.chunks.push(chunk); + if (this.buffer) { + this.buffer = Buffer.concat([this.buffer, chunk]); + } else { + this.buffer = chunk; + } if (this.checkBOM) { - if (this.handleBOM()) { - callback(); - return; + 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; } } - while (this.hasCurrentByte()) { - const byte = this.currentByte(); + while (this.pos < this.buffer.length) { if (this.eventEndCheck) { if (this.crlfCheck) { - if (byte === LF) { + if (this.buffer[this.pos] === LF) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.crlfCheck = false; - this.consumeCurrentByte(); continue; } this.crlfCheck = false; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.consumeCurrentByte(); - if (this.hasPendingEvent()) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; + if (this.event.data !== void 0 || this.event.event || this.event.id || this.event.retry) { this.processEvent(this.event); } this.clearEvent(); @@ -18421,16 +18082,17 @@ var require_eventsource_stream = __commonJS({ this.eventEndCheck = false; continue; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.parseLine(this.readLine(), this.event); - this.consumeCurrentByte(); + this.parseLine(this.buffer.subarray(0, this.pos), this.event); + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.eventEndCheck = true; continue; } - this.advanceCursor(); + this.pos++; } callback(); } @@ -18446,42 +18108,43 @@ var require_eventsource_stream = __commonJS({ if (colonPosition === 0) { return; } - let fieldLength = line.length; - let valueStart = line.length; + let field = ""; + let value = ""; if (colonPosition !== -1) { - fieldLength = colonPosition; - valueStart = colonPosition + 1; + field = line.subarray(0, colonPosition).toString("utf8"); + let valueStart = colonPosition + 1; if (line[valueStart] === SPACE) { ++valueStart; } + value = line.subarray(valueStart).toString("utf8"); + } else { + field = line.toString("utf8"); + value = ""; } - if (isFieldName(line, fieldLength, DATA)) { - const value = line.toString("utf8", valueStart); - if (event.data === void 0) { - event.data = value; - } else { - event.data += ` + switch (field) { + case "data": + if (event[field] === void 0) { + event[field] = value; + } else { + event[field] += ` ${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; - } + } + 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; } } /** @@ -18506,120 +18169,12 @@ ${value}`; } } clearEvent() { - 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(); + this.event = { + data: void 0, + event: void 0, + id: void 0, + retry: void 0 + }; } }; module.exports = { diff --git a/.github/actions/javascript/getPullRequestDetails/index.js b/.github/actions/javascript/getPullRequestDetails/index.js index b7443787fc9b..78b36a004849 100644 --- a/.github/actions/javascript/getPullRequestDetails/index.js +++ b/.github/actions/javascript/getPullRequestDetails/index.js @@ -1863,66 +1863,10 @@ var require_request = __commonJS({ return false; } } - /** - * @param {number|null} statusCode - * @param {Buffer[]|null} headers - * @param {import('node:stream').Duplex} socket - * @param {string} [statusText] - */ - onUpgrade(statusCode, headers, socket, statusText = "") { - this.onFinally(); + onUpgrade(statusCode, headers, socket) { assert(!this.aborted); assert(!this.completed); - 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(error2) { - assert(!this.aborted); - assert(this.completed); - if (channels.error.hasSubscribers) { - channels.error.publish({ request: this, error: error2 }); - } - } - /** - * @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: [] }); - } + return this[kHandler].onUpgrade(statusCode, headers, socket); } onComplete(trailers) { this.onFinally(); @@ -1989,11 +1933,7 @@ var require_request = __commonJS({ } else if (typeof val[i] === "object") { throw new InvalidArgumentError(`invalid ${key} header`); } else { - const str = `${val[i]}`; - if (!isValidHeaderValue(str)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } - arr.push(str); + arr.push(`${val[i]}`); } } val = arr; @@ -2005,9 +1945,6 @@ var require_request = __commonJS({ val = ""; } else { val = `${val}`; - if (!isValidHeaderValue(val)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } } if (headerName === "host") { if (request2.host !== null) { @@ -2117,21 +2054,13 @@ var require_dispatcher_base = __commonJS({ var kOnDestroyed = /* @__PURE__ */ Symbol("onDestroyed"); var kOnClosed = /* @__PURE__ */ Symbol("onClosed"); var kInterceptedDispatch = /* @__PURE__ */ Symbol("Intercepted Dispatch"); - var kWebSocketOptions = /* @__PURE__ */ Symbol("webSocketOptions"); var DispatcherBase = class extends Dispatcher { - constructor(opts) { + constructor() { super(); this[kDestroyed] = false; this[kOnDestroyed] = null; this[kClosed] = false; this[kOnClosed] = []; - this[kWebSocketOptions] = opts?.webSocket ?? {}; - } - get webSocketOptions() { - return { - maxFragments: this[kWebSocketOptions].maxFragments ?? 131072, - maxPayloadSize: this[kWebSocketOptions].maxPayloadSize ?? 128 * 1024 * 1024 - }; } get destroyed() { return this[kDestroyed]; @@ -5738,7 +5667,6 @@ var require_client_h1 = __commonJS({ RequestContentLengthMismatchError, ResponseContentLengthMismatchError, RequestAbortedError, - InvalidArgumentError, HeadersTimeoutError, HeadersOverflowError, SocketError, @@ -5785,9 +5713,6 @@ var require_client_h1 = __commonJS({ var FastBuffer = Buffer[Symbol.species]; var addListener = util.addListener; var removeAllListeners = util.removeAllListeners; - var kIdleSocketValidation = /* @__PURE__ */ Symbol("kIdleSocketValidation"); - var kIdleSocketValidationTimeout = /* @__PURE__ */ Symbol("kIdleSocketValidationTimeout"); - var kSocketUsed = /* @__PURE__ */ Symbol("kSocketUsed"); var extractBody; async function lazyllhttp() { const llhttpWasmData = process.env.JEST_WORKER_ID ? require_llhttp_wasm() : void 0; @@ -5950,55 +5875,24 @@ var require_client_h1 = __commonJS({ currentBufferRef = null; } const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr; - if (ret !== constants3.ERROR.OK) { - const body = data.subarray(offset); - if (ret === constants3.ERROR.PAUSED_UPGRADE) { - this.onUpgrade(body); - } else if (ret === constants3.ERROR.PAUSED) { - this.paused = true; - socket.unshift(body); - } else { - throw this.createError(ret, body); + if (ret === constants3.ERROR.PAUSED_UPGRADE) { + this.onUpgrade(data.slice(offset)); + } else if (ret === constants3.ERROR.PAUSED) { + this.paused = true; + socket.unshift(data.slice(offset)); + } else if (ret !== constants3.ERROR.OK) { + const ptr = llhttp.llhttp_get_error_reason(this.ptr); + let message = ""; + if (ptr) { + const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); + message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; } + throw new HTTPParserError(message, constants3.ERROR[ret], data.slice(offset)); } } catch (err) { util.destroy(socket, err); } } - finish() { - assert(currentParser === null); - assert(this.ptr != null); - assert(!this.paused); - const { llhttp } = this; - let ret; - try { - currentParser = this; - ret = llhttp.llhttp_finish(this.ptr); - } finally { - currentParser = null; - } - if (ret === constants3.ERROR.OK) { - return null; - } - if (ret === constants3.ERROR.PAUSED || ret === constants3.ERROR.PAUSED_UPGRADE) { - this.paused = true; - return null; - } - return this.createError(ret, EMPTY_BUF); - } - createError(ret, data) { - const { llhttp, contentLength, bytesRead } = this; - if (contentLength && bytesRead !== parseInt(contentLength, 10)) { - return new ResponseContentLengthMismatchError(); - } - const ptr = llhttp.llhttp_get_error_reason(this.ptr); - let message = ""; - if (ptr) { - const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); - message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; - } - return new HTTPParserError(message, constants3.ERROR[ret], data); - } destroy() { assert(this.ptr != null); assert(currentParser == null); @@ -6018,10 +5912,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6065,7 +5955,7 @@ var require_client_h1 = __commonJS({ } } onUpgrade(head) { - const { upgrade, client, socket, headers, statusCode, statusText } = this; + const { upgrade, client, socket, headers, statusCode } = this; assert(upgrade); assert(client[kSocket] === socket); assert(!socket.destroyed); @@ -6090,10 +5980,9 @@ var require_client_h1 = __commonJS({ client[kQueue][client[kRunningIdx]++] = null; client.emit("disconnect", client[kUrl], [client], new InformationalError("upgrade")); try { - request2.onUpgrade(statusCode, headers, socket, statusText); - } catch (error2) { - util.errorRequest(client, request2, error2); - util.destroy(socket, error2); + request2.onUpgrade(statusCode, headers, socket); + } catch (err) { + util.destroy(socket, err); } client[kResume](); } @@ -6102,10 +5991,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6231,7 +6116,6 @@ var require_client_h1 = __commonJS({ } request2.onComplete(headers); client[kQueue][client[kRunningIdx]++] = null; - socket[kSocketUsed] = true; if (socket[kWriting]) { assert(client[kRunning] === 0); util.destroy(socket, new InformationalError("reset")); @@ -6275,19 +6159,12 @@ var require_client_h1 = __commonJS({ socket[kWriting] = false; socket[kReset] = false; socket[kBlocking] = false; - socket[kIdleSocketValidation] = 0; - socket[kIdleSocketValidationTimeout] = null; - socket[kSocketUsed] = false; socket[kParser] = new Parser(client, socket, llhttpInstance); addListener(socket, "error", function(err) { assert(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID"); const parser = this[kParser]; if (err.code === "ECONNRESET" && parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - this[kError] = parserErr; - this[kClient][kOnError](parserErr); - } + parser.onMessageComplete(); return; } this[kError] = err; @@ -6302,10 +6179,7 @@ var require_client_h1 = __commonJS({ addListener(socket, "end", function() { const parser = this[kParser]; if (parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - util.destroy(this, parserErr); - } + parser.onMessageComplete(); return; } util.destroy(this, new SocketError("other side closed", util.getSocketInfo(this))); @@ -6313,10 +6187,9 @@ var require_client_h1 = __commonJS({ addListener(socket, "close", function() { const client2 = this[kClient]; const parser = this[kParser]; - clearIdleSocketValidation(this); if (parser) { if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { - this[kError] = parser.finish() || this[kError]; + parser.onMessageComplete(); } this[kParser].destroy(); this[kParser] = null; @@ -6365,7 +6238,7 @@ var require_client_h1 = __commonJS({ return socket.destroyed; }, busy(request2) { - if (socket[kWriting] || socket[kReset] || socket[kBlocking] || socket[kIdleSocketValidation] === 1) { + if (socket[kWriting] || socket[kReset] || socket[kBlocking]) { return true; } if (request2) { @@ -6383,23 +6256,6 @@ var require_client_h1 = __commonJS({ } }; } - function clearIdleSocketValidation(socket) { - if (socket[kIdleSocketValidationTimeout]) { - clearImmediate(socket[kIdleSocketValidationTimeout]); - socket[kIdleSocketValidationTimeout] = null; - } - socket[kIdleSocketValidation] = 0; - } - function scheduleIdleSocketValidation(client, socket) { - socket[kIdleSocketValidation] = 1; - socket[kIdleSocketValidationTimeout] = setImmediate(() => { - socket[kIdleSocketValidationTimeout] = null; - socket[kIdleSocketValidation] = 2; - if (client[kSocket] === socket && !socket.destroyed) { - client[kResume](); - } - }); - } function resumeH1(client) { const socket = client[kSocket]; if (socket && !socket.destroyed) { @@ -6412,29 +6268,6 @@ var require_client_h1 = __commonJS({ socket.ref(); socket[kNoRef] = false; } - if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) { - if (socket[kIdleSocketValidation] === 0) { - scheduleIdleSocketValidation(client, socket); - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - if (socket[kIdleSocketValidation] === 1) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - } - if (client[kRunning] === 0) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - } if (client[kSize] === 0) { if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) { socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE); @@ -6465,16 +6298,8 @@ var require_client_h1 = __commonJS({ } body = bodyStream.stream; contentLength = bodyStream.length; - } else if (util.isBlobLike(body) && request2.contentType == null) { - const contentType = body.type; - if (contentType) { - const contentTypeValue = `${contentType}`; - if (!util.isValidHeaderValue(contentTypeValue)) { - util.errorRequest(client, request2, new InvalidArgumentError("invalid content-type header")); - return false; - } - headers.push("content-type", contentTypeValue); - } + } else if (util.isBlobLike(body) && request2.contentType == null && body.type) { + headers.push("content-type", body.type); } if (body && typeof body.read === "function") { body.read(0); @@ -6495,18 +6320,11 @@ var require_client_h1 = __commonJS({ process.emitWarning(new RequestContentLengthMismatchError()); } const socket = client[kSocket]; - clearIdleSocketValidation(socket); - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (request2.upgrade || request2.method === "CONNECT") { - util.destroy(socket, new InformationalError("aborted")); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - util.errorRequest(client, request2, error2 || new RequestAbortedError()); + util.errorRequest(client, request2, err || new RequestAbortedError()); util.destroy(body); util.destroy(socket, new InformationalError("aborted")); }; @@ -6862,7 +6680,6 @@ var require_client_h2 = __commonJS({ "node_modules/undici/lib/dispatcher/client-h2.js"(exports, module) { "use strict"; var assert = __require("node:assert"); - var { errorMonitor } = __require("node:events"); var { pipeline } = __require("node:stream"); var util = require_util(); var { @@ -6923,10 +6740,6 @@ var require_client_h2 = __commonJS({ } return result; } - function parseH2ResponseHeaders(headers) { - const { [HTTP2_HEADER_STATUS]: _statusCode, ...realHeaders } = headers; - return parseH2Headers(realHeaders); - } async function connectH2(client, socket) { client[kSocket] = socket; if (!h2ExperimentalWarned) { @@ -7090,22 +6903,16 @@ var require_client_h2 = __commonJS({ const { hostname, port } = client[kUrl]; headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ""}`; headers[HTTP2_HEADER_METHOD] = method; - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (method === "CONNECT" && stream != null) { - util.destroy(stream, error2 || new RequestAbortedError()); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - error2 = error2 || new RequestAbortedError(); - util.errorRequest(client, request2, error2); + err = err || new RequestAbortedError(); + util.errorRequest(client, request2, err); if (stream != null) { - util.destroy(stream, error2); + util.destroy(stream, err); } - util.destroy(body, error2); + util.destroy(body, err); client[kQueue][client[kRunningIdx]++] = null; client[kResume](); }; @@ -7120,42 +6927,18 @@ var require_client_h2 = __commonJS({ if (method === "CONNECT") { session.ref(); stream = session.request(headers, { endStream: false, signal }); - let upgradeResponseFinished = false; - const onResponse = (headers2) => { - upgradeResponseFinished = true; - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeResponse(Number(headers2[HTTP2_HEADER_STATUS]), headers2, parseH2ResponseHeaders); - }; - const onUpgradeError = (error2) => { - upgradeResponseFinished = true; - stream.off("response", onResponse); - request2.onUpgradeError(error2); - }; - const onReady = () => { - try { - request2.onUpgrade(null, null, stream); - } catch (error2) { - stream.off("response", onResponse); - abort(error2); - return; - } - if (request2.aborted) { - return; - } - stream.off("error", abort); - stream.once(errorMonitor, onUpgradeError); + if (stream.id && !stream.pending) { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; client[kQueue][client[kRunningIdx]++] = null; - }; - stream.once("response", onResponse); - stream.once("error", abort); - ++session[kOpenStreams]; - onReady(); + } else { + stream.once("ready", () => { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; + client[kQueue][client[kRunningIdx]++] = null; + }); + } stream.once("close", () => { - if (!upgradeResponseFinished && request2.completed) { - stream.off("response", onResponse); - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeError(new InformationalError(`HTTP/2: "stream error" received - code ${stream.rstCode}`)); - } session[kOpenStreams] -= 1; if (session[kOpenStreams] === 0) session.unref(); }); @@ -7716,10 +7499,9 @@ var require_client = __commonJS({ autoSelectFamilyAttemptTimeout, // h2 maxConcurrentStreams, - allowH2, - webSocket + allowH2 } = {}) { - super({ webSocket }); + super(); if (keepAlive !== void 0) { throw new InvalidArgumentError("unsupported keepAlive, use pipelining=0 instead"); } @@ -8225,8 +8007,8 @@ var require_pool_base = __commonJS({ var kRemoveClient = /* @__PURE__ */ Symbol("remove client"); var kStats = /* @__PURE__ */ Symbol("stats"); var PoolBase = class extends DispatcherBase { - constructor(opts) { - super(opts); + constructor() { + super(); this[kQueue] = new FixedQueue(); this[kClients] = []; this[kQueued] = 0; @@ -8397,6 +8179,7 @@ var require_pool = __commonJS({ allowH2, ...options } = {}) { + super(); if (connections != null && (!Number.isFinite(connections) || connections < 0)) { throw new InvalidArgumentError("invalid connections"); } @@ -8417,7 +8200,6 @@ var require_pool = __commonJS({ ...connect }); } - super(options); this[kInterceptors] = options.interceptors?.Pool && Array.isArray(options.interceptors.Pool) ? options.interceptors.Pool : []; this[kConnections] = connections || null; this[kUrl] = util.parseOrigin(origin); @@ -8617,6 +8399,7 @@ var require_agent = __commonJS({ } var Agent = class extends DispatcherBase { constructor({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { + super(); if (typeof factory !== "function") { throw new InvalidArgumentError("factory must be a function."); } @@ -8626,7 +8409,6 @@ var require_agent = __commonJS({ if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { throw new InvalidArgumentError("maxRedirections must be a positive number"); } - super(options); if (connect && typeof connect !== "function") { connect = { ...connect }; } @@ -9067,24 +8849,6 @@ var require_retry_handler = __commonJS({ const current = Date.now(); return new Date(retryAfter).getTime() - current; } - function validatePartialResponseContentLength(headers, range, statusCode, retryCount) { - const contentLength = headers["content-length"]; - if (contentLength == null) { - return null; - } - if (!Number.isFinite(range.start) || !Number.isFinite(range.end)) { - return null; - } - const length = Number(contentLength); - const expectedLength = range.end - range.start + 1; - if (!Number.isFinite(length) || length !== expectedLength) { - return new RequestRetryError("Content-Length mismatch", statusCode, { - headers, - data: { count: retryCount } - }); - } - return null; - } var RetryHandler = class _RetryHandler { constructor(opts, handlers) { const { retryOptions, ...dispatchOpts } = opts; @@ -9138,7 +8902,6 @@ var require_retry_handler = __commonJS({ this.end = null; this.etag = null; this.resume = null; - this.headersSent = false; this.handler.onConnect((reason) => { this.aborted = true; if (this.abort) { @@ -9148,17 +8911,6 @@ var require_retry_handler = __commonJS({ } }); } - 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(); @@ -9220,9 +8972,7 @@ var require_retry_handler = __commonJS({ const headers = parseHeaders(rawHeaders); this.retryCount += 1; if (statusCode >= 300) { - if (!this.headersSent && this.retryOpts.statusCodes.includes(statusCode) === false) { - this.headersSent = true; - this.checkpointResponseEnd(headers, resume); + if (this.retryOpts.statusCodes.includes(statusCode) === false) { return this.handler.onHeaders( statusCode, rawHeaders, @@ -9271,21 +9021,9 @@ var require_retry_handler = __commonJS({ ); return false; } - const contentLengthError = validatePartialResponseContentLength(headers, contentRange, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = contentRange; - 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; - } + assert(this.start === start, "content-range mismatch"); + assert(this.end == null || this.end === end, "content-range mismatch"); this.resume = resume; return true; } @@ -9293,7 +9031,6 @@ var require_retry_handler = __commonJS({ if (statusCode === 206) { const range = parseRangeHeader(headers["content-range"]); if (range == null) { - this.headersSent = true; return this.handler.onHeaders( statusCode, rawHeaders, @@ -9301,11 +9038,6 @@ var require_retry_handler = __commonJS({ statusMessage ); } - const contentLengthError = validatePartialResponseContentLength(headers, range, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = range; assert( start != null && Number.isFinite(start), @@ -9325,7 +9057,6 @@ var require_retry_handler = __commonJS({ "invalid content-length" ); this.resume = resume; - this.headersSent = true; this.etag = headers.etag != null ? headers.etag : null; if (this.etag != null && this.etag.startsWith("W/")) { this.etag = null; @@ -9353,7 +9084,7 @@ var require_retry_handler = __commonJS({ return this.handler.onComplete(rawTrailers); } onError(err) { - if (this.aborted || isDisturbed(this.opts.body) || this.headersSent && this.resume == null) { + if (this.aborted || isDisturbed(this.opts.body)) { return this.handler.onError(err); } if (this.retryCount - this.retryCountCheckpoint > 0) { @@ -16152,48 +15883,14 @@ var require_util6 = __commonJS({ for (let i = 0; i < path.length; ++i) { const code = path.charCodeAt(i); if (code < 32 || // exclude CTLs (0-31) - code > 126 || // exclude DEL and non-ascii + code === 127 || // DEL code === 59) { throw new Error("Invalid cookie path"); } } } - function isLetterOrDigit(code) { - return code >= 48 && code <= 57 || // 0-9 - code >= 65 && code <= 90 || // A-Z - code >= 97 && code <= 122; - } function validateCookieDomain(domain) { - if (domain === " ") { - return; - } - if (domain.length > 255) { - throw new Error("Invalid cookie domain"); - } - let labelLength = 0; - for (let i = 0; i < domain.length; ++i) { - const code = domain.charCodeAt(i); - if (code === 46) { - if (labelLength === 0) { - throw new Error("Invalid cookie domain"); - } - if (domain.charCodeAt(i - 1) === 45) { - throw new Error("Invalid cookie domain"); - } - labelLength = 0; - continue; - } - if (labelLength === 0 && !isLetterOrDigit(code)) { - throw new Error("Invalid cookie domain"); - } - if (!isLetterOrDigit(code) && code !== 45) { - throw new Error("Invalid cookie domain"); - } - if (++labelLength > 63) { - throw new Error("Invalid cookie domain"); - } - } - if (labelLength === 0 || domain.charCodeAt(domain.length - 1) === 45) { + if (domain.startsWith("-") || domain.endsWith(".") || domain.endsWith("-")) { throw new Error("Invalid cookie domain"); } } @@ -16276,11 +15973,7 @@ var require_util6 = __commonJS({ throw new Error("Invalid unparsed"); } const [key, ...value] = part.split("="); - const trimmedKey = key.trim(); - const joinedValue = value.join("="); - validateCookieName(trimmedKey); - validateCookieValue(joinedValue); - out.push(`${trimmedKey}=${joinedValue}`); + out.push(`${key.trim()}=${value.join("=")}`); } return out.join("; "); } @@ -16410,14 +16103,18 @@ var require_parse = __commonJS({ } else if (attributeNameLowercase === "httponly") { cookieAttributeList.httpOnly = true; } else if (attributeNameLowercase === "samesite") { + let enforcement = "Default"; const attributeValueLowercase = attributeValue.toLowerCase(); - if (attributeValueLowercase === "none") { - cookieAttributeList.sameSite = "None"; - } else if (attributeValueLowercase === "strict") { - cookieAttributeList.sameSite = "Strict"; - } else if (attributeValueLowercase === "lax") { - cookieAttributeList.sameSite = "Lax"; + if (attributeValueLowercase.includes("none")) { + enforcement = "None"; + } + if (attributeValueLowercase.includes("strict")) { + enforcement = "Strict"; + } + if (attributeValueLowercase.includes("lax")) { + enforcement = "Lax"; } + cookieAttributeList.sameSite = enforcement; } else { cookieAttributeList.unparsed ??= []; cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`); @@ -17239,7 +16936,7 @@ var require_connection = __commonJS({ const secProtocol = response.headersList.get("Sec-WebSocket-Protocol"); if (secProtocol !== null) { const requestProtocols = getDecodeSplit("sec-websocket-protocol", request2.headersList); - if (requestProtocols === null || !requestProtocols.includes(secProtocol)) { + if (!requestProtocols.includes(secProtocol)) { failWebsocketConnection(ws, "Protocol was not set in the opening handshake."); return; } @@ -17345,26 +17042,31 @@ var require_permessage_deflate = __commonJS({ var tail = Buffer.from([0, 0, 255, 255]); var kBuffer = /* @__PURE__ */ Symbol("kBuffer"); var kLength = /* @__PURE__ */ Symbol("kLength"); + var kDefaultMaxDecompressedSize = 4 * 1024 * 1024; var PerMessageDeflate = class { /** @type {import('node:zlib').InflateRaw} */ #inflate; #options = {}; - #maxPayloadSize = 0; + /** @type {number} */ + #maxDecompressedSize; + /** @type {boolean} */ + #aborted = false; + /** @type {Function|null} */ + #currentCallback = null; /** * @param {Map} extensions + * @param {{ maxDecompressedMessageSize?: number }} [options] */ - constructor(extensions, options) { + constructor(extensions, options = {}) { this.#options.serverNoContextTakeover = extensions.has("server_no_context_takeover"); this.#options.serverMaxWindowBits = extensions.get("server_max_window_bits"); - this.#maxPayloadSize = options.maxPayloadSize; + this.#maxDecompressedSize = options.maxDecompressedMessageSize ?? kDefaultMaxDecompressedSize; } - /** - * Decompress a compressed payload. - * @param {Buffer} chunk Compressed data - * @param {boolean} fin Final fragment flag - * @param {Function} callback Callback function - */ decompress(chunk, fin, callback) { + if (this.#aborted) { + callback(new MessageSizeExceededError()); + return; + } if (!this.#inflate) { let windowBits = Z_DEFAULT_WINDOWBITS; if (this.#options.serverMaxWindowBits) { @@ -17383,12 +17085,20 @@ var require_permessage_deflate = __commonJS({ this.#inflate[kBuffer] = []; this.#inflate[kLength] = 0; this.#inflate.on("data", (data) => { + if (this.#aborted) { + return; + } this.#inflate[kLength] += data.length; - if (this.#maxPayloadSize > 0 && this.#inflate[kLength] > this.#maxPayloadSize) { - callback(new MessageSizeExceededError()); + if (this.#inflate[kLength] > this.#maxDecompressedSize) { + this.#aborted = true; this.#inflate.removeAllListeners(); this.#inflate.destroy(); this.#inflate = null; + if (this.#currentCallback) { + const cb = this.#currentCallback; + this.#currentCallback = null; + cb(new MessageSizeExceededError()); + } return; } this.#inflate[kBuffer].push(data); @@ -17398,17 +17108,19 @@ var require_permessage_deflate = __commonJS({ callback(err); }); } + this.#currentCallback = callback; this.#inflate.write(chunk); if (fin) { this.#inflate.write(tail); } this.#inflate.flush(() => { - if (!this.#inflate) { + if (this.#aborted || !this.#inflate) { return; } const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]); this.#inflate[kBuffer].length = 0; this.#inflate[kLength] = 0; + this.#currentCallback = null; callback(null, full); }); } @@ -17439,14 +17151,8 @@ var require_receiver = __commonJS({ var { WebsocketFrameSend } = require_frame(); var { closeWebSocketConnection } = require_connection(); var { PerMessageDeflate } = require_permessage_deflate(); - var { MessageSizeExceededError } = require_errors(); - function failWebsocketConnectionWithCode(ws, code, reason) { - closeWebSocketConnection(ws, code, reason, Buffer.byteLength(reason)); - failWebsocketConnection(ws, reason); - } var ByteParser = class extends Writable { #buffers = []; - #fragmentsBytes = 0; #byteOffset = 0; #loop = false; #state = parserStates.INFO; @@ -17454,21 +17160,18 @@ var require_receiver = __commonJS({ #fragments = []; /** @type {Map} */ #extensions; - /** @type {number} */ - #maxFragments; - /** @type {number} */ - #maxPayloadSize; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {import('./websocket').WebSocket} ws * @param {Map|null} extensions - * @param {{ maxFragments?: number, maxPayloadSize?: number }} [options] + * @param {{ maxDecompressedMessageSize?: number }} [options] */ constructor(ws, extensions, options = {}) { super(); this.ws = ws; this.#extensions = extensions == null ? /* @__PURE__ */ new Map() : extensions; - this.#maxFragments = options.maxFragments ?? 0; - this.#maxPayloadSize = options.maxPayloadSize ?? 0; + this.#options = options; if (this.#extensions.has("permessage-deflate")) { this.#extensions.set("permessage-deflate", new PerMessageDeflate(extensions, options)); } @@ -17483,13 +17186,6 @@ var require_receiver = __commonJS({ this.#loop = true; this.run(callback); } - #validatePayloadLength() { - if (this.#maxPayloadSize > 0 && !isControlFrame(this.#info.opcode) && this.#info.payloadLength + this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, "Payload size exceeds maximum allowed size"); - return false; - } - return true; - } /** * Runs whenever a new chunk is received. * Callback is called whenever there are no more chunks buffering, @@ -17549,9 +17245,6 @@ var require_receiver = __commonJS({ if (payloadLength <= 125) { this.#info.payloadLength = payloadLength; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (payloadLength === 126) { this.#state = parserStates.PAYLOADLENGTH_16; } else if (payloadLength === 127) { @@ -17572,9 +17265,6 @@ var require_receiver = __commonJS({ const buffer = this.consume(2); this.#info.payloadLength = buffer.readUInt16BE(0); this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.PAYLOADLENGTH_64) { if (this.#byteOffset < 8) { return callback(); @@ -17588,9 +17278,6 @@ var require_receiver = __commonJS({ } this.#info.payloadLength = lower; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.READ_DATA) { if (this.#byteOffset < this.#info.payloadLength) { return callback(); @@ -17601,46 +17288,32 @@ var require_receiver = __commonJS({ this.#state = parserStates.INFO; } else { if (!this.#info.compressed) { - if (!this.writeFragments(body)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } + this.#fragments.push(body); if (!this.#info.fragmented && this.#info.fin) { - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); + const fullMessage = Buffer.concat(this.#fragments); + websocketMessageReceived(this.ws, this.#info.binaryType, fullMessage); + this.#fragments.length = 0; } this.#state = parserStates.INFO; } else { - this.#extensions.get("permessage-deflate").decompress( - body, - this.#info.fin, - (error2, data) => { - if (error2) { - const code = error2 instanceof MessageSizeExceededError ? 1009 : 1007; - failWebsocketConnectionWithCode(this.ws, code, error2.message); - return; - } - if (!this.writeFragments(data)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } - if (!this.#info.fin) { - this.#state = parserStates.INFO; - this.#loop = true; - this.run(callback); - return; - } - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); - this.#loop = true; + this.#extensions.get("permessage-deflate").decompress(body, this.#info.fin, (error2, data) => { + if (error2) { + failWebsocketConnection(this.ws, error2.message); + return; + } + this.#fragments.push(data); + if (!this.#info.fin) { this.#state = parserStates.INFO; + this.#loop = true; this.run(callback); + return; } - ); + websocketMessageReceived(this.ws, this.#info.binaryType, Buffer.concat(this.#fragments)); + this.#loop = true; + this.#state = parserStates.INFO; + this.#fragments.length = 0; + this.run(callback); + }); this.#loop = false; break; } @@ -17683,26 +17356,6 @@ var require_receiver = __commonJS({ this.#byteOffset -= n; return buffer; } - writeFragments(fragment) { - if (this.#maxFragments > 0 && this.#fragments.length === this.#maxFragments) { - failWebsocketConnectionWithCode(this.ws, 1008, "Too many message fragments"); - return false; - } - this.#fragmentsBytes += fragment.length; - this.#fragments.push(fragment); - return true; - } - consumeFragments() { - const fragments = this.#fragments; - if (fragments.length === 1) { - this.#fragmentsBytes = 0; - return fragments.shift(); - } - const output = Buffer.concat(fragments, this.#fragmentsBytes); - this.#fragments = []; - this.#fragmentsBytes = 0; - return output; - } parseCloseBody(data) { assert(data.length !== 1); let code; @@ -17914,6 +17567,8 @@ var require_websocket = __commonJS({ #extensions = ""; /** @type {SendQueue} */ #sendQueue; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {string} url * @param {string|string[]} protocols @@ -17957,6 +17612,9 @@ var require_websocket = __commonJS({ throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError"); } this[kWebSocketURL] = new URL(urlRecord.href); + this.#options = { + maxDecompressedMessageSize: options.maxDecompressedMessageSize + }; const client = environmentSettingsObject.settingsObject; this[kController] = establishWebSocketConnection( urlRecord, @@ -18140,13 +17798,7 @@ var require_websocket = __commonJS({ */ #onConnectionEstablished(response, parsedExtensions) { this[kResponse] = response; - const webSocketOptions = this[kController]?.dispatcher?.webSocketOptions; - const maxFragments = webSocketOptions?.maxFragments; - const maxPayloadSize = webSocketOptions?.maxPayloadSize; - const parser = new ByteParser(this, parsedExtensions, { - maxFragments, - maxPayloadSize - }); + const parser = new ByteParser(this, parsedExtensions, this.#options); parser.on("drain", onParserDrain); parser.on("error", onParserError.bind(this)); response.socket.ws = this; @@ -18221,6 +17873,19 @@ var require_websocket = __commonJS({ { key: "headers", converter: webidl.nullableConverter(webidl.converters.HeadersInit) + }, + { + key: "maxDecompressedMessageSize", + converter: webidl.nullableConverter((V) => { + V = webidl.converters["unsigned long long"](V); + if (V <= 0) { + throw webidl.errors.exception({ + header: "WebSocket constructor", + message: "maxDecompressedMessageSize must be greater than 0" + }); + } + return V; + }) } ]); webidl.converters["DOMString or sequence or WebSocketInit"] = function(V) { @@ -18299,40 +17964,6 @@ 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; - } - function isValidLastEventIdBytes(buffer, start) { - for (let i = start; i < buffer.length; i++) { - if (buffer[i] === 0) { - 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; - } var EventSourceStream = class extends Transform { /** * @type {eventSourceSettings} @@ -18352,13 +17983,10 @@ var require_eventsource_stream = __commonJS({ */ eventEndCheck = false; /** - * @type {Buffer[]} + * @type {Buffer} */ - chunks = []; - chunkIndex = 0; + buffer = null; pos = 0; - lineChunkIndex = 0; - linePos = 0; event = { data: void 0, event: void 0, @@ -18389,30 +18017,63 @@ var require_eventsource_stream = __commonJS({ callback(); return; } - this.chunks.push(chunk); + if (this.buffer) { + this.buffer = Buffer.concat([this.buffer, chunk]); + } else { + this.buffer = chunk; + } if (this.checkBOM) { - if (this.handleBOM()) { - callback(); - return; + 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; } } - while (this.hasCurrentByte()) { - const byte = this.currentByte(); + while (this.pos < this.buffer.length) { if (this.eventEndCheck) { if (this.crlfCheck) { - if (byte === LF) { + if (this.buffer[this.pos] === LF) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.crlfCheck = false; - this.consumeCurrentByte(); continue; } this.crlfCheck = false; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.consumeCurrentByte(); - if (this.hasPendingEvent()) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; + if (this.event.data !== void 0 || this.event.event || this.event.id || this.event.retry) { this.processEvent(this.event); } this.clearEvent(); @@ -18421,16 +18082,17 @@ var require_eventsource_stream = __commonJS({ this.eventEndCheck = false; continue; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.parseLine(this.readLine(), this.event); - this.consumeCurrentByte(); + this.parseLine(this.buffer.subarray(0, this.pos), this.event); + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.eventEndCheck = true; continue; } - this.advanceCursor(); + this.pos++; } callback(); } @@ -18446,42 +18108,43 @@ var require_eventsource_stream = __commonJS({ if (colonPosition === 0) { return; } - let fieldLength = line.length; - let valueStart = line.length; + let field = ""; + let value = ""; if (colonPosition !== -1) { - fieldLength = colonPosition; - valueStart = colonPosition + 1; + field = line.subarray(0, colonPosition).toString("utf8"); + let valueStart = colonPosition + 1; if (line[valueStart] === SPACE) { ++valueStart; } + value = line.subarray(valueStart).toString("utf8"); + } else { + field = line.toString("utf8"); + value = ""; } - if (isFieldName(line, fieldLength, DATA)) { - const value = line.toString("utf8", valueStart); - if (event.data === void 0) { - event.data = value; - } else { - event.data += ` + switch (field) { + case "data": + if (event[field] === void 0) { + event[field] = value; + } else { + event[field] += ` ${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; - } + } + 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; } } /** @@ -18506,120 +18169,12 @@ ${value}`; } } clearEvent() { - 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(); + this.event = { + data: void 0, + event: void 0, + id: void 0, + retry: void 0 + }; } }; module.exports = { diff --git a/.github/actions/javascript/getPullRequestIncrementalChanges/index.js b/.github/actions/javascript/getPullRequestIncrementalChanges/index.js index e868a069ae7e..21c54003dde2 100644 --- a/.github/actions/javascript/getPullRequestIncrementalChanges/index.js +++ b/.github/actions/javascript/getPullRequestIncrementalChanges/index.js @@ -1863,66 +1863,10 @@ var require_request = __commonJS({ return false; } } - /** - * @param {number|null} statusCode - * @param {Buffer[]|null} headers - * @param {import('node:stream').Duplex} socket - * @param {string} [statusText] - */ - onUpgrade(statusCode, headers, socket, statusText = "") { - this.onFinally(); + onUpgrade(statusCode, headers, socket) { assert(!this.aborted); assert(!this.completed); - 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(error3) { - assert(!this.aborted); - assert(this.completed); - if (channels.error.hasSubscribers) { - channels.error.publish({ request: this, error: error3 }); - } - } - /** - * @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: [] }); - } + return this[kHandler].onUpgrade(statusCode, headers, socket); } onComplete(trailers) { this.onFinally(); @@ -1989,11 +1933,7 @@ var require_request = __commonJS({ } else if (typeof val[i] === "object") { throw new InvalidArgumentError(`invalid ${key} header`); } else { - const str = `${val[i]}`; - if (!isValidHeaderValue(str)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } - arr.push(str); + arr.push(`${val[i]}`); } } val = arr; @@ -2005,9 +1945,6 @@ var require_request = __commonJS({ val = ""; } else { val = `${val}`; - if (!isValidHeaderValue(val)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } } if (headerName === "host") { if (request2.host !== null) { @@ -2117,21 +2054,13 @@ var require_dispatcher_base = __commonJS({ var kOnDestroyed = /* @__PURE__ */ Symbol("onDestroyed"); var kOnClosed = /* @__PURE__ */ Symbol("onClosed"); var kInterceptedDispatch = /* @__PURE__ */ Symbol("Intercepted Dispatch"); - var kWebSocketOptions = /* @__PURE__ */ Symbol("webSocketOptions"); var DispatcherBase = class extends Dispatcher { - constructor(opts) { + constructor() { super(); this[kDestroyed] = false; this[kOnDestroyed] = null; this[kClosed] = false; this[kOnClosed] = []; - this[kWebSocketOptions] = opts?.webSocket ?? {}; - } - get webSocketOptions() { - return { - maxFragments: this[kWebSocketOptions].maxFragments ?? 131072, - maxPayloadSize: this[kWebSocketOptions].maxPayloadSize ?? 128 * 1024 * 1024 - }; } get destroyed() { return this[kDestroyed]; @@ -5738,7 +5667,6 @@ var require_client_h1 = __commonJS({ RequestContentLengthMismatchError, ResponseContentLengthMismatchError, RequestAbortedError, - InvalidArgumentError, HeadersTimeoutError, HeadersOverflowError, SocketError, @@ -5785,9 +5713,6 @@ var require_client_h1 = __commonJS({ var FastBuffer = Buffer[Symbol.species]; var addListener = util.addListener; var removeAllListeners = util.removeAllListeners; - var kIdleSocketValidation = /* @__PURE__ */ Symbol("kIdleSocketValidation"); - var kIdleSocketValidationTimeout = /* @__PURE__ */ Symbol("kIdleSocketValidationTimeout"); - var kSocketUsed = /* @__PURE__ */ Symbol("kSocketUsed"); var extractBody; async function lazyllhttp() { const llhttpWasmData = process.env.JEST_WORKER_ID ? require_llhttp_wasm() : void 0; @@ -5950,55 +5875,24 @@ var require_client_h1 = __commonJS({ currentBufferRef = null; } const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr; - if (ret !== constants3.ERROR.OK) { - const body = data.subarray(offset); - if (ret === constants3.ERROR.PAUSED_UPGRADE) { - this.onUpgrade(body); - } else if (ret === constants3.ERROR.PAUSED) { - this.paused = true; - socket.unshift(body); - } else { - throw this.createError(ret, body); + if (ret === constants3.ERROR.PAUSED_UPGRADE) { + this.onUpgrade(data.slice(offset)); + } else if (ret === constants3.ERROR.PAUSED) { + this.paused = true; + socket.unshift(data.slice(offset)); + } else if (ret !== constants3.ERROR.OK) { + const ptr = llhttp.llhttp_get_error_reason(this.ptr); + let message = ""; + if (ptr) { + const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); + message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; } + throw new HTTPParserError(message, constants3.ERROR[ret], data.slice(offset)); } } catch (err) { util.destroy(socket, err); } } - finish() { - assert(currentParser === null); - assert(this.ptr != null); - assert(!this.paused); - const { llhttp } = this; - let ret; - try { - currentParser = this; - ret = llhttp.llhttp_finish(this.ptr); - } finally { - currentParser = null; - } - if (ret === constants3.ERROR.OK) { - return null; - } - if (ret === constants3.ERROR.PAUSED || ret === constants3.ERROR.PAUSED_UPGRADE) { - this.paused = true; - return null; - } - return this.createError(ret, EMPTY_BUF); - } - createError(ret, data) { - const { llhttp, contentLength, bytesRead } = this; - if (contentLength && bytesRead !== parseInt(contentLength, 10)) { - return new ResponseContentLengthMismatchError(); - } - const ptr = llhttp.llhttp_get_error_reason(this.ptr); - let message = ""; - if (ptr) { - const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); - message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; - } - return new HTTPParserError(message, constants3.ERROR[ret], data); - } destroy() { assert(this.ptr != null); assert(currentParser == null); @@ -6018,10 +5912,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6065,7 +5955,7 @@ var require_client_h1 = __commonJS({ } } onUpgrade(head) { - const { upgrade, client, socket, headers, statusCode, statusText } = this; + const { upgrade, client, socket, headers, statusCode } = this; assert(upgrade); assert(client[kSocket] === socket); assert(!socket.destroyed); @@ -6090,10 +5980,9 @@ var require_client_h1 = __commonJS({ client[kQueue][client[kRunningIdx]++] = null; client.emit("disconnect", client[kUrl], [client], new InformationalError("upgrade")); try { - request2.onUpgrade(statusCode, headers, socket, statusText); - } catch (error3) { - util.errorRequest(client, request2, error3); - util.destroy(socket, error3); + request2.onUpgrade(statusCode, headers, socket); + } catch (err) { + util.destroy(socket, err); } client[kResume](); } @@ -6102,10 +5991,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6231,7 +6116,6 @@ var require_client_h1 = __commonJS({ } request2.onComplete(headers); client[kQueue][client[kRunningIdx]++] = null; - socket[kSocketUsed] = true; if (socket[kWriting]) { assert(client[kRunning] === 0); util.destroy(socket, new InformationalError("reset")); @@ -6275,19 +6159,12 @@ var require_client_h1 = __commonJS({ socket[kWriting] = false; socket[kReset] = false; socket[kBlocking] = false; - socket[kIdleSocketValidation] = 0; - socket[kIdleSocketValidationTimeout] = null; - socket[kSocketUsed] = false; socket[kParser] = new Parser(client, socket, llhttpInstance); addListener(socket, "error", function(err) { assert(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID"); const parser = this[kParser]; if (err.code === "ECONNRESET" && parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - this[kError] = parserErr; - this[kClient][kOnError](parserErr); - } + parser.onMessageComplete(); return; } this[kError] = err; @@ -6302,10 +6179,7 @@ var require_client_h1 = __commonJS({ addListener(socket, "end", function() { const parser = this[kParser]; if (parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - util.destroy(this, parserErr); - } + parser.onMessageComplete(); return; } util.destroy(this, new SocketError("other side closed", util.getSocketInfo(this))); @@ -6313,10 +6187,9 @@ var require_client_h1 = __commonJS({ addListener(socket, "close", function() { const client2 = this[kClient]; const parser = this[kParser]; - clearIdleSocketValidation(this); if (parser) { if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { - this[kError] = parser.finish() || this[kError]; + parser.onMessageComplete(); } this[kParser].destroy(); this[kParser] = null; @@ -6365,7 +6238,7 @@ var require_client_h1 = __commonJS({ return socket.destroyed; }, busy(request2) { - if (socket[kWriting] || socket[kReset] || socket[kBlocking] || socket[kIdleSocketValidation] === 1) { + if (socket[kWriting] || socket[kReset] || socket[kBlocking]) { return true; } if (request2) { @@ -6383,23 +6256,6 @@ var require_client_h1 = __commonJS({ } }; } - function clearIdleSocketValidation(socket) { - if (socket[kIdleSocketValidationTimeout]) { - clearImmediate(socket[kIdleSocketValidationTimeout]); - socket[kIdleSocketValidationTimeout] = null; - } - socket[kIdleSocketValidation] = 0; - } - function scheduleIdleSocketValidation(client, socket) { - socket[kIdleSocketValidation] = 1; - socket[kIdleSocketValidationTimeout] = setImmediate(() => { - socket[kIdleSocketValidationTimeout] = null; - socket[kIdleSocketValidation] = 2; - if (client[kSocket] === socket && !socket.destroyed) { - client[kResume](); - } - }); - } function resumeH1(client) { const socket = client[kSocket]; if (socket && !socket.destroyed) { @@ -6412,29 +6268,6 @@ var require_client_h1 = __commonJS({ socket.ref(); socket[kNoRef] = false; } - if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) { - if (socket[kIdleSocketValidation] === 0) { - scheduleIdleSocketValidation(client, socket); - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - if (socket[kIdleSocketValidation] === 1) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - } - if (client[kRunning] === 0) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - } if (client[kSize] === 0) { if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) { socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE); @@ -6465,16 +6298,8 @@ var require_client_h1 = __commonJS({ } body = bodyStream.stream; contentLength = bodyStream.length; - } else if (util.isBlobLike(body) && request2.contentType == null) { - const contentType = body.type; - if (contentType) { - const contentTypeValue = `${contentType}`; - if (!util.isValidHeaderValue(contentTypeValue)) { - util.errorRequest(client, request2, new InvalidArgumentError("invalid content-type header")); - return false; - } - headers.push("content-type", contentTypeValue); - } + } else if (util.isBlobLike(body) && request2.contentType == null && body.type) { + headers.push("content-type", body.type); } if (body && typeof body.read === "function") { body.read(0); @@ -6495,18 +6320,11 @@ var require_client_h1 = __commonJS({ process.emitWarning(new RequestContentLengthMismatchError()); } const socket = client[kSocket]; - clearIdleSocketValidation(socket); - const abort = (error3) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (request2.upgrade || request2.method === "CONNECT") { - util.destroy(socket, new InformationalError("aborted")); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - util.errorRequest(client, request2, error3 || new RequestAbortedError()); + util.errorRequest(client, request2, err || new RequestAbortedError()); util.destroy(body); util.destroy(socket, new InformationalError("aborted")); }; @@ -6862,7 +6680,6 @@ var require_client_h2 = __commonJS({ "node_modules/undici/lib/dispatcher/client-h2.js"(exports, module) { "use strict"; var assert = __require("node:assert"); - var { errorMonitor } = __require("node:events"); var { pipeline } = __require("node:stream"); var util = require_util(); var { @@ -6923,10 +6740,6 @@ var require_client_h2 = __commonJS({ } return result; } - function parseH2ResponseHeaders(headers) { - const { [HTTP2_HEADER_STATUS]: _statusCode, ...realHeaders } = headers; - return parseH2Headers(realHeaders); - } async function connectH2(client, socket) { client[kSocket] = socket; if (!h2ExperimentalWarned) { @@ -7090,22 +6903,16 @@ var require_client_h2 = __commonJS({ const { hostname, port } = client[kUrl]; headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ""}`; headers[HTTP2_HEADER_METHOD] = method; - const abort = (error3) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (method === "CONNECT" && stream != null) { - util.destroy(stream, error3 || new RequestAbortedError()); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - error3 = error3 || new RequestAbortedError(); - util.errorRequest(client, request2, error3); + err = err || new RequestAbortedError(); + util.errorRequest(client, request2, err); if (stream != null) { - util.destroy(stream, error3); + util.destroy(stream, err); } - util.destroy(body, error3); + util.destroy(body, err); client[kQueue][client[kRunningIdx]++] = null; client[kResume](); }; @@ -7120,42 +6927,18 @@ var require_client_h2 = __commonJS({ if (method === "CONNECT") { session.ref(); stream = session.request(headers, { endStream: false, signal }); - let upgradeResponseFinished = false; - const onResponse = (headers2) => { - upgradeResponseFinished = true; - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeResponse(Number(headers2[HTTP2_HEADER_STATUS]), headers2, parseH2ResponseHeaders); - }; - const onUpgradeError = (error3) => { - upgradeResponseFinished = true; - stream.off("response", onResponse); - request2.onUpgradeError(error3); - }; - const onReady = () => { - try { - request2.onUpgrade(null, null, stream); - } catch (error3) { - stream.off("response", onResponse); - abort(error3); - return; - } - if (request2.aborted) { - return; - } - stream.off("error", abort); - stream.once(errorMonitor, onUpgradeError); + if (stream.id && !stream.pending) { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; client[kQueue][client[kRunningIdx]++] = null; - }; - stream.once("response", onResponse); - stream.once("error", abort); - ++session[kOpenStreams]; - onReady(); + } else { + stream.once("ready", () => { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; + client[kQueue][client[kRunningIdx]++] = null; + }); + } stream.once("close", () => { - if (!upgradeResponseFinished && request2.completed) { - stream.off("response", onResponse); - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeError(new InformationalError(`HTTP/2: "stream error" received - code ${stream.rstCode}`)); - } session[kOpenStreams] -= 1; if (session[kOpenStreams] === 0) session.unref(); }); @@ -7716,10 +7499,9 @@ var require_client = __commonJS({ autoSelectFamilyAttemptTimeout, // h2 maxConcurrentStreams, - allowH2, - webSocket + allowH2 } = {}) { - super({ webSocket }); + super(); if (keepAlive !== void 0) { throw new InvalidArgumentError("unsupported keepAlive, use pipelining=0 instead"); } @@ -8225,8 +8007,8 @@ var require_pool_base = __commonJS({ var kRemoveClient = /* @__PURE__ */ Symbol("remove client"); var kStats = /* @__PURE__ */ Symbol("stats"); var PoolBase = class extends DispatcherBase { - constructor(opts) { - super(opts); + constructor() { + super(); this[kQueue] = new FixedQueue(); this[kClients] = []; this[kQueued] = 0; @@ -8397,6 +8179,7 @@ var require_pool = __commonJS({ allowH2, ...options } = {}) { + super(); if (connections != null && (!Number.isFinite(connections) || connections < 0)) { throw new InvalidArgumentError("invalid connections"); } @@ -8417,7 +8200,6 @@ var require_pool = __commonJS({ ...connect }); } - super(options); this[kInterceptors] = options.interceptors?.Pool && Array.isArray(options.interceptors.Pool) ? options.interceptors.Pool : []; this[kConnections] = connections || null; this[kUrl] = util.parseOrigin(origin); @@ -8617,6 +8399,7 @@ var require_agent = __commonJS({ } var Agent = class extends DispatcherBase { constructor({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { + super(); if (typeof factory !== "function") { throw new InvalidArgumentError("factory must be a function."); } @@ -8626,7 +8409,6 @@ var require_agent = __commonJS({ if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { throw new InvalidArgumentError("maxRedirections must be a positive number"); } - super(options); if (connect && typeof connect !== "function") { connect = { ...connect }; } @@ -9067,24 +8849,6 @@ var require_retry_handler = __commonJS({ const current = Date.now(); return new Date(retryAfter).getTime() - current; } - function validatePartialResponseContentLength(headers, range, statusCode, retryCount) { - const contentLength = headers["content-length"]; - if (contentLength == null) { - return null; - } - if (!Number.isFinite(range.start) || !Number.isFinite(range.end)) { - return null; - } - const length = Number(contentLength); - const expectedLength = range.end - range.start + 1; - if (!Number.isFinite(length) || length !== expectedLength) { - return new RequestRetryError("Content-Length mismatch", statusCode, { - headers, - data: { count: retryCount } - }); - } - return null; - } var RetryHandler = class _RetryHandler { constructor(opts, handlers) { const { retryOptions, ...dispatchOpts } = opts; @@ -9138,7 +8902,6 @@ var require_retry_handler = __commonJS({ this.end = null; this.etag = null; this.resume = null; - this.headersSent = false; this.handler.onConnect((reason) => { this.aborted = true; if (this.abort) { @@ -9148,17 +8911,6 @@ var require_retry_handler = __commonJS({ } }); } - 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(); @@ -9220,9 +8972,7 @@ var require_retry_handler = __commonJS({ const headers = parseHeaders(rawHeaders); this.retryCount += 1; if (statusCode >= 300) { - if (!this.headersSent && this.retryOpts.statusCodes.includes(statusCode) === false) { - this.headersSent = true; - this.checkpointResponseEnd(headers, resume); + if (this.retryOpts.statusCodes.includes(statusCode) === false) { return this.handler.onHeaders( statusCode, rawHeaders, @@ -9271,21 +9021,9 @@ var require_retry_handler = __commonJS({ ); return false; } - const contentLengthError = validatePartialResponseContentLength(headers, contentRange, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = contentRange; - 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; - } + assert(this.start === start, "content-range mismatch"); + assert(this.end == null || this.end === end, "content-range mismatch"); this.resume = resume; return true; } @@ -9293,7 +9031,6 @@ var require_retry_handler = __commonJS({ if (statusCode === 206) { const range = parseRangeHeader(headers["content-range"]); if (range == null) { - this.headersSent = true; return this.handler.onHeaders( statusCode, rawHeaders, @@ -9301,11 +9038,6 @@ var require_retry_handler = __commonJS({ statusMessage ); } - const contentLengthError = validatePartialResponseContentLength(headers, range, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = range; assert( start != null && Number.isFinite(start), @@ -9325,7 +9057,6 @@ var require_retry_handler = __commonJS({ "invalid content-length" ); this.resume = resume; - this.headersSent = true; this.etag = headers.etag != null ? headers.etag : null; if (this.etag != null && this.etag.startsWith("W/")) { this.etag = null; @@ -9353,7 +9084,7 @@ var require_retry_handler = __commonJS({ return this.handler.onComplete(rawTrailers); } onError(err) { - if (this.aborted || isDisturbed(this.opts.body) || this.headersSent && this.resume == null) { + if (this.aborted || isDisturbed(this.opts.body)) { return this.handler.onError(err); } if (this.retryCount - this.retryCountCheckpoint > 0) { @@ -16152,48 +15883,14 @@ var require_util6 = __commonJS({ for (let i = 0; i < path2.length; ++i) { const code = path2.charCodeAt(i); if (code < 32 || // exclude CTLs (0-31) - code > 126 || // exclude DEL and non-ascii + code === 127 || // DEL code === 59) { throw new Error("Invalid cookie path"); } } } - function isLetterOrDigit(code) { - return code >= 48 && code <= 57 || // 0-9 - code >= 65 && code <= 90 || // A-Z - code >= 97 && code <= 122; - } function validateCookieDomain(domain) { - if (domain === " ") { - return; - } - if (domain.length > 255) { - throw new Error("Invalid cookie domain"); - } - let labelLength = 0; - for (let i = 0; i < domain.length; ++i) { - const code = domain.charCodeAt(i); - if (code === 46) { - if (labelLength === 0) { - throw new Error("Invalid cookie domain"); - } - if (domain.charCodeAt(i - 1) === 45) { - throw new Error("Invalid cookie domain"); - } - labelLength = 0; - continue; - } - if (labelLength === 0 && !isLetterOrDigit(code)) { - throw new Error("Invalid cookie domain"); - } - if (!isLetterOrDigit(code) && code !== 45) { - throw new Error("Invalid cookie domain"); - } - if (++labelLength > 63) { - throw new Error("Invalid cookie domain"); - } - } - if (labelLength === 0 || domain.charCodeAt(domain.length - 1) === 45) { + if (domain.startsWith("-") || domain.endsWith(".") || domain.endsWith("-")) { throw new Error("Invalid cookie domain"); } } @@ -16276,11 +15973,7 @@ var require_util6 = __commonJS({ throw new Error("Invalid unparsed"); } const [key, ...value] = part.split("="); - const trimmedKey = key.trim(); - const joinedValue = value.join("="); - validateCookieName(trimmedKey); - validateCookieValue(joinedValue); - out.push(`${trimmedKey}=${joinedValue}`); + out.push(`${key.trim()}=${value.join("=")}`); } return out.join("; "); } @@ -16410,14 +16103,18 @@ var require_parse = __commonJS({ } else if (attributeNameLowercase === "httponly") { cookieAttributeList.httpOnly = true; } else if (attributeNameLowercase === "samesite") { + let enforcement = "Default"; const attributeValueLowercase = attributeValue.toLowerCase(); - if (attributeValueLowercase === "none") { - cookieAttributeList.sameSite = "None"; - } else if (attributeValueLowercase === "strict") { - cookieAttributeList.sameSite = "Strict"; - } else if (attributeValueLowercase === "lax") { - cookieAttributeList.sameSite = "Lax"; + if (attributeValueLowercase.includes("none")) { + enforcement = "None"; + } + if (attributeValueLowercase.includes("strict")) { + enforcement = "Strict"; + } + if (attributeValueLowercase.includes("lax")) { + enforcement = "Lax"; } + cookieAttributeList.sameSite = enforcement; } else { cookieAttributeList.unparsed ??= []; cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`); @@ -17239,7 +16936,7 @@ var require_connection = __commonJS({ const secProtocol = response.headersList.get("Sec-WebSocket-Protocol"); if (secProtocol !== null) { const requestProtocols = getDecodeSplit("sec-websocket-protocol", request2.headersList); - if (requestProtocols === null || !requestProtocols.includes(secProtocol)) { + if (!requestProtocols.includes(secProtocol)) { failWebsocketConnection(ws, "Protocol was not set in the opening handshake."); return; } @@ -17345,26 +17042,31 @@ var require_permessage_deflate = __commonJS({ var tail = Buffer.from([0, 0, 255, 255]); var kBuffer = /* @__PURE__ */ Symbol("kBuffer"); var kLength = /* @__PURE__ */ Symbol("kLength"); + var kDefaultMaxDecompressedSize = 4 * 1024 * 1024; var PerMessageDeflate = class { /** @type {import('node:zlib').InflateRaw} */ #inflate; #options = {}; - #maxPayloadSize = 0; + /** @type {number} */ + #maxDecompressedSize; + /** @type {boolean} */ + #aborted = false; + /** @type {Function|null} */ + #currentCallback = null; /** * @param {Map} extensions + * @param {{ maxDecompressedMessageSize?: number }} [options] */ - constructor(extensions, options) { + constructor(extensions, options = {}) { this.#options.serverNoContextTakeover = extensions.has("server_no_context_takeover"); this.#options.serverMaxWindowBits = extensions.get("server_max_window_bits"); - this.#maxPayloadSize = options.maxPayloadSize; + this.#maxDecompressedSize = options.maxDecompressedMessageSize ?? kDefaultMaxDecompressedSize; } - /** - * Decompress a compressed payload. - * @param {Buffer} chunk Compressed data - * @param {boolean} fin Final fragment flag - * @param {Function} callback Callback function - */ decompress(chunk, fin, callback) { + if (this.#aborted) { + callback(new MessageSizeExceededError()); + return; + } if (!this.#inflate) { let windowBits = Z_DEFAULT_WINDOWBITS; if (this.#options.serverMaxWindowBits) { @@ -17383,12 +17085,20 @@ var require_permessage_deflate = __commonJS({ this.#inflate[kBuffer] = []; this.#inflate[kLength] = 0; this.#inflate.on("data", (data) => { + if (this.#aborted) { + return; + } this.#inflate[kLength] += data.length; - if (this.#maxPayloadSize > 0 && this.#inflate[kLength] > this.#maxPayloadSize) { - callback(new MessageSizeExceededError()); + if (this.#inflate[kLength] > this.#maxDecompressedSize) { + this.#aborted = true; this.#inflate.removeAllListeners(); this.#inflate.destroy(); this.#inflate = null; + if (this.#currentCallback) { + const cb = this.#currentCallback; + this.#currentCallback = null; + cb(new MessageSizeExceededError()); + } return; } this.#inflate[kBuffer].push(data); @@ -17398,17 +17108,19 @@ var require_permessage_deflate = __commonJS({ callback(err); }); } + this.#currentCallback = callback; this.#inflate.write(chunk); if (fin) { this.#inflate.write(tail); } this.#inflate.flush(() => { - if (!this.#inflate) { + if (this.#aborted || !this.#inflate) { return; } const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]); this.#inflate[kBuffer].length = 0; this.#inflate[kLength] = 0; + this.#currentCallback = null; callback(null, full); }); } @@ -17439,14 +17151,8 @@ var require_receiver = __commonJS({ var { WebsocketFrameSend } = require_frame(); var { closeWebSocketConnection } = require_connection(); var { PerMessageDeflate } = require_permessage_deflate(); - var { MessageSizeExceededError } = require_errors(); - function failWebsocketConnectionWithCode(ws, code, reason) { - closeWebSocketConnection(ws, code, reason, Buffer.byteLength(reason)); - failWebsocketConnection(ws, reason); - } var ByteParser = class extends Writable { #buffers = []; - #fragmentsBytes = 0; #byteOffset = 0; #loop = false; #state = parserStates.INFO; @@ -17454,21 +17160,18 @@ var require_receiver = __commonJS({ #fragments = []; /** @type {Map} */ #extensions; - /** @type {number} */ - #maxFragments; - /** @type {number} */ - #maxPayloadSize; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {import('./websocket').WebSocket} ws * @param {Map|null} extensions - * @param {{ maxFragments?: number, maxPayloadSize?: number }} [options] + * @param {{ maxDecompressedMessageSize?: number }} [options] */ constructor(ws, extensions, options = {}) { super(); this.ws = ws; this.#extensions = extensions == null ? /* @__PURE__ */ new Map() : extensions; - this.#maxFragments = options.maxFragments ?? 0; - this.#maxPayloadSize = options.maxPayloadSize ?? 0; + this.#options = options; if (this.#extensions.has("permessage-deflate")) { this.#extensions.set("permessage-deflate", new PerMessageDeflate(extensions, options)); } @@ -17483,13 +17186,6 @@ var require_receiver = __commonJS({ this.#loop = true; this.run(callback); } - #validatePayloadLength() { - if (this.#maxPayloadSize > 0 && !isControlFrame(this.#info.opcode) && this.#info.payloadLength + this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, "Payload size exceeds maximum allowed size"); - return false; - } - return true; - } /** * Runs whenever a new chunk is received. * Callback is called whenever there are no more chunks buffering, @@ -17549,9 +17245,6 @@ var require_receiver = __commonJS({ if (payloadLength <= 125) { this.#info.payloadLength = payloadLength; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (payloadLength === 126) { this.#state = parserStates.PAYLOADLENGTH_16; } else if (payloadLength === 127) { @@ -17572,9 +17265,6 @@ var require_receiver = __commonJS({ const buffer = this.consume(2); this.#info.payloadLength = buffer.readUInt16BE(0); this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.PAYLOADLENGTH_64) { if (this.#byteOffset < 8) { return callback(); @@ -17588,9 +17278,6 @@ var require_receiver = __commonJS({ } this.#info.payloadLength = lower; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.READ_DATA) { if (this.#byteOffset < this.#info.payloadLength) { return callback(); @@ -17601,46 +17288,32 @@ var require_receiver = __commonJS({ this.#state = parserStates.INFO; } else { if (!this.#info.compressed) { - if (!this.writeFragments(body)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } + this.#fragments.push(body); if (!this.#info.fragmented && this.#info.fin) { - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); + const fullMessage = Buffer.concat(this.#fragments); + websocketMessageReceived(this.ws, this.#info.binaryType, fullMessage); + this.#fragments.length = 0; } this.#state = parserStates.INFO; } else { - this.#extensions.get("permessage-deflate").decompress( - body, - this.#info.fin, - (error3, data) => { - if (error3) { - const code = error3 instanceof MessageSizeExceededError ? 1009 : 1007; - failWebsocketConnectionWithCode(this.ws, code, error3.message); - return; - } - if (!this.writeFragments(data)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } - if (!this.#info.fin) { - this.#state = parserStates.INFO; - this.#loop = true; - this.run(callback); - return; - } - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); - this.#loop = true; + this.#extensions.get("permessage-deflate").decompress(body, this.#info.fin, (error3, data) => { + if (error3) { + failWebsocketConnection(this.ws, error3.message); + return; + } + this.#fragments.push(data); + if (!this.#info.fin) { this.#state = parserStates.INFO; + this.#loop = true; this.run(callback); + return; } - ); + websocketMessageReceived(this.ws, this.#info.binaryType, Buffer.concat(this.#fragments)); + this.#loop = true; + this.#state = parserStates.INFO; + this.#fragments.length = 0; + this.run(callback); + }); this.#loop = false; break; } @@ -17683,26 +17356,6 @@ var require_receiver = __commonJS({ this.#byteOffset -= n; return buffer; } - writeFragments(fragment) { - if (this.#maxFragments > 0 && this.#fragments.length === this.#maxFragments) { - failWebsocketConnectionWithCode(this.ws, 1008, "Too many message fragments"); - return false; - } - this.#fragmentsBytes += fragment.length; - this.#fragments.push(fragment); - return true; - } - consumeFragments() { - const fragments = this.#fragments; - if (fragments.length === 1) { - this.#fragmentsBytes = 0; - return fragments.shift(); - } - const output = Buffer.concat(fragments, this.#fragmentsBytes); - this.#fragments = []; - this.#fragmentsBytes = 0; - return output; - } parseCloseBody(data) { assert(data.length !== 1); let code; @@ -17914,6 +17567,8 @@ var require_websocket = __commonJS({ #extensions = ""; /** @type {SendQueue} */ #sendQueue; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {string} url * @param {string|string[]} protocols @@ -17957,6 +17612,9 @@ var require_websocket = __commonJS({ throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError"); } this[kWebSocketURL] = new URL(urlRecord.href); + this.#options = { + maxDecompressedMessageSize: options.maxDecompressedMessageSize + }; const client = environmentSettingsObject.settingsObject; this[kController] = establishWebSocketConnection( urlRecord, @@ -18140,13 +17798,7 @@ var require_websocket = __commonJS({ */ #onConnectionEstablished(response, parsedExtensions) { this[kResponse] = response; - const webSocketOptions = this[kController]?.dispatcher?.webSocketOptions; - const maxFragments = webSocketOptions?.maxFragments; - const maxPayloadSize = webSocketOptions?.maxPayloadSize; - const parser = new ByteParser(this, parsedExtensions, { - maxFragments, - maxPayloadSize - }); + const parser = new ByteParser(this, parsedExtensions, this.#options); parser.on("drain", onParserDrain); parser.on("error", onParserError.bind(this)); response.socket.ws = this; @@ -18221,6 +17873,19 @@ var require_websocket = __commonJS({ { key: "headers", converter: webidl.nullableConverter(webidl.converters.HeadersInit) + }, + { + key: "maxDecompressedMessageSize", + converter: webidl.nullableConverter((V) => { + V = webidl.converters["unsigned long long"](V); + if (V <= 0) { + throw webidl.errors.exception({ + header: "WebSocket constructor", + message: "maxDecompressedMessageSize must be greater than 0" + }); + } + return V; + }) } ]); webidl.converters["DOMString or sequence or WebSocketInit"] = function(V) { @@ -18299,40 +17964,6 @@ 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; - } - function isValidLastEventIdBytes(buffer, start) { - for (let i = start; i < buffer.length; i++) { - if (buffer[i] === 0) { - 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; - } var EventSourceStream = class extends Transform { /** * @type {eventSourceSettings} @@ -18352,13 +17983,10 @@ var require_eventsource_stream = __commonJS({ */ eventEndCheck = false; /** - * @type {Buffer[]} + * @type {Buffer} */ - chunks = []; - chunkIndex = 0; + buffer = null; pos = 0; - lineChunkIndex = 0; - linePos = 0; event = { data: void 0, event: void 0, @@ -18389,30 +18017,63 @@ var require_eventsource_stream = __commonJS({ callback(); return; } - this.chunks.push(chunk); + if (this.buffer) { + this.buffer = Buffer.concat([this.buffer, chunk]); + } else { + this.buffer = chunk; + } if (this.checkBOM) { - if (this.handleBOM()) { - callback(); - return; + 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; } } - while (this.hasCurrentByte()) { - const byte = this.currentByte(); + while (this.pos < this.buffer.length) { if (this.eventEndCheck) { if (this.crlfCheck) { - if (byte === LF) { + if (this.buffer[this.pos] === LF) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.crlfCheck = false; - this.consumeCurrentByte(); continue; } this.crlfCheck = false; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.consumeCurrentByte(); - if (this.hasPendingEvent()) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; + if (this.event.data !== void 0 || this.event.event || this.event.id || this.event.retry) { this.processEvent(this.event); } this.clearEvent(); @@ -18421,16 +18082,17 @@ var require_eventsource_stream = __commonJS({ this.eventEndCheck = false; continue; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.parseLine(this.readLine(), this.event); - this.consumeCurrentByte(); + this.parseLine(this.buffer.subarray(0, this.pos), this.event); + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.eventEndCheck = true; continue; } - this.advanceCursor(); + this.pos++; } callback(); } @@ -18446,42 +18108,43 @@ var require_eventsource_stream = __commonJS({ if (colonPosition === 0) { return; } - let fieldLength = line.length; - let valueStart = line.length; + let field = ""; + let value = ""; if (colonPosition !== -1) { - fieldLength = colonPosition; - valueStart = colonPosition + 1; + field = line.subarray(0, colonPosition).toString("utf8"); + let valueStart = colonPosition + 1; if (line[valueStart] === SPACE) { ++valueStart; } + value = line.subarray(valueStart).toString("utf8"); + } else { + field = line.toString("utf8"); + value = ""; } - if (isFieldName(line, fieldLength, DATA)) { - const value = line.toString("utf8", valueStart); - if (event.data === void 0) { - event.data = value; - } else { - event.data += ` + switch (field) { + case "data": + if (event[field] === void 0) { + event[field] = value; + } else { + event[field] += ` ${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; - } + } + 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; } } /** @@ -18506,120 +18169,12 @@ ${value}`; } } clearEvent() { - 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(); + this.event = { + data: void 0, + event: void 0, + id: void 0, + retry: void 0 + }; } }; module.exports = { diff --git a/.github/actions/javascript/isAuthorizedContributor/index.js b/.github/actions/javascript/isAuthorizedContributor/index.js index d43a19fced4c..fea991ad887f 100644 --- a/.github/actions/javascript/isAuthorizedContributor/index.js +++ b/.github/actions/javascript/isAuthorizedContributor/index.js @@ -1863,66 +1863,10 @@ var require_request = __commonJS({ return false; } } - /** - * @param {number|null} statusCode - * @param {Buffer[]|null} headers - * @param {import('node:stream').Duplex} socket - * @param {string} [statusText] - */ - onUpgrade(statusCode, headers, socket, statusText = "") { - this.onFinally(); + onUpgrade(statusCode, headers, socket) { assert(!this.aborted); assert(!this.completed); - 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(error2) { - assert(!this.aborted); - assert(this.completed); - if (channels.error.hasSubscribers) { - channels.error.publish({ request: this, error: error2 }); - } - } - /** - * @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: [] }); - } + return this[kHandler].onUpgrade(statusCode, headers, socket); } onComplete(trailers) { this.onFinally(); @@ -1989,11 +1933,7 @@ var require_request = __commonJS({ } else if (typeof val[i] === "object") { throw new InvalidArgumentError(`invalid ${key} header`); } else { - const str = `${val[i]}`; - if (!isValidHeaderValue(str)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } - arr.push(str); + arr.push(`${val[i]}`); } } val = arr; @@ -2005,9 +1945,6 @@ var require_request = __commonJS({ val = ""; } else { val = `${val}`; - if (!isValidHeaderValue(val)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } } if (headerName === "host") { if (request2.host !== null) { @@ -2117,21 +2054,13 @@ var require_dispatcher_base = __commonJS({ var kOnDestroyed = /* @__PURE__ */ Symbol("onDestroyed"); var kOnClosed = /* @__PURE__ */ Symbol("onClosed"); var kInterceptedDispatch = /* @__PURE__ */ Symbol("Intercepted Dispatch"); - var kWebSocketOptions = /* @__PURE__ */ Symbol("webSocketOptions"); var DispatcherBase = class extends Dispatcher { - constructor(opts) { + constructor() { super(); this[kDestroyed] = false; this[kOnDestroyed] = null; this[kClosed] = false; this[kOnClosed] = []; - this[kWebSocketOptions] = opts?.webSocket ?? {}; - } - get webSocketOptions() { - return { - maxFragments: this[kWebSocketOptions].maxFragments ?? 131072, - maxPayloadSize: this[kWebSocketOptions].maxPayloadSize ?? 128 * 1024 * 1024 - }; } get destroyed() { return this[kDestroyed]; @@ -5738,7 +5667,6 @@ var require_client_h1 = __commonJS({ RequestContentLengthMismatchError, ResponseContentLengthMismatchError, RequestAbortedError, - InvalidArgumentError, HeadersTimeoutError, HeadersOverflowError, SocketError, @@ -5785,9 +5713,6 @@ var require_client_h1 = __commonJS({ var FastBuffer = Buffer[Symbol.species]; var addListener = util.addListener; var removeAllListeners = util.removeAllListeners; - var kIdleSocketValidation = /* @__PURE__ */ Symbol("kIdleSocketValidation"); - var kIdleSocketValidationTimeout = /* @__PURE__ */ Symbol("kIdleSocketValidationTimeout"); - var kSocketUsed = /* @__PURE__ */ Symbol("kSocketUsed"); var extractBody; async function lazyllhttp() { const llhttpWasmData = process.env.JEST_WORKER_ID ? require_llhttp_wasm() : void 0; @@ -5950,55 +5875,24 @@ var require_client_h1 = __commonJS({ currentBufferRef = null; } const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr; - if (ret !== constants3.ERROR.OK) { - const body = data.subarray(offset); - if (ret === constants3.ERROR.PAUSED_UPGRADE) { - this.onUpgrade(body); - } else if (ret === constants3.ERROR.PAUSED) { - this.paused = true; - socket.unshift(body); - } else { - throw this.createError(ret, body); + if (ret === constants3.ERROR.PAUSED_UPGRADE) { + this.onUpgrade(data.slice(offset)); + } else if (ret === constants3.ERROR.PAUSED) { + this.paused = true; + socket.unshift(data.slice(offset)); + } else if (ret !== constants3.ERROR.OK) { + const ptr = llhttp.llhttp_get_error_reason(this.ptr); + let message = ""; + if (ptr) { + const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); + message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; } + throw new HTTPParserError(message, constants3.ERROR[ret], data.slice(offset)); } } catch (err) { util.destroy(socket, err); } } - finish() { - assert(currentParser === null); - assert(this.ptr != null); - assert(!this.paused); - const { llhttp } = this; - let ret; - try { - currentParser = this; - ret = llhttp.llhttp_finish(this.ptr); - } finally { - currentParser = null; - } - if (ret === constants3.ERROR.OK) { - return null; - } - if (ret === constants3.ERROR.PAUSED || ret === constants3.ERROR.PAUSED_UPGRADE) { - this.paused = true; - return null; - } - return this.createError(ret, EMPTY_BUF); - } - createError(ret, data) { - const { llhttp, contentLength, bytesRead } = this; - if (contentLength && bytesRead !== parseInt(contentLength, 10)) { - return new ResponseContentLengthMismatchError(); - } - const ptr = llhttp.llhttp_get_error_reason(this.ptr); - let message = ""; - if (ptr) { - const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); - message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; - } - return new HTTPParserError(message, constants3.ERROR[ret], data); - } destroy() { assert(this.ptr != null); assert(currentParser == null); @@ -6018,10 +5912,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6065,7 +5955,7 @@ var require_client_h1 = __commonJS({ } } onUpgrade(head) { - const { upgrade, client, socket, headers, statusCode, statusText } = this; + const { upgrade, client, socket, headers, statusCode } = this; assert(upgrade); assert(client[kSocket] === socket); assert(!socket.destroyed); @@ -6090,10 +5980,9 @@ var require_client_h1 = __commonJS({ client[kQueue][client[kRunningIdx]++] = null; client.emit("disconnect", client[kUrl], [client], new InformationalError("upgrade")); try { - request2.onUpgrade(statusCode, headers, socket, statusText); - } catch (error2) { - util.errorRequest(client, request2, error2); - util.destroy(socket, error2); + request2.onUpgrade(statusCode, headers, socket); + } catch (err) { + util.destroy(socket, err); } client[kResume](); } @@ -6102,10 +5991,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6231,7 +6116,6 @@ var require_client_h1 = __commonJS({ } request2.onComplete(headers); client[kQueue][client[kRunningIdx]++] = null; - socket[kSocketUsed] = true; if (socket[kWriting]) { assert(client[kRunning] === 0); util.destroy(socket, new InformationalError("reset")); @@ -6275,19 +6159,12 @@ var require_client_h1 = __commonJS({ socket[kWriting] = false; socket[kReset] = false; socket[kBlocking] = false; - socket[kIdleSocketValidation] = 0; - socket[kIdleSocketValidationTimeout] = null; - socket[kSocketUsed] = false; socket[kParser] = new Parser(client, socket, llhttpInstance); addListener(socket, "error", function(err) { assert(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID"); const parser = this[kParser]; if (err.code === "ECONNRESET" && parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - this[kError] = parserErr; - this[kClient][kOnError](parserErr); - } + parser.onMessageComplete(); return; } this[kError] = err; @@ -6302,10 +6179,7 @@ var require_client_h1 = __commonJS({ addListener(socket, "end", function() { const parser = this[kParser]; if (parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - util.destroy(this, parserErr); - } + parser.onMessageComplete(); return; } util.destroy(this, new SocketError("other side closed", util.getSocketInfo(this))); @@ -6313,10 +6187,9 @@ var require_client_h1 = __commonJS({ addListener(socket, "close", function() { const client2 = this[kClient]; const parser = this[kParser]; - clearIdleSocketValidation(this); if (parser) { if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { - this[kError] = parser.finish() || this[kError]; + parser.onMessageComplete(); } this[kParser].destroy(); this[kParser] = null; @@ -6365,7 +6238,7 @@ var require_client_h1 = __commonJS({ return socket.destroyed; }, busy(request2) { - if (socket[kWriting] || socket[kReset] || socket[kBlocking] || socket[kIdleSocketValidation] === 1) { + if (socket[kWriting] || socket[kReset] || socket[kBlocking]) { return true; } if (request2) { @@ -6383,23 +6256,6 @@ var require_client_h1 = __commonJS({ } }; } - function clearIdleSocketValidation(socket) { - if (socket[kIdleSocketValidationTimeout]) { - clearImmediate(socket[kIdleSocketValidationTimeout]); - socket[kIdleSocketValidationTimeout] = null; - } - socket[kIdleSocketValidation] = 0; - } - function scheduleIdleSocketValidation(client, socket) { - socket[kIdleSocketValidation] = 1; - socket[kIdleSocketValidationTimeout] = setImmediate(() => { - socket[kIdleSocketValidationTimeout] = null; - socket[kIdleSocketValidation] = 2; - if (client[kSocket] === socket && !socket.destroyed) { - client[kResume](); - } - }); - } function resumeH1(client) { const socket = client[kSocket]; if (socket && !socket.destroyed) { @@ -6412,29 +6268,6 @@ var require_client_h1 = __commonJS({ socket.ref(); socket[kNoRef] = false; } - if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) { - if (socket[kIdleSocketValidation] === 0) { - scheduleIdleSocketValidation(client, socket); - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - if (socket[kIdleSocketValidation] === 1) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - } - if (client[kRunning] === 0) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - } if (client[kSize] === 0) { if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) { socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE); @@ -6465,16 +6298,8 @@ var require_client_h1 = __commonJS({ } body = bodyStream.stream; contentLength = bodyStream.length; - } else if (util.isBlobLike(body) && request2.contentType == null) { - const contentType = body.type; - if (contentType) { - const contentTypeValue = `${contentType}`; - if (!util.isValidHeaderValue(contentTypeValue)) { - util.errorRequest(client, request2, new InvalidArgumentError("invalid content-type header")); - return false; - } - headers.push("content-type", contentTypeValue); - } + } else if (util.isBlobLike(body) && request2.contentType == null && body.type) { + headers.push("content-type", body.type); } if (body && typeof body.read === "function") { body.read(0); @@ -6495,18 +6320,11 @@ var require_client_h1 = __commonJS({ process.emitWarning(new RequestContentLengthMismatchError()); } const socket = client[kSocket]; - clearIdleSocketValidation(socket); - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (request2.upgrade || request2.method === "CONNECT") { - util.destroy(socket, new InformationalError("aborted")); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - util.errorRequest(client, request2, error2 || new RequestAbortedError()); + util.errorRequest(client, request2, err || new RequestAbortedError()); util.destroy(body); util.destroy(socket, new InformationalError("aborted")); }; @@ -6862,7 +6680,6 @@ var require_client_h2 = __commonJS({ "node_modules/undici/lib/dispatcher/client-h2.js"(exports, module) { "use strict"; var assert = __require("node:assert"); - var { errorMonitor } = __require("node:events"); var { pipeline } = __require("node:stream"); var util = require_util(); var { @@ -6923,10 +6740,6 @@ var require_client_h2 = __commonJS({ } return result; } - function parseH2ResponseHeaders(headers) { - const { [HTTP2_HEADER_STATUS]: _statusCode, ...realHeaders } = headers; - return parseH2Headers(realHeaders); - } async function connectH2(client, socket) { client[kSocket] = socket; if (!h2ExperimentalWarned) { @@ -7090,22 +6903,16 @@ var require_client_h2 = __commonJS({ const { hostname, port } = client[kUrl]; headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ""}`; headers[HTTP2_HEADER_METHOD] = method; - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (method === "CONNECT" && stream != null) { - util.destroy(stream, error2 || new RequestAbortedError()); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - error2 = error2 || new RequestAbortedError(); - util.errorRequest(client, request2, error2); + err = err || new RequestAbortedError(); + util.errorRequest(client, request2, err); if (stream != null) { - util.destroy(stream, error2); + util.destroy(stream, err); } - util.destroy(body, error2); + util.destroy(body, err); client[kQueue][client[kRunningIdx]++] = null; client[kResume](); }; @@ -7120,42 +6927,18 @@ var require_client_h2 = __commonJS({ if (method === "CONNECT") { session.ref(); stream = session.request(headers, { endStream: false, signal }); - let upgradeResponseFinished = false; - const onResponse = (headers2) => { - upgradeResponseFinished = true; - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeResponse(Number(headers2[HTTP2_HEADER_STATUS]), headers2, parseH2ResponseHeaders); - }; - const onUpgradeError = (error2) => { - upgradeResponseFinished = true; - stream.off("response", onResponse); - request2.onUpgradeError(error2); - }; - const onReady = () => { - try { - request2.onUpgrade(null, null, stream); - } catch (error2) { - stream.off("response", onResponse); - abort(error2); - return; - } - if (request2.aborted) { - return; - } - stream.off("error", abort); - stream.once(errorMonitor, onUpgradeError); + if (stream.id && !stream.pending) { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; client[kQueue][client[kRunningIdx]++] = null; - }; - stream.once("response", onResponse); - stream.once("error", abort); - ++session[kOpenStreams]; - onReady(); + } else { + stream.once("ready", () => { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; + client[kQueue][client[kRunningIdx]++] = null; + }); + } stream.once("close", () => { - if (!upgradeResponseFinished && request2.completed) { - stream.off("response", onResponse); - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeError(new InformationalError(`HTTP/2: "stream error" received - code ${stream.rstCode}`)); - } session[kOpenStreams] -= 1; if (session[kOpenStreams] === 0) session.unref(); }); @@ -7716,10 +7499,9 @@ var require_client = __commonJS({ autoSelectFamilyAttemptTimeout, // h2 maxConcurrentStreams, - allowH2, - webSocket + allowH2 } = {}) { - super({ webSocket }); + super(); if (keepAlive !== void 0) { throw new InvalidArgumentError("unsupported keepAlive, use pipelining=0 instead"); } @@ -8225,8 +8007,8 @@ var require_pool_base = __commonJS({ var kRemoveClient = /* @__PURE__ */ Symbol("remove client"); var kStats = /* @__PURE__ */ Symbol("stats"); var PoolBase = class extends DispatcherBase { - constructor(opts) { - super(opts); + constructor() { + super(); this[kQueue] = new FixedQueue(); this[kClients] = []; this[kQueued] = 0; @@ -8397,6 +8179,7 @@ var require_pool = __commonJS({ allowH2, ...options } = {}) { + super(); if (connections != null && (!Number.isFinite(connections) || connections < 0)) { throw new InvalidArgumentError("invalid connections"); } @@ -8417,7 +8200,6 @@ var require_pool = __commonJS({ ...connect }); } - super(options); this[kInterceptors] = options.interceptors?.Pool && Array.isArray(options.interceptors.Pool) ? options.interceptors.Pool : []; this[kConnections] = connections || null; this[kUrl] = util.parseOrigin(origin); @@ -8617,6 +8399,7 @@ var require_agent = __commonJS({ } var Agent = class extends DispatcherBase { constructor({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { + super(); if (typeof factory !== "function") { throw new InvalidArgumentError("factory must be a function."); } @@ -8626,7 +8409,6 @@ var require_agent = __commonJS({ if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { throw new InvalidArgumentError("maxRedirections must be a positive number"); } - super(options); if (connect && typeof connect !== "function") { connect = { ...connect }; } @@ -9067,24 +8849,6 @@ var require_retry_handler = __commonJS({ const current = Date.now(); return new Date(retryAfter).getTime() - current; } - function validatePartialResponseContentLength(headers, range, statusCode, retryCount) { - const contentLength = headers["content-length"]; - if (contentLength == null) { - return null; - } - if (!Number.isFinite(range.start) || !Number.isFinite(range.end)) { - return null; - } - const length = Number(contentLength); - const expectedLength = range.end - range.start + 1; - if (!Number.isFinite(length) || length !== expectedLength) { - return new RequestRetryError("Content-Length mismatch", statusCode, { - headers, - data: { count: retryCount } - }); - } - return null; - } var RetryHandler = class _RetryHandler { constructor(opts, handlers) { const { retryOptions, ...dispatchOpts } = opts; @@ -9138,7 +8902,6 @@ var require_retry_handler = __commonJS({ this.end = null; this.etag = null; this.resume = null; - this.headersSent = false; this.handler.onConnect((reason) => { this.aborted = true; if (this.abort) { @@ -9148,17 +8911,6 @@ var require_retry_handler = __commonJS({ } }); } - 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(); @@ -9220,9 +8972,7 @@ var require_retry_handler = __commonJS({ const headers = parseHeaders(rawHeaders); this.retryCount += 1; if (statusCode >= 300) { - if (!this.headersSent && this.retryOpts.statusCodes.includes(statusCode) === false) { - this.headersSent = true; - this.checkpointResponseEnd(headers, resume); + if (this.retryOpts.statusCodes.includes(statusCode) === false) { return this.handler.onHeaders( statusCode, rawHeaders, @@ -9271,21 +9021,9 @@ var require_retry_handler = __commonJS({ ); return false; } - const contentLengthError = validatePartialResponseContentLength(headers, contentRange, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = contentRange; - 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; - } + assert(this.start === start, "content-range mismatch"); + assert(this.end == null || this.end === end, "content-range mismatch"); this.resume = resume; return true; } @@ -9293,7 +9031,6 @@ var require_retry_handler = __commonJS({ if (statusCode === 206) { const range = parseRangeHeader(headers["content-range"]); if (range == null) { - this.headersSent = true; return this.handler.onHeaders( statusCode, rawHeaders, @@ -9301,11 +9038,6 @@ var require_retry_handler = __commonJS({ statusMessage ); } - const contentLengthError = validatePartialResponseContentLength(headers, range, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = range; assert( start != null && Number.isFinite(start), @@ -9325,7 +9057,6 @@ var require_retry_handler = __commonJS({ "invalid content-length" ); this.resume = resume; - this.headersSent = true; this.etag = headers.etag != null ? headers.etag : null; if (this.etag != null && this.etag.startsWith("W/")) { this.etag = null; @@ -9353,7 +9084,7 @@ var require_retry_handler = __commonJS({ return this.handler.onComplete(rawTrailers); } onError(err) { - if (this.aborted || isDisturbed(this.opts.body) || this.headersSent && this.resume == null) { + if (this.aborted || isDisturbed(this.opts.body)) { return this.handler.onError(err); } if (this.retryCount - this.retryCountCheckpoint > 0) { @@ -16152,48 +15883,14 @@ var require_util6 = __commonJS({ for (let i = 0; i < path.length; ++i) { const code = path.charCodeAt(i); if (code < 32 || // exclude CTLs (0-31) - code > 126 || // exclude DEL and non-ascii + code === 127 || // DEL code === 59) { throw new Error("Invalid cookie path"); } } } - function isLetterOrDigit(code) { - return code >= 48 && code <= 57 || // 0-9 - code >= 65 && code <= 90 || // A-Z - code >= 97 && code <= 122; - } function validateCookieDomain(domain) { - if (domain === " ") { - return; - } - if (domain.length > 255) { - throw new Error("Invalid cookie domain"); - } - let labelLength = 0; - for (let i = 0; i < domain.length; ++i) { - const code = domain.charCodeAt(i); - if (code === 46) { - if (labelLength === 0) { - throw new Error("Invalid cookie domain"); - } - if (domain.charCodeAt(i - 1) === 45) { - throw new Error("Invalid cookie domain"); - } - labelLength = 0; - continue; - } - if (labelLength === 0 && !isLetterOrDigit(code)) { - throw new Error("Invalid cookie domain"); - } - if (!isLetterOrDigit(code) && code !== 45) { - throw new Error("Invalid cookie domain"); - } - if (++labelLength > 63) { - throw new Error("Invalid cookie domain"); - } - } - if (labelLength === 0 || domain.charCodeAt(domain.length - 1) === 45) { + if (domain.startsWith("-") || domain.endsWith(".") || domain.endsWith("-")) { throw new Error("Invalid cookie domain"); } } @@ -16276,11 +15973,7 @@ var require_util6 = __commonJS({ throw new Error("Invalid unparsed"); } const [key, ...value] = part.split("="); - const trimmedKey = key.trim(); - const joinedValue = value.join("="); - validateCookieName(trimmedKey); - validateCookieValue(joinedValue); - out.push(`${trimmedKey}=${joinedValue}`); + out.push(`${key.trim()}=${value.join("=")}`); } return out.join("; "); } @@ -16410,14 +16103,18 @@ var require_parse = __commonJS({ } else if (attributeNameLowercase === "httponly") { cookieAttributeList.httpOnly = true; } else if (attributeNameLowercase === "samesite") { + let enforcement = "Default"; const attributeValueLowercase = attributeValue.toLowerCase(); - if (attributeValueLowercase === "none") { - cookieAttributeList.sameSite = "None"; - } else if (attributeValueLowercase === "strict") { - cookieAttributeList.sameSite = "Strict"; - } else if (attributeValueLowercase === "lax") { - cookieAttributeList.sameSite = "Lax"; + if (attributeValueLowercase.includes("none")) { + enforcement = "None"; + } + if (attributeValueLowercase.includes("strict")) { + enforcement = "Strict"; + } + if (attributeValueLowercase.includes("lax")) { + enforcement = "Lax"; } + cookieAttributeList.sameSite = enforcement; } else { cookieAttributeList.unparsed ??= []; cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`); @@ -17239,7 +16936,7 @@ var require_connection = __commonJS({ const secProtocol = response.headersList.get("Sec-WebSocket-Protocol"); if (secProtocol !== null) { const requestProtocols = getDecodeSplit("sec-websocket-protocol", request2.headersList); - if (requestProtocols === null || !requestProtocols.includes(secProtocol)) { + if (!requestProtocols.includes(secProtocol)) { failWebsocketConnection(ws, "Protocol was not set in the opening handshake."); return; } @@ -17345,26 +17042,31 @@ var require_permessage_deflate = __commonJS({ var tail = Buffer.from([0, 0, 255, 255]); var kBuffer = /* @__PURE__ */ Symbol("kBuffer"); var kLength = /* @__PURE__ */ Symbol("kLength"); + var kDefaultMaxDecompressedSize = 4 * 1024 * 1024; var PerMessageDeflate = class { /** @type {import('node:zlib').InflateRaw} */ #inflate; #options = {}; - #maxPayloadSize = 0; + /** @type {number} */ + #maxDecompressedSize; + /** @type {boolean} */ + #aborted = false; + /** @type {Function|null} */ + #currentCallback = null; /** * @param {Map} extensions + * @param {{ maxDecompressedMessageSize?: number }} [options] */ - constructor(extensions, options) { + constructor(extensions, options = {}) { this.#options.serverNoContextTakeover = extensions.has("server_no_context_takeover"); this.#options.serverMaxWindowBits = extensions.get("server_max_window_bits"); - this.#maxPayloadSize = options.maxPayloadSize; + this.#maxDecompressedSize = options.maxDecompressedMessageSize ?? kDefaultMaxDecompressedSize; } - /** - * Decompress a compressed payload. - * @param {Buffer} chunk Compressed data - * @param {boolean} fin Final fragment flag - * @param {Function} callback Callback function - */ decompress(chunk, fin, callback) { + if (this.#aborted) { + callback(new MessageSizeExceededError()); + return; + } if (!this.#inflate) { let windowBits = Z_DEFAULT_WINDOWBITS; if (this.#options.serverMaxWindowBits) { @@ -17383,12 +17085,20 @@ var require_permessage_deflate = __commonJS({ this.#inflate[kBuffer] = []; this.#inflate[kLength] = 0; this.#inflate.on("data", (data) => { + if (this.#aborted) { + return; + } this.#inflate[kLength] += data.length; - if (this.#maxPayloadSize > 0 && this.#inflate[kLength] > this.#maxPayloadSize) { - callback(new MessageSizeExceededError()); + if (this.#inflate[kLength] > this.#maxDecompressedSize) { + this.#aborted = true; this.#inflate.removeAllListeners(); this.#inflate.destroy(); this.#inflate = null; + if (this.#currentCallback) { + const cb = this.#currentCallback; + this.#currentCallback = null; + cb(new MessageSizeExceededError()); + } return; } this.#inflate[kBuffer].push(data); @@ -17398,17 +17108,19 @@ var require_permessage_deflate = __commonJS({ callback(err); }); } + this.#currentCallback = callback; this.#inflate.write(chunk); if (fin) { this.#inflate.write(tail); } this.#inflate.flush(() => { - if (!this.#inflate) { + if (this.#aborted || !this.#inflate) { return; } const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]); this.#inflate[kBuffer].length = 0; this.#inflate[kLength] = 0; + this.#currentCallback = null; callback(null, full); }); } @@ -17439,14 +17151,8 @@ var require_receiver = __commonJS({ var { WebsocketFrameSend } = require_frame(); var { closeWebSocketConnection } = require_connection(); var { PerMessageDeflate } = require_permessage_deflate(); - var { MessageSizeExceededError } = require_errors(); - function failWebsocketConnectionWithCode(ws, code, reason) { - closeWebSocketConnection(ws, code, reason, Buffer.byteLength(reason)); - failWebsocketConnection(ws, reason); - } var ByteParser = class extends Writable { #buffers = []; - #fragmentsBytes = 0; #byteOffset = 0; #loop = false; #state = parserStates.INFO; @@ -17454,21 +17160,18 @@ var require_receiver = __commonJS({ #fragments = []; /** @type {Map} */ #extensions; - /** @type {number} */ - #maxFragments; - /** @type {number} */ - #maxPayloadSize; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {import('./websocket').WebSocket} ws * @param {Map|null} extensions - * @param {{ maxFragments?: number, maxPayloadSize?: number }} [options] + * @param {{ maxDecompressedMessageSize?: number }} [options] */ constructor(ws, extensions, options = {}) { super(); this.ws = ws; this.#extensions = extensions == null ? /* @__PURE__ */ new Map() : extensions; - this.#maxFragments = options.maxFragments ?? 0; - this.#maxPayloadSize = options.maxPayloadSize ?? 0; + this.#options = options; if (this.#extensions.has("permessage-deflate")) { this.#extensions.set("permessage-deflate", new PerMessageDeflate(extensions, options)); } @@ -17483,13 +17186,6 @@ var require_receiver = __commonJS({ this.#loop = true; this.run(callback); } - #validatePayloadLength() { - if (this.#maxPayloadSize > 0 && !isControlFrame(this.#info.opcode) && this.#info.payloadLength + this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, "Payload size exceeds maximum allowed size"); - return false; - } - return true; - } /** * Runs whenever a new chunk is received. * Callback is called whenever there are no more chunks buffering, @@ -17549,9 +17245,6 @@ var require_receiver = __commonJS({ if (payloadLength <= 125) { this.#info.payloadLength = payloadLength; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (payloadLength === 126) { this.#state = parserStates.PAYLOADLENGTH_16; } else if (payloadLength === 127) { @@ -17572,9 +17265,6 @@ var require_receiver = __commonJS({ const buffer = this.consume(2); this.#info.payloadLength = buffer.readUInt16BE(0); this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.PAYLOADLENGTH_64) { if (this.#byteOffset < 8) { return callback(); @@ -17588,9 +17278,6 @@ var require_receiver = __commonJS({ } this.#info.payloadLength = lower; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.READ_DATA) { if (this.#byteOffset < this.#info.payloadLength) { return callback(); @@ -17601,46 +17288,32 @@ var require_receiver = __commonJS({ this.#state = parserStates.INFO; } else { if (!this.#info.compressed) { - if (!this.writeFragments(body)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } + this.#fragments.push(body); if (!this.#info.fragmented && this.#info.fin) { - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); + const fullMessage = Buffer.concat(this.#fragments); + websocketMessageReceived(this.ws, this.#info.binaryType, fullMessage); + this.#fragments.length = 0; } this.#state = parserStates.INFO; } else { - this.#extensions.get("permessage-deflate").decompress( - body, - this.#info.fin, - (error2, data) => { - if (error2) { - const code = error2 instanceof MessageSizeExceededError ? 1009 : 1007; - failWebsocketConnectionWithCode(this.ws, code, error2.message); - return; - } - if (!this.writeFragments(data)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } - if (!this.#info.fin) { - this.#state = parserStates.INFO; - this.#loop = true; - this.run(callback); - return; - } - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); - this.#loop = true; + this.#extensions.get("permessage-deflate").decompress(body, this.#info.fin, (error2, data) => { + if (error2) { + failWebsocketConnection(this.ws, error2.message); + return; + } + this.#fragments.push(data); + if (!this.#info.fin) { this.#state = parserStates.INFO; + this.#loop = true; this.run(callback); + return; } - ); + websocketMessageReceived(this.ws, this.#info.binaryType, Buffer.concat(this.#fragments)); + this.#loop = true; + this.#state = parserStates.INFO; + this.#fragments.length = 0; + this.run(callback); + }); this.#loop = false; break; } @@ -17683,26 +17356,6 @@ var require_receiver = __commonJS({ this.#byteOffset -= n; return buffer; } - writeFragments(fragment) { - if (this.#maxFragments > 0 && this.#fragments.length === this.#maxFragments) { - failWebsocketConnectionWithCode(this.ws, 1008, "Too many message fragments"); - return false; - } - this.#fragmentsBytes += fragment.length; - this.#fragments.push(fragment); - return true; - } - consumeFragments() { - const fragments = this.#fragments; - if (fragments.length === 1) { - this.#fragmentsBytes = 0; - return fragments.shift(); - } - const output = Buffer.concat(fragments, this.#fragmentsBytes); - this.#fragments = []; - this.#fragmentsBytes = 0; - return output; - } parseCloseBody(data) { assert(data.length !== 1); let code; @@ -17914,6 +17567,8 @@ var require_websocket = __commonJS({ #extensions = ""; /** @type {SendQueue} */ #sendQueue; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {string} url * @param {string|string[]} protocols @@ -17957,6 +17612,9 @@ var require_websocket = __commonJS({ throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError"); } this[kWebSocketURL] = new URL(urlRecord.href); + this.#options = { + maxDecompressedMessageSize: options.maxDecompressedMessageSize + }; const client = environmentSettingsObject.settingsObject; this[kController] = establishWebSocketConnection( urlRecord, @@ -18140,13 +17798,7 @@ var require_websocket = __commonJS({ */ #onConnectionEstablished(response, parsedExtensions) { this[kResponse] = response; - const webSocketOptions = this[kController]?.dispatcher?.webSocketOptions; - const maxFragments = webSocketOptions?.maxFragments; - const maxPayloadSize = webSocketOptions?.maxPayloadSize; - const parser = new ByteParser(this, parsedExtensions, { - maxFragments, - maxPayloadSize - }); + const parser = new ByteParser(this, parsedExtensions, this.#options); parser.on("drain", onParserDrain); parser.on("error", onParserError.bind(this)); response.socket.ws = this; @@ -18221,6 +17873,19 @@ var require_websocket = __commonJS({ { key: "headers", converter: webidl.nullableConverter(webidl.converters.HeadersInit) + }, + { + key: "maxDecompressedMessageSize", + converter: webidl.nullableConverter((V) => { + V = webidl.converters["unsigned long long"](V); + if (V <= 0) { + throw webidl.errors.exception({ + header: "WebSocket constructor", + message: "maxDecompressedMessageSize must be greater than 0" + }); + } + return V; + }) } ]); webidl.converters["DOMString or sequence or WebSocketInit"] = function(V) { @@ -18299,40 +17964,6 @@ 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; - } - function isValidLastEventIdBytes(buffer, start) { - for (let i = start; i < buffer.length; i++) { - if (buffer[i] === 0) { - 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; - } var EventSourceStream = class extends Transform { /** * @type {eventSourceSettings} @@ -18352,13 +17983,10 @@ var require_eventsource_stream = __commonJS({ */ eventEndCheck = false; /** - * @type {Buffer[]} + * @type {Buffer} */ - chunks = []; - chunkIndex = 0; + buffer = null; pos = 0; - lineChunkIndex = 0; - linePos = 0; event = { data: void 0, event: void 0, @@ -18389,30 +18017,63 @@ var require_eventsource_stream = __commonJS({ callback(); return; } - this.chunks.push(chunk); + if (this.buffer) { + this.buffer = Buffer.concat([this.buffer, chunk]); + } else { + this.buffer = chunk; + } if (this.checkBOM) { - if (this.handleBOM()) { - callback(); - return; + 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; } } - while (this.hasCurrentByte()) { - const byte = this.currentByte(); + while (this.pos < this.buffer.length) { if (this.eventEndCheck) { if (this.crlfCheck) { - if (byte === LF) { + if (this.buffer[this.pos] === LF) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.crlfCheck = false; - this.consumeCurrentByte(); continue; } this.crlfCheck = false; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.consumeCurrentByte(); - if (this.hasPendingEvent()) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; + if (this.event.data !== void 0 || this.event.event || this.event.id || this.event.retry) { this.processEvent(this.event); } this.clearEvent(); @@ -18421,16 +18082,17 @@ var require_eventsource_stream = __commonJS({ this.eventEndCheck = false; continue; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.parseLine(this.readLine(), this.event); - this.consumeCurrentByte(); + this.parseLine(this.buffer.subarray(0, this.pos), this.event); + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.eventEndCheck = true; continue; } - this.advanceCursor(); + this.pos++; } callback(); } @@ -18446,42 +18108,43 @@ var require_eventsource_stream = __commonJS({ if (colonPosition === 0) { return; } - let fieldLength = line.length; - let valueStart = line.length; + let field = ""; + let value = ""; if (colonPosition !== -1) { - fieldLength = colonPosition; - valueStart = colonPosition + 1; + field = line.subarray(0, colonPosition).toString("utf8"); + let valueStart = colonPosition + 1; if (line[valueStart] === SPACE) { ++valueStart; } + value = line.subarray(valueStart).toString("utf8"); + } else { + field = line.toString("utf8"); + value = ""; } - if (isFieldName(line, fieldLength, DATA)) { - const value = line.toString("utf8", valueStart); - if (event.data === void 0) { - event.data = value; - } else { - event.data += ` + switch (field) { + case "data": + if (event[field] === void 0) { + event[field] = value; + } else { + event[field] += ` ${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; - } + } + 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; } } /** @@ -18506,120 +18169,12 @@ ${value}`; } } clearEvent() { - 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(); + this.event = { + data: void 0, + event: void 0, + id: void 0, + retry: void 0 + }; } }; module.exports = { diff --git a/.github/actions/javascript/isDeployChecklistLocked/index.js b/.github/actions/javascript/isDeployChecklistLocked/index.js index cfe1ac778241..ebdf2bf6961c 100644 --- a/.github/actions/javascript/isDeployChecklistLocked/index.js +++ b/.github/actions/javascript/isDeployChecklistLocked/index.js @@ -3432,7 +3432,6 @@ var require_CONST = __commonJS({ REPLACE_CARD: "replace_card", SHIP_CARD: "ship_card", REPORT_CARD_FRAUD: "report_card_fraud", - APPROVE_DIGITAL_WALLET: "approve_digital_wallet", ISSUE_CARD: "issue_card", UPDATE_CARD: "update_card", UPDATE_PERSONAL_DETAILS: "update_personal_details", @@ -22076,117 +22075,6 @@ var require_str = __commonJS({ } return parameter; } - function compare(strA, strB) { - if (strA < strB) { - return -1; - } - if (strA > strB) { - return 1; - } - return 0; - } - function caseInsensitiveCompare(strA, strB) { - const lowerCaseStrA = strA.toLocaleLowerCase(); - const lowerCaseStrB = strB.toLocaleLowerCase(); - return compare(lowerCaseStrA, lowerCaseStrB); - } - function contains(haystack, needle) { - return haystack.indexOf(needle) !== -1; - } - function cutAfter(str, substr) { - const index = str.indexOf(substr); - if (index !== -1) { - return str.substring(0, index); - } - return str; - } - function cutBefore(str, substr) { - const index = str.indexOf(substr); - if (index !== -1) { - return str.substring(index + substr.length); - } - return str; - } - function extractEmailDomain(email) { - return cutBefore(email, "@"); - } - function getExtension(url) { - var _a, _b; - if (typeof url !== "string") { - Log_1.default.warn("Str.getExtension: url is not a string", { url }); - return void 0; - } - return (_b = (_a = url.split(".").pop()) === null || _a === void 0 ? void 0 : _a.split("?")[0]) === null || _b === void 0 ? void 0 : _b.toLowerCase(); - } - function getRawByteSize(inputChar) { - const onlyChar = String(inputChar); - const c = onlyChar.charCodeAt(0); - if (c < 1 << 7) { - return 1; - } - if (c < 1 << 11) { - return 2; - } - if (c < 1 << 16) { - return 3; - } - if (c < 1 << 21) { - return 4; - } - if (c < 1 << 26) { - return 5; - } - if (c < 1 << 31) { - return 6; - } - return Number.NaN; - } - function htmlDecode(s) { - return HtmlEntities.decode(s); - } - function htmlEncode(s) { - return HtmlEntities.encode(s); - } - function isTypeOf(obj, type) { - return Object.prototype.toString.call(obj) === `[object ${type}]`; - } - function isNumber(obj) { - return isTypeOf(obj, "Number"); - } - function isString(obj) { - return isTypeOf(obj, "String"); - } - function isUndefined(obj) { - return obj === void 0; - } - function isValidE164Phone(phone) { - return Constants.CONST.SMS.E164_REGEX.test(phone); - } - function isValidEmail(str) { - if (!str || typeof str !== "string") { - return false; - } - const unicodeVersion = punycode_1.default.toUnicode(str); - if (String(unicodeVersion).match(Constants.CONST.REG_EXP.EMOJI_RULE)) { - return false; - } - return !!String(str).match(Constants.CONST.REG_EXP.EMAIL); - } - function maskFirstNCharacters(str, num, mask) { - if (!isString(str) || !isString(mask) || str.length === 0 || !isNumber(num)) { - return str; - } - return str.substring(0, num).replaceAll(/./g, mask) + str.substring(num); - } - function removeSMSDomain(text) { - return text.replaceAll(REMOVE_SMS_DOMAIN_PATTERN, ""); - } - function removeTrailingComma(str) { - return str.trim().replaceAll(/(,$)/g, ""); - } - function startsWith(haystack, needle) { - return isString(haystack) && isString(needle) && haystack.substring(0, needle.length) === needle; - } var Str2 = { /** * Return true if the string is ending with the provided suffix @@ -22244,14 +22132,18 @@ var require_str = __commonJS({ * @param s The string to decode. * @returns The decoded string. */ - htmlDecode, + htmlDecode(s) { + return HtmlEntities.decode(s); + }, /** * HTML encodes the given string. * * @param s The string to encode. * @return string @p s HTML encoded. */ - htmlEncode, + htmlEncode(s) { + return HtmlEntities.encode(s); + }, /** * Decodes the given HTML encoded string. * @@ -22293,7 +22185,7 @@ var require_str = __commonJS({ * @returns True when first === second, ignoring HTML encoding */ htmlEncodingInsensitiveEquals(first, second) { - return first === second || htmlDecode(first) === second || htmlEncode(first) === second; + return first === second || this.htmlDecode(first) === second || this.htmlEncode(first) === second; }, /** * Creates an ID that can be used as an HTML attribute from @p str. @@ -22376,14 +22268,36 @@ var require_str = __commonJS({ * one. * @returns Byte size of the character */ - getRawByteSize, + getRawByteSize(inputChar) { + const onlyChar = String(inputChar); + const c = onlyChar.charCodeAt(0); + if (c < 1 << 7) { + return 1; + } + if (c < 1 << 11) { + return 2; + } + if (c < 1 << 16) { + return 3; + } + if (c < 1 << 21) { + return 4; + } + if (c < 1 << 26) { + return 5; + } + if (c < 1 << 31) { + return 6; + } + return Number.NaN; + }, /** * Gets the length of a string in bytes, including non-ASCII characters * @returns The number of bytes used by string */ getByteLength(input) { const stringInput = String(input); - const byteLength = Array.from(stringInput).reduce((acc, char) => acc + getRawByteSize(char), 0); + const byteLength = Array.from(stringInput).reduce((acc, char) => acc + this.getRawByteSize(char), 0); return byteLength; }, /** @@ -22395,7 +22309,7 @@ var require_str = __commonJS({ const stringInput = String(input); let totalByteLength = 0; for (let i = 0; i < stringInput.length; i++) { - const charByteSize = getRawByteSize(stringInput[i]); + const charByteSize = this.getRawByteSize(stringInput[i]); if (charByteSize + totalByteLength > maxSize) { return `${stringInput.substr(0, i - 3)}...`; } @@ -22410,7 +22324,9 @@ var require_str = __commonJS({ * @param needle The case-sensitive string to search for * @returns True if the haystack starts with the needle. */ - startsWith, + startsWith(haystack, needle) { + return this.isString(haystack) && this.isString(needle) && haystack.substring(0, needle.length) === needle; + }, /** * Gets the textual value of the given string. * @@ -22418,7 +22334,7 @@ var require_str = __commonJS({ * @returns The text from within the HTML string. */ stripHTML(str) { - if (!isString(str)) { + if (!this.isString(str)) { return ""; } return str.replaceAll(/<[^>]*>?/gm, ""); @@ -22441,7 +22357,13 @@ var require_str = __commonJS({ * @param substr The substring to search for. * @returns The cut/trimmed string. */ - cutAfter, + cutAfter(str, substr) { + const index = str.indexOf(substr); + if (index !== -1) { + return str.substring(0, index); + } + return str; + }, /** * Returns a string containing all the characters str from after the first * occurrence of substr to the end of the string. @@ -22451,7 +22373,13 @@ var require_str = __commonJS({ * @param substr The substring to search for. * @returns The cut/trimmed string. */ - cutBefore, + cutBefore(str, substr) { + const index = str.indexOf(substr); + if (index !== -1) { + return str.substring(index + substr.length); + } + return str; + }, /** * Checks that the string is a domain name (e.g. example.com) * @@ -22478,7 +22406,16 @@ var require_str = __commonJS({ * * @returns True if the string is an email */ - isValidEmail, + isValidEmail(str) { + if (!str || typeof str !== "string") { + return false; + } + const unicodeVersion = punycode_1.default.toUnicode(str); + if (String(unicodeVersion).match(Constants.CONST.REG_EXP.EMOJI_RULE)) { + return false; + } + return !!String(str).match(Constants.CONST.REG_EXP.EMAIL); + }, /** * Checks if the string is an valid email address formed during comment markdown formation. * @@ -22496,7 +22433,9 @@ var require_str = __commonJS({ * * @returns string with the trailing comma removed */ - removeTrailingComma, + removeTrailingComma(str) { + return str.trim().replaceAll(/(,$)/g, ""); + }, /** * Checks that the string is a list of coma separated email addresss. * @@ -22505,12 +22444,12 @@ var require_str = __commonJS({ * @returns True if all emails are valid or if input is empty */ areValidEmails(str) { - const string = removeTrailingComma(str); + const string = this.removeTrailingComma(str); if (string === "") { return true; } const emails = string.split(","); - const result = emails.every((email) => isValidEmail(email.trim())); + const result = emails.every((email) => this.isValidEmail(email.trim())); return result; }, /** @@ -22527,7 +22466,9 @@ var require_str = __commonJS({ * * @returns The domain name in the email address. */ - extractEmailDomain, + extractEmailDomain(email) { + return this.cutBefore(email, "@"); + }, /** * Tries to extract the company name from the given email address * (e.g. "yelp" for "joe@yelp.co.uk"). @@ -22537,7 +22478,7 @@ var require_str = __commonJS({ * @returns The company name in the email address or null. */ extractCompanyNameFromEmailDomain(email) { - const domain = extractEmailDomain(email); + const domain = this.extractEmailDomain(email); if (!domain) { return null; } @@ -22556,7 +22497,7 @@ var require_str = __commonJS({ * @returns The local part in the email address. */ extractEmailLocalPart(email) { - return cutAfter(email, "@"); + return this.cutAfter(email, "@"); }, /** * Sanitize phone number to return only numbers. Return null if non valid phone number. @@ -22614,13 +22555,13 @@ var require_str = __commonJS({ * @returns true if the length is in the range, false otherwise */ isOfLength(str, minimumLength, maximumLength) { - if (!isString(str)) { + if (!this.isString(str)) { return false; } if (str.length < minimumLength) { return false; } - if (!isUndefined(maximumLength) && str.length > maximumLength) { + if (!this.isUndefined(maximumLength) && str.length > maximumLength) { return false; } return true; @@ -22673,7 +22614,9 @@ var require_str = __commonJS({ * * @returns Returns true if the haystack contains the needle */ - contains, + contains(haystack, needle) { + return haystack.indexOf(needle) !== -1; + }, /** * Returns true if the haystack contains the needle, ignoring case * @@ -22683,7 +22626,7 @@ var require_str = __commonJS({ * @returns Returns true if the haystack contains the needle, ignoring case */ caseInsensitiveContains(haystack, needle) { - return contains(haystack.toLowerCase(), needle.toLowerCase()); + return this.contains(haystack.toLowerCase(), needle.toLowerCase()); }, /** * Case insensitive compare function @@ -22695,7 +22638,11 @@ var require_str = __commonJS({ * 1 if first string > second string * 0 if first string = second string */ - caseInsensitiveCompare, + caseInsensitiveCompare(strA, strB) { + const lowerCaseStrA = strA.toLocaleLowerCase(); + const lowerCaseStrB = strB.toLocaleLowerCase(); + return this.compare(lowerCaseStrA, lowerCaseStrB); + }, /** * Case insensitive equals * @@ -22704,7 +22651,7 @@ var require_str = __commonJS({ * @returns true when first == second except for case */ caseInsensitiveEquals(strA, strB) { - return caseInsensitiveCompare(strA, strB) === 0; + return this.caseInsensitiveCompare(strA, strB) === 0; }, /** * Compare function @@ -22716,7 +22663,15 @@ var require_str = __commonJS({ * 1 if first string > second string * 0 if first string = second string */ - compare, + compare(strA, strB) { + if (strA < strB) { + return -1; + } + if (strA > strB) { + return 1; + } + return 0; + }, /** * Check if a file extension is supported by SmartReports */ @@ -22735,37 +22690,45 @@ var require_str = __commonJS({ const accountNumber = String(num); const len = accountNumber.length; if (len < 6 || len > 20) { - return maskFirstNCharacters(accountNumber, len, "X"); + return this.maskFirstNCharacters(accountNumber, len, "X"); } if (len < 14) { - return maskFirstNCharacters(accountNumber, len - 4, "X"); + return this.maskFirstNCharacters(accountNumber, len - 4, "X"); } const first = accountNumber.substr(0, 6); const last = accountNumber.substr(7); - const masked = maskFirstNCharacters(last, len - 11, "X"); + const masked = this.maskFirstNCharacters(last, len - 11, "X"); return `${first}${masked}`; }, /** * Checks if something is a string * Stolen from underscore */ - isString, + isString(obj) { + return this.isTypeOf(obj, "String"); + }, /** * Checks if something is a number * Stolen from underscore * @param obj */ - isNumber, + isNumber(obj) { + return this.isTypeOf(obj, "Number"); + }, /** * Checks if something is a certain type * Stolen from underscore */ - isTypeOf, + isTypeOf(obj, type) { + return Object.prototype.toString.call(obj) === `[object ${type}]`; + }, /** * Checks to see if something is undefined * Stolen from underscore */ - isUndefined, + isUndefined(obj) { + return obj === void 0; + }, /** * Replace first N characters of the string with maskChar * eg: maskFirstNCharacters( '1234567890', 6, 'X' ) yields XXXXXX7890 @@ -22774,7 +22737,12 @@ var require_str = __commonJS({ * @param mask String we want replace the first N chars with * @returns Masked string */ - maskFirstNCharacters, + maskFirstNCharacters(str, num, mask) { + if (!this.isString(str) || !this.isString(mask) || str.length === 0 || !this.isNumber(num)) { + return str; + } + return str.substring(0, num).replaceAll(/./g, mask) + str.substring(num); + }, /** * Trim a string */ @@ -22786,7 +22754,7 @@ var require_str = __commonJS({ * @param percentageString The percentage as a string */ percentageStringToNumber(percentageString) { - return Number(cutAfter(percentageString, "%")); + return Number(this.cutAfter(percentageString, "%")); }, /** * Remove all the spaces from a string @@ -22830,7 +22798,7 @@ var require_str = __commonJS({ * Converts a value to boolean, case-insensitive. */ toBool(value) { - if (isString(value)) { + if (this.isString(value)) { return value.toLowerCase() === "true"; } return !!value; @@ -22880,7 +22848,9 @@ var require_str = __commonJS({ /** * Check for whether a phone number is valid according to E.164 standard. */ - isValidE164Phone, + isValidE164Phone(phone) { + return Constants.CONST.SMS.E164_REGEX.test(phone); + }, /** * Check for whether a phone number is valid in different formats/standards. For example: * significant: 4404589784 @@ -22906,12 +22876,14 @@ var require_str = __commonJS({ /** * Returns text without our SMS domain */ - removeSMSDomain, + removeSMSDomain(text) { + return text.replaceAll(REMOVE_SMS_DOMAIN_PATTERN, ""); + }, /** * Returns true if the text is a valid E.164 phone number with our SMS domain removed */ isSMSLogin(text) { - return isValidE164Phone(removeSMSDomain(text)); + return this.isValidE164Phone(this.removeSMSDomain(text)); }, /** * This method will return all matches of a single regex like preg_match_all() in PHP. This is not a common part of @@ -22964,7 +22936,7 @@ var require_str = __commonJS({ return url; } const website = match[3] ? match[2] : `${defaultScheme}://${match[2]}`; - return website.toLowerCase() + cutBefore(match[1], match[2]); + return website.toLowerCase() + this.cutBefore(match[1], match[2]); }, /** * Checks if parameter is a string or function @@ -22976,7 +22948,14 @@ var require_str = __commonJS({ * Get file extension for a given url with or * without query parameters */ - getExtension, + getExtension(url) { + var _a, _b; + if (typeof url !== "string") { + Log_1.default.warn("Str.getExtension: url is not a string", { url }); + return void 0; + } + return (_b = (_a = url.split(".").pop()) === null || _a === void 0 ? void 0 : _a.split("?")[0]) === null || _b === void 0 ? void 0 : _b.toLowerCase(); + }, /** * Takes in a URL and checks if the file extension is PDF * @@ -22984,7 +22963,7 @@ var require_str = __commonJS({ * @returns Whether file path is PDF or not */ isPDF(url) { - return getExtension(url) === "pdf"; + return this.getExtension(url) === "pdf"; }, /** * Takes in a URL and checks if the file extension is an image @@ -22995,7 +22974,7 @@ var require_str = __commonJS({ * https://reactnative.dev/docs/image#source */ isImage(url) { - const extension = getExtension(url); + const extension = this.getExtension(url); if (!extension) { return false; } @@ -23011,7 +22990,7 @@ var require_str = __commonJS({ * https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Video_codecs */ isVideo(url) { - const extension = getExtension(url); + const extension = this.getExtension(url); if (!extension) { return false; } @@ -23024,7 +23003,7 @@ var require_str = __commonJS({ * @returns True if is a domain account email, otherwise false. */ isDomainEmail(email) { - return startsWith(email, "+@"); + return this.startsWith(email, "+@"); }, /** * Find the minimum indentation of any line in the string, @@ -24162,17 +24141,13 @@ ${g2} }, { name: "anchor", - regex: /(\]\()?<(a)[^><]*href\s*=\s*(['"])(.*?)\3(?:".*?"|'.*?'|[^'"><])*>([\s\S]*?)<\/\2>(?![^<]*(<\/pre>|<\/code>))/gi, - replacement: (_extras, _match, g1, _g2, _g3, g4, g5) => { - const incompleteLinkStart = g1 !== null && g1 !== void 0 ? g1 : ""; - const email = g4.startsWith("mailto:") ? g4.slice(7) : ""; - if (email === g5) { - return `${incompleteLinkStart}${email}`; - } - if (incompleteLinkStart && (g4 === g5 || g4 === `https://${g5}`)) { - return `${incompleteLinkStart}${g5}`; + regex: /<(a)[^><]*href\s*=\s*(['"])(.*?)\2(?:".*?"|'.*?'|[^'"><])*>([\s\S]*?)<\/\1>(?![^<]*(<\/pre>|<\/code>))/gi, + replacement: (_extras, _match, _g1, _g2, g3, g4) => { + const email = g3.startsWith("mailto:") ? g3.slice(7) : ""; + if (email === g4) { + return email; } - return `${incompleteLinkStart}[${g5}](${email || g4})`; + return `[${g4}](${email || g3})`; } }, { @@ -28472,66 +28447,10 @@ var require_request = __commonJS({ return false; } } - /** - * @param {number|null} statusCode - * @param {Buffer[]|null} headers - * @param {import('node:stream').Duplex} socket - * @param {string} [statusText] - */ - onUpgrade(statusCode, headers, socket, statusText = "") { - this.onFinally(); + onUpgrade(statusCode, headers, socket) { assert(!this.aborted); assert(!this.completed); - 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(error2) { - assert(!this.aborted); - assert(this.completed); - if (channels.error.hasSubscribers) { - channels.error.publish({ request: this, error: error2 }); - } - } - /** - * @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: [] }); - } + return this[kHandler].onUpgrade(statusCode, headers, socket); } onComplete(trailers) { this.onFinally(); @@ -28598,11 +28517,7 @@ var require_request = __commonJS({ } else if (typeof val[i] === "object") { throw new InvalidArgumentError(`invalid ${key} header`); } else { - const str = `${val[i]}`; - if (!isValidHeaderValue(str)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } - arr.push(str); + arr.push(`${val[i]}`); } } val = arr; @@ -28614,9 +28529,6 @@ var require_request = __commonJS({ val = ""; } else { val = `${val}`; - if (!isValidHeaderValue(val)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } } if (headerName === "host") { if (request2.host !== null) { @@ -28726,21 +28638,13 @@ var require_dispatcher_base = __commonJS({ var kOnDestroyed = /* @__PURE__ */ Symbol("onDestroyed"); var kOnClosed = /* @__PURE__ */ Symbol("onClosed"); var kInterceptedDispatch = /* @__PURE__ */ Symbol("Intercepted Dispatch"); - var kWebSocketOptions = /* @__PURE__ */ Symbol("webSocketOptions"); var DispatcherBase = class extends Dispatcher { - constructor(opts) { + constructor() { super(); this[kDestroyed] = false; this[kOnDestroyed] = null; this[kClosed] = false; this[kOnClosed] = []; - this[kWebSocketOptions] = opts?.webSocket ?? {}; - } - get webSocketOptions() { - return { - maxFragments: this[kWebSocketOptions].maxFragments ?? 131072, - maxPayloadSize: this[kWebSocketOptions].maxPayloadSize ?? 128 * 1024 * 1024 - }; } get destroyed() { return this[kDestroyed]; @@ -32347,7 +32251,6 @@ var require_client_h1 = __commonJS({ RequestContentLengthMismatchError, ResponseContentLengthMismatchError, RequestAbortedError, - InvalidArgumentError, HeadersTimeoutError, HeadersOverflowError, SocketError, @@ -32394,9 +32297,6 @@ var require_client_h1 = __commonJS({ var FastBuffer = Buffer[Symbol.species]; var addListener = util.addListener; var removeAllListeners = util.removeAllListeners; - var kIdleSocketValidation = /* @__PURE__ */ Symbol("kIdleSocketValidation"); - var kIdleSocketValidationTimeout = /* @__PURE__ */ Symbol("kIdleSocketValidationTimeout"); - var kSocketUsed = /* @__PURE__ */ Symbol("kSocketUsed"); var extractBody; async function lazyllhttp() { const llhttpWasmData = process.env.JEST_WORKER_ID ? require_llhttp_wasm() : void 0; @@ -32559,55 +32459,24 @@ var require_client_h1 = __commonJS({ currentBufferRef = null; } const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr; - if (ret !== constants3.ERROR.OK) { - const body = data.subarray(offset); - if (ret === constants3.ERROR.PAUSED_UPGRADE) { - this.onUpgrade(body); - } else if (ret === constants3.ERROR.PAUSED) { - this.paused = true; - socket.unshift(body); - } else { - throw this.createError(ret, body); - } + if (ret === constants3.ERROR.PAUSED_UPGRADE) { + this.onUpgrade(data.slice(offset)); + } else if (ret === constants3.ERROR.PAUSED) { + this.paused = true; + socket.unshift(data.slice(offset)); + } else if (ret !== constants3.ERROR.OK) { + const ptr = llhttp.llhttp_get_error_reason(this.ptr); + let message = ""; + if (ptr) { + const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); + message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; + } + throw new HTTPParserError(message, constants3.ERROR[ret], data.slice(offset)); } } catch (err) { util.destroy(socket, err); } } - finish() { - assert(currentParser === null); - assert(this.ptr != null); - assert(!this.paused); - const { llhttp } = this; - let ret; - try { - currentParser = this; - ret = llhttp.llhttp_finish(this.ptr); - } finally { - currentParser = null; - } - if (ret === constants3.ERROR.OK) { - return null; - } - if (ret === constants3.ERROR.PAUSED || ret === constants3.ERROR.PAUSED_UPGRADE) { - this.paused = true; - return null; - } - return this.createError(ret, EMPTY_BUF); - } - createError(ret, data) { - const { llhttp, contentLength, bytesRead } = this; - if (contentLength && bytesRead !== parseInt(contentLength, 10)) { - return new ResponseContentLengthMismatchError(); - } - const ptr = llhttp.llhttp_get_error_reason(this.ptr); - let message = ""; - if (ptr) { - const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); - message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; - } - return new HTTPParserError(message, constants3.ERROR[ret], data); - } destroy() { assert(this.ptr != null); assert(currentParser == null); @@ -32627,10 +32496,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -32674,7 +32539,7 @@ var require_client_h1 = __commonJS({ } } onUpgrade(head) { - const { upgrade, client, socket, headers, statusCode, statusText } = this; + const { upgrade, client, socket, headers, statusCode } = this; assert(upgrade); assert(client[kSocket] === socket); assert(!socket.destroyed); @@ -32699,10 +32564,9 @@ var require_client_h1 = __commonJS({ client[kQueue][client[kRunningIdx]++] = null; client.emit("disconnect", client[kUrl], [client], new InformationalError("upgrade")); try { - request2.onUpgrade(statusCode, headers, socket, statusText); - } catch (error2) { - util.errorRequest(client, request2, error2); - util.destroy(socket, error2); + request2.onUpgrade(statusCode, headers, socket); + } catch (err) { + util.destroy(socket, err); } client[kResume](); } @@ -32711,10 +32575,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -32840,7 +32700,6 @@ var require_client_h1 = __commonJS({ } request2.onComplete(headers); client[kQueue][client[kRunningIdx]++] = null; - socket[kSocketUsed] = true; if (socket[kWriting]) { assert(client[kRunning] === 0); util.destroy(socket, new InformationalError("reset")); @@ -32884,19 +32743,12 @@ var require_client_h1 = __commonJS({ socket[kWriting] = false; socket[kReset] = false; socket[kBlocking] = false; - socket[kIdleSocketValidation] = 0; - socket[kIdleSocketValidationTimeout] = null; - socket[kSocketUsed] = false; socket[kParser] = new Parser(client, socket, llhttpInstance); addListener(socket, "error", function(err) { assert(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID"); const parser = this[kParser]; if (err.code === "ECONNRESET" && parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - this[kError] = parserErr; - this[kClient][kOnError](parserErr); - } + parser.onMessageComplete(); return; } this[kError] = err; @@ -32911,10 +32763,7 @@ var require_client_h1 = __commonJS({ addListener(socket, "end", function() { const parser = this[kParser]; if (parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - util.destroy(this, parserErr); - } + parser.onMessageComplete(); return; } util.destroy(this, new SocketError("other side closed", util.getSocketInfo(this))); @@ -32922,10 +32771,9 @@ var require_client_h1 = __commonJS({ addListener(socket, "close", function() { const client2 = this[kClient]; const parser = this[kParser]; - clearIdleSocketValidation(this); if (parser) { if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { - this[kError] = parser.finish() || this[kError]; + parser.onMessageComplete(); } this[kParser].destroy(); this[kParser] = null; @@ -32974,7 +32822,7 @@ var require_client_h1 = __commonJS({ return socket.destroyed; }, busy(request2) { - if (socket[kWriting] || socket[kReset] || socket[kBlocking] || socket[kIdleSocketValidation] === 1) { + if (socket[kWriting] || socket[kReset] || socket[kBlocking]) { return true; } if (request2) { @@ -32992,23 +32840,6 @@ var require_client_h1 = __commonJS({ } }; } - function clearIdleSocketValidation(socket) { - if (socket[kIdleSocketValidationTimeout]) { - clearImmediate(socket[kIdleSocketValidationTimeout]); - socket[kIdleSocketValidationTimeout] = null; - } - socket[kIdleSocketValidation] = 0; - } - function scheduleIdleSocketValidation(client, socket) { - socket[kIdleSocketValidation] = 1; - socket[kIdleSocketValidationTimeout] = setImmediate(() => { - socket[kIdleSocketValidationTimeout] = null; - socket[kIdleSocketValidation] = 2; - if (client[kSocket] === socket && !socket.destroyed) { - client[kResume](); - } - }); - } function resumeH1(client) { const socket = client[kSocket]; if (socket && !socket.destroyed) { @@ -33021,29 +32852,6 @@ var require_client_h1 = __commonJS({ socket.ref(); socket[kNoRef] = false; } - if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) { - if (socket[kIdleSocketValidation] === 0) { - scheduleIdleSocketValidation(client, socket); - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - if (socket[kIdleSocketValidation] === 1) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - } - if (client[kRunning] === 0) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - } if (client[kSize] === 0) { if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) { socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE); @@ -33074,16 +32882,8 @@ var require_client_h1 = __commonJS({ } body = bodyStream.stream; contentLength = bodyStream.length; - } else if (util.isBlobLike(body) && request2.contentType == null) { - const contentType = body.type; - if (contentType) { - const contentTypeValue = `${contentType}`; - if (!util.isValidHeaderValue(contentTypeValue)) { - util.errorRequest(client, request2, new InvalidArgumentError("invalid content-type header")); - return false; - } - headers.push("content-type", contentTypeValue); - } + } else if (util.isBlobLike(body) && request2.contentType == null && body.type) { + headers.push("content-type", body.type); } if (body && typeof body.read === "function") { body.read(0); @@ -33104,18 +32904,11 @@ var require_client_h1 = __commonJS({ process.emitWarning(new RequestContentLengthMismatchError()); } const socket = client[kSocket]; - clearIdleSocketValidation(socket); - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (request2.upgrade || request2.method === "CONNECT") { - util.destroy(socket, new InformationalError("aborted")); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - util.errorRequest(client, request2, error2 || new RequestAbortedError()); + util.errorRequest(client, request2, err || new RequestAbortedError()); util.destroy(body); util.destroy(socket, new InformationalError("aborted")); }; @@ -33471,7 +33264,6 @@ var require_client_h2 = __commonJS({ "node_modules/undici/lib/dispatcher/client-h2.js"(exports, module) { "use strict"; var assert = __require("node:assert"); - var { errorMonitor } = __require("node:events"); var { pipeline } = __require("node:stream"); var util = require_util(); var { @@ -33532,10 +33324,6 @@ var require_client_h2 = __commonJS({ } return result; } - function parseH2ResponseHeaders(headers) { - const { [HTTP2_HEADER_STATUS]: _statusCode, ...realHeaders } = headers; - return parseH2Headers(realHeaders); - } async function connectH2(client, socket) { client[kSocket] = socket; if (!h2ExperimentalWarned) { @@ -33699,22 +33487,16 @@ var require_client_h2 = __commonJS({ const { hostname, port } = client[kUrl]; headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ""}`; headers[HTTP2_HEADER_METHOD] = method; - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (method === "CONNECT" && stream != null) { - util.destroy(stream, error2 || new RequestAbortedError()); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - error2 = error2 || new RequestAbortedError(); - util.errorRequest(client, request2, error2); + err = err || new RequestAbortedError(); + util.errorRequest(client, request2, err); if (stream != null) { - util.destroy(stream, error2); + util.destroy(stream, err); } - util.destroy(body, error2); + util.destroy(body, err); client[kQueue][client[kRunningIdx]++] = null; client[kResume](); }; @@ -33729,42 +33511,18 @@ var require_client_h2 = __commonJS({ if (method === "CONNECT") { session.ref(); stream = session.request(headers, { endStream: false, signal }); - let upgradeResponseFinished = false; - const onResponse = (headers2) => { - upgradeResponseFinished = true; - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeResponse(Number(headers2[HTTP2_HEADER_STATUS]), headers2, parseH2ResponseHeaders); - }; - const onUpgradeError = (error2) => { - upgradeResponseFinished = true; - stream.off("response", onResponse); - request2.onUpgradeError(error2); - }; - const onReady = () => { - try { - request2.onUpgrade(null, null, stream); - } catch (error2) { - stream.off("response", onResponse); - abort(error2); - return; - } - if (request2.aborted) { - return; - } - stream.off("error", abort); - stream.once(errorMonitor, onUpgradeError); + if (stream.id && !stream.pending) { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; client[kQueue][client[kRunningIdx]++] = null; - }; - stream.once("response", onResponse); - stream.once("error", abort); - ++session[kOpenStreams]; - onReady(); + } else { + stream.once("ready", () => { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; + client[kQueue][client[kRunningIdx]++] = null; + }); + } stream.once("close", () => { - if (!upgradeResponseFinished && request2.completed) { - stream.off("response", onResponse); - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeError(new InformationalError(`HTTP/2: "stream error" received - code ${stream.rstCode}`)); - } session[kOpenStreams] -= 1; if (session[kOpenStreams] === 0) session.unref(); }); @@ -34325,10 +34083,9 @@ var require_client = __commonJS({ autoSelectFamilyAttemptTimeout, // h2 maxConcurrentStreams, - allowH2, - webSocket + allowH2 } = {}) { - super({ webSocket }); + super(); if (keepAlive !== void 0) { throw new InvalidArgumentError("unsupported keepAlive, use pipelining=0 instead"); } @@ -34834,8 +34591,8 @@ var require_pool_base = __commonJS({ var kRemoveClient = /* @__PURE__ */ Symbol("remove client"); var kStats = /* @__PURE__ */ Symbol("stats"); var PoolBase = class extends DispatcherBase { - constructor(opts) { - super(opts); + constructor() { + super(); this[kQueue] = new FixedQueue(); this[kClients] = []; this[kQueued] = 0; @@ -35006,6 +34763,7 @@ var require_pool = __commonJS({ allowH2, ...options } = {}) { + super(); if (connections != null && (!Number.isFinite(connections) || connections < 0)) { throw new InvalidArgumentError("invalid connections"); } @@ -35026,7 +34784,6 @@ var require_pool = __commonJS({ ...connect }); } - super(options); this[kInterceptors] = options.interceptors?.Pool && Array.isArray(options.interceptors.Pool) ? options.interceptors.Pool : []; this[kConnections] = connections || null; this[kUrl] = util.parseOrigin(origin); @@ -35226,6 +34983,7 @@ var require_agent = __commonJS({ } var Agent = class extends DispatcherBase { constructor({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { + super(); if (typeof factory !== "function") { throw new InvalidArgumentError("factory must be a function."); } @@ -35235,7 +34993,6 @@ var require_agent = __commonJS({ if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { throw new InvalidArgumentError("maxRedirections must be a positive number"); } - super(options); if (connect && typeof connect !== "function") { connect = { ...connect }; } @@ -35676,24 +35433,6 @@ var require_retry_handler = __commonJS({ const current = Date.now(); return new Date(retryAfter).getTime() - current; } - function validatePartialResponseContentLength(headers, range, statusCode, retryCount) { - const contentLength = headers["content-length"]; - if (contentLength == null) { - return null; - } - if (!Number.isFinite(range.start) || !Number.isFinite(range.end)) { - return null; - } - const length = Number(contentLength); - const expectedLength = range.end - range.start + 1; - if (!Number.isFinite(length) || length !== expectedLength) { - return new RequestRetryError("Content-Length mismatch", statusCode, { - headers, - data: { count: retryCount } - }); - } - return null; - } var RetryHandler = class _RetryHandler { constructor(opts, handlers) { const { retryOptions, ...dispatchOpts } = opts; @@ -35747,7 +35486,6 @@ var require_retry_handler = __commonJS({ this.end = null; this.etag = null; this.resume = null; - this.headersSent = false; this.handler.onConnect((reason) => { this.aborted = true; if (this.abort) { @@ -35757,17 +35495,6 @@ var require_retry_handler = __commonJS({ } }); } - 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(); @@ -35829,9 +35556,7 @@ var require_retry_handler = __commonJS({ const headers = parseHeaders(rawHeaders); this.retryCount += 1; if (statusCode >= 300) { - if (!this.headersSent && this.retryOpts.statusCodes.includes(statusCode) === false) { - this.headersSent = true; - this.checkpointResponseEnd(headers, resume); + if (this.retryOpts.statusCodes.includes(statusCode) === false) { return this.handler.onHeaders( statusCode, rawHeaders, @@ -35880,21 +35605,9 @@ var require_retry_handler = __commonJS({ ); return false; } - const contentLengthError = validatePartialResponseContentLength(headers, contentRange, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = contentRange; - 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; - } + assert(this.start === start, "content-range mismatch"); + assert(this.end == null || this.end === end, "content-range mismatch"); this.resume = resume; return true; } @@ -35902,7 +35615,6 @@ var require_retry_handler = __commonJS({ if (statusCode === 206) { const range = parseRangeHeader(headers["content-range"]); if (range == null) { - this.headersSent = true; return this.handler.onHeaders( statusCode, rawHeaders, @@ -35910,11 +35622,6 @@ var require_retry_handler = __commonJS({ statusMessage ); } - const contentLengthError = validatePartialResponseContentLength(headers, range, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = range; assert( start != null && Number.isFinite(start), @@ -35934,7 +35641,6 @@ var require_retry_handler = __commonJS({ "invalid content-length" ); this.resume = resume; - this.headersSent = true; this.etag = headers.etag != null ? headers.etag : null; if (this.etag != null && this.etag.startsWith("W/")) { this.etag = null; @@ -35962,7 +35668,7 @@ var require_retry_handler = __commonJS({ return this.handler.onComplete(rawTrailers); } onError(err) { - if (this.aborted || isDisturbed(this.opts.body) || this.headersSent && this.resume == null) { + if (this.aborted || isDisturbed(this.opts.body)) { return this.handler.onError(err); } if (this.retryCount - this.retryCountCheckpoint > 0) { @@ -42761,48 +42467,14 @@ var require_util6 = __commonJS({ for (let i = 0; i < path.length; ++i) { const code = path.charCodeAt(i); if (code < 32 || // exclude CTLs (0-31) - code > 126 || // exclude DEL and non-ascii + code === 127 || // DEL code === 59) { throw new Error("Invalid cookie path"); } } } - function isLetterOrDigit(code) { - return code >= 48 && code <= 57 || // 0-9 - code >= 65 && code <= 90 || // A-Z - code >= 97 && code <= 122; - } function validateCookieDomain(domain) { - if (domain === " ") { - return; - } - if (domain.length > 255) { - throw new Error("Invalid cookie domain"); - } - let labelLength = 0; - for (let i = 0; i < domain.length; ++i) { - const code = domain.charCodeAt(i); - if (code === 46) { - if (labelLength === 0) { - throw new Error("Invalid cookie domain"); - } - if (domain.charCodeAt(i - 1) === 45) { - throw new Error("Invalid cookie domain"); - } - labelLength = 0; - continue; - } - if (labelLength === 0 && !isLetterOrDigit(code)) { - throw new Error("Invalid cookie domain"); - } - if (!isLetterOrDigit(code) && code !== 45) { - throw new Error("Invalid cookie domain"); - } - if (++labelLength > 63) { - throw new Error("Invalid cookie domain"); - } - } - if (labelLength === 0 || domain.charCodeAt(domain.length - 1) === 45) { + if (domain.startsWith("-") || domain.endsWith(".") || domain.endsWith("-")) { throw new Error("Invalid cookie domain"); } } @@ -42885,11 +42557,7 @@ var require_util6 = __commonJS({ throw new Error("Invalid unparsed"); } const [key, ...value] = part.split("="); - const trimmedKey = key.trim(); - const joinedValue = value.join("="); - validateCookieName(trimmedKey); - validateCookieValue(joinedValue); - out.push(`${trimmedKey}=${joinedValue}`); + out.push(`${key.trim()}=${value.join("=")}`); } return out.join("; "); } @@ -43019,14 +42687,18 @@ var require_parse = __commonJS({ } else if (attributeNameLowercase === "httponly") { cookieAttributeList.httpOnly = true; } else if (attributeNameLowercase === "samesite") { + let enforcement = "Default"; const attributeValueLowercase = attributeValue.toLowerCase(); - if (attributeValueLowercase === "none") { - cookieAttributeList.sameSite = "None"; - } else if (attributeValueLowercase === "strict") { - cookieAttributeList.sameSite = "Strict"; - } else if (attributeValueLowercase === "lax") { - cookieAttributeList.sameSite = "Lax"; + if (attributeValueLowercase.includes("none")) { + enforcement = "None"; + } + if (attributeValueLowercase.includes("strict")) { + enforcement = "Strict"; + } + if (attributeValueLowercase.includes("lax")) { + enforcement = "Lax"; } + cookieAttributeList.sameSite = enforcement; } else { cookieAttributeList.unparsed ??= []; cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`); @@ -43848,7 +43520,7 @@ var require_connection = __commonJS({ const secProtocol = response.headersList.get("Sec-WebSocket-Protocol"); if (secProtocol !== null) { const requestProtocols = getDecodeSplit("sec-websocket-protocol", request2.headersList); - if (requestProtocols === null || !requestProtocols.includes(secProtocol)) { + if (!requestProtocols.includes(secProtocol)) { failWebsocketConnection(ws, "Protocol was not set in the opening handshake."); return; } @@ -43954,26 +43626,31 @@ var require_permessage_deflate = __commonJS({ var tail = Buffer.from([0, 0, 255, 255]); var kBuffer = /* @__PURE__ */ Symbol("kBuffer"); var kLength = /* @__PURE__ */ Symbol("kLength"); + var kDefaultMaxDecompressedSize = 4 * 1024 * 1024; var PerMessageDeflate = class { /** @type {import('node:zlib').InflateRaw} */ #inflate; #options = {}; - #maxPayloadSize = 0; + /** @type {number} */ + #maxDecompressedSize; + /** @type {boolean} */ + #aborted = false; + /** @type {Function|null} */ + #currentCallback = null; /** * @param {Map} extensions + * @param {{ maxDecompressedMessageSize?: number }} [options] */ - constructor(extensions, options) { + constructor(extensions, options = {}) { this.#options.serverNoContextTakeover = extensions.has("server_no_context_takeover"); this.#options.serverMaxWindowBits = extensions.get("server_max_window_bits"); - this.#maxPayloadSize = options.maxPayloadSize; + this.#maxDecompressedSize = options.maxDecompressedMessageSize ?? kDefaultMaxDecompressedSize; } - /** - * Decompress a compressed payload. - * @param {Buffer} chunk Compressed data - * @param {boolean} fin Final fragment flag - * @param {Function} callback Callback function - */ decompress(chunk, fin, callback) { + if (this.#aborted) { + callback(new MessageSizeExceededError()); + return; + } if (!this.#inflate) { let windowBits = Z_DEFAULT_WINDOWBITS; if (this.#options.serverMaxWindowBits) { @@ -43992,12 +43669,20 @@ var require_permessage_deflate = __commonJS({ this.#inflate[kBuffer] = []; this.#inflate[kLength] = 0; this.#inflate.on("data", (data) => { + if (this.#aborted) { + return; + } this.#inflate[kLength] += data.length; - if (this.#maxPayloadSize > 0 && this.#inflate[kLength] > this.#maxPayloadSize) { - callback(new MessageSizeExceededError()); + if (this.#inflate[kLength] > this.#maxDecompressedSize) { + this.#aborted = true; this.#inflate.removeAllListeners(); this.#inflate.destroy(); this.#inflate = null; + if (this.#currentCallback) { + const cb = this.#currentCallback; + this.#currentCallback = null; + cb(new MessageSizeExceededError()); + } return; } this.#inflate[kBuffer].push(data); @@ -44007,17 +43692,19 @@ var require_permessage_deflate = __commonJS({ callback(err); }); } + this.#currentCallback = callback; this.#inflate.write(chunk); if (fin) { this.#inflate.write(tail); } this.#inflate.flush(() => { - if (!this.#inflate) { + if (this.#aborted || !this.#inflate) { return; } const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]); this.#inflate[kBuffer].length = 0; this.#inflate[kLength] = 0; + this.#currentCallback = null; callback(null, full); }); } @@ -44048,14 +43735,8 @@ var require_receiver = __commonJS({ var { WebsocketFrameSend } = require_frame(); var { closeWebSocketConnection } = require_connection(); var { PerMessageDeflate } = require_permessage_deflate(); - var { MessageSizeExceededError } = require_errors(); - function failWebsocketConnectionWithCode(ws, code, reason) { - closeWebSocketConnection(ws, code, reason, Buffer.byteLength(reason)); - failWebsocketConnection(ws, reason); - } var ByteParser = class extends Writable { #buffers = []; - #fragmentsBytes = 0; #byteOffset = 0; #loop = false; #state = parserStates.INFO; @@ -44063,21 +43744,18 @@ var require_receiver = __commonJS({ #fragments = []; /** @type {Map} */ #extensions; - /** @type {number} */ - #maxFragments; - /** @type {number} */ - #maxPayloadSize; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {import('./websocket').WebSocket} ws * @param {Map|null} extensions - * @param {{ maxFragments?: number, maxPayloadSize?: number }} [options] + * @param {{ maxDecompressedMessageSize?: number }} [options] */ constructor(ws, extensions, options = {}) { super(); this.ws = ws; this.#extensions = extensions == null ? /* @__PURE__ */ new Map() : extensions; - this.#maxFragments = options.maxFragments ?? 0; - this.#maxPayloadSize = options.maxPayloadSize ?? 0; + this.#options = options; if (this.#extensions.has("permessage-deflate")) { this.#extensions.set("permessage-deflate", new PerMessageDeflate(extensions, options)); } @@ -44092,13 +43770,6 @@ var require_receiver = __commonJS({ this.#loop = true; this.run(callback); } - #validatePayloadLength() { - if (this.#maxPayloadSize > 0 && !isControlFrame(this.#info.opcode) && this.#info.payloadLength + this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, "Payload size exceeds maximum allowed size"); - return false; - } - return true; - } /** * Runs whenever a new chunk is received. * Callback is called whenever there are no more chunks buffering, @@ -44158,9 +43829,6 @@ var require_receiver = __commonJS({ if (payloadLength <= 125) { this.#info.payloadLength = payloadLength; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (payloadLength === 126) { this.#state = parserStates.PAYLOADLENGTH_16; } else if (payloadLength === 127) { @@ -44181,9 +43849,6 @@ var require_receiver = __commonJS({ const buffer = this.consume(2); this.#info.payloadLength = buffer.readUInt16BE(0); this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.PAYLOADLENGTH_64) { if (this.#byteOffset < 8) { return callback(); @@ -44197,9 +43862,6 @@ var require_receiver = __commonJS({ } this.#info.payloadLength = lower; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.READ_DATA) { if (this.#byteOffset < this.#info.payloadLength) { return callback(); @@ -44210,46 +43872,32 @@ var require_receiver = __commonJS({ this.#state = parserStates.INFO; } else { if (!this.#info.compressed) { - if (!this.writeFragments(body)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } + this.#fragments.push(body); if (!this.#info.fragmented && this.#info.fin) { - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); + const fullMessage = Buffer.concat(this.#fragments); + websocketMessageReceived(this.ws, this.#info.binaryType, fullMessage); + this.#fragments.length = 0; } this.#state = parserStates.INFO; } else { - this.#extensions.get("permessage-deflate").decompress( - body, - this.#info.fin, - (error2, data) => { - if (error2) { - const code = error2 instanceof MessageSizeExceededError ? 1009 : 1007; - failWebsocketConnectionWithCode(this.ws, code, error2.message); - return; - } - if (!this.writeFragments(data)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } - if (!this.#info.fin) { - this.#state = parserStates.INFO; - this.#loop = true; - this.run(callback); - return; - } - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); - this.#loop = true; + this.#extensions.get("permessage-deflate").decompress(body, this.#info.fin, (error2, data) => { + if (error2) { + failWebsocketConnection(this.ws, error2.message); + return; + } + this.#fragments.push(data); + if (!this.#info.fin) { this.#state = parserStates.INFO; + this.#loop = true; this.run(callback); + return; } - ); + websocketMessageReceived(this.ws, this.#info.binaryType, Buffer.concat(this.#fragments)); + this.#loop = true; + this.#state = parserStates.INFO; + this.#fragments.length = 0; + this.run(callback); + }); this.#loop = false; break; } @@ -44292,26 +43940,6 @@ var require_receiver = __commonJS({ this.#byteOffset -= n; return buffer; } - writeFragments(fragment) { - if (this.#maxFragments > 0 && this.#fragments.length === this.#maxFragments) { - failWebsocketConnectionWithCode(this.ws, 1008, "Too many message fragments"); - return false; - } - this.#fragmentsBytes += fragment.length; - this.#fragments.push(fragment); - return true; - } - consumeFragments() { - const fragments = this.#fragments; - if (fragments.length === 1) { - this.#fragmentsBytes = 0; - return fragments.shift(); - } - const output = Buffer.concat(fragments, this.#fragmentsBytes); - this.#fragments = []; - this.#fragmentsBytes = 0; - return output; - } parseCloseBody(data) { assert(data.length !== 1); let code; @@ -44523,6 +44151,8 @@ var require_websocket = __commonJS({ #extensions = ""; /** @type {SendQueue} */ #sendQueue; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {string} url * @param {string|string[]} protocols @@ -44566,6 +44196,9 @@ var require_websocket = __commonJS({ throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError"); } this[kWebSocketURL] = new URL(urlRecord.href); + this.#options = { + maxDecompressedMessageSize: options.maxDecompressedMessageSize + }; const client = environmentSettingsObject.settingsObject; this[kController] = establishWebSocketConnection( urlRecord, @@ -44749,13 +44382,7 @@ var require_websocket = __commonJS({ */ #onConnectionEstablished(response, parsedExtensions) { this[kResponse] = response; - const webSocketOptions = this[kController]?.dispatcher?.webSocketOptions; - const maxFragments = webSocketOptions?.maxFragments; - const maxPayloadSize = webSocketOptions?.maxPayloadSize; - const parser = new ByteParser(this, parsedExtensions, { - maxFragments, - maxPayloadSize - }); + const parser = new ByteParser(this, parsedExtensions, this.#options); parser.on("drain", onParserDrain); parser.on("error", onParserError.bind(this)); response.socket.ws = this; @@ -44830,6 +44457,19 @@ var require_websocket = __commonJS({ { key: "headers", converter: webidl.nullableConverter(webidl.converters.HeadersInit) + }, + { + key: "maxDecompressedMessageSize", + converter: webidl.nullableConverter((V) => { + V = webidl.converters["unsigned long long"](V); + if (V <= 0) { + throw webidl.errors.exception({ + header: "WebSocket constructor", + message: "maxDecompressedMessageSize must be greater than 0" + }); + } + return V; + }) } ]); webidl.converters["DOMString or sequence or WebSocketInit"] = function(V) { @@ -44908,40 +44548,6 @@ 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; - } - function isValidLastEventIdBytes(buffer, start) { - for (let i = start; i < buffer.length; i++) { - if (buffer[i] === 0) { - 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; - } var EventSourceStream = class extends Transform { /** * @type {eventSourceSettings} @@ -44961,13 +44567,10 @@ var require_eventsource_stream = __commonJS({ */ eventEndCheck = false; /** - * @type {Buffer[]} + * @type {Buffer} */ - chunks = []; - chunkIndex = 0; + buffer = null; pos = 0; - lineChunkIndex = 0; - linePos = 0; event = { data: void 0, event: void 0, @@ -44998,30 +44601,63 @@ var require_eventsource_stream = __commonJS({ callback(); return; } - this.chunks.push(chunk); + if (this.buffer) { + this.buffer = Buffer.concat([this.buffer, chunk]); + } else { + this.buffer = chunk; + } if (this.checkBOM) { - if (this.handleBOM()) { - callback(); - return; + 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; } } - while (this.hasCurrentByte()) { - const byte = this.currentByte(); + while (this.pos < this.buffer.length) { if (this.eventEndCheck) { if (this.crlfCheck) { - if (byte === LF) { + if (this.buffer[this.pos] === LF) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.crlfCheck = false; - this.consumeCurrentByte(); continue; } this.crlfCheck = false; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.consumeCurrentByte(); - if (this.hasPendingEvent()) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; + if (this.event.data !== void 0 || this.event.event || this.event.id || this.event.retry) { this.processEvent(this.event); } this.clearEvent(); @@ -45030,16 +44666,17 @@ var require_eventsource_stream = __commonJS({ this.eventEndCheck = false; continue; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.parseLine(this.readLine(), this.event); - this.consumeCurrentByte(); + this.parseLine(this.buffer.subarray(0, this.pos), this.event); + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.eventEndCheck = true; continue; } - this.advanceCursor(); + this.pos++; } callback(); } @@ -45055,42 +44692,43 @@ var require_eventsource_stream = __commonJS({ if (colonPosition === 0) { return; } - let fieldLength = line.length; - let valueStart = line.length; + let field = ""; + let value = ""; if (colonPosition !== -1) { - fieldLength = colonPosition; - valueStart = colonPosition + 1; + field = line.subarray(0, colonPosition).toString("utf8"); + let valueStart = colonPosition + 1; if (line[valueStart] === SPACE) { ++valueStart; } + value = line.subarray(valueStart).toString("utf8"); + } else { + field = line.toString("utf8"); + value = ""; } - if (isFieldName(line, fieldLength, DATA)) { - const value = line.toString("utf8", valueStart); - if (event.data === void 0) { - event.data = value; - } else { - event.data += ` + switch (field) { + case "data": + if (event[field] === void 0) { + event[field] = value; + } else { + event[field] += ` ${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; - } + } + 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; } } /** @@ -45115,120 +44753,12 @@ ${value}`; } } clearEvent() { - 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(); + this.event = { + data: void 0, + event: void 0, + id: void 0, + retry: void 0 + }; } }; module.exports = { diff --git a/.github/actions/javascript/markPullRequestsAsDeployed/index.js b/.github/actions/javascript/markPullRequestsAsDeployed/index.js index 5eca45f374da..62a50ec22616 100644 --- a/.github/actions/javascript/markPullRequestsAsDeployed/index.js +++ b/.github/actions/javascript/markPullRequestsAsDeployed/index.js @@ -1863,66 +1863,10 @@ var require_request = __commonJS({ return false; } } - /** - * @param {number|null} statusCode - * @param {Buffer[]|null} headers - * @param {import('node:stream').Duplex} socket - * @param {string} [statusText] - */ - onUpgrade(statusCode, headers, socket, statusText = "") { - this.onFinally(); + onUpgrade(statusCode, headers, socket) { assert(!this.aborted); assert(!this.completed); - 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(error2) { - assert(!this.aborted); - assert(this.completed); - if (channels.error.hasSubscribers) { - channels.error.publish({ request: this, error: error2 }); - } - } - /** - * @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: [] }); - } + return this[kHandler].onUpgrade(statusCode, headers, socket); } onComplete(trailers) { this.onFinally(); @@ -1989,11 +1933,7 @@ var require_request = __commonJS({ } else if (typeof val[i] === "object") { throw new InvalidArgumentError(`invalid ${key} header`); } else { - const str = `${val[i]}`; - if (!isValidHeaderValue(str)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } - arr.push(str); + arr.push(`${val[i]}`); } } val = arr; @@ -2005,9 +1945,6 @@ var require_request = __commonJS({ val = ""; } else { val = `${val}`; - if (!isValidHeaderValue(val)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } } if (headerName === "host") { if (request2.host !== null) { @@ -2117,21 +2054,13 @@ var require_dispatcher_base = __commonJS({ var kOnDestroyed = /* @__PURE__ */ Symbol("onDestroyed"); var kOnClosed = /* @__PURE__ */ Symbol("onClosed"); var kInterceptedDispatch = /* @__PURE__ */ Symbol("Intercepted Dispatch"); - var kWebSocketOptions = /* @__PURE__ */ Symbol("webSocketOptions"); var DispatcherBase = class extends Dispatcher { - constructor(opts) { + constructor() { super(); this[kDestroyed] = false; this[kOnDestroyed] = null; this[kClosed] = false; this[kOnClosed] = []; - this[kWebSocketOptions] = opts?.webSocket ?? {}; - } - get webSocketOptions() { - return { - maxFragments: this[kWebSocketOptions].maxFragments ?? 131072, - maxPayloadSize: this[kWebSocketOptions].maxPayloadSize ?? 128 * 1024 * 1024 - }; } get destroyed() { return this[kDestroyed]; @@ -5738,7 +5667,6 @@ var require_client_h1 = __commonJS({ RequestContentLengthMismatchError, ResponseContentLengthMismatchError, RequestAbortedError, - InvalidArgumentError, HeadersTimeoutError, HeadersOverflowError, SocketError, @@ -5785,9 +5713,6 @@ var require_client_h1 = __commonJS({ var FastBuffer = Buffer[Symbol.species]; var addListener = util.addListener; var removeAllListeners = util.removeAllListeners; - var kIdleSocketValidation = /* @__PURE__ */ Symbol("kIdleSocketValidation"); - var kIdleSocketValidationTimeout = /* @__PURE__ */ Symbol("kIdleSocketValidationTimeout"); - var kSocketUsed = /* @__PURE__ */ Symbol("kSocketUsed"); var extractBody; async function lazyllhttp() { const llhttpWasmData = process.env.JEST_WORKER_ID ? require_llhttp_wasm() : void 0; @@ -5950,55 +5875,24 @@ var require_client_h1 = __commonJS({ currentBufferRef = null; } const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr; - if (ret !== constants3.ERROR.OK) { - const body = data.subarray(offset); - if (ret === constants3.ERROR.PAUSED_UPGRADE) { - this.onUpgrade(body); - } else if (ret === constants3.ERROR.PAUSED) { - this.paused = true; - socket.unshift(body); - } else { - throw this.createError(ret, body); + if (ret === constants3.ERROR.PAUSED_UPGRADE) { + this.onUpgrade(data.slice(offset)); + } else if (ret === constants3.ERROR.PAUSED) { + this.paused = true; + socket.unshift(data.slice(offset)); + } else if (ret !== constants3.ERROR.OK) { + const ptr = llhttp.llhttp_get_error_reason(this.ptr); + let message = ""; + if (ptr) { + const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); + message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; } + throw new HTTPParserError(message, constants3.ERROR[ret], data.slice(offset)); } } catch (err) { util.destroy(socket, err); } } - finish() { - assert(currentParser === null); - assert(this.ptr != null); - assert(!this.paused); - const { llhttp } = this; - let ret; - try { - currentParser = this; - ret = llhttp.llhttp_finish(this.ptr); - } finally { - currentParser = null; - } - if (ret === constants3.ERROR.OK) { - return null; - } - if (ret === constants3.ERROR.PAUSED || ret === constants3.ERROR.PAUSED_UPGRADE) { - this.paused = true; - return null; - } - return this.createError(ret, EMPTY_BUF); - } - createError(ret, data) { - const { llhttp, contentLength, bytesRead } = this; - if (contentLength && bytesRead !== parseInt(contentLength, 10)) { - return new ResponseContentLengthMismatchError(); - } - const ptr = llhttp.llhttp_get_error_reason(this.ptr); - let message = ""; - if (ptr) { - const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); - message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; - } - return new HTTPParserError(message, constants3.ERROR[ret], data); - } destroy() { assert(this.ptr != null); assert(currentParser == null); @@ -6018,10 +5912,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6065,7 +5955,7 @@ var require_client_h1 = __commonJS({ } } onUpgrade(head) { - const { upgrade, client, socket, headers, statusCode, statusText } = this; + const { upgrade, client, socket, headers, statusCode } = this; assert(upgrade); assert(client[kSocket] === socket); assert(!socket.destroyed); @@ -6090,10 +5980,9 @@ var require_client_h1 = __commonJS({ client[kQueue][client[kRunningIdx]++] = null; client.emit("disconnect", client[kUrl], [client], new InformationalError("upgrade")); try { - request2.onUpgrade(statusCode, headers, socket, statusText); - } catch (error2) { - util.errorRequest(client, request2, error2); - util.destroy(socket, error2); + request2.onUpgrade(statusCode, headers, socket); + } catch (err) { + util.destroy(socket, err); } client[kResume](); } @@ -6102,10 +5991,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6231,7 +6116,6 @@ var require_client_h1 = __commonJS({ } request2.onComplete(headers); client[kQueue][client[kRunningIdx]++] = null; - socket[kSocketUsed] = true; if (socket[kWriting]) { assert(client[kRunning] === 0); util.destroy(socket, new InformationalError("reset")); @@ -6275,19 +6159,12 @@ var require_client_h1 = __commonJS({ socket[kWriting] = false; socket[kReset] = false; socket[kBlocking] = false; - socket[kIdleSocketValidation] = 0; - socket[kIdleSocketValidationTimeout] = null; - socket[kSocketUsed] = false; socket[kParser] = new Parser(client, socket, llhttpInstance); addListener(socket, "error", function(err) { assert(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID"); const parser = this[kParser]; if (err.code === "ECONNRESET" && parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - this[kError] = parserErr; - this[kClient][kOnError](parserErr); - } + parser.onMessageComplete(); return; } this[kError] = err; @@ -6302,10 +6179,7 @@ var require_client_h1 = __commonJS({ addListener(socket, "end", function() { const parser = this[kParser]; if (parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - util.destroy(this, parserErr); - } + parser.onMessageComplete(); return; } util.destroy(this, new SocketError("other side closed", util.getSocketInfo(this))); @@ -6313,10 +6187,9 @@ var require_client_h1 = __commonJS({ addListener(socket, "close", function() { const client2 = this[kClient]; const parser = this[kParser]; - clearIdleSocketValidation(this); if (parser) { if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { - this[kError] = parser.finish() || this[kError]; + parser.onMessageComplete(); } this[kParser].destroy(); this[kParser] = null; @@ -6365,7 +6238,7 @@ var require_client_h1 = __commonJS({ return socket.destroyed; }, busy(request2) { - if (socket[kWriting] || socket[kReset] || socket[kBlocking] || socket[kIdleSocketValidation] === 1) { + if (socket[kWriting] || socket[kReset] || socket[kBlocking]) { return true; } if (request2) { @@ -6383,23 +6256,6 @@ var require_client_h1 = __commonJS({ } }; } - function clearIdleSocketValidation(socket) { - if (socket[kIdleSocketValidationTimeout]) { - clearImmediate(socket[kIdleSocketValidationTimeout]); - socket[kIdleSocketValidationTimeout] = null; - } - socket[kIdleSocketValidation] = 0; - } - function scheduleIdleSocketValidation(client, socket) { - socket[kIdleSocketValidation] = 1; - socket[kIdleSocketValidationTimeout] = setImmediate(() => { - socket[kIdleSocketValidationTimeout] = null; - socket[kIdleSocketValidation] = 2; - if (client[kSocket] === socket && !socket.destroyed) { - client[kResume](); - } - }); - } function resumeH1(client) { const socket = client[kSocket]; if (socket && !socket.destroyed) { @@ -6412,29 +6268,6 @@ var require_client_h1 = __commonJS({ socket.ref(); socket[kNoRef] = false; } - if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) { - if (socket[kIdleSocketValidation] === 0) { - scheduleIdleSocketValidation(client, socket); - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - if (socket[kIdleSocketValidation] === 1) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - } - if (client[kRunning] === 0) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - } if (client[kSize] === 0) { if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) { socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE); @@ -6465,16 +6298,8 @@ var require_client_h1 = __commonJS({ } body = bodyStream.stream; contentLength = bodyStream.length; - } else if (util.isBlobLike(body) && request2.contentType == null) { - const contentType = body.type; - if (contentType) { - const contentTypeValue = `${contentType}`; - if (!util.isValidHeaderValue(contentTypeValue)) { - util.errorRequest(client, request2, new InvalidArgumentError("invalid content-type header")); - return false; - } - headers.push("content-type", contentTypeValue); - } + } else if (util.isBlobLike(body) && request2.contentType == null && body.type) { + headers.push("content-type", body.type); } if (body && typeof body.read === "function") { body.read(0); @@ -6495,18 +6320,11 @@ var require_client_h1 = __commonJS({ process.emitWarning(new RequestContentLengthMismatchError()); } const socket = client[kSocket]; - clearIdleSocketValidation(socket); - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (request2.upgrade || request2.method === "CONNECT") { - util.destroy(socket, new InformationalError("aborted")); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - util.errorRequest(client, request2, error2 || new RequestAbortedError()); + util.errorRequest(client, request2, err || new RequestAbortedError()); util.destroy(body); util.destroy(socket, new InformationalError("aborted")); }; @@ -6862,7 +6680,6 @@ var require_client_h2 = __commonJS({ "node_modules/undici/lib/dispatcher/client-h2.js"(exports, module) { "use strict"; var assert = __require("node:assert"); - var { errorMonitor } = __require("node:events"); var { pipeline } = __require("node:stream"); var util = require_util(); var { @@ -6923,10 +6740,6 @@ var require_client_h2 = __commonJS({ } return result; } - function parseH2ResponseHeaders(headers) { - const { [HTTP2_HEADER_STATUS]: _statusCode, ...realHeaders } = headers; - return parseH2Headers(realHeaders); - } async function connectH2(client, socket) { client[kSocket] = socket; if (!h2ExperimentalWarned) { @@ -7090,22 +6903,16 @@ var require_client_h2 = __commonJS({ const { hostname, port } = client[kUrl]; headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ""}`; headers[HTTP2_HEADER_METHOD] = method; - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (method === "CONNECT" && stream != null) { - util.destroy(stream, error2 || new RequestAbortedError()); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - error2 = error2 || new RequestAbortedError(); - util.errorRequest(client, request2, error2); + err = err || new RequestAbortedError(); + util.errorRequest(client, request2, err); if (stream != null) { - util.destroy(stream, error2); + util.destroy(stream, err); } - util.destroy(body, error2); + util.destroy(body, err); client[kQueue][client[kRunningIdx]++] = null; client[kResume](); }; @@ -7120,42 +6927,18 @@ var require_client_h2 = __commonJS({ if (method === "CONNECT") { session.ref(); stream = session.request(headers, { endStream: false, signal }); - let upgradeResponseFinished = false; - const onResponse = (headers2) => { - upgradeResponseFinished = true; - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeResponse(Number(headers2[HTTP2_HEADER_STATUS]), headers2, parseH2ResponseHeaders); - }; - const onUpgradeError = (error2) => { - upgradeResponseFinished = true; - stream.off("response", onResponse); - request2.onUpgradeError(error2); - }; - const onReady = () => { - try { - request2.onUpgrade(null, null, stream); - } catch (error2) { - stream.off("response", onResponse); - abort(error2); - return; - } - if (request2.aborted) { - return; - } - stream.off("error", abort); - stream.once(errorMonitor, onUpgradeError); + if (stream.id && !stream.pending) { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; client[kQueue][client[kRunningIdx]++] = null; - }; - stream.once("response", onResponse); - stream.once("error", abort); - ++session[kOpenStreams]; - onReady(); + } else { + stream.once("ready", () => { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; + client[kQueue][client[kRunningIdx]++] = null; + }); + } stream.once("close", () => { - if (!upgradeResponseFinished && request2.completed) { - stream.off("response", onResponse); - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeError(new InformationalError(`HTTP/2: "stream error" received - code ${stream.rstCode}`)); - } session[kOpenStreams] -= 1; if (session[kOpenStreams] === 0) session.unref(); }); @@ -7716,10 +7499,9 @@ var require_client = __commonJS({ autoSelectFamilyAttemptTimeout, // h2 maxConcurrentStreams, - allowH2, - webSocket + allowH2 } = {}) { - super({ webSocket }); + super(); if (keepAlive !== void 0) { throw new InvalidArgumentError("unsupported keepAlive, use pipelining=0 instead"); } @@ -8225,8 +8007,8 @@ var require_pool_base = __commonJS({ var kRemoveClient = /* @__PURE__ */ Symbol("remove client"); var kStats = /* @__PURE__ */ Symbol("stats"); var PoolBase = class extends DispatcherBase { - constructor(opts) { - super(opts); + constructor() { + super(); this[kQueue] = new FixedQueue(); this[kClients] = []; this[kQueued] = 0; @@ -8397,6 +8179,7 @@ var require_pool = __commonJS({ allowH2, ...options } = {}) { + super(); if (connections != null && (!Number.isFinite(connections) || connections < 0)) { throw new InvalidArgumentError("invalid connections"); } @@ -8417,7 +8200,6 @@ var require_pool = __commonJS({ ...connect }); } - super(options); this[kInterceptors] = options.interceptors?.Pool && Array.isArray(options.interceptors.Pool) ? options.interceptors.Pool : []; this[kConnections] = connections || null; this[kUrl] = util.parseOrigin(origin); @@ -8617,6 +8399,7 @@ var require_agent = __commonJS({ } var Agent = class extends DispatcherBase { constructor({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { + super(); if (typeof factory !== "function") { throw new InvalidArgumentError("factory must be a function."); } @@ -8626,7 +8409,6 @@ var require_agent = __commonJS({ if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { throw new InvalidArgumentError("maxRedirections must be a positive number"); } - super(options); if (connect && typeof connect !== "function") { connect = { ...connect }; } @@ -9067,24 +8849,6 @@ var require_retry_handler = __commonJS({ const current = Date.now(); return new Date(retryAfter).getTime() - current; } - function validatePartialResponseContentLength(headers, range, statusCode, retryCount) { - const contentLength = headers["content-length"]; - if (contentLength == null) { - return null; - } - if (!Number.isFinite(range.start) || !Number.isFinite(range.end)) { - return null; - } - const length = Number(contentLength); - const expectedLength = range.end - range.start + 1; - if (!Number.isFinite(length) || length !== expectedLength) { - return new RequestRetryError("Content-Length mismatch", statusCode, { - headers, - data: { count: retryCount } - }); - } - return null; - } var RetryHandler = class _RetryHandler { constructor(opts, handlers) { const { retryOptions, ...dispatchOpts } = opts; @@ -9138,7 +8902,6 @@ var require_retry_handler = __commonJS({ this.end = null; this.etag = null; this.resume = null; - this.headersSent = false; this.handler.onConnect((reason) => { this.aborted = true; if (this.abort) { @@ -9148,17 +8911,6 @@ var require_retry_handler = __commonJS({ } }); } - 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(); @@ -9220,9 +8972,7 @@ var require_retry_handler = __commonJS({ const headers = parseHeaders(rawHeaders); this.retryCount += 1; if (statusCode >= 300) { - if (!this.headersSent && this.retryOpts.statusCodes.includes(statusCode) === false) { - this.headersSent = true; - this.checkpointResponseEnd(headers, resume); + if (this.retryOpts.statusCodes.includes(statusCode) === false) { return this.handler.onHeaders( statusCode, rawHeaders, @@ -9271,21 +9021,9 @@ var require_retry_handler = __commonJS({ ); return false; } - const contentLengthError = validatePartialResponseContentLength(headers, contentRange, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = contentRange; - 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; - } + assert(this.start === start, "content-range mismatch"); + assert(this.end == null || this.end === end, "content-range mismatch"); this.resume = resume; return true; } @@ -9293,7 +9031,6 @@ var require_retry_handler = __commonJS({ if (statusCode === 206) { const range = parseRangeHeader(headers["content-range"]); if (range == null) { - this.headersSent = true; return this.handler.onHeaders( statusCode, rawHeaders, @@ -9301,11 +9038,6 @@ var require_retry_handler = __commonJS({ statusMessage ); } - const contentLengthError = validatePartialResponseContentLength(headers, range, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = range; assert( start != null && Number.isFinite(start), @@ -9325,7 +9057,6 @@ var require_retry_handler = __commonJS({ "invalid content-length" ); this.resume = resume; - this.headersSent = true; this.etag = headers.etag != null ? headers.etag : null; if (this.etag != null && this.etag.startsWith("W/")) { this.etag = null; @@ -9353,7 +9084,7 @@ var require_retry_handler = __commonJS({ return this.handler.onComplete(rawTrailers); } onError(err) { - if (this.aborted || isDisturbed(this.opts.body) || this.headersSent && this.resume == null) { + if (this.aborted || isDisturbed(this.opts.body)) { return this.handler.onError(err); } if (this.retryCount - this.retryCountCheckpoint > 0) { @@ -16152,48 +15883,14 @@ var require_util6 = __commonJS({ for (let i = 0; i < path.length; ++i) { const code = path.charCodeAt(i); if (code < 32 || // exclude CTLs (0-31) - code > 126 || // exclude DEL and non-ascii + code === 127 || // DEL code === 59) { throw new Error("Invalid cookie path"); } } } - function isLetterOrDigit(code) { - return code >= 48 && code <= 57 || // 0-9 - code >= 65 && code <= 90 || // A-Z - code >= 97 && code <= 122; - } function validateCookieDomain(domain) { - if (domain === " ") { - return; - } - if (domain.length > 255) { - throw new Error("Invalid cookie domain"); - } - let labelLength = 0; - for (let i = 0; i < domain.length; ++i) { - const code = domain.charCodeAt(i); - if (code === 46) { - if (labelLength === 0) { - throw new Error("Invalid cookie domain"); - } - if (domain.charCodeAt(i - 1) === 45) { - throw new Error("Invalid cookie domain"); - } - labelLength = 0; - continue; - } - if (labelLength === 0 && !isLetterOrDigit(code)) { - throw new Error("Invalid cookie domain"); - } - if (!isLetterOrDigit(code) && code !== 45) { - throw new Error("Invalid cookie domain"); - } - if (++labelLength > 63) { - throw new Error("Invalid cookie domain"); - } - } - if (labelLength === 0 || domain.charCodeAt(domain.length - 1) === 45) { + if (domain.startsWith("-") || domain.endsWith(".") || domain.endsWith("-")) { throw new Error("Invalid cookie domain"); } } @@ -16276,11 +15973,7 @@ var require_util6 = __commonJS({ throw new Error("Invalid unparsed"); } const [key, ...value] = part.split("="); - const trimmedKey = key.trim(); - const joinedValue = value.join("="); - validateCookieName(trimmedKey); - validateCookieValue(joinedValue); - out.push(`${trimmedKey}=${joinedValue}`); + out.push(`${key.trim()}=${value.join("=")}`); } return out.join("; "); } @@ -16410,14 +16103,18 @@ var require_parse = __commonJS({ } else if (attributeNameLowercase === "httponly") { cookieAttributeList.httpOnly = true; } else if (attributeNameLowercase === "samesite") { + let enforcement = "Default"; const attributeValueLowercase = attributeValue.toLowerCase(); - if (attributeValueLowercase === "none") { - cookieAttributeList.sameSite = "None"; - } else if (attributeValueLowercase === "strict") { - cookieAttributeList.sameSite = "Strict"; - } else if (attributeValueLowercase === "lax") { - cookieAttributeList.sameSite = "Lax"; + if (attributeValueLowercase.includes("none")) { + enforcement = "None"; + } + if (attributeValueLowercase.includes("strict")) { + enforcement = "Strict"; + } + if (attributeValueLowercase.includes("lax")) { + enforcement = "Lax"; } + cookieAttributeList.sameSite = enforcement; } else { cookieAttributeList.unparsed ??= []; cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`); @@ -17239,7 +16936,7 @@ var require_connection = __commonJS({ const secProtocol = response.headersList.get("Sec-WebSocket-Protocol"); if (secProtocol !== null) { const requestProtocols = getDecodeSplit("sec-websocket-protocol", request2.headersList); - if (requestProtocols === null || !requestProtocols.includes(secProtocol)) { + if (!requestProtocols.includes(secProtocol)) { failWebsocketConnection(ws, "Protocol was not set in the opening handshake."); return; } @@ -17345,26 +17042,31 @@ var require_permessage_deflate = __commonJS({ var tail = Buffer.from([0, 0, 255, 255]); var kBuffer = /* @__PURE__ */ Symbol("kBuffer"); var kLength = /* @__PURE__ */ Symbol("kLength"); + var kDefaultMaxDecompressedSize = 4 * 1024 * 1024; var PerMessageDeflate = class { /** @type {import('node:zlib').InflateRaw} */ #inflate; #options = {}; - #maxPayloadSize = 0; + /** @type {number} */ + #maxDecompressedSize; + /** @type {boolean} */ + #aborted = false; + /** @type {Function|null} */ + #currentCallback = null; /** * @param {Map} extensions + * @param {{ maxDecompressedMessageSize?: number }} [options] */ - constructor(extensions, options) { + constructor(extensions, options = {}) { this.#options.serverNoContextTakeover = extensions.has("server_no_context_takeover"); this.#options.serverMaxWindowBits = extensions.get("server_max_window_bits"); - this.#maxPayloadSize = options.maxPayloadSize; + this.#maxDecompressedSize = options.maxDecompressedMessageSize ?? kDefaultMaxDecompressedSize; } - /** - * Decompress a compressed payload. - * @param {Buffer} chunk Compressed data - * @param {boolean} fin Final fragment flag - * @param {Function} callback Callback function - */ decompress(chunk, fin, callback) { + if (this.#aborted) { + callback(new MessageSizeExceededError()); + return; + } if (!this.#inflate) { let windowBits = Z_DEFAULT_WINDOWBITS; if (this.#options.serverMaxWindowBits) { @@ -17383,12 +17085,20 @@ var require_permessage_deflate = __commonJS({ this.#inflate[kBuffer] = []; this.#inflate[kLength] = 0; this.#inflate.on("data", (data) => { + if (this.#aborted) { + return; + } this.#inflate[kLength] += data.length; - if (this.#maxPayloadSize > 0 && this.#inflate[kLength] > this.#maxPayloadSize) { - callback(new MessageSizeExceededError()); + if (this.#inflate[kLength] > this.#maxDecompressedSize) { + this.#aborted = true; this.#inflate.removeAllListeners(); this.#inflate.destroy(); this.#inflate = null; + if (this.#currentCallback) { + const cb = this.#currentCallback; + this.#currentCallback = null; + cb(new MessageSizeExceededError()); + } return; } this.#inflate[kBuffer].push(data); @@ -17398,17 +17108,19 @@ var require_permessage_deflate = __commonJS({ callback(err); }); } + this.#currentCallback = callback; this.#inflate.write(chunk); if (fin) { this.#inflate.write(tail); } this.#inflate.flush(() => { - if (!this.#inflate) { + if (this.#aborted || !this.#inflate) { return; } const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]); this.#inflate[kBuffer].length = 0; this.#inflate[kLength] = 0; + this.#currentCallback = null; callback(null, full); }); } @@ -17439,14 +17151,8 @@ var require_receiver = __commonJS({ var { WebsocketFrameSend } = require_frame(); var { closeWebSocketConnection } = require_connection(); var { PerMessageDeflate } = require_permessage_deflate(); - var { MessageSizeExceededError } = require_errors(); - function failWebsocketConnectionWithCode(ws, code, reason) { - closeWebSocketConnection(ws, code, reason, Buffer.byteLength(reason)); - failWebsocketConnection(ws, reason); - } var ByteParser = class extends Writable { #buffers = []; - #fragmentsBytes = 0; #byteOffset = 0; #loop = false; #state = parserStates.INFO; @@ -17454,21 +17160,18 @@ var require_receiver = __commonJS({ #fragments = []; /** @type {Map} */ #extensions; - /** @type {number} */ - #maxFragments; - /** @type {number} */ - #maxPayloadSize; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {import('./websocket').WebSocket} ws * @param {Map|null} extensions - * @param {{ maxFragments?: number, maxPayloadSize?: number }} [options] + * @param {{ maxDecompressedMessageSize?: number }} [options] */ constructor(ws, extensions, options = {}) { super(); this.ws = ws; this.#extensions = extensions == null ? /* @__PURE__ */ new Map() : extensions; - this.#maxFragments = options.maxFragments ?? 0; - this.#maxPayloadSize = options.maxPayloadSize ?? 0; + this.#options = options; if (this.#extensions.has("permessage-deflate")) { this.#extensions.set("permessage-deflate", new PerMessageDeflate(extensions, options)); } @@ -17483,13 +17186,6 @@ var require_receiver = __commonJS({ this.#loop = true; this.run(callback); } - #validatePayloadLength() { - if (this.#maxPayloadSize > 0 && !isControlFrame(this.#info.opcode) && this.#info.payloadLength + this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, "Payload size exceeds maximum allowed size"); - return false; - } - return true; - } /** * Runs whenever a new chunk is received. * Callback is called whenever there are no more chunks buffering, @@ -17549,9 +17245,6 @@ var require_receiver = __commonJS({ if (payloadLength <= 125) { this.#info.payloadLength = payloadLength; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (payloadLength === 126) { this.#state = parserStates.PAYLOADLENGTH_16; } else if (payloadLength === 127) { @@ -17572,9 +17265,6 @@ var require_receiver = __commonJS({ const buffer = this.consume(2); this.#info.payloadLength = buffer.readUInt16BE(0); this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.PAYLOADLENGTH_64) { if (this.#byteOffset < 8) { return callback(); @@ -17588,9 +17278,6 @@ var require_receiver = __commonJS({ } this.#info.payloadLength = lower; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.READ_DATA) { if (this.#byteOffset < this.#info.payloadLength) { return callback(); @@ -17601,46 +17288,32 @@ var require_receiver = __commonJS({ this.#state = parserStates.INFO; } else { if (!this.#info.compressed) { - if (!this.writeFragments(body)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } + this.#fragments.push(body); if (!this.#info.fragmented && this.#info.fin) { - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); + const fullMessage = Buffer.concat(this.#fragments); + websocketMessageReceived(this.ws, this.#info.binaryType, fullMessage); + this.#fragments.length = 0; } this.#state = parserStates.INFO; } else { - this.#extensions.get("permessage-deflate").decompress( - body, - this.#info.fin, - (error2, data) => { - if (error2) { - const code = error2 instanceof MessageSizeExceededError ? 1009 : 1007; - failWebsocketConnectionWithCode(this.ws, code, error2.message); - return; - } - if (!this.writeFragments(data)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } - if (!this.#info.fin) { - this.#state = parserStates.INFO; - this.#loop = true; - this.run(callback); - return; - } - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); - this.#loop = true; + this.#extensions.get("permessage-deflate").decompress(body, this.#info.fin, (error2, data) => { + if (error2) { + failWebsocketConnection(this.ws, error2.message); + return; + } + this.#fragments.push(data); + if (!this.#info.fin) { this.#state = parserStates.INFO; + this.#loop = true; this.run(callback); + return; } - ); + websocketMessageReceived(this.ws, this.#info.binaryType, Buffer.concat(this.#fragments)); + this.#loop = true; + this.#state = parserStates.INFO; + this.#fragments.length = 0; + this.run(callback); + }); this.#loop = false; break; } @@ -17683,26 +17356,6 @@ var require_receiver = __commonJS({ this.#byteOffset -= n; return buffer; } - writeFragments(fragment) { - if (this.#maxFragments > 0 && this.#fragments.length === this.#maxFragments) { - failWebsocketConnectionWithCode(this.ws, 1008, "Too many message fragments"); - return false; - } - this.#fragmentsBytes += fragment.length; - this.#fragments.push(fragment); - return true; - } - consumeFragments() { - const fragments = this.#fragments; - if (fragments.length === 1) { - this.#fragmentsBytes = 0; - return fragments.shift(); - } - const output = Buffer.concat(fragments, this.#fragmentsBytes); - this.#fragments = []; - this.#fragmentsBytes = 0; - return output; - } parseCloseBody(data) { assert(data.length !== 1); let code; @@ -17914,6 +17567,8 @@ var require_websocket = __commonJS({ #extensions = ""; /** @type {SendQueue} */ #sendQueue; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {string} url * @param {string|string[]} protocols @@ -17957,6 +17612,9 @@ var require_websocket = __commonJS({ throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError"); } this[kWebSocketURL] = new URL(urlRecord.href); + this.#options = { + maxDecompressedMessageSize: options.maxDecompressedMessageSize + }; const client = environmentSettingsObject.settingsObject; this[kController] = establishWebSocketConnection( urlRecord, @@ -18140,13 +17798,7 @@ var require_websocket = __commonJS({ */ #onConnectionEstablished(response, parsedExtensions) { this[kResponse] = response; - const webSocketOptions = this[kController]?.dispatcher?.webSocketOptions; - const maxFragments = webSocketOptions?.maxFragments; - const maxPayloadSize = webSocketOptions?.maxPayloadSize; - const parser = new ByteParser(this, parsedExtensions, { - maxFragments, - maxPayloadSize - }); + const parser = new ByteParser(this, parsedExtensions, this.#options); parser.on("drain", onParserDrain); parser.on("error", onParserError.bind(this)); response.socket.ws = this; @@ -18221,6 +17873,19 @@ var require_websocket = __commonJS({ { key: "headers", converter: webidl.nullableConverter(webidl.converters.HeadersInit) + }, + { + key: "maxDecompressedMessageSize", + converter: webidl.nullableConverter((V) => { + V = webidl.converters["unsigned long long"](V); + if (V <= 0) { + throw webidl.errors.exception({ + header: "WebSocket constructor", + message: "maxDecompressedMessageSize must be greater than 0" + }); + } + return V; + }) } ]); webidl.converters["DOMString or sequence or WebSocketInit"] = function(V) { @@ -18299,40 +17964,6 @@ 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; - } - function isValidLastEventIdBytes(buffer, start) { - for (let i = start; i < buffer.length; i++) { - if (buffer[i] === 0) { - 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; - } var EventSourceStream = class extends Transform { /** * @type {eventSourceSettings} @@ -18352,13 +17983,10 @@ var require_eventsource_stream = __commonJS({ */ eventEndCheck = false; /** - * @type {Buffer[]} + * @type {Buffer} */ - chunks = []; - chunkIndex = 0; + buffer = null; pos = 0; - lineChunkIndex = 0; - linePos = 0; event = { data: void 0, event: void 0, @@ -18389,30 +18017,63 @@ var require_eventsource_stream = __commonJS({ callback(); return; } - this.chunks.push(chunk); + if (this.buffer) { + this.buffer = Buffer.concat([this.buffer, chunk]); + } else { + this.buffer = chunk; + } if (this.checkBOM) { - if (this.handleBOM()) { - callback(); - return; + 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; } } - while (this.hasCurrentByte()) { - const byte = this.currentByte(); + while (this.pos < this.buffer.length) { if (this.eventEndCheck) { if (this.crlfCheck) { - if (byte === LF) { + if (this.buffer[this.pos] === LF) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.crlfCheck = false; - this.consumeCurrentByte(); continue; } this.crlfCheck = false; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.consumeCurrentByte(); - if (this.hasPendingEvent()) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; + if (this.event.data !== void 0 || this.event.event || this.event.id || this.event.retry) { this.processEvent(this.event); } this.clearEvent(); @@ -18421,16 +18082,17 @@ var require_eventsource_stream = __commonJS({ this.eventEndCheck = false; continue; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.parseLine(this.readLine(), this.event); - this.consumeCurrentByte(); + this.parseLine(this.buffer.subarray(0, this.pos), this.event); + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.eventEndCheck = true; continue; } - this.advanceCursor(); + this.pos++; } callback(); } @@ -18446,42 +18108,43 @@ var require_eventsource_stream = __commonJS({ if (colonPosition === 0) { return; } - let fieldLength = line.length; - let valueStart = line.length; + let field = ""; + let value = ""; if (colonPosition !== -1) { - fieldLength = colonPosition; - valueStart = colonPosition + 1; + field = line.subarray(0, colonPosition).toString("utf8"); + let valueStart = colonPosition + 1; if (line[valueStart] === SPACE) { ++valueStart; } + value = line.subarray(valueStart).toString("utf8"); + } else { + field = line.toString("utf8"); + value = ""; } - if (isFieldName(line, fieldLength, DATA)) { - const value = line.toString("utf8", valueStart); - if (event.data === void 0) { - event.data = value; - } else { - event.data += ` + switch (field) { + case "data": + if (event[field] === void 0) { + event[field] = value; + } else { + event[field] += ` ${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; - } + } + 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; } } /** @@ -18506,120 +18169,12 @@ ${value}`; } } clearEvent() { - 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(); + this.event = { + data: void 0, + event: void 0, + id: void 0, + retry: void 0 + }; } }; module.exports = { diff --git a/.github/actions/javascript/postOrReplaceComment/index.js b/.github/actions/javascript/postOrReplaceComment/index.js index 195707dedc9f..fb9eb8df9e7b 100644 --- a/.github/actions/javascript/postOrReplaceComment/index.js +++ b/.github/actions/javascript/postOrReplaceComment/index.js @@ -1863,66 +1863,10 @@ var require_request = __commonJS({ return false; } } - /** - * @param {number|null} statusCode - * @param {Buffer[]|null} headers - * @param {import('node:stream').Duplex} socket - * @param {string} [statusText] - */ - onUpgrade(statusCode, headers, socket, statusText = "") { - this.onFinally(); + onUpgrade(statusCode, headers, socket) { assert(!this.aborted); assert(!this.completed); - 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(error2) { - assert(!this.aborted); - assert(this.completed); - if (channels.error.hasSubscribers) { - channels.error.publish({ request: this, error: error2 }); - } - } - /** - * @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: [] }); - } + return this[kHandler].onUpgrade(statusCode, headers, socket); } onComplete(trailers) { this.onFinally(); @@ -1989,11 +1933,7 @@ var require_request = __commonJS({ } else if (typeof val[i] === "object") { throw new InvalidArgumentError(`invalid ${key} header`); } else { - const str = `${val[i]}`; - if (!isValidHeaderValue(str)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } - arr.push(str); + arr.push(`${val[i]}`); } } val = arr; @@ -2005,9 +1945,6 @@ var require_request = __commonJS({ val = ""; } else { val = `${val}`; - if (!isValidHeaderValue(val)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } } if (headerName === "host") { if (request2.host !== null) { @@ -2117,21 +2054,13 @@ var require_dispatcher_base = __commonJS({ var kOnDestroyed = /* @__PURE__ */ Symbol("onDestroyed"); var kOnClosed = /* @__PURE__ */ Symbol("onClosed"); var kInterceptedDispatch = /* @__PURE__ */ Symbol("Intercepted Dispatch"); - var kWebSocketOptions = /* @__PURE__ */ Symbol("webSocketOptions"); var DispatcherBase = class extends Dispatcher { - constructor(opts) { + constructor() { super(); this[kDestroyed] = false; this[kOnDestroyed] = null; this[kClosed] = false; this[kOnClosed] = []; - this[kWebSocketOptions] = opts?.webSocket ?? {}; - } - get webSocketOptions() { - return { - maxFragments: this[kWebSocketOptions].maxFragments ?? 131072, - maxPayloadSize: this[kWebSocketOptions].maxPayloadSize ?? 128 * 1024 * 1024 - }; } get destroyed() { return this[kDestroyed]; @@ -5738,7 +5667,6 @@ var require_client_h1 = __commonJS({ RequestContentLengthMismatchError, ResponseContentLengthMismatchError, RequestAbortedError, - InvalidArgumentError, HeadersTimeoutError, HeadersOverflowError, SocketError, @@ -5785,9 +5713,6 @@ var require_client_h1 = __commonJS({ var FastBuffer = Buffer[Symbol.species]; var addListener = util.addListener; var removeAllListeners = util.removeAllListeners; - var kIdleSocketValidation = /* @__PURE__ */ Symbol("kIdleSocketValidation"); - var kIdleSocketValidationTimeout = /* @__PURE__ */ Symbol("kIdleSocketValidationTimeout"); - var kSocketUsed = /* @__PURE__ */ Symbol("kSocketUsed"); var extractBody; async function lazyllhttp() { const llhttpWasmData = process.env.JEST_WORKER_ID ? require_llhttp_wasm() : void 0; @@ -5950,55 +5875,24 @@ var require_client_h1 = __commonJS({ currentBufferRef = null; } const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr; - if (ret !== constants3.ERROR.OK) { - const body = data.subarray(offset); - if (ret === constants3.ERROR.PAUSED_UPGRADE) { - this.onUpgrade(body); - } else if (ret === constants3.ERROR.PAUSED) { - this.paused = true; - socket.unshift(body); - } else { - throw this.createError(ret, body); + if (ret === constants3.ERROR.PAUSED_UPGRADE) { + this.onUpgrade(data.slice(offset)); + } else if (ret === constants3.ERROR.PAUSED) { + this.paused = true; + socket.unshift(data.slice(offset)); + } else if (ret !== constants3.ERROR.OK) { + const ptr = llhttp.llhttp_get_error_reason(this.ptr); + let message = ""; + if (ptr) { + const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); + message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; } + throw new HTTPParserError(message, constants3.ERROR[ret], data.slice(offset)); } } catch (err) { util.destroy(socket, err); } } - finish() { - assert(currentParser === null); - assert(this.ptr != null); - assert(!this.paused); - const { llhttp } = this; - let ret; - try { - currentParser = this; - ret = llhttp.llhttp_finish(this.ptr); - } finally { - currentParser = null; - } - if (ret === constants3.ERROR.OK) { - return null; - } - if (ret === constants3.ERROR.PAUSED || ret === constants3.ERROR.PAUSED_UPGRADE) { - this.paused = true; - return null; - } - return this.createError(ret, EMPTY_BUF); - } - createError(ret, data) { - const { llhttp, contentLength, bytesRead } = this; - if (contentLength && bytesRead !== parseInt(contentLength, 10)) { - return new ResponseContentLengthMismatchError(); - } - const ptr = llhttp.llhttp_get_error_reason(this.ptr); - let message = ""; - if (ptr) { - const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); - message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; - } - return new HTTPParserError(message, constants3.ERROR[ret], data); - } destroy() { assert(this.ptr != null); assert(currentParser == null); @@ -6018,10 +5912,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6065,7 +5955,7 @@ var require_client_h1 = __commonJS({ } } onUpgrade(head) { - const { upgrade, client, socket, headers, statusCode, statusText } = this; + const { upgrade, client, socket, headers, statusCode } = this; assert(upgrade); assert(client[kSocket] === socket); assert(!socket.destroyed); @@ -6090,10 +5980,9 @@ var require_client_h1 = __commonJS({ client[kQueue][client[kRunningIdx]++] = null; client.emit("disconnect", client[kUrl], [client], new InformationalError("upgrade")); try { - request2.onUpgrade(statusCode, headers, socket, statusText); - } catch (error2) { - util.errorRequest(client, request2, error2); - util.destroy(socket, error2); + request2.onUpgrade(statusCode, headers, socket); + } catch (err) { + util.destroy(socket, err); } client[kResume](); } @@ -6102,10 +5991,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6231,7 +6116,6 @@ var require_client_h1 = __commonJS({ } request2.onComplete(headers); client[kQueue][client[kRunningIdx]++] = null; - socket[kSocketUsed] = true; if (socket[kWriting]) { assert(client[kRunning] === 0); util.destroy(socket, new InformationalError("reset")); @@ -6275,19 +6159,12 @@ var require_client_h1 = __commonJS({ socket[kWriting] = false; socket[kReset] = false; socket[kBlocking] = false; - socket[kIdleSocketValidation] = 0; - socket[kIdleSocketValidationTimeout] = null; - socket[kSocketUsed] = false; socket[kParser] = new Parser(client, socket, llhttpInstance); addListener(socket, "error", function(err) { assert(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID"); const parser = this[kParser]; if (err.code === "ECONNRESET" && parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - this[kError] = parserErr; - this[kClient][kOnError](parserErr); - } + parser.onMessageComplete(); return; } this[kError] = err; @@ -6302,10 +6179,7 @@ var require_client_h1 = __commonJS({ addListener(socket, "end", function() { const parser = this[kParser]; if (parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - util.destroy(this, parserErr); - } + parser.onMessageComplete(); return; } util.destroy(this, new SocketError("other side closed", util.getSocketInfo(this))); @@ -6313,10 +6187,9 @@ var require_client_h1 = __commonJS({ addListener(socket, "close", function() { const client2 = this[kClient]; const parser = this[kParser]; - clearIdleSocketValidation(this); if (parser) { if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { - this[kError] = parser.finish() || this[kError]; + parser.onMessageComplete(); } this[kParser].destroy(); this[kParser] = null; @@ -6365,7 +6238,7 @@ var require_client_h1 = __commonJS({ return socket.destroyed; }, busy(request2) { - if (socket[kWriting] || socket[kReset] || socket[kBlocking] || socket[kIdleSocketValidation] === 1) { + if (socket[kWriting] || socket[kReset] || socket[kBlocking]) { return true; } if (request2) { @@ -6383,23 +6256,6 @@ var require_client_h1 = __commonJS({ } }; } - function clearIdleSocketValidation(socket) { - if (socket[kIdleSocketValidationTimeout]) { - clearImmediate(socket[kIdleSocketValidationTimeout]); - socket[kIdleSocketValidationTimeout] = null; - } - socket[kIdleSocketValidation] = 0; - } - function scheduleIdleSocketValidation(client, socket) { - socket[kIdleSocketValidation] = 1; - socket[kIdleSocketValidationTimeout] = setImmediate(() => { - socket[kIdleSocketValidationTimeout] = null; - socket[kIdleSocketValidation] = 2; - if (client[kSocket] === socket && !socket.destroyed) { - client[kResume](); - } - }); - } function resumeH1(client) { const socket = client[kSocket]; if (socket && !socket.destroyed) { @@ -6412,29 +6268,6 @@ var require_client_h1 = __commonJS({ socket.ref(); socket[kNoRef] = false; } - if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) { - if (socket[kIdleSocketValidation] === 0) { - scheduleIdleSocketValidation(client, socket); - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - if (socket[kIdleSocketValidation] === 1) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - } - if (client[kRunning] === 0) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - } if (client[kSize] === 0) { if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) { socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE); @@ -6465,16 +6298,8 @@ var require_client_h1 = __commonJS({ } body = bodyStream.stream; contentLength = bodyStream.length; - } else if (util.isBlobLike(body) && request2.contentType == null) { - const contentType = body.type; - if (contentType) { - const contentTypeValue = `${contentType}`; - if (!util.isValidHeaderValue(contentTypeValue)) { - util.errorRequest(client, request2, new InvalidArgumentError("invalid content-type header")); - return false; - } - headers.push("content-type", contentTypeValue); - } + } else if (util.isBlobLike(body) && request2.contentType == null && body.type) { + headers.push("content-type", body.type); } if (body && typeof body.read === "function") { body.read(0); @@ -6495,18 +6320,11 @@ var require_client_h1 = __commonJS({ process.emitWarning(new RequestContentLengthMismatchError()); } const socket = client[kSocket]; - clearIdleSocketValidation(socket); - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (request2.upgrade || request2.method === "CONNECT") { - util.destroy(socket, new InformationalError("aborted")); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - util.errorRequest(client, request2, error2 || new RequestAbortedError()); + util.errorRequest(client, request2, err || new RequestAbortedError()); util.destroy(body); util.destroy(socket, new InformationalError("aborted")); }; @@ -6862,7 +6680,6 @@ var require_client_h2 = __commonJS({ "node_modules/undici/lib/dispatcher/client-h2.js"(exports, module) { "use strict"; var assert = __require("node:assert"); - var { errorMonitor } = __require("node:events"); var { pipeline } = __require("node:stream"); var util = require_util(); var { @@ -6923,10 +6740,6 @@ var require_client_h2 = __commonJS({ } return result; } - function parseH2ResponseHeaders(headers) { - const { [HTTP2_HEADER_STATUS]: _statusCode, ...realHeaders } = headers; - return parseH2Headers(realHeaders); - } async function connectH2(client, socket) { client[kSocket] = socket; if (!h2ExperimentalWarned) { @@ -7090,22 +6903,16 @@ var require_client_h2 = __commonJS({ const { hostname, port } = client[kUrl]; headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ""}`; headers[HTTP2_HEADER_METHOD] = method; - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (method === "CONNECT" && stream != null) { - util.destroy(stream, error2 || new RequestAbortedError()); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - error2 = error2 || new RequestAbortedError(); - util.errorRequest(client, request2, error2); + err = err || new RequestAbortedError(); + util.errorRequest(client, request2, err); if (stream != null) { - util.destroy(stream, error2); + util.destroy(stream, err); } - util.destroy(body, error2); + util.destroy(body, err); client[kQueue][client[kRunningIdx]++] = null; client[kResume](); }; @@ -7120,42 +6927,18 @@ var require_client_h2 = __commonJS({ if (method === "CONNECT") { session.ref(); stream = session.request(headers, { endStream: false, signal }); - let upgradeResponseFinished = false; - const onResponse = (headers2) => { - upgradeResponseFinished = true; - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeResponse(Number(headers2[HTTP2_HEADER_STATUS]), headers2, parseH2ResponseHeaders); - }; - const onUpgradeError = (error2) => { - upgradeResponseFinished = true; - stream.off("response", onResponse); - request2.onUpgradeError(error2); - }; - const onReady = () => { - try { - request2.onUpgrade(null, null, stream); - } catch (error2) { - stream.off("response", onResponse); - abort(error2); - return; - } - if (request2.aborted) { - return; - } - stream.off("error", abort); - stream.once(errorMonitor, onUpgradeError); + if (stream.id && !stream.pending) { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; client[kQueue][client[kRunningIdx]++] = null; - }; - stream.once("response", onResponse); - stream.once("error", abort); - ++session[kOpenStreams]; - onReady(); + } else { + stream.once("ready", () => { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; + client[kQueue][client[kRunningIdx]++] = null; + }); + } stream.once("close", () => { - if (!upgradeResponseFinished && request2.completed) { - stream.off("response", onResponse); - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeError(new InformationalError(`HTTP/2: "stream error" received - code ${stream.rstCode}`)); - } session[kOpenStreams] -= 1; if (session[kOpenStreams] === 0) session.unref(); }); @@ -7716,10 +7499,9 @@ var require_client = __commonJS({ autoSelectFamilyAttemptTimeout, // h2 maxConcurrentStreams, - allowH2, - webSocket + allowH2 } = {}) { - super({ webSocket }); + super(); if (keepAlive !== void 0) { throw new InvalidArgumentError("unsupported keepAlive, use pipelining=0 instead"); } @@ -8225,8 +8007,8 @@ var require_pool_base = __commonJS({ var kRemoveClient = /* @__PURE__ */ Symbol("remove client"); var kStats = /* @__PURE__ */ Symbol("stats"); var PoolBase = class extends DispatcherBase { - constructor(opts) { - super(opts); + constructor() { + super(); this[kQueue] = new FixedQueue(); this[kClients] = []; this[kQueued] = 0; @@ -8397,6 +8179,7 @@ var require_pool = __commonJS({ allowH2, ...options } = {}) { + super(); if (connections != null && (!Number.isFinite(connections) || connections < 0)) { throw new InvalidArgumentError("invalid connections"); } @@ -8417,7 +8200,6 @@ var require_pool = __commonJS({ ...connect }); } - super(options); this[kInterceptors] = options.interceptors?.Pool && Array.isArray(options.interceptors.Pool) ? options.interceptors.Pool : []; this[kConnections] = connections || null; this[kUrl] = util.parseOrigin(origin); @@ -8617,6 +8399,7 @@ var require_agent = __commonJS({ } var Agent = class extends DispatcherBase { constructor({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { + super(); if (typeof factory !== "function") { throw new InvalidArgumentError("factory must be a function."); } @@ -8626,7 +8409,6 @@ var require_agent = __commonJS({ if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { throw new InvalidArgumentError("maxRedirections must be a positive number"); } - super(options); if (connect && typeof connect !== "function") { connect = { ...connect }; } @@ -9067,24 +8849,6 @@ var require_retry_handler = __commonJS({ const current = Date.now(); return new Date(retryAfter).getTime() - current; } - function validatePartialResponseContentLength(headers, range, statusCode, retryCount) { - const contentLength = headers["content-length"]; - if (contentLength == null) { - return null; - } - if (!Number.isFinite(range.start) || !Number.isFinite(range.end)) { - return null; - } - const length = Number(contentLength); - const expectedLength = range.end - range.start + 1; - if (!Number.isFinite(length) || length !== expectedLength) { - return new RequestRetryError("Content-Length mismatch", statusCode, { - headers, - data: { count: retryCount } - }); - } - return null; - } var RetryHandler = class _RetryHandler { constructor(opts, handlers) { const { retryOptions, ...dispatchOpts } = opts; @@ -9138,7 +8902,6 @@ var require_retry_handler = __commonJS({ this.end = null; this.etag = null; this.resume = null; - this.headersSent = false; this.handler.onConnect((reason) => { this.aborted = true; if (this.abort) { @@ -9148,17 +8911,6 @@ var require_retry_handler = __commonJS({ } }); } - 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(); @@ -9220,9 +8972,7 @@ var require_retry_handler = __commonJS({ const headers = parseHeaders(rawHeaders); this.retryCount += 1; if (statusCode >= 300) { - if (!this.headersSent && this.retryOpts.statusCodes.includes(statusCode) === false) { - this.headersSent = true; - this.checkpointResponseEnd(headers, resume); + if (this.retryOpts.statusCodes.includes(statusCode) === false) { return this.handler.onHeaders( statusCode, rawHeaders, @@ -9271,21 +9021,9 @@ var require_retry_handler = __commonJS({ ); return false; } - const contentLengthError = validatePartialResponseContentLength(headers, contentRange, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = contentRange; - 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; - } + assert(this.start === start, "content-range mismatch"); + assert(this.end == null || this.end === end, "content-range mismatch"); this.resume = resume; return true; } @@ -9293,7 +9031,6 @@ var require_retry_handler = __commonJS({ if (statusCode === 206) { const range = parseRangeHeader(headers["content-range"]); if (range == null) { - this.headersSent = true; return this.handler.onHeaders( statusCode, rawHeaders, @@ -9301,11 +9038,6 @@ var require_retry_handler = __commonJS({ statusMessage ); } - const contentLengthError = validatePartialResponseContentLength(headers, range, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = range; assert( start != null && Number.isFinite(start), @@ -9325,7 +9057,6 @@ var require_retry_handler = __commonJS({ "invalid content-length" ); this.resume = resume; - this.headersSent = true; this.etag = headers.etag != null ? headers.etag : null; if (this.etag != null && this.etag.startsWith("W/")) { this.etag = null; @@ -9353,7 +9084,7 @@ var require_retry_handler = __commonJS({ return this.handler.onComplete(rawTrailers); } onError(err) { - if (this.aborted || isDisturbed(this.opts.body) || this.headersSent && this.resume == null) { + if (this.aborted || isDisturbed(this.opts.body)) { return this.handler.onError(err); } if (this.retryCount - this.retryCountCheckpoint > 0) { @@ -16152,48 +15883,14 @@ var require_util6 = __commonJS({ for (let i = 0; i < path.length; ++i) { const code = path.charCodeAt(i); if (code < 32 || // exclude CTLs (0-31) - code > 126 || // exclude DEL and non-ascii + code === 127 || // DEL code === 59) { throw new Error("Invalid cookie path"); } } } - function isLetterOrDigit(code) { - return code >= 48 && code <= 57 || // 0-9 - code >= 65 && code <= 90 || // A-Z - code >= 97 && code <= 122; - } function validateCookieDomain(domain) { - if (domain === " ") { - return; - } - if (domain.length > 255) { - throw new Error("Invalid cookie domain"); - } - let labelLength = 0; - for (let i = 0; i < domain.length; ++i) { - const code = domain.charCodeAt(i); - if (code === 46) { - if (labelLength === 0) { - throw new Error("Invalid cookie domain"); - } - if (domain.charCodeAt(i - 1) === 45) { - throw new Error("Invalid cookie domain"); - } - labelLength = 0; - continue; - } - if (labelLength === 0 && !isLetterOrDigit(code)) { - throw new Error("Invalid cookie domain"); - } - if (!isLetterOrDigit(code) && code !== 45) { - throw new Error("Invalid cookie domain"); - } - if (++labelLength > 63) { - throw new Error("Invalid cookie domain"); - } - } - if (labelLength === 0 || domain.charCodeAt(domain.length - 1) === 45) { + if (domain.startsWith("-") || domain.endsWith(".") || domain.endsWith("-")) { throw new Error("Invalid cookie domain"); } } @@ -16276,11 +15973,7 @@ var require_util6 = __commonJS({ throw new Error("Invalid unparsed"); } const [key, ...value] = part.split("="); - const trimmedKey = key.trim(); - const joinedValue = value.join("="); - validateCookieName(trimmedKey); - validateCookieValue(joinedValue); - out.push(`${trimmedKey}=${joinedValue}`); + out.push(`${key.trim()}=${value.join("=")}`); } return out.join("; "); } @@ -16410,14 +16103,18 @@ var require_parse = __commonJS({ } else if (attributeNameLowercase === "httponly") { cookieAttributeList.httpOnly = true; } else if (attributeNameLowercase === "samesite") { + let enforcement = "Default"; const attributeValueLowercase = attributeValue.toLowerCase(); - if (attributeValueLowercase === "none") { - cookieAttributeList.sameSite = "None"; - } else if (attributeValueLowercase === "strict") { - cookieAttributeList.sameSite = "Strict"; - } else if (attributeValueLowercase === "lax") { - cookieAttributeList.sameSite = "Lax"; + if (attributeValueLowercase.includes("none")) { + enforcement = "None"; + } + if (attributeValueLowercase.includes("strict")) { + enforcement = "Strict"; + } + if (attributeValueLowercase.includes("lax")) { + enforcement = "Lax"; } + cookieAttributeList.sameSite = enforcement; } else { cookieAttributeList.unparsed ??= []; cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`); @@ -17239,7 +16936,7 @@ var require_connection = __commonJS({ const secProtocol = response.headersList.get("Sec-WebSocket-Protocol"); if (secProtocol !== null) { const requestProtocols = getDecodeSplit("sec-websocket-protocol", request2.headersList); - if (requestProtocols === null || !requestProtocols.includes(secProtocol)) { + if (!requestProtocols.includes(secProtocol)) { failWebsocketConnection(ws, "Protocol was not set in the opening handshake."); return; } @@ -17345,26 +17042,31 @@ var require_permessage_deflate = __commonJS({ var tail = Buffer.from([0, 0, 255, 255]); var kBuffer = /* @__PURE__ */ Symbol("kBuffer"); var kLength = /* @__PURE__ */ Symbol("kLength"); + var kDefaultMaxDecompressedSize = 4 * 1024 * 1024; var PerMessageDeflate = class { /** @type {import('node:zlib').InflateRaw} */ #inflate; #options = {}; - #maxPayloadSize = 0; + /** @type {number} */ + #maxDecompressedSize; + /** @type {boolean} */ + #aborted = false; + /** @type {Function|null} */ + #currentCallback = null; /** * @param {Map} extensions + * @param {{ maxDecompressedMessageSize?: number }} [options] */ - constructor(extensions, options) { + constructor(extensions, options = {}) { this.#options.serverNoContextTakeover = extensions.has("server_no_context_takeover"); this.#options.serverMaxWindowBits = extensions.get("server_max_window_bits"); - this.#maxPayloadSize = options.maxPayloadSize; + this.#maxDecompressedSize = options.maxDecompressedMessageSize ?? kDefaultMaxDecompressedSize; } - /** - * Decompress a compressed payload. - * @param {Buffer} chunk Compressed data - * @param {boolean} fin Final fragment flag - * @param {Function} callback Callback function - */ decompress(chunk, fin, callback) { + if (this.#aborted) { + callback(new MessageSizeExceededError()); + return; + } if (!this.#inflate) { let windowBits = Z_DEFAULT_WINDOWBITS; if (this.#options.serverMaxWindowBits) { @@ -17383,12 +17085,20 @@ var require_permessage_deflate = __commonJS({ this.#inflate[kBuffer] = []; this.#inflate[kLength] = 0; this.#inflate.on("data", (data) => { + if (this.#aborted) { + return; + } this.#inflate[kLength] += data.length; - if (this.#maxPayloadSize > 0 && this.#inflate[kLength] > this.#maxPayloadSize) { - callback(new MessageSizeExceededError()); + if (this.#inflate[kLength] > this.#maxDecompressedSize) { + this.#aborted = true; this.#inflate.removeAllListeners(); this.#inflate.destroy(); this.#inflate = null; + if (this.#currentCallback) { + const cb = this.#currentCallback; + this.#currentCallback = null; + cb(new MessageSizeExceededError()); + } return; } this.#inflate[kBuffer].push(data); @@ -17398,17 +17108,19 @@ var require_permessage_deflate = __commonJS({ callback(err); }); } + this.#currentCallback = callback; this.#inflate.write(chunk); if (fin) { this.#inflate.write(tail); } this.#inflate.flush(() => { - if (!this.#inflate) { + if (this.#aborted || !this.#inflate) { return; } const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]); this.#inflate[kBuffer].length = 0; this.#inflate[kLength] = 0; + this.#currentCallback = null; callback(null, full); }); } @@ -17439,14 +17151,8 @@ var require_receiver = __commonJS({ var { WebsocketFrameSend } = require_frame(); var { closeWebSocketConnection } = require_connection(); var { PerMessageDeflate } = require_permessage_deflate(); - var { MessageSizeExceededError } = require_errors(); - function failWebsocketConnectionWithCode(ws, code, reason) { - closeWebSocketConnection(ws, code, reason, Buffer.byteLength(reason)); - failWebsocketConnection(ws, reason); - } var ByteParser = class extends Writable { #buffers = []; - #fragmentsBytes = 0; #byteOffset = 0; #loop = false; #state = parserStates.INFO; @@ -17454,21 +17160,18 @@ var require_receiver = __commonJS({ #fragments = []; /** @type {Map} */ #extensions; - /** @type {number} */ - #maxFragments; - /** @type {number} */ - #maxPayloadSize; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {import('./websocket').WebSocket} ws * @param {Map|null} extensions - * @param {{ maxFragments?: number, maxPayloadSize?: number }} [options] + * @param {{ maxDecompressedMessageSize?: number }} [options] */ constructor(ws, extensions, options = {}) { super(); this.ws = ws; this.#extensions = extensions == null ? /* @__PURE__ */ new Map() : extensions; - this.#maxFragments = options.maxFragments ?? 0; - this.#maxPayloadSize = options.maxPayloadSize ?? 0; + this.#options = options; if (this.#extensions.has("permessage-deflate")) { this.#extensions.set("permessage-deflate", new PerMessageDeflate(extensions, options)); } @@ -17483,13 +17186,6 @@ var require_receiver = __commonJS({ this.#loop = true; this.run(callback); } - #validatePayloadLength() { - if (this.#maxPayloadSize > 0 && !isControlFrame(this.#info.opcode) && this.#info.payloadLength + this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, "Payload size exceeds maximum allowed size"); - return false; - } - return true; - } /** * Runs whenever a new chunk is received. * Callback is called whenever there are no more chunks buffering, @@ -17549,9 +17245,6 @@ var require_receiver = __commonJS({ if (payloadLength <= 125) { this.#info.payloadLength = payloadLength; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (payloadLength === 126) { this.#state = parserStates.PAYLOADLENGTH_16; } else if (payloadLength === 127) { @@ -17572,9 +17265,6 @@ var require_receiver = __commonJS({ const buffer = this.consume(2); this.#info.payloadLength = buffer.readUInt16BE(0); this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.PAYLOADLENGTH_64) { if (this.#byteOffset < 8) { return callback(); @@ -17588,9 +17278,6 @@ var require_receiver = __commonJS({ } this.#info.payloadLength = lower; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.READ_DATA) { if (this.#byteOffset < this.#info.payloadLength) { return callback(); @@ -17601,46 +17288,32 @@ var require_receiver = __commonJS({ this.#state = parserStates.INFO; } else { if (!this.#info.compressed) { - if (!this.writeFragments(body)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } + this.#fragments.push(body); if (!this.#info.fragmented && this.#info.fin) { - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); + const fullMessage = Buffer.concat(this.#fragments); + websocketMessageReceived(this.ws, this.#info.binaryType, fullMessage); + this.#fragments.length = 0; } this.#state = parserStates.INFO; } else { - this.#extensions.get("permessage-deflate").decompress( - body, - this.#info.fin, - (error2, data) => { - if (error2) { - const code = error2 instanceof MessageSizeExceededError ? 1009 : 1007; - failWebsocketConnectionWithCode(this.ws, code, error2.message); - return; - } - if (!this.writeFragments(data)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } - if (!this.#info.fin) { - this.#state = parserStates.INFO; - this.#loop = true; - this.run(callback); - return; - } - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); - this.#loop = true; + this.#extensions.get("permessage-deflate").decompress(body, this.#info.fin, (error2, data) => { + if (error2) { + failWebsocketConnection(this.ws, error2.message); + return; + } + this.#fragments.push(data); + if (!this.#info.fin) { this.#state = parserStates.INFO; + this.#loop = true; this.run(callback); + return; } - ); + websocketMessageReceived(this.ws, this.#info.binaryType, Buffer.concat(this.#fragments)); + this.#loop = true; + this.#state = parserStates.INFO; + this.#fragments.length = 0; + this.run(callback); + }); this.#loop = false; break; } @@ -17683,26 +17356,6 @@ var require_receiver = __commonJS({ this.#byteOffset -= n; return buffer; } - writeFragments(fragment) { - if (this.#maxFragments > 0 && this.#fragments.length === this.#maxFragments) { - failWebsocketConnectionWithCode(this.ws, 1008, "Too many message fragments"); - return false; - } - this.#fragmentsBytes += fragment.length; - this.#fragments.push(fragment); - return true; - } - consumeFragments() { - const fragments = this.#fragments; - if (fragments.length === 1) { - this.#fragmentsBytes = 0; - return fragments.shift(); - } - const output = Buffer.concat(fragments, this.#fragmentsBytes); - this.#fragments = []; - this.#fragmentsBytes = 0; - return output; - } parseCloseBody(data) { assert(data.length !== 1); let code; @@ -17914,6 +17567,8 @@ var require_websocket = __commonJS({ #extensions = ""; /** @type {SendQueue} */ #sendQueue; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {string} url * @param {string|string[]} protocols @@ -17957,6 +17612,9 @@ var require_websocket = __commonJS({ throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError"); } this[kWebSocketURL] = new URL(urlRecord.href); + this.#options = { + maxDecompressedMessageSize: options.maxDecompressedMessageSize + }; const client = environmentSettingsObject.settingsObject; this[kController] = establishWebSocketConnection( urlRecord, @@ -18140,13 +17798,7 @@ var require_websocket = __commonJS({ */ #onConnectionEstablished(response, parsedExtensions) { this[kResponse] = response; - const webSocketOptions = this[kController]?.dispatcher?.webSocketOptions; - const maxFragments = webSocketOptions?.maxFragments; - const maxPayloadSize = webSocketOptions?.maxPayloadSize; - const parser = new ByteParser(this, parsedExtensions, { - maxFragments, - maxPayloadSize - }); + const parser = new ByteParser(this, parsedExtensions, this.#options); parser.on("drain", onParserDrain); parser.on("error", onParserError.bind(this)); response.socket.ws = this; @@ -18221,6 +17873,19 @@ var require_websocket = __commonJS({ { key: "headers", converter: webidl.nullableConverter(webidl.converters.HeadersInit) + }, + { + key: "maxDecompressedMessageSize", + converter: webidl.nullableConverter((V) => { + V = webidl.converters["unsigned long long"](V); + if (V <= 0) { + throw webidl.errors.exception({ + header: "WebSocket constructor", + message: "maxDecompressedMessageSize must be greater than 0" + }); + } + return V; + }) } ]); webidl.converters["DOMString or sequence or WebSocketInit"] = function(V) { @@ -18299,40 +17964,6 @@ 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; - } - function isValidLastEventIdBytes(buffer, start) { - for (let i = start; i < buffer.length; i++) { - if (buffer[i] === 0) { - 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; - } var EventSourceStream = class extends Transform { /** * @type {eventSourceSettings} @@ -18352,13 +17983,10 @@ var require_eventsource_stream = __commonJS({ */ eventEndCheck = false; /** - * @type {Buffer[]} + * @type {Buffer} */ - chunks = []; - chunkIndex = 0; + buffer = null; pos = 0; - lineChunkIndex = 0; - linePos = 0; event = { data: void 0, event: void 0, @@ -18389,30 +18017,63 @@ var require_eventsource_stream = __commonJS({ callback(); return; } - this.chunks.push(chunk); + if (this.buffer) { + this.buffer = Buffer.concat([this.buffer, chunk]); + } else { + this.buffer = chunk; + } if (this.checkBOM) { - if (this.handleBOM()) { - callback(); - return; + 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; } } - while (this.hasCurrentByte()) { - const byte = this.currentByte(); + while (this.pos < this.buffer.length) { if (this.eventEndCheck) { if (this.crlfCheck) { - if (byte === LF) { + if (this.buffer[this.pos] === LF) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.crlfCheck = false; - this.consumeCurrentByte(); continue; } this.crlfCheck = false; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.consumeCurrentByte(); - if (this.hasPendingEvent()) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; + if (this.event.data !== void 0 || this.event.event || this.event.id || this.event.retry) { this.processEvent(this.event); } this.clearEvent(); @@ -18421,16 +18082,17 @@ var require_eventsource_stream = __commonJS({ this.eventEndCheck = false; continue; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.parseLine(this.readLine(), this.event); - this.consumeCurrentByte(); + this.parseLine(this.buffer.subarray(0, this.pos), this.event); + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.eventEndCheck = true; continue; } - this.advanceCursor(); + this.pos++; } callback(); } @@ -18446,42 +18108,43 @@ var require_eventsource_stream = __commonJS({ if (colonPosition === 0) { return; } - let fieldLength = line.length; - let valueStart = line.length; + let field = ""; + let value = ""; if (colonPosition !== -1) { - fieldLength = colonPosition; - valueStart = colonPosition + 1; + field = line.subarray(0, colonPosition).toString("utf8"); + let valueStart = colonPosition + 1; if (line[valueStart] === SPACE) { ++valueStart; } + value = line.subarray(valueStart).toString("utf8"); + } else { + field = line.toString("utf8"); + value = ""; } - if (isFieldName(line, fieldLength, DATA)) { - const value = line.toString("utf8", valueStart); - if (event.data === void 0) { - event.data = value; - } else { - event.data += ` + switch (field) { + case "data": + if (event[field] === void 0) { + event[field] = value; + } else { + event[field] += ` ${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; - } + } + 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; } } /** @@ -18506,120 +18169,12 @@ ${value}`; } } clearEvent() { - 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(); + this.event = { + data: void 0, + event: void 0, + id: void 0, + retry: void 0 + }; } }; module.exports = { diff --git a/.github/actions/javascript/proposalPoliceComment/index.js b/.github/actions/javascript/proposalPoliceComment/index.js index 58a12c5fb27a..126b34462df4 100644 --- a/.github/actions/javascript/proposalPoliceComment/index.js +++ b/.github/actions/javascript/proposalPoliceComment/index.js @@ -1863,66 +1863,10 @@ var require_request = __commonJS({ return false; } } - /** - * @param {number|null} statusCode - * @param {Buffer[]|null} headers - * @param {import('node:stream').Duplex} socket - * @param {string} [statusText] - */ - onUpgrade(statusCode, headers, socket, statusText = "") { - this.onFinally(); + onUpgrade(statusCode, headers, socket) { assert(!this.aborted); assert(!this.completed); - 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(error2) { - assert(!this.aborted); - assert(this.completed); - if (channels.error.hasSubscribers) { - channels.error.publish({ request: this, error: error2 }); - } - } - /** - * @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: [] }); - } + return this[kHandler].onUpgrade(statusCode, headers, socket); } onComplete(trailers) { this.onFinally(); @@ -1989,11 +1933,7 @@ var require_request = __commonJS({ } else if (typeof val[i] === "object") { throw new InvalidArgumentError(`invalid ${key} header`); } else { - const str2 = `${val[i]}`; - if (!isValidHeaderValue(str2)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } - arr.push(str2); + arr.push(`${val[i]}`); } } val = arr; @@ -2005,9 +1945,6 @@ var require_request = __commonJS({ val = ""; } else { val = `${val}`; - if (!isValidHeaderValue(val)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } } if (headerName === "host") { if (request2.host !== null) { @@ -2117,21 +2054,13 @@ var require_dispatcher_base = __commonJS({ var kOnDestroyed = /* @__PURE__ */ Symbol("onDestroyed"); var kOnClosed = /* @__PURE__ */ Symbol("onClosed"); var kInterceptedDispatch = /* @__PURE__ */ Symbol("Intercepted Dispatch"); - var kWebSocketOptions = /* @__PURE__ */ Symbol("webSocketOptions"); var DispatcherBase = class extends Dispatcher { - constructor(opts) { + constructor() { super(); this[kDestroyed] = false; this[kOnDestroyed] = null; this[kClosed] = false; this[kOnClosed] = []; - this[kWebSocketOptions] = opts?.webSocket ?? {}; - } - get webSocketOptions() { - return { - maxFragments: this[kWebSocketOptions].maxFragments ?? 131072, - maxPayloadSize: this[kWebSocketOptions].maxPayloadSize ?? 128 * 1024 * 1024 - }; } get destroyed() { return this[kDestroyed]; @@ -5738,7 +5667,6 @@ var require_client_h1 = __commonJS({ RequestContentLengthMismatchError, ResponseContentLengthMismatchError, RequestAbortedError, - InvalidArgumentError, HeadersTimeoutError, HeadersOverflowError, SocketError, @@ -5785,9 +5713,6 @@ var require_client_h1 = __commonJS({ var FastBuffer = Buffer[Symbol.species]; var addListener = util.addListener; var removeAllListeners = util.removeAllListeners; - var kIdleSocketValidation = /* @__PURE__ */ Symbol("kIdleSocketValidation"); - var kIdleSocketValidationTimeout = /* @__PURE__ */ Symbol("kIdleSocketValidationTimeout"); - var kSocketUsed = /* @__PURE__ */ Symbol("kSocketUsed"); var extractBody; async function lazyllhttp() { const llhttpWasmData = process.env.JEST_WORKER_ID ? require_llhttp_wasm() : void 0; @@ -5950,55 +5875,24 @@ var require_client_h1 = __commonJS({ currentBufferRef = null; } const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr; - if (ret !== constants3.ERROR.OK) { - const body = data.subarray(offset); - if (ret === constants3.ERROR.PAUSED_UPGRADE) { - this.onUpgrade(body); - } else if (ret === constants3.ERROR.PAUSED) { - this.paused = true; - socket.unshift(body); - } else { - throw this.createError(ret, body); - } + if (ret === constants3.ERROR.PAUSED_UPGRADE) { + this.onUpgrade(data.slice(offset)); + } else if (ret === constants3.ERROR.PAUSED) { + this.paused = true; + socket.unshift(data.slice(offset)); + } else if (ret !== constants3.ERROR.OK) { + const ptr = llhttp.llhttp_get_error_reason(this.ptr); + let message2 = ""; + if (ptr) { + const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); + message2 = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; + } + throw new HTTPParserError(message2, constants3.ERROR[ret], data.slice(offset)); } } catch (err) { util.destroy(socket, err); } } - finish() { - assert(currentParser === null); - assert(this.ptr != null); - assert(!this.paused); - const { llhttp } = this; - let ret; - try { - currentParser = this; - ret = llhttp.llhttp_finish(this.ptr); - } finally { - currentParser = null; - } - if (ret === constants3.ERROR.OK) { - return null; - } - if (ret === constants3.ERROR.PAUSED || ret === constants3.ERROR.PAUSED_UPGRADE) { - this.paused = true; - return null; - } - return this.createError(ret, EMPTY_BUF); - } - createError(ret, data) { - const { llhttp, contentLength, bytesRead } = this; - if (contentLength && bytesRead !== parseInt(contentLength, 10)) { - return new ResponseContentLengthMismatchError(); - } - const ptr = llhttp.llhttp_get_error_reason(this.ptr); - let message2 = ""; - if (ptr) { - const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); - message2 = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; - } - return new HTTPParserError(message2, constants3.ERROR[ret], data); - } destroy() { assert(this.ptr != null); assert(currentParser == null); @@ -6018,10 +5912,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6065,7 +5955,7 @@ var require_client_h1 = __commonJS({ } } onUpgrade(head) { - const { upgrade, client, socket, headers, statusCode, statusText } = this; + const { upgrade, client, socket, headers, statusCode } = this; assert(upgrade); assert(client[kSocket] === socket); assert(!socket.destroyed); @@ -6090,10 +5980,9 @@ var require_client_h1 = __commonJS({ client[kQueue][client[kRunningIdx]++] = null; client.emit("disconnect", client[kUrl], [client], new InformationalError("upgrade")); try { - request2.onUpgrade(statusCode, headers, socket, statusText); - } catch (error2) { - util.errorRequest(client, request2, error2); - util.destroy(socket, error2); + request2.onUpgrade(statusCode, headers, socket); + } catch (err) { + util.destroy(socket, err); } client[kResume](); } @@ -6102,10 +5991,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6231,7 +6116,6 @@ var require_client_h1 = __commonJS({ } request2.onComplete(headers); client[kQueue][client[kRunningIdx]++] = null; - socket[kSocketUsed] = true; if (socket[kWriting]) { assert(client[kRunning] === 0); util.destroy(socket, new InformationalError("reset")); @@ -6275,19 +6159,12 @@ var require_client_h1 = __commonJS({ socket[kWriting] = false; socket[kReset] = false; socket[kBlocking] = false; - socket[kIdleSocketValidation] = 0; - socket[kIdleSocketValidationTimeout] = null; - socket[kSocketUsed] = false; socket[kParser] = new Parser(client, socket, llhttpInstance); addListener(socket, "error", function(err) { assert(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID"); const parser = this[kParser]; if (err.code === "ECONNRESET" && parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - this[kError] = parserErr; - this[kClient][kOnError](parserErr); - } + parser.onMessageComplete(); return; } this[kError] = err; @@ -6302,10 +6179,7 @@ var require_client_h1 = __commonJS({ addListener(socket, "end", function() { const parser = this[kParser]; if (parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - util.destroy(this, parserErr); - } + parser.onMessageComplete(); return; } util.destroy(this, new SocketError("other side closed", util.getSocketInfo(this))); @@ -6313,10 +6187,9 @@ var require_client_h1 = __commonJS({ addListener(socket, "close", function() { const client2 = this[kClient]; const parser = this[kParser]; - clearIdleSocketValidation(this); if (parser) { if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { - this[kError] = parser.finish() || this[kError]; + parser.onMessageComplete(); } this[kParser].destroy(); this[kParser] = null; @@ -6365,7 +6238,7 @@ var require_client_h1 = __commonJS({ return socket.destroyed; }, busy(request2) { - if (socket[kWriting] || socket[kReset] || socket[kBlocking] || socket[kIdleSocketValidation] === 1) { + if (socket[kWriting] || socket[kReset] || socket[kBlocking]) { return true; } if (request2) { @@ -6383,23 +6256,6 @@ var require_client_h1 = __commonJS({ } }; } - function clearIdleSocketValidation(socket) { - if (socket[kIdleSocketValidationTimeout]) { - clearImmediate(socket[kIdleSocketValidationTimeout]); - socket[kIdleSocketValidationTimeout] = null; - } - socket[kIdleSocketValidation] = 0; - } - function scheduleIdleSocketValidation(client, socket) { - socket[kIdleSocketValidation] = 1; - socket[kIdleSocketValidationTimeout] = setImmediate(() => { - socket[kIdleSocketValidationTimeout] = null; - socket[kIdleSocketValidation] = 2; - if (client[kSocket] === socket && !socket.destroyed) { - client[kResume](); - } - }); - } function resumeH1(client) { const socket = client[kSocket]; if (socket && !socket.destroyed) { @@ -6412,29 +6268,6 @@ var require_client_h1 = __commonJS({ socket.ref(); socket[kNoRef] = false; } - if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) { - if (socket[kIdleSocketValidation] === 0) { - scheduleIdleSocketValidation(client, socket); - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - if (socket[kIdleSocketValidation] === 1) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - } - if (client[kRunning] === 0) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - } if (client[kSize] === 0) { if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) { socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE); @@ -6465,16 +6298,8 @@ var require_client_h1 = __commonJS({ } body = bodyStream.stream; contentLength = bodyStream.length; - } else if (util.isBlobLike(body) && request2.contentType == null) { - const contentType = body.type; - if (contentType) { - const contentTypeValue = `${contentType}`; - if (!util.isValidHeaderValue(contentTypeValue)) { - util.errorRequest(client, request2, new InvalidArgumentError("invalid content-type header")); - return false; - } - headers.push("content-type", contentTypeValue); - } + } else if (util.isBlobLike(body) && request2.contentType == null && body.type) { + headers.push("content-type", body.type); } if (body && typeof body.read === "function") { body.read(0); @@ -6495,18 +6320,11 @@ var require_client_h1 = __commonJS({ process.emitWarning(new RequestContentLengthMismatchError()); } const socket = client[kSocket]; - clearIdleSocketValidation(socket); - const abort = (error2) => { - if (request2.aborted) { + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - if (request2.completed) { - if (request2.upgrade || request2.method === "CONNECT") { - util.destroy(socket, new InformationalError("aborted")); - } - return; - } - util.errorRequest(client, request2, error2 || new RequestAbortedError()); + util.errorRequest(client, request2, err || new RequestAbortedError()); util.destroy(body); util.destroy(socket, new InformationalError("aborted")); }; @@ -6862,7 +6680,6 @@ var require_client_h2 = __commonJS({ "node_modules/undici/lib/dispatcher/client-h2.js"(exports, module) { "use strict"; var assert = __require("node:assert"); - var { errorMonitor } = __require("node:events"); var { pipeline } = __require("node:stream"); var util = require_util(); var { @@ -6923,10 +6740,6 @@ var require_client_h2 = __commonJS({ } return result; } - function parseH2ResponseHeaders(headers) { - const { [HTTP2_HEADER_STATUS]: _statusCode, ...realHeaders } = headers; - return parseH2Headers(realHeaders); - } async function connectH2(client, socket) { client[kSocket] = socket; if (!h2ExperimentalWarned) { @@ -7090,22 +6903,16 @@ var require_client_h2 = __commonJS({ const { hostname, port } = client[kUrl]; headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ""}`; headers[HTTP2_HEADER_METHOD] = method; - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (method === "CONNECT" && stream != null) { - util.destroy(stream, error2 || new RequestAbortedError()); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - error2 = error2 || new RequestAbortedError(); - util.errorRequest(client, request2, error2); + err = err || new RequestAbortedError(); + util.errorRequest(client, request2, err); if (stream != null) { - util.destroy(stream, error2); + util.destroy(stream, err); } - util.destroy(body, error2); + util.destroy(body, err); client[kQueue][client[kRunningIdx]++] = null; client[kResume](); }; @@ -7120,42 +6927,18 @@ var require_client_h2 = __commonJS({ if (method === "CONNECT") { session.ref(); stream = session.request(headers, { endStream: false, signal }); - let upgradeResponseFinished = false; - const onResponse = (headers2) => { - upgradeResponseFinished = true; - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeResponse(Number(headers2[HTTP2_HEADER_STATUS]), headers2, parseH2ResponseHeaders); - }; - const onUpgradeError = (error2) => { - upgradeResponseFinished = true; - stream.off("response", onResponse); - request2.onUpgradeError(error2); - }; - const onReady = () => { - try { - request2.onUpgrade(null, null, stream); - } catch (error2) { - stream.off("response", onResponse); - abort(error2); - return; - } - if (request2.aborted) { - return; - } - stream.off("error", abort); - stream.once(errorMonitor, onUpgradeError); + if (stream.id && !stream.pending) { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; client[kQueue][client[kRunningIdx]++] = null; - }; - stream.once("response", onResponse); - stream.once("error", abort); - ++session[kOpenStreams]; - onReady(); + } else { + stream.once("ready", () => { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; + client[kQueue][client[kRunningIdx]++] = null; + }); + } stream.once("close", () => { - if (!upgradeResponseFinished && request2.completed) { - stream.off("response", onResponse); - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeError(new InformationalError(`HTTP/2: "stream error" received - code ${stream.rstCode}`)); - } session[kOpenStreams] -= 1; if (session[kOpenStreams] === 0) session.unref(); }); @@ -7716,10 +7499,9 @@ var require_client = __commonJS({ autoSelectFamilyAttemptTimeout, // h2 maxConcurrentStreams, - allowH2, - webSocket + allowH2 } = {}) { - super({ webSocket }); + super(); if (keepAlive !== void 0) { throw new InvalidArgumentError("unsupported keepAlive, use pipelining=0 instead"); } @@ -8225,8 +8007,8 @@ var require_pool_base = __commonJS({ var kRemoveClient = /* @__PURE__ */ Symbol("remove client"); var kStats = /* @__PURE__ */ Symbol("stats"); var PoolBase = class extends DispatcherBase { - constructor(opts) { - super(opts); + constructor() { + super(); this[kQueue] = new FixedQueue(); this[kClients] = []; this[kQueued] = 0; @@ -8397,6 +8179,7 @@ var require_pool = __commonJS({ allowH2, ...options } = {}) { + super(); if (connections != null && (!Number.isFinite(connections) || connections < 0)) { throw new InvalidArgumentError("invalid connections"); } @@ -8417,7 +8200,6 @@ var require_pool = __commonJS({ ...connect }); } - super(options); this[kInterceptors] = options.interceptors?.Pool && Array.isArray(options.interceptors.Pool) ? options.interceptors.Pool : []; this[kConnections] = connections || null; this[kUrl] = util.parseOrigin(origin); @@ -8617,6 +8399,7 @@ var require_agent = __commonJS({ } var Agent = class extends DispatcherBase { constructor({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { + super(); if (typeof factory !== "function") { throw new InvalidArgumentError("factory must be a function."); } @@ -8626,7 +8409,6 @@ var require_agent = __commonJS({ if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { throw new InvalidArgumentError("maxRedirections must be a positive number"); } - super(options); if (connect && typeof connect !== "function") { connect = { ...connect }; } @@ -9067,24 +8849,6 @@ var require_retry_handler = __commonJS({ const current = Date.now(); return new Date(retryAfter).getTime() - current; } - function validatePartialResponseContentLength(headers, range, statusCode, retryCount) { - const contentLength = headers["content-length"]; - if (contentLength == null) { - return null; - } - if (!Number.isFinite(range.start) || !Number.isFinite(range.end)) { - return null; - } - const length = Number(contentLength); - const expectedLength = range.end - range.start + 1; - if (!Number.isFinite(length) || length !== expectedLength) { - return new RequestRetryError("Content-Length mismatch", statusCode, { - headers, - data: { count: retryCount } - }); - } - return null; - } var RetryHandler = class _RetryHandler { constructor(opts, handlers) { const { retryOptions, ...dispatchOpts } = opts; @@ -9138,7 +8902,6 @@ var require_retry_handler = __commonJS({ this.end = null; this.etag = null; this.resume = null; - this.headersSent = false; this.handler.onConnect((reason) => { this.aborted = true; if (this.abort) { @@ -9148,17 +8911,6 @@ var require_retry_handler = __commonJS({ } }); } - 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(); @@ -9220,9 +8972,7 @@ var require_retry_handler = __commonJS({ const headers = parseHeaders(rawHeaders); this.retryCount += 1; if (statusCode >= 300) { - if (!this.headersSent && this.retryOpts.statusCodes.includes(statusCode) === false) { - this.headersSent = true; - this.checkpointResponseEnd(headers, resume); + if (this.retryOpts.statusCodes.includes(statusCode) === false) { return this.handler.onHeaders( statusCode, rawHeaders, @@ -9271,21 +9021,9 @@ var require_retry_handler = __commonJS({ ); return false; } - const contentLengthError = validatePartialResponseContentLength(headers, contentRange, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = contentRange; - 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; - } + assert(this.start === start, "content-range mismatch"); + assert(this.end == null || this.end === end, "content-range mismatch"); this.resume = resume; return true; } @@ -9293,7 +9031,6 @@ var require_retry_handler = __commonJS({ if (statusCode === 206) { const range = parseRangeHeader(headers["content-range"]); if (range == null) { - this.headersSent = true; return this.handler.onHeaders( statusCode, rawHeaders, @@ -9301,11 +9038,6 @@ var require_retry_handler = __commonJS({ statusMessage ); } - const contentLengthError = validatePartialResponseContentLength(headers, range, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = range; assert( start != null && Number.isFinite(start), @@ -9325,7 +9057,6 @@ var require_retry_handler = __commonJS({ "invalid content-length" ); this.resume = resume; - this.headersSent = true; this.etag = headers.etag != null ? headers.etag : null; if (this.etag != null && this.etag.startsWith("W/")) { this.etag = null; @@ -9353,7 +9084,7 @@ var require_retry_handler = __commonJS({ return this.handler.onComplete(rawTrailers); } onError(err) { - if (this.aborted || isDisturbed(this.opts.body) || this.headersSent && this.resume == null) { + if (this.aborted || isDisturbed(this.opts.body)) { return this.handler.onError(err); } if (this.retryCount - this.retryCountCheckpoint > 0) { @@ -16152,48 +15883,14 @@ var require_util6 = __commonJS({ for (let i = 0; i < path2.length; ++i) { const code = path2.charCodeAt(i); if (code < 32 || // exclude CTLs (0-31) - code > 126 || // exclude DEL and non-ascii + code === 127 || // DEL code === 59) { throw new Error("Invalid cookie path"); } } } - function isLetterOrDigit(code) { - return code >= 48 && code <= 57 || // 0-9 - code >= 65 && code <= 90 || // A-Z - code >= 97 && code <= 122; - } function validateCookieDomain(domain) { - if (domain === " ") { - return; - } - if (domain.length > 255) { - throw new Error("Invalid cookie domain"); - } - let labelLength = 0; - for (let i = 0; i < domain.length; ++i) { - const code = domain.charCodeAt(i); - if (code === 46) { - if (labelLength === 0) { - throw new Error("Invalid cookie domain"); - } - if (domain.charCodeAt(i - 1) === 45) { - throw new Error("Invalid cookie domain"); - } - labelLength = 0; - continue; - } - if (labelLength === 0 && !isLetterOrDigit(code)) { - throw new Error("Invalid cookie domain"); - } - if (!isLetterOrDigit(code) && code !== 45) { - throw new Error("Invalid cookie domain"); - } - if (++labelLength > 63) { - throw new Error("Invalid cookie domain"); - } - } - if (labelLength === 0 || domain.charCodeAt(domain.length - 1) === 45) { + if (domain.startsWith("-") || domain.endsWith(".") || domain.endsWith("-")) { throw new Error("Invalid cookie domain"); } } @@ -16276,11 +15973,7 @@ var require_util6 = __commonJS({ throw new Error("Invalid unparsed"); } const [key, ...value] = part.split("="); - const trimmedKey = key.trim(); - const joinedValue = value.join("="); - validateCookieName(trimmedKey); - validateCookieValue(joinedValue); - out.push(`${trimmedKey}=${joinedValue}`); + out.push(`${key.trim()}=${value.join("=")}`); } return out.join("; "); } @@ -16410,14 +16103,18 @@ var require_parse = __commonJS({ } else if (attributeNameLowercase === "httponly") { cookieAttributeList.httpOnly = true; } else if (attributeNameLowercase === "samesite") { + let enforcement = "Default"; const attributeValueLowercase = attributeValue.toLowerCase(); - if (attributeValueLowercase === "none") { - cookieAttributeList.sameSite = "None"; - } else if (attributeValueLowercase === "strict") { - cookieAttributeList.sameSite = "Strict"; - } else if (attributeValueLowercase === "lax") { - cookieAttributeList.sameSite = "Lax"; + if (attributeValueLowercase.includes("none")) { + enforcement = "None"; + } + if (attributeValueLowercase.includes("strict")) { + enforcement = "Strict"; + } + if (attributeValueLowercase.includes("lax")) { + enforcement = "Lax"; } + cookieAttributeList.sameSite = enforcement; } else { cookieAttributeList.unparsed ??= []; cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`); @@ -17239,7 +16936,7 @@ var require_connection = __commonJS({ const secProtocol = response.headersList.get("Sec-WebSocket-Protocol"); if (secProtocol !== null) { const requestProtocols = getDecodeSplit("sec-websocket-protocol", request2.headersList); - if (requestProtocols === null || !requestProtocols.includes(secProtocol)) { + if (!requestProtocols.includes(secProtocol)) { failWebsocketConnection(ws, "Protocol was not set in the opening handshake."); return; } @@ -17345,26 +17042,31 @@ var require_permessage_deflate = __commonJS({ var tail = Buffer.from([0, 0, 255, 255]); var kBuffer = /* @__PURE__ */ Symbol("kBuffer"); var kLength = /* @__PURE__ */ Symbol("kLength"); + var kDefaultMaxDecompressedSize = 4 * 1024 * 1024; var PerMessageDeflate = class { /** @type {import('node:zlib').InflateRaw} */ #inflate; #options = {}; - #maxPayloadSize = 0; + /** @type {number} */ + #maxDecompressedSize; + /** @type {boolean} */ + #aborted = false; + /** @type {Function|null} */ + #currentCallback = null; /** * @param {Map} extensions + * @param {{ maxDecompressedMessageSize?: number }} [options] */ - constructor(extensions, options) { + constructor(extensions, options = {}) { this.#options.serverNoContextTakeover = extensions.has("server_no_context_takeover"); this.#options.serverMaxWindowBits = extensions.get("server_max_window_bits"); - this.#maxPayloadSize = options.maxPayloadSize; + this.#maxDecompressedSize = options.maxDecompressedMessageSize ?? kDefaultMaxDecompressedSize; } - /** - * Decompress a compressed payload. - * @param {Buffer} chunk Compressed data - * @param {boolean} fin Final fragment flag - * @param {Function} callback Callback function - */ decompress(chunk, fin, callback) { + if (this.#aborted) { + callback(new MessageSizeExceededError()); + return; + } if (!this.#inflate) { let windowBits = Z_DEFAULT_WINDOWBITS; if (this.#options.serverMaxWindowBits) { @@ -17383,12 +17085,20 @@ var require_permessage_deflate = __commonJS({ this.#inflate[kBuffer] = []; this.#inflate[kLength] = 0; this.#inflate.on("data", (data) => { + if (this.#aborted) { + return; + } this.#inflate[kLength] += data.length; - if (this.#maxPayloadSize > 0 && this.#inflate[kLength] > this.#maxPayloadSize) { - callback(new MessageSizeExceededError()); + if (this.#inflate[kLength] > this.#maxDecompressedSize) { + this.#aborted = true; this.#inflate.removeAllListeners(); this.#inflate.destroy(); this.#inflate = null; + if (this.#currentCallback) { + const cb = this.#currentCallback; + this.#currentCallback = null; + cb(new MessageSizeExceededError()); + } return; } this.#inflate[kBuffer].push(data); @@ -17398,17 +17108,19 @@ var require_permessage_deflate = __commonJS({ callback(err); }); } + this.#currentCallback = callback; this.#inflate.write(chunk); if (fin) { this.#inflate.write(tail); } this.#inflate.flush(() => { - if (!this.#inflate) { + if (this.#aborted || !this.#inflate) { return; } const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]); this.#inflate[kBuffer].length = 0; this.#inflate[kLength] = 0; + this.#currentCallback = null; callback(null, full); }); } @@ -17439,14 +17151,8 @@ var require_receiver = __commonJS({ var { WebsocketFrameSend } = require_frame(); var { closeWebSocketConnection } = require_connection(); var { PerMessageDeflate } = require_permessage_deflate(); - var { MessageSizeExceededError } = require_errors(); - function failWebsocketConnectionWithCode(ws, code, reason) { - closeWebSocketConnection(ws, code, reason, Buffer.byteLength(reason)); - failWebsocketConnection(ws, reason); - } var ByteParser = class extends Writable { #buffers = []; - #fragmentsBytes = 0; #byteOffset = 0; #loop = false; #state = parserStates.INFO; @@ -17454,21 +17160,18 @@ var require_receiver = __commonJS({ #fragments = []; /** @type {Map} */ #extensions; - /** @type {number} */ - #maxFragments; - /** @type {number} */ - #maxPayloadSize; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {import('./websocket').WebSocket} ws * @param {Map|null} extensions - * @param {{ maxFragments?: number, maxPayloadSize?: number }} [options] + * @param {{ maxDecompressedMessageSize?: number }} [options] */ constructor(ws, extensions, options = {}) { super(); this.ws = ws; this.#extensions = extensions == null ? /* @__PURE__ */ new Map() : extensions; - this.#maxFragments = options.maxFragments ?? 0; - this.#maxPayloadSize = options.maxPayloadSize ?? 0; + this.#options = options; if (this.#extensions.has("permessage-deflate")) { this.#extensions.set("permessage-deflate", new PerMessageDeflate(extensions, options)); } @@ -17483,13 +17186,6 @@ var require_receiver = __commonJS({ this.#loop = true; this.run(callback); } - #validatePayloadLength() { - if (this.#maxPayloadSize > 0 && !isControlFrame(this.#info.opcode) && this.#info.payloadLength + this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, "Payload size exceeds maximum allowed size"); - return false; - } - return true; - } /** * Runs whenever a new chunk is received. * Callback is called whenever there are no more chunks buffering, @@ -17549,9 +17245,6 @@ var require_receiver = __commonJS({ if (payloadLength <= 125) { this.#info.payloadLength = payloadLength; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (payloadLength === 126) { this.#state = parserStates.PAYLOADLENGTH_16; } else if (payloadLength === 127) { @@ -17572,9 +17265,6 @@ var require_receiver = __commonJS({ const buffer = this.consume(2); this.#info.payloadLength = buffer.readUInt16BE(0); this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.PAYLOADLENGTH_64) { if (this.#byteOffset < 8) { return callback(); @@ -17588,9 +17278,6 @@ var require_receiver = __commonJS({ } this.#info.payloadLength = lower; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.READ_DATA) { if (this.#byteOffset < this.#info.payloadLength) { return callback(); @@ -17601,46 +17288,32 @@ var require_receiver = __commonJS({ this.#state = parserStates.INFO; } else { if (!this.#info.compressed) { - if (!this.writeFragments(body)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } + this.#fragments.push(body); if (!this.#info.fragmented && this.#info.fin) { - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); + const fullMessage = Buffer.concat(this.#fragments); + websocketMessageReceived(this.ws, this.#info.binaryType, fullMessage); + this.#fragments.length = 0; } this.#state = parserStates.INFO; } else { - this.#extensions.get("permessage-deflate").decompress( - body, - this.#info.fin, - (error2, data) => { - if (error2) { - const code = error2 instanceof MessageSizeExceededError ? 1009 : 1007; - failWebsocketConnectionWithCode(this.ws, code, error2.message); - return; - } - if (!this.writeFragments(data)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } - if (!this.#info.fin) { - this.#state = parserStates.INFO; - this.#loop = true; - this.run(callback); - return; - } - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); - this.#loop = true; + this.#extensions.get("permessage-deflate").decompress(body, this.#info.fin, (error2, data) => { + if (error2) { + failWebsocketConnection(this.ws, error2.message); + return; + } + this.#fragments.push(data); + if (!this.#info.fin) { this.#state = parserStates.INFO; + this.#loop = true; this.run(callback); + return; } - ); + websocketMessageReceived(this.ws, this.#info.binaryType, Buffer.concat(this.#fragments)); + this.#loop = true; + this.#state = parserStates.INFO; + this.#fragments.length = 0; + this.run(callback); + }); this.#loop = false; break; } @@ -17683,26 +17356,6 @@ var require_receiver = __commonJS({ this.#byteOffset -= n; return buffer; } - writeFragments(fragment) { - if (this.#maxFragments > 0 && this.#fragments.length === this.#maxFragments) { - failWebsocketConnectionWithCode(this.ws, 1008, "Too many message fragments"); - return false; - } - this.#fragmentsBytes += fragment.length; - this.#fragments.push(fragment); - return true; - } - consumeFragments() { - const fragments = this.#fragments; - if (fragments.length === 1) { - this.#fragmentsBytes = 0; - return fragments.shift(); - } - const output = Buffer.concat(fragments, this.#fragmentsBytes); - this.#fragments = []; - this.#fragmentsBytes = 0; - return output; - } parseCloseBody(data) { assert(data.length !== 1); let code; @@ -17914,6 +17567,8 @@ var require_websocket = __commonJS({ #extensions = ""; /** @type {SendQueue} */ #sendQueue; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {string} url * @param {string|string[]} protocols @@ -17957,6 +17612,9 @@ var require_websocket = __commonJS({ throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError"); } this[kWebSocketURL] = new URL(urlRecord.href); + this.#options = { + maxDecompressedMessageSize: options.maxDecompressedMessageSize + }; const client = environmentSettingsObject.settingsObject; this[kController] = establishWebSocketConnection( urlRecord, @@ -18140,13 +17798,7 @@ var require_websocket = __commonJS({ */ #onConnectionEstablished(response, parsedExtensions) { this[kResponse] = response; - const webSocketOptions = this[kController]?.dispatcher?.webSocketOptions; - const maxFragments = webSocketOptions?.maxFragments; - const maxPayloadSize = webSocketOptions?.maxPayloadSize; - const parser = new ByteParser(this, parsedExtensions, { - maxFragments, - maxPayloadSize - }); + const parser = new ByteParser(this, parsedExtensions, this.#options); parser.on("drain", onParserDrain); parser.on("error", onParserError.bind(this)); response.socket.ws = this; @@ -18221,6 +17873,19 @@ var require_websocket = __commonJS({ { key: "headers", converter: webidl.nullableConverter(webidl.converters.HeadersInit) + }, + { + key: "maxDecompressedMessageSize", + converter: webidl.nullableConverter((V) => { + V = webidl.converters["unsigned long long"](V); + if (V <= 0) { + throw webidl.errors.exception({ + header: "WebSocket constructor", + message: "maxDecompressedMessageSize must be greater than 0" + }); + } + return V; + }) } ]); webidl.converters["DOMString or sequence or WebSocketInit"] = function(V) { @@ -18299,40 +17964,6 @@ 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; - } - function isValidLastEventIdBytes(buffer, start) { - for (let i = start; i < buffer.length; i++) { - if (buffer[i] === 0) { - 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; - } var EventSourceStream = class extends Transform { /** * @type {eventSourceSettings} @@ -18352,13 +17983,10 @@ var require_eventsource_stream = __commonJS({ */ eventEndCheck = false; /** - * @type {Buffer[]} + * @type {Buffer} */ - chunks = []; - chunkIndex = 0; + buffer = null; pos = 0; - lineChunkIndex = 0; - linePos = 0; event = { data: void 0, event: void 0, @@ -18389,30 +18017,63 @@ var require_eventsource_stream = __commonJS({ callback(); return; } - this.chunks.push(chunk); + if (this.buffer) { + this.buffer = Buffer.concat([this.buffer, chunk]); + } else { + this.buffer = chunk; + } if (this.checkBOM) { - if (this.handleBOM()) { - callback(); - return; + 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; } } - while (this.hasCurrentByte()) { - const byte = this.currentByte(); + while (this.pos < this.buffer.length) { if (this.eventEndCheck) { if (this.crlfCheck) { - if (byte === LF) { + if (this.buffer[this.pos] === LF) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.crlfCheck = false; - this.consumeCurrentByte(); continue; } this.crlfCheck = false; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.consumeCurrentByte(); - if (this.hasPendingEvent()) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; + if (this.event.data !== void 0 || this.event.event || this.event.id || this.event.retry) { this.processEvent(this.event); } this.clearEvent(); @@ -18421,16 +18082,17 @@ var require_eventsource_stream = __commonJS({ this.eventEndCheck = false; continue; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.parseLine(this.readLine(), this.event); - this.consumeCurrentByte(); + this.parseLine(this.buffer.subarray(0, this.pos), this.event); + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.eventEndCheck = true; continue; } - this.advanceCursor(); + this.pos++; } callback(); } @@ -18446,42 +18108,43 @@ var require_eventsource_stream = __commonJS({ if (colonPosition === 0) { return; } - let fieldLength = line.length; - let valueStart = line.length; + let field = ""; + let value = ""; if (colonPosition !== -1) { - fieldLength = colonPosition; - valueStart = colonPosition + 1; + field = line.subarray(0, colonPosition).toString("utf8"); + let valueStart = colonPosition + 1; if (line[valueStart] === SPACE) { ++valueStart; } + value = line.subarray(valueStart).toString("utf8"); + } else { + field = line.toString("utf8"); + value = ""; } - if (isFieldName(line, fieldLength, DATA)) { - const value = line.toString("utf8", valueStart); - if (event.data === void 0) { - event.data = value; - } else { - event.data += ` + switch (field) { + case "data": + if (event[field] === void 0) { + event[field] = value; + } else { + event[field] += ` ${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; - } + } + 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; } } /** @@ -18506,120 +18169,12 @@ ${value}`; } } clearEvent() { - 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(); + this.event = { + data: void 0, + event: void 0, + id: void 0, + retry: void 0 + }; } }; module.exports = { @@ -24691,7 +24246,6 @@ var require_CONST = __commonJS({ REPLACE_CARD: "replace_card", SHIP_CARD: "ship_card", REPORT_CARD_FRAUD: "report_card_fraud", - APPROVE_DIGITAL_WALLET: "approve_digital_wallet", ISSUE_CARD: "issue_card", UPDATE_CARD: "update_card", UPDATE_PERSONAL_DETAILS: "update_personal_details", @@ -43335,117 +42889,6 @@ var require_str = __commonJS({ } return parameter; } - function compare(strA, strB) { - if (strA < strB) { - return -1; - } - if (strA > strB) { - return 1; - } - return 0; - } - function caseInsensitiveCompare(strA, strB) { - const lowerCaseStrA = strA.toLocaleLowerCase(); - const lowerCaseStrB = strB.toLocaleLowerCase(); - return compare(lowerCaseStrA, lowerCaseStrB); - } - function contains(haystack, needle) { - return haystack.indexOf(needle) !== -1; - } - function cutAfter(str2, substr) { - const index = str2.indexOf(substr); - if (index !== -1) { - return str2.substring(0, index); - } - return str2; - } - function cutBefore(str2, substr) { - const index = str2.indexOf(substr); - if (index !== -1) { - return str2.substring(index + substr.length); - } - return str2; - } - function extractEmailDomain(email) { - return cutBefore(email, "@"); - } - function getExtension(url) { - var _a3, _b; - if (typeof url !== "string") { - Log_1.default.warn("Str.getExtension: url is not a string", { url }); - return void 0; - } - return (_b = (_a3 = url.split(".").pop()) === null || _a3 === void 0 ? void 0 : _a3.split("?")[0]) === null || _b === void 0 ? void 0 : _b.toLowerCase(); - } - function getRawByteSize(inputChar) { - const onlyChar = String(inputChar); - const c = onlyChar.charCodeAt(0); - if (c < 1 << 7) { - return 1; - } - if (c < 1 << 11) { - return 2; - } - if (c < 1 << 16) { - return 3; - } - if (c < 1 << 21) { - return 4; - } - if (c < 1 << 26) { - return 5; - } - if (c < 1 << 31) { - return 6; - } - return Number.NaN; - } - function htmlDecode(s) { - return HtmlEntities.decode(s); - } - function htmlEncode(s) { - return HtmlEntities.encode(s); - } - function isTypeOf(obj, type) { - return Object.prototype.toString.call(obj) === `[object ${type}]`; - } - function isNumber(obj) { - return isTypeOf(obj, "Number"); - } - function isString(obj) { - return isTypeOf(obj, "String"); - } - function isUndefined(obj) { - return obj === void 0; - } - function isValidE164Phone(phone) { - return Constants.CONST.SMS.E164_REGEX.test(phone); - } - function isValidEmail(str2) { - if (!str2 || typeof str2 !== "string") { - return false; - } - const unicodeVersion = punycode_1.default.toUnicode(str2); - if (String(unicodeVersion).match(Constants.CONST.REG_EXP.EMOJI_RULE)) { - return false; - } - return !!String(str2).match(Constants.CONST.REG_EXP.EMAIL); - } - function maskFirstNCharacters(str2, num, mask) { - if (!isString(str2) || !isString(mask) || str2.length === 0 || !isNumber(num)) { - return str2; - } - return str2.substring(0, num).replaceAll(/./g, mask) + str2.substring(num); - } - function removeSMSDomain(text) { - return text.replaceAll(REMOVE_SMS_DOMAIN_PATTERN, ""); - } - function removeTrailingComma(str2) { - return str2.trim().replaceAll(/(,$)/g, ""); - } - function startsWith(haystack, needle) { - return isString(haystack) && isString(needle) && haystack.substring(0, needle.length) === needle; - } var Str6 = { /** * Return true if the string is ending with the provided suffix @@ -43503,14 +42946,18 @@ var require_str = __commonJS({ * @param s The string to decode. * @returns The decoded string. */ - htmlDecode, + htmlDecode(s) { + return HtmlEntities.decode(s); + }, /** * HTML encodes the given string. * * @param s The string to encode. * @return string @p s HTML encoded. */ - htmlEncode, + htmlEncode(s) { + return HtmlEntities.encode(s); + }, /** * Decodes the given HTML encoded string. * @@ -43552,7 +42999,7 @@ var require_str = __commonJS({ * @returns True when first === second, ignoring HTML encoding */ htmlEncodingInsensitiveEquals(first, second) { - return first === second || htmlDecode(first) === second || htmlEncode(first) === second; + return first === second || this.htmlDecode(first) === second || this.htmlEncode(first) === second; }, /** * Creates an ID that can be used as an HTML attribute from @p str. @@ -43635,14 +43082,36 @@ var require_str = __commonJS({ * one. * @returns Byte size of the character */ - getRawByteSize, + getRawByteSize(inputChar) { + const onlyChar = String(inputChar); + const c = onlyChar.charCodeAt(0); + if (c < 1 << 7) { + return 1; + } + if (c < 1 << 11) { + return 2; + } + if (c < 1 << 16) { + return 3; + } + if (c < 1 << 21) { + return 4; + } + if (c < 1 << 26) { + return 5; + } + if (c < 1 << 31) { + return 6; + } + return Number.NaN; + }, /** * Gets the length of a string in bytes, including non-ASCII characters * @returns The number of bytes used by string */ getByteLength(input) { const stringInput = String(input); - const byteLength = Array.from(stringInput).reduce((acc, char) => acc + getRawByteSize(char), 0); + const byteLength = Array.from(stringInput).reduce((acc, char) => acc + this.getRawByteSize(char), 0); return byteLength; }, /** @@ -43654,7 +43123,7 @@ var require_str = __commonJS({ const stringInput = String(input); let totalByteLength = 0; for (let i = 0; i < stringInput.length; i++) { - const charByteSize = getRawByteSize(stringInput[i]); + const charByteSize = this.getRawByteSize(stringInput[i]); if (charByteSize + totalByteLength > maxSize) { return `${stringInput.substr(0, i - 3)}...`; } @@ -43669,7 +43138,9 @@ var require_str = __commonJS({ * @param needle The case-sensitive string to search for * @returns True if the haystack starts with the needle. */ - startsWith, + startsWith(haystack, needle) { + return this.isString(haystack) && this.isString(needle) && haystack.substring(0, needle.length) === needle; + }, /** * Gets the textual value of the given string. * @@ -43677,7 +43148,7 @@ var require_str = __commonJS({ * @returns The text from within the HTML string. */ stripHTML(str2) { - if (!isString(str2)) { + if (!this.isString(str2)) { return ""; } return str2.replaceAll(/<[^>]*>?/gm, ""); @@ -43700,7 +43171,13 @@ var require_str = __commonJS({ * @param substr The substring to search for. * @returns The cut/trimmed string. */ - cutAfter, + cutAfter(str2, substr) { + const index = str2.indexOf(substr); + if (index !== -1) { + return str2.substring(0, index); + } + return str2; + }, /** * Returns a string containing all the characters str from after the first * occurrence of substr to the end of the string. @@ -43710,7 +43187,13 @@ var require_str = __commonJS({ * @param substr The substring to search for. * @returns The cut/trimmed string. */ - cutBefore, + cutBefore(str2, substr) { + const index = str2.indexOf(substr); + if (index !== -1) { + return str2.substring(index + substr.length); + } + return str2; + }, /** * Checks that the string is a domain name (e.g. example.com) * @@ -43737,7 +43220,16 @@ var require_str = __commonJS({ * * @returns True if the string is an email */ - isValidEmail, + isValidEmail(str2) { + if (!str2 || typeof str2 !== "string") { + return false; + } + const unicodeVersion = punycode_1.default.toUnicode(str2); + if (String(unicodeVersion).match(Constants.CONST.REG_EXP.EMOJI_RULE)) { + return false; + } + return !!String(str2).match(Constants.CONST.REG_EXP.EMAIL); + }, /** * Checks if the string is an valid email address formed during comment markdown formation. * @@ -43755,7 +43247,9 @@ var require_str = __commonJS({ * * @returns string with the trailing comma removed */ - removeTrailingComma, + removeTrailingComma(str2) { + return str2.trim().replaceAll(/(,$)/g, ""); + }, /** * Checks that the string is a list of coma separated email addresss. * @@ -43764,12 +43258,12 @@ var require_str = __commonJS({ * @returns True if all emails are valid or if input is empty */ areValidEmails(str2) { - const string = removeTrailingComma(str2); + const string = this.removeTrailingComma(str2); if (string === "") { return true; } const emails = string.split(","); - const result = emails.every((email) => isValidEmail(email.trim())); + const result = emails.every((email) => this.isValidEmail(email.trim())); return result; }, /** @@ -43786,7 +43280,9 @@ var require_str = __commonJS({ * * @returns The domain name in the email address. */ - extractEmailDomain, + extractEmailDomain(email) { + return this.cutBefore(email, "@"); + }, /** * Tries to extract the company name from the given email address * (e.g. "yelp" for "joe@yelp.co.uk"). @@ -43796,7 +43292,7 @@ var require_str = __commonJS({ * @returns The company name in the email address or null. */ extractCompanyNameFromEmailDomain(email) { - const domain = extractEmailDomain(email); + const domain = this.extractEmailDomain(email); if (!domain) { return null; } @@ -43815,7 +43311,7 @@ var require_str = __commonJS({ * @returns The local part in the email address. */ extractEmailLocalPart(email) { - return cutAfter(email, "@"); + return this.cutAfter(email, "@"); }, /** * Sanitize phone number to return only numbers. Return null if non valid phone number. @@ -43873,13 +43369,13 @@ var require_str = __commonJS({ * @returns true if the length is in the range, false otherwise */ isOfLength(str2, minimumLength, maximumLength) { - if (!isString(str2)) { + if (!this.isString(str2)) { return false; } if (str2.length < minimumLength) { return false; } - if (!isUndefined(maximumLength) && str2.length > maximumLength) { + if (!this.isUndefined(maximumLength) && str2.length > maximumLength) { return false; } return true; @@ -43932,7 +43428,9 @@ var require_str = __commonJS({ * * @returns Returns true if the haystack contains the needle */ - contains, + contains(haystack, needle) { + return haystack.indexOf(needle) !== -1; + }, /** * Returns true if the haystack contains the needle, ignoring case * @@ -43942,7 +43440,7 @@ var require_str = __commonJS({ * @returns Returns true if the haystack contains the needle, ignoring case */ caseInsensitiveContains(haystack, needle) { - return contains(haystack.toLowerCase(), needle.toLowerCase()); + return this.contains(haystack.toLowerCase(), needle.toLowerCase()); }, /** * Case insensitive compare function @@ -43954,7 +43452,11 @@ var require_str = __commonJS({ * 1 if first string > second string * 0 if first string = second string */ - caseInsensitiveCompare, + caseInsensitiveCompare(strA, strB) { + const lowerCaseStrA = strA.toLocaleLowerCase(); + const lowerCaseStrB = strB.toLocaleLowerCase(); + return this.compare(lowerCaseStrA, lowerCaseStrB); + }, /** * Case insensitive equals * @@ -43963,7 +43465,7 @@ var require_str = __commonJS({ * @returns true when first == second except for case */ caseInsensitiveEquals(strA, strB) { - return caseInsensitiveCompare(strA, strB) === 0; + return this.caseInsensitiveCompare(strA, strB) === 0; }, /** * Compare function @@ -43975,7 +43477,15 @@ var require_str = __commonJS({ * 1 if first string > second string * 0 if first string = second string */ - compare, + compare(strA, strB) { + if (strA < strB) { + return -1; + } + if (strA > strB) { + return 1; + } + return 0; + }, /** * Check if a file extension is supported by SmartReports */ @@ -43994,37 +43504,45 @@ var require_str = __commonJS({ const accountNumber = String(num); const len = accountNumber.length; if (len < 6 || len > 20) { - return maskFirstNCharacters(accountNumber, len, "X"); + return this.maskFirstNCharacters(accountNumber, len, "X"); } if (len < 14) { - return maskFirstNCharacters(accountNumber, len - 4, "X"); + return this.maskFirstNCharacters(accountNumber, len - 4, "X"); } const first = accountNumber.substr(0, 6); const last = accountNumber.substr(7); - const masked = maskFirstNCharacters(last, len - 11, "X"); + const masked = this.maskFirstNCharacters(last, len - 11, "X"); return `${first}${masked}`; }, /** * Checks if something is a string * Stolen from underscore */ - isString, + isString(obj) { + return this.isTypeOf(obj, "String"); + }, /** * Checks if something is a number * Stolen from underscore * @param obj */ - isNumber, + isNumber(obj) { + return this.isTypeOf(obj, "Number"); + }, /** * Checks if something is a certain type * Stolen from underscore */ - isTypeOf, + isTypeOf(obj, type) { + return Object.prototype.toString.call(obj) === `[object ${type}]`; + }, /** * Checks to see if something is undefined * Stolen from underscore */ - isUndefined, + isUndefined(obj) { + return obj === void 0; + }, /** * Replace first N characters of the string with maskChar * eg: maskFirstNCharacters( '1234567890', 6, 'X' ) yields XXXXXX7890 @@ -44033,7 +43551,12 @@ var require_str = __commonJS({ * @param mask String we want replace the first N chars with * @returns Masked string */ - maskFirstNCharacters, + maskFirstNCharacters(str2, num, mask) { + if (!this.isString(str2) || !this.isString(mask) || str2.length === 0 || !this.isNumber(num)) { + return str2; + } + return str2.substring(0, num).replaceAll(/./g, mask) + str2.substring(num); + }, /** * Trim a string */ @@ -44045,7 +43568,7 @@ var require_str = __commonJS({ * @param percentageString The percentage as a string */ percentageStringToNumber(percentageString) { - return Number(cutAfter(percentageString, "%")); + return Number(this.cutAfter(percentageString, "%")); }, /** * Remove all the spaces from a string @@ -44089,7 +43612,7 @@ var require_str = __commonJS({ * Converts a value to boolean, case-insensitive. */ toBool(value) { - if (isString(value)) { + if (this.isString(value)) { return value.toLowerCase() === "true"; } return !!value; @@ -44139,7 +43662,9 @@ var require_str = __commonJS({ /** * Check for whether a phone number is valid according to E.164 standard. */ - isValidE164Phone, + isValidE164Phone(phone) { + return Constants.CONST.SMS.E164_REGEX.test(phone); + }, /** * Check for whether a phone number is valid in different formats/standards. For example: * significant: 4404589784 @@ -44165,12 +43690,14 @@ var require_str = __commonJS({ /** * Returns text without our SMS domain */ - removeSMSDomain, + removeSMSDomain(text) { + return text.replaceAll(REMOVE_SMS_DOMAIN_PATTERN, ""); + }, /** * Returns true if the text is a valid E.164 phone number with our SMS domain removed */ isSMSLogin(text) { - return isValidE164Phone(removeSMSDomain(text)); + return this.isValidE164Phone(this.removeSMSDomain(text)); }, /** * This method will return all matches of a single regex like preg_match_all() in PHP. This is not a common part of @@ -44223,7 +43750,7 @@ var require_str = __commonJS({ return url; } const website = match2[3] ? match2[2] : `${defaultScheme}://${match2[2]}`; - return website.toLowerCase() + cutBefore(match2[1], match2[2]); + return website.toLowerCase() + this.cutBefore(match2[1], match2[2]); }, /** * Checks if parameter is a string or function @@ -44235,7 +43762,14 @@ var require_str = __commonJS({ * Get file extension for a given url with or * without query parameters */ - getExtension, + getExtension(url) { + var _a3, _b; + if (typeof url !== "string") { + Log_1.default.warn("Str.getExtension: url is not a string", { url }); + return void 0; + } + return (_b = (_a3 = url.split(".").pop()) === null || _a3 === void 0 ? void 0 : _a3.split("?")[0]) === null || _b === void 0 ? void 0 : _b.toLowerCase(); + }, /** * Takes in a URL and checks if the file extension is PDF * @@ -44243,7 +43777,7 @@ var require_str = __commonJS({ * @returns Whether file path is PDF or not */ isPDF(url) { - return getExtension(url) === "pdf"; + return this.getExtension(url) === "pdf"; }, /** * Takes in a URL and checks if the file extension is an image @@ -44254,7 +43788,7 @@ var require_str = __commonJS({ * https://reactnative.dev/docs/image#source */ isImage(url) { - const extension = getExtension(url); + const extension = this.getExtension(url); if (!extension) { return false; } @@ -44270,7 +43804,7 @@ var require_str = __commonJS({ * https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Video_codecs */ isVideo(url) { - const extension = getExtension(url); + const extension = this.getExtension(url); if (!extension) { return false; } @@ -44283,7 +43817,7 @@ var require_str = __commonJS({ * @returns True if is a domain account email, otherwise false. */ isDomainEmail(email) { - return startsWith(email, "+@"); + return this.startsWith(email, "+@"); }, /** * Find the minimum indentation of any line in the string, @@ -45421,17 +44955,13 @@ ${g2} }, { name: "anchor", - regex: /(\]\()?<(a)[^><]*href\s*=\s*(['"])(.*?)\3(?:".*?"|'.*?'|[^'"><])*>([\s\S]*?)<\/\2>(?![^<]*(<\/pre>|<\/code>))/gi, - replacement: (_extras, _match, g1, _g2, _g3, g4, g5) => { - const incompleteLinkStart = g1 !== null && g1 !== void 0 ? g1 : ""; - const email = g4.startsWith("mailto:") ? g4.slice(7) : ""; - if (email === g5) { - return `${incompleteLinkStart}${email}`; - } - if (incompleteLinkStart && (g4 === g5 || g4 === `https://${g5}`)) { - return `${incompleteLinkStart}${g5}`; + regex: /<(a)[^><]*href\s*=\s*(['"])(.*?)\2(?:".*?"|'.*?'|[^'"><])*>([\s\S]*?)<\/\1>(?![^<]*(<\/pre>|<\/code>))/gi, + replacement: (_extras, _match, _g1, _g2, g3, g4) => { + const email = g3.startsWith("mailto:") ? g3.slice(7) : ""; + if (email === g4) { + return email; } - return `${incompleteLinkStart}[${g5}](${email || g4})`; + return `[${g4}](${email || g3})`; } }, { diff --git a/.github/actions/javascript/reopenIssueWithComment/index.js b/.github/actions/javascript/reopenIssueWithComment/index.js index 2fe118ee3e64..f237f20694fd 100644 --- a/.github/actions/javascript/reopenIssueWithComment/index.js +++ b/.github/actions/javascript/reopenIssueWithComment/index.js @@ -1863,66 +1863,10 @@ var require_request = __commonJS({ return false; } } - /** - * @param {number|null} statusCode - * @param {Buffer[]|null} headers - * @param {import('node:stream').Duplex} socket - * @param {string} [statusText] - */ - onUpgrade(statusCode, headers, socket, statusText = "") { - this.onFinally(); + onUpgrade(statusCode, headers, socket) { assert(!this.aborted); assert(!this.completed); - 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(error2) { - assert(!this.aborted); - assert(this.completed); - if (channels.error.hasSubscribers) { - channels.error.publish({ request: this, error: error2 }); - } - } - /** - * @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: [] }); - } + return this[kHandler].onUpgrade(statusCode, headers, socket); } onComplete(trailers) { this.onFinally(); @@ -1989,11 +1933,7 @@ var require_request = __commonJS({ } else if (typeof val[i] === "object") { throw new InvalidArgumentError(`invalid ${key} header`); } else { - const str = `${val[i]}`; - if (!isValidHeaderValue(str)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } - arr.push(str); + arr.push(`${val[i]}`); } } val = arr; @@ -2005,9 +1945,6 @@ var require_request = __commonJS({ val = ""; } else { val = `${val}`; - if (!isValidHeaderValue(val)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } } if (headerName === "host") { if (request2.host !== null) { @@ -2117,21 +2054,13 @@ var require_dispatcher_base = __commonJS({ var kOnDestroyed = /* @__PURE__ */ Symbol("onDestroyed"); var kOnClosed = /* @__PURE__ */ Symbol("onClosed"); var kInterceptedDispatch = /* @__PURE__ */ Symbol("Intercepted Dispatch"); - var kWebSocketOptions = /* @__PURE__ */ Symbol("webSocketOptions"); var DispatcherBase = class extends Dispatcher { - constructor(opts) { + constructor() { super(); this[kDestroyed] = false; this[kOnDestroyed] = null; this[kClosed] = false; this[kOnClosed] = []; - this[kWebSocketOptions] = opts?.webSocket ?? {}; - } - get webSocketOptions() { - return { - maxFragments: this[kWebSocketOptions].maxFragments ?? 131072, - maxPayloadSize: this[kWebSocketOptions].maxPayloadSize ?? 128 * 1024 * 1024 - }; } get destroyed() { return this[kDestroyed]; @@ -5738,7 +5667,6 @@ var require_client_h1 = __commonJS({ RequestContentLengthMismatchError, ResponseContentLengthMismatchError, RequestAbortedError, - InvalidArgumentError, HeadersTimeoutError, HeadersOverflowError, SocketError, @@ -5785,9 +5713,6 @@ var require_client_h1 = __commonJS({ var FastBuffer = Buffer[Symbol.species]; var addListener = util.addListener; var removeAllListeners = util.removeAllListeners; - var kIdleSocketValidation = /* @__PURE__ */ Symbol("kIdleSocketValidation"); - var kIdleSocketValidationTimeout = /* @__PURE__ */ Symbol("kIdleSocketValidationTimeout"); - var kSocketUsed = /* @__PURE__ */ Symbol("kSocketUsed"); var extractBody; async function lazyllhttp() { const llhttpWasmData = process.env.JEST_WORKER_ID ? require_llhttp_wasm() : void 0; @@ -5950,55 +5875,24 @@ var require_client_h1 = __commonJS({ currentBufferRef = null; } const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr; - if (ret !== constants3.ERROR.OK) { - const body = data.subarray(offset); - if (ret === constants3.ERROR.PAUSED_UPGRADE) { - this.onUpgrade(body); - } else if (ret === constants3.ERROR.PAUSED) { - this.paused = true; - socket.unshift(body); - } else { - throw this.createError(ret, body); + if (ret === constants3.ERROR.PAUSED_UPGRADE) { + this.onUpgrade(data.slice(offset)); + } else if (ret === constants3.ERROR.PAUSED) { + this.paused = true; + socket.unshift(data.slice(offset)); + } else if (ret !== constants3.ERROR.OK) { + const ptr = llhttp.llhttp_get_error_reason(this.ptr); + let message = ""; + if (ptr) { + const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); + message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; } + throw new HTTPParserError(message, constants3.ERROR[ret], data.slice(offset)); } } catch (err) { util.destroy(socket, err); } } - finish() { - assert(currentParser === null); - assert(this.ptr != null); - assert(!this.paused); - const { llhttp } = this; - let ret; - try { - currentParser = this; - ret = llhttp.llhttp_finish(this.ptr); - } finally { - currentParser = null; - } - if (ret === constants3.ERROR.OK) { - return null; - } - if (ret === constants3.ERROR.PAUSED || ret === constants3.ERROR.PAUSED_UPGRADE) { - this.paused = true; - return null; - } - return this.createError(ret, EMPTY_BUF); - } - createError(ret, data) { - const { llhttp, contentLength, bytesRead } = this; - if (contentLength && bytesRead !== parseInt(contentLength, 10)) { - return new ResponseContentLengthMismatchError(); - } - const ptr = llhttp.llhttp_get_error_reason(this.ptr); - let message = ""; - if (ptr) { - const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); - message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; - } - return new HTTPParserError(message, constants3.ERROR[ret], data); - } destroy() { assert(this.ptr != null); assert(currentParser == null); @@ -6018,10 +5912,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6065,7 +5955,7 @@ var require_client_h1 = __commonJS({ } } onUpgrade(head) { - const { upgrade, client, socket, headers, statusCode, statusText } = this; + const { upgrade, client, socket, headers, statusCode } = this; assert(upgrade); assert(client[kSocket] === socket); assert(!socket.destroyed); @@ -6090,10 +5980,9 @@ var require_client_h1 = __commonJS({ client[kQueue][client[kRunningIdx]++] = null; client.emit("disconnect", client[kUrl], [client], new InformationalError("upgrade")); try { - request2.onUpgrade(statusCode, headers, socket, statusText); - } catch (error2) { - util.errorRequest(client, request2, error2); - util.destroy(socket, error2); + request2.onUpgrade(statusCode, headers, socket); + } catch (err) { + util.destroy(socket, err); } client[kResume](); } @@ -6102,10 +5991,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6231,7 +6116,6 @@ var require_client_h1 = __commonJS({ } request2.onComplete(headers); client[kQueue][client[kRunningIdx]++] = null; - socket[kSocketUsed] = true; if (socket[kWriting]) { assert(client[kRunning] === 0); util.destroy(socket, new InformationalError("reset")); @@ -6275,19 +6159,12 @@ var require_client_h1 = __commonJS({ socket[kWriting] = false; socket[kReset] = false; socket[kBlocking] = false; - socket[kIdleSocketValidation] = 0; - socket[kIdleSocketValidationTimeout] = null; - socket[kSocketUsed] = false; socket[kParser] = new Parser(client, socket, llhttpInstance); addListener(socket, "error", function(err) { assert(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID"); const parser = this[kParser]; if (err.code === "ECONNRESET" && parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - this[kError] = parserErr; - this[kClient][kOnError](parserErr); - } + parser.onMessageComplete(); return; } this[kError] = err; @@ -6302,10 +6179,7 @@ var require_client_h1 = __commonJS({ addListener(socket, "end", function() { const parser = this[kParser]; if (parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - util.destroy(this, parserErr); - } + parser.onMessageComplete(); return; } util.destroy(this, new SocketError("other side closed", util.getSocketInfo(this))); @@ -6313,10 +6187,9 @@ var require_client_h1 = __commonJS({ addListener(socket, "close", function() { const client2 = this[kClient]; const parser = this[kParser]; - clearIdleSocketValidation(this); if (parser) { if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { - this[kError] = parser.finish() || this[kError]; + parser.onMessageComplete(); } this[kParser].destroy(); this[kParser] = null; @@ -6365,7 +6238,7 @@ var require_client_h1 = __commonJS({ return socket.destroyed; }, busy(request2) { - if (socket[kWriting] || socket[kReset] || socket[kBlocking] || socket[kIdleSocketValidation] === 1) { + if (socket[kWriting] || socket[kReset] || socket[kBlocking]) { return true; } if (request2) { @@ -6383,23 +6256,6 @@ var require_client_h1 = __commonJS({ } }; } - function clearIdleSocketValidation(socket) { - if (socket[kIdleSocketValidationTimeout]) { - clearImmediate(socket[kIdleSocketValidationTimeout]); - socket[kIdleSocketValidationTimeout] = null; - } - socket[kIdleSocketValidation] = 0; - } - function scheduleIdleSocketValidation(client, socket) { - socket[kIdleSocketValidation] = 1; - socket[kIdleSocketValidationTimeout] = setImmediate(() => { - socket[kIdleSocketValidationTimeout] = null; - socket[kIdleSocketValidation] = 2; - if (client[kSocket] === socket && !socket.destroyed) { - client[kResume](); - } - }); - } function resumeH1(client) { const socket = client[kSocket]; if (socket && !socket.destroyed) { @@ -6412,29 +6268,6 @@ var require_client_h1 = __commonJS({ socket.ref(); socket[kNoRef] = false; } - if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) { - if (socket[kIdleSocketValidation] === 0) { - scheduleIdleSocketValidation(client, socket); - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - if (socket[kIdleSocketValidation] === 1) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - } - if (client[kRunning] === 0) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - } if (client[kSize] === 0) { if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) { socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE); @@ -6465,16 +6298,8 @@ var require_client_h1 = __commonJS({ } body = bodyStream.stream; contentLength = bodyStream.length; - } else if (util.isBlobLike(body) && request2.contentType == null) { - const contentType = body.type; - if (contentType) { - const contentTypeValue = `${contentType}`; - if (!util.isValidHeaderValue(contentTypeValue)) { - util.errorRequest(client, request2, new InvalidArgumentError("invalid content-type header")); - return false; - } - headers.push("content-type", contentTypeValue); - } + } else if (util.isBlobLike(body) && request2.contentType == null && body.type) { + headers.push("content-type", body.type); } if (body && typeof body.read === "function") { body.read(0); @@ -6495,18 +6320,11 @@ var require_client_h1 = __commonJS({ process.emitWarning(new RequestContentLengthMismatchError()); } const socket = client[kSocket]; - clearIdleSocketValidation(socket); - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (request2.upgrade || request2.method === "CONNECT") { - util.destroy(socket, new InformationalError("aborted")); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - util.errorRequest(client, request2, error2 || new RequestAbortedError()); + util.errorRequest(client, request2, err || new RequestAbortedError()); util.destroy(body); util.destroy(socket, new InformationalError("aborted")); }; @@ -6862,7 +6680,6 @@ var require_client_h2 = __commonJS({ "node_modules/undici/lib/dispatcher/client-h2.js"(exports, module) { "use strict"; var assert = __require("node:assert"); - var { errorMonitor } = __require("node:events"); var { pipeline } = __require("node:stream"); var util = require_util(); var { @@ -6923,10 +6740,6 @@ var require_client_h2 = __commonJS({ } return result; } - function parseH2ResponseHeaders(headers) { - const { [HTTP2_HEADER_STATUS]: _statusCode, ...realHeaders } = headers; - return parseH2Headers(realHeaders); - } async function connectH2(client, socket) { client[kSocket] = socket; if (!h2ExperimentalWarned) { @@ -7090,22 +6903,16 @@ var require_client_h2 = __commonJS({ const { hostname, port } = client[kUrl]; headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ""}`; headers[HTTP2_HEADER_METHOD] = method; - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (method === "CONNECT" && stream != null) { - util.destroy(stream, error2 || new RequestAbortedError()); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - error2 = error2 || new RequestAbortedError(); - util.errorRequest(client, request2, error2); + err = err || new RequestAbortedError(); + util.errorRequest(client, request2, err); if (stream != null) { - util.destroy(stream, error2); + util.destroy(stream, err); } - util.destroy(body, error2); + util.destroy(body, err); client[kQueue][client[kRunningIdx]++] = null; client[kResume](); }; @@ -7120,42 +6927,18 @@ var require_client_h2 = __commonJS({ if (method === "CONNECT") { session.ref(); stream = session.request(headers, { endStream: false, signal }); - let upgradeResponseFinished = false; - const onResponse = (headers2) => { - upgradeResponseFinished = true; - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeResponse(Number(headers2[HTTP2_HEADER_STATUS]), headers2, parseH2ResponseHeaders); - }; - const onUpgradeError = (error2) => { - upgradeResponseFinished = true; - stream.off("response", onResponse); - request2.onUpgradeError(error2); - }; - const onReady = () => { - try { - request2.onUpgrade(null, null, stream); - } catch (error2) { - stream.off("response", onResponse); - abort(error2); - return; - } - if (request2.aborted) { - return; - } - stream.off("error", abort); - stream.once(errorMonitor, onUpgradeError); + if (stream.id && !stream.pending) { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; client[kQueue][client[kRunningIdx]++] = null; - }; - stream.once("response", onResponse); - stream.once("error", abort); - ++session[kOpenStreams]; - onReady(); + } else { + stream.once("ready", () => { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; + client[kQueue][client[kRunningIdx]++] = null; + }); + } stream.once("close", () => { - if (!upgradeResponseFinished && request2.completed) { - stream.off("response", onResponse); - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeError(new InformationalError(`HTTP/2: "stream error" received - code ${stream.rstCode}`)); - } session[kOpenStreams] -= 1; if (session[kOpenStreams] === 0) session.unref(); }); @@ -7716,10 +7499,9 @@ var require_client = __commonJS({ autoSelectFamilyAttemptTimeout, // h2 maxConcurrentStreams, - allowH2, - webSocket + allowH2 } = {}) { - super({ webSocket }); + super(); if (keepAlive !== void 0) { throw new InvalidArgumentError("unsupported keepAlive, use pipelining=0 instead"); } @@ -8225,8 +8007,8 @@ var require_pool_base = __commonJS({ var kRemoveClient = /* @__PURE__ */ Symbol("remove client"); var kStats = /* @__PURE__ */ Symbol("stats"); var PoolBase = class extends DispatcherBase { - constructor(opts) { - super(opts); + constructor() { + super(); this[kQueue] = new FixedQueue(); this[kClients] = []; this[kQueued] = 0; @@ -8397,6 +8179,7 @@ var require_pool = __commonJS({ allowH2, ...options } = {}) { + super(); if (connections != null && (!Number.isFinite(connections) || connections < 0)) { throw new InvalidArgumentError("invalid connections"); } @@ -8417,7 +8200,6 @@ var require_pool = __commonJS({ ...connect }); } - super(options); this[kInterceptors] = options.interceptors?.Pool && Array.isArray(options.interceptors.Pool) ? options.interceptors.Pool : []; this[kConnections] = connections || null; this[kUrl] = util.parseOrigin(origin); @@ -8617,6 +8399,7 @@ var require_agent = __commonJS({ } var Agent = class extends DispatcherBase { constructor({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { + super(); if (typeof factory !== "function") { throw new InvalidArgumentError("factory must be a function."); } @@ -8626,7 +8409,6 @@ var require_agent = __commonJS({ if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { throw new InvalidArgumentError("maxRedirections must be a positive number"); } - super(options); if (connect && typeof connect !== "function") { connect = { ...connect }; } @@ -9067,24 +8849,6 @@ var require_retry_handler = __commonJS({ const current = Date.now(); return new Date(retryAfter).getTime() - current; } - function validatePartialResponseContentLength(headers, range, statusCode, retryCount) { - const contentLength = headers["content-length"]; - if (contentLength == null) { - return null; - } - if (!Number.isFinite(range.start) || !Number.isFinite(range.end)) { - return null; - } - const length = Number(contentLength); - const expectedLength = range.end - range.start + 1; - if (!Number.isFinite(length) || length !== expectedLength) { - return new RequestRetryError("Content-Length mismatch", statusCode, { - headers, - data: { count: retryCount } - }); - } - return null; - } var RetryHandler = class _RetryHandler { constructor(opts, handlers) { const { retryOptions, ...dispatchOpts } = opts; @@ -9138,7 +8902,6 @@ var require_retry_handler = __commonJS({ this.end = null; this.etag = null; this.resume = null; - this.headersSent = false; this.handler.onConnect((reason) => { this.aborted = true; if (this.abort) { @@ -9148,17 +8911,6 @@ var require_retry_handler = __commonJS({ } }); } - 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(); @@ -9220,9 +8972,7 @@ var require_retry_handler = __commonJS({ const headers = parseHeaders(rawHeaders); this.retryCount += 1; if (statusCode >= 300) { - if (!this.headersSent && this.retryOpts.statusCodes.includes(statusCode) === false) { - this.headersSent = true; - this.checkpointResponseEnd(headers, resume); + if (this.retryOpts.statusCodes.includes(statusCode) === false) { return this.handler.onHeaders( statusCode, rawHeaders, @@ -9271,21 +9021,9 @@ var require_retry_handler = __commonJS({ ); return false; } - const contentLengthError = validatePartialResponseContentLength(headers, contentRange, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = contentRange; - 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; - } + assert(this.start === start, "content-range mismatch"); + assert(this.end == null || this.end === end, "content-range mismatch"); this.resume = resume; return true; } @@ -9293,7 +9031,6 @@ var require_retry_handler = __commonJS({ if (statusCode === 206) { const range = parseRangeHeader(headers["content-range"]); if (range == null) { - this.headersSent = true; return this.handler.onHeaders( statusCode, rawHeaders, @@ -9301,11 +9038,6 @@ var require_retry_handler = __commonJS({ statusMessage ); } - const contentLengthError = validatePartialResponseContentLength(headers, range, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = range; assert( start != null && Number.isFinite(start), @@ -9325,7 +9057,6 @@ var require_retry_handler = __commonJS({ "invalid content-length" ); this.resume = resume; - this.headersSent = true; this.etag = headers.etag != null ? headers.etag : null; if (this.etag != null && this.etag.startsWith("W/")) { this.etag = null; @@ -9353,7 +9084,7 @@ var require_retry_handler = __commonJS({ return this.handler.onComplete(rawTrailers); } onError(err) { - if (this.aborted || isDisturbed(this.opts.body) || this.headersSent && this.resume == null) { + if (this.aborted || isDisturbed(this.opts.body)) { return this.handler.onError(err); } if (this.retryCount - this.retryCountCheckpoint > 0) { @@ -16152,48 +15883,14 @@ var require_util6 = __commonJS({ for (let i = 0; i < path.length; ++i) { const code = path.charCodeAt(i); if (code < 32 || // exclude CTLs (0-31) - code > 126 || // exclude DEL and non-ascii + code === 127 || // DEL code === 59) { throw new Error("Invalid cookie path"); } } } - function isLetterOrDigit(code) { - return code >= 48 && code <= 57 || // 0-9 - code >= 65 && code <= 90 || // A-Z - code >= 97 && code <= 122; - } function validateCookieDomain(domain) { - if (domain === " ") { - return; - } - if (domain.length > 255) { - throw new Error("Invalid cookie domain"); - } - let labelLength = 0; - for (let i = 0; i < domain.length; ++i) { - const code = domain.charCodeAt(i); - if (code === 46) { - if (labelLength === 0) { - throw new Error("Invalid cookie domain"); - } - if (domain.charCodeAt(i - 1) === 45) { - throw new Error("Invalid cookie domain"); - } - labelLength = 0; - continue; - } - if (labelLength === 0 && !isLetterOrDigit(code)) { - throw new Error("Invalid cookie domain"); - } - if (!isLetterOrDigit(code) && code !== 45) { - throw new Error("Invalid cookie domain"); - } - if (++labelLength > 63) { - throw new Error("Invalid cookie domain"); - } - } - if (labelLength === 0 || domain.charCodeAt(domain.length - 1) === 45) { + if (domain.startsWith("-") || domain.endsWith(".") || domain.endsWith("-")) { throw new Error("Invalid cookie domain"); } } @@ -16276,11 +15973,7 @@ var require_util6 = __commonJS({ throw new Error("Invalid unparsed"); } const [key, ...value] = part.split("="); - const trimmedKey = key.trim(); - const joinedValue = value.join("="); - validateCookieName(trimmedKey); - validateCookieValue(joinedValue); - out.push(`${trimmedKey}=${joinedValue}`); + out.push(`${key.trim()}=${value.join("=")}`); } return out.join("; "); } @@ -16410,14 +16103,18 @@ var require_parse = __commonJS({ } else if (attributeNameLowercase === "httponly") { cookieAttributeList.httpOnly = true; } else if (attributeNameLowercase === "samesite") { + let enforcement = "Default"; const attributeValueLowercase = attributeValue.toLowerCase(); - if (attributeValueLowercase === "none") { - cookieAttributeList.sameSite = "None"; - } else if (attributeValueLowercase === "strict") { - cookieAttributeList.sameSite = "Strict"; - } else if (attributeValueLowercase === "lax") { - cookieAttributeList.sameSite = "Lax"; + if (attributeValueLowercase.includes("none")) { + enforcement = "None"; + } + if (attributeValueLowercase.includes("strict")) { + enforcement = "Strict"; + } + if (attributeValueLowercase.includes("lax")) { + enforcement = "Lax"; } + cookieAttributeList.sameSite = enforcement; } else { cookieAttributeList.unparsed ??= []; cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`); @@ -17239,7 +16936,7 @@ var require_connection = __commonJS({ const secProtocol = response.headersList.get("Sec-WebSocket-Protocol"); if (secProtocol !== null) { const requestProtocols = getDecodeSplit("sec-websocket-protocol", request2.headersList); - if (requestProtocols === null || !requestProtocols.includes(secProtocol)) { + if (!requestProtocols.includes(secProtocol)) { failWebsocketConnection(ws, "Protocol was not set in the opening handshake."); return; } @@ -17345,26 +17042,31 @@ var require_permessage_deflate = __commonJS({ var tail = Buffer.from([0, 0, 255, 255]); var kBuffer = /* @__PURE__ */ Symbol("kBuffer"); var kLength = /* @__PURE__ */ Symbol("kLength"); + var kDefaultMaxDecompressedSize = 4 * 1024 * 1024; var PerMessageDeflate = class { /** @type {import('node:zlib').InflateRaw} */ #inflate; #options = {}; - #maxPayloadSize = 0; + /** @type {number} */ + #maxDecompressedSize; + /** @type {boolean} */ + #aborted = false; + /** @type {Function|null} */ + #currentCallback = null; /** * @param {Map} extensions + * @param {{ maxDecompressedMessageSize?: number }} [options] */ - constructor(extensions, options) { + constructor(extensions, options = {}) { this.#options.serverNoContextTakeover = extensions.has("server_no_context_takeover"); this.#options.serverMaxWindowBits = extensions.get("server_max_window_bits"); - this.#maxPayloadSize = options.maxPayloadSize; + this.#maxDecompressedSize = options.maxDecompressedMessageSize ?? kDefaultMaxDecompressedSize; } - /** - * Decompress a compressed payload. - * @param {Buffer} chunk Compressed data - * @param {boolean} fin Final fragment flag - * @param {Function} callback Callback function - */ decompress(chunk, fin, callback) { + if (this.#aborted) { + callback(new MessageSizeExceededError()); + return; + } if (!this.#inflate) { let windowBits = Z_DEFAULT_WINDOWBITS; if (this.#options.serverMaxWindowBits) { @@ -17383,12 +17085,20 @@ var require_permessage_deflate = __commonJS({ this.#inflate[kBuffer] = []; this.#inflate[kLength] = 0; this.#inflate.on("data", (data) => { + if (this.#aborted) { + return; + } this.#inflate[kLength] += data.length; - if (this.#maxPayloadSize > 0 && this.#inflate[kLength] > this.#maxPayloadSize) { - callback(new MessageSizeExceededError()); + if (this.#inflate[kLength] > this.#maxDecompressedSize) { + this.#aborted = true; this.#inflate.removeAllListeners(); this.#inflate.destroy(); this.#inflate = null; + if (this.#currentCallback) { + const cb = this.#currentCallback; + this.#currentCallback = null; + cb(new MessageSizeExceededError()); + } return; } this.#inflate[kBuffer].push(data); @@ -17398,17 +17108,19 @@ var require_permessage_deflate = __commonJS({ callback(err); }); } + this.#currentCallback = callback; this.#inflate.write(chunk); if (fin) { this.#inflate.write(tail); } this.#inflate.flush(() => { - if (!this.#inflate) { + if (this.#aborted || !this.#inflate) { return; } const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]); this.#inflate[kBuffer].length = 0; this.#inflate[kLength] = 0; + this.#currentCallback = null; callback(null, full); }); } @@ -17439,14 +17151,8 @@ var require_receiver = __commonJS({ var { WebsocketFrameSend } = require_frame(); var { closeWebSocketConnection } = require_connection(); var { PerMessageDeflate } = require_permessage_deflate(); - var { MessageSizeExceededError } = require_errors(); - function failWebsocketConnectionWithCode(ws, code, reason) { - closeWebSocketConnection(ws, code, reason, Buffer.byteLength(reason)); - failWebsocketConnection(ws, reason); - } var ByteParser = class extends Writable { #buffers = []; - #fragmentsBytes = 0; #byteOffset = 0; #loop = false; #state = parserStates.INFO; @@ -17454,21 +17160,18 @@ var require_receiver = __commonJS({ #fragments = []; /** @type {Map} */ #extensions; - /** @type {number} */ - #maxFragments; - /** @type {number} */ - #maxPayloadSize; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {import('./websocket').WebSocket} ws * @param {Map|null} extensions - * @param {{ maxFragments?: number, maxPayloadSize?: number }} [options] + * @param {{ maxDecompressedMessageSize?: number }} [options] */ constructor(ws, extensions, options = {}) { super(); this.ws = ws; this.#extensions = extensions == null ? /* @__PURE__ */ new Map() : extensions; - this.#maxFragments = options.maxFragments ?? 0; - this.#maxPayloadSize = options.maxPayloadSize ?? 0; + this.#options = options; if (this.#extensions.has("permessage-deflate")) { this.#extensions.set("permessage-deflate", new PerMessageDeflate(extensions, options)); } @@ -17483,13 +17186,6 @@ var require_receiver = __commonJS({ this.#loop = true; this.run(callback); } - #validatePayloadLength() { - if (this.#maxPayloadSize > 0 && !isControlFrame(this.#info.opcode) && this.#info.payloadLength + this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, "Payload size exceeds maximum allowed size"); - return false; - } - return true; - } /** * Runs whenever a new chunk is received. * Callback is called whenever there are no more chunks buffering, @@ -17549,9 +17245,6 @@ var require_receiver = __commonJS({ if (payloadLength <= 125) { this.#info.payloadLength = payloadLength; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (payloadLength === 126) { this.#state = parserStates.PAYLOADLENGTH_16; } else if (payloadLength === 127) { @@ -17572,9 +17265,6 @@ var require_receiver = __commonJS({ const buffer = this.consume(2); this.#info.payloadLength = buffer.readUInt16BE(0); this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.PAYLOADLENGTH_64) { if (this.#byteOffset < 8) { return callback(); @@ -17588,9 +17278,6 @@ var require_receiver = __commonJS({ } this.#info.payloadLength = lower; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.READ_DATA) { if (this.#byteOffset < this.#info.payloadLength) { return callback(); @@ -17601,46 +17288,32 @@ var require_receiver = __commonJS({ this.#state = parserStates.INFO; } else { if (!this.#info.compressed) { - if (!this.writeFragments(body)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } + this.#fragments.push(body); if (!this.#info.fragmented && this.#info.fin) { - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); + const fullMessage = Buffer.concat(this.#fragments); + websocketMessageReceived(this.ws, this.#info.binaryType, fullMessage); + this.#fragments.length = 0; } this.#state = parserStates.INFO; } else { - this.#extensions.get("permessage-deflate").decompress( - body, - this.#info.fin, - (error2, data) => { - if (error2) { - const code = error2 instanceof MessageSizeExceededError ? 1009 : 1007; - failWebsocketConnectionWithCode(this.ws, code, error2.message); - return; - } - if (!this.writeFragments(data)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } - if (!this.#info.fin) { - this.#state = parserStates.INFO; - this.#loop = true; - this.run(callback); - return; - } - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); - this.#loop = true; + this.#extensions.get("permessage-deflate").decompress(body, this.#info.fin, (error2, data) => { + if (error2) { + failWebsocketConnection(this.ws, error2.message); + return; + } + this.#fragments.push(data); + if (!this.#info.fin) { this.#state = parserStates.INFO; + this.#loop = true; this.run(callback); + return; } - ); + websocketMessageReceived(this.ws, this.#info.binaryType, Buffer.concat(this.#fragments)); + this.#loop = true; + this.#state = parserStates.INFO; + this.#fragments.length = 0; + this.run(callback); + }); this.#loop = false; break; } @@ -17683,26 +17356,6 @@ var require_receiver = __commonJS({ this.#byteOffset -= n; return buffer; } - writeFragments(fragment) { - if (this.#maxFragments > 0 && this.#fragments.length === this.#maxFragments) { - failWebsocketConnectionWithCode(this.ws, 1008, "Too many message fragments"); - return false; - } - this.#fragmentsBytes += fragment.length; - this.#fragments.push(fragment); - return true; - } - consumeFragments() { - const fragments = this.#fragments; - if (fragments.length === 1) { - this.#fragmentsBytes = 0; - return fragments.shift(); - } - const output = Buffer.concat(fragments, this.#fragmentsBytes); - this.#fragments = []; - this.#fragmentsBytes = 0; - return output; - } parseCloseBody(data) { assert(data.length !== 1); let code; @@ -17914,6 +17567,8 @@ var require_websocket = __commonJS({ #extensions = ""; /** @type {SendQueue} */ #sendQueue; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {string} url * @param {string|string[]} protocols @@ -17957,6 +17612,9 @@ var require_websocket = __commonJS({ throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError"); } this[kWebSocketURL] = new URL(urlRecord.href); + this.#options = { + maxDecompressedMessageSize: options.maxDecompressedMessageSize + }; const client = environmentSettingsObject.settingsObject; this[kController] = establishWebSocketConnection( urlRecord, @@ -18140,13 +17798,7 @@ var require_websocket = __commonJS({ */ #onConnectionEstablished(response, parsedExtensions) { this[kResponse] = response; - const webSocketOptions = this[kController]?.dispatcher?.webSocketOptions; - const maxFragments = webSocketOptions?.maxFragments; - const maxPayloadSize = webSocketOptions?.maxPayloadSize; - const parser = new ByteParser(this, parsedExtensions, { - maxFragments, - maxPayloadSize - }); + const parser = new ByteParser(this, parsedExtensions, this.#options); parser.on("drain", onParserDrain); parser.on("error", onParserError.bind(this)); response.socket.ws = this; @@ -18221,6 +17873,19 @@ var require_websocket = __commonJS({ { key: "headers", converter: webidl.nullableConverter(webidl.converters.HeadersInit) + }, + { + key: "maxDecompressedMessageSize", + converter: webidl.nullableConverter((V) => { + V = webidl.converters["unsigned long long"](V); + if (V <= 0) { + throw webidl.errors.exception({ + header: "WebSocket constructor", + message: "maxDecompressedMessageSize must be greater than 0" + }); + } + return V; + }) } ]); webidl.converters["DOMString or sequence or WebSocketInit"] = function(V) { @@ -18299,40 +17964,6 @@ 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; - } - function isValidLastEventIdBytes(buffer, start) { - for (let i = start; i < buffer.length; i++) { - if (buffer[i] === 0) { - 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; - } var EventSourceStream = class extends Transform { /** * @type {eventSourceSettings} @@ -18352,13 +17983,10 @@ var require_eventsource_stream = __commonJS({ */ eventEndCheck = false; /** - * @type {Buffer[]} + * @type {Buffer} */ - chunks = []; - chunkIndex = 0; + buffer = null; pos = 0; - lineChunkIndex = 0; - linePos = 0; event = { data: void 0, event: void 0, @@ -18389,30 +18017,63 @@ var require_eventsource_stream = __commonJS({ callback(); return; } - this.chunks.push(chunk); + if (this.buffer) { + this.buffer = Buffer.concat([this.buffer, chunk]); + } else { + this.buffer = chunk; + } if (this.checkBOM) { - if (this.handleBOM()) { - callback(); - return; + 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; } } - while (this.hasCurrentByte()) { - const byte = this.currentByte(); + while (this.pos < this.buffer.length) { if (this.eventEndCheck) { if (this.crlfCheck) { - if (byte === LF) { + if (this.buffer[this.pos] === LF) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.crlfCheck = false; - this.consumeCurrentByte(); continue; } this.crlfCheck = false; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.consumeCurrentByte(); - if (this.hasPendingEvent()) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; + if (this.event.data !== void 0 || this.event.event || this.event.id || this.event.retry) { this.processEvent(this.event); } this.clearEvent(); @@ -18421,16 +18082,17 @@ var require_eventsource_stream = __commonJS({ this.eventEndCheck = false; continue; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.parseLine(this.readLine(), this.event); - this.consumeCurrentByte(); + this.parseLine(this.buffer.subarray(0, this.pos), this.event); + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.eventEndCheck = true; continue; } - this.advanceCursor(); + this.pos++; } callback(); } @@ -18446,42 +18108,43 @@ var require_eventsource_stream = __commonJS({ if (colonPosition === 0) { return; } - let fieldLength = line.length; - let valueStart = line.length; + let field = ""; + let value = ""; if (colonPosition !== -1) { - fieldLength = colonPosition; - valueStart = colonPosition + 1; + field = line.subarray(0, colonPosition).toString("utf8"); + let valueStart = colonPosition + 1; if (line[valueStart] === SPACE) { ++valueStart; } + value = line.subarray(valueStart).toString("utf8"); + } else { + field = line.toString("utf8"); + value = ""; } - if (isFieldName(line, fieldLength, DATA)) { - const value = line.toString("utf8", valueStart); - if (event.data === void 0) { - event.data = value; - } else { - event.data += ` + switch (field) { + case "data": + if (event[field] === void 0) { + event[field] = value; + } else { + event[field] += ` ${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; - } + } + 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; } } /** @@ -18506,120 +18169,12 @@ ${value}`; } } clearEvent() { - 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(); + this.event = { + data: void 0, + event: void 0, + id: void 0, + retry: void 0 + }; } }; module.exports = { diff --git a/.github/actions/javascript/reviewerChecklist/index.js b/.github/actions/javascript/reviewerChecklist/index.js index 8e220a2cf59e..a9419acf5a2e 100644 --- a/.github/actions/javascript/reviewerChecklist/index.js +++ b/.github/actions/javascript/reviewerChecklist/index.js @@ -1863,66 +1863,10 @@ var require_request = __commonJS({ return false; } } - /** - * @param {number|null} statusCode - * @param {Buffer[]|null} headers - * @param {import('node:stream').Duplex} socket - * @param {string} [statusText] - */ - onUpgrade(statusCode, headers, socket, statusText = "") { - this.onFinally(); + onUpgrade(statusCode, headers, socket) { assert(!this.aborted); assert(!this.completed); - 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(error2) { - assert(!this.aborted); - assert(this.completed); - if (channels.error.hasSubscribers) { - channels.error.publish({ request: this, error: error2 }); - } - } - /** - * @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: [] }); - } + return this[kHandler].onUpgrade(statusCode, headers, socket); } onComplete(trailers) { this.onFinally(); @@ -1989,11 +1933,7 @@ var require_request = __commonJS({ } else if (typeof val[i] === "object") { throw new InvalidArgumentError(`invalid ${key} header`); } else { - const str = `${val[i]}`; - if (!isValidHeaderValue(str)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } - arr.push(str); + arr.push(`${val[i]}`); } } val = arr; @@ -2005,9 +1945,6 @@ var require_request = __commonJS({ val = ""; } else { val = `${val}`; - if (!isValidHeaderValue(val)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } } if (headerName === "host") { if (request2.host !== null) { @@ -2117,21 +2054,13 @@ var require_dispatcher_base = __commonJS({ var kOnDestroyed = /* @__PURE__ */ Symbol("onDestroyed"); var kOnClosed = /* @__PURE__ */ Symbol("onClosed"); var kInterceptedDispatch = /* @__PURE__ */ Symbol("Intercepted Dispatch"); - var kWebSocketOptions = /* @__PURE__ */ Symbol("webSocketOptions"); var DispatcherBase = class extends Dispatcher { - constructor(opts) { + constructor() { super(); this[kDestroyed] = false; this[kOnDestroyed] = null; this[kClosed] = false; this[kOnClosed] = []; - this[kWebSocketOptions] = opts?.webSocket ?? {}; - } - get webSocketOptions() { - return { - maxFragments: this[kWebSocketOptions].maxFragments ?? 131072, - maxPayloadSize: this[kWebSocketOptions].maxPayloadSize ?? 128 * 1024 * 1024 - }; } get destroyed() { return this[kDestroyed]; @@ -5738,7 +5667,6 @@ var require_client_h1 = __commonJS({ RequestContentLengthMismatchError, ResponseContentLengthMismatchError, RequestAbortedError, - InvalidArgumentError, HeadersTimeoutError, HeadersOverflowError, SocketError, @@ -5785,9 +5713,6 @@ var require_client_h1 = __commonJS({ var FastBuffer = Buffer[Symbol.species]; var addListener = util.addListener; var removeAllListeners = util.removeAllListeners; - var kIdleSocketValidation = /* @__PURE__ */ Symbol("kIdleSocketValidation"); - var kIdleSocketValidationTimeout = /* @__PURE__ */ Symbol("kIdleSocketValidationTimeout"); - var kSocketUsed = /* @__PURE__ */ Symbol("kSocketUsed"); var extractBody; async function lazyllhttp() { const llhttpWasmData = process.env.JEST_WORKER_ID ? require_llhttp_wasm() : void 0; @@ -5950,55 +5875,24 @@ var require_client_h1 = __commonJS({ currentBufferRef = null; } const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr; - if (ret !== constants3.ERROR.OK) { - const body = data.subarray(offset); - if (ret === constants3.ERROR.PAUSED_UPGRADE) { - this.onUpgrade(body); - } else if (ret === constants3.ERROR.PAUSED) { - this.paused = true; - socket.unshift(body); - } else { - throw this.createError(ret, body); + if (ret === constants3.ERROR.PAUSED_UPGRADE) { + this.onUpgrade(data.slice(offset)); + } else if (ret === constants3.ERROR.PAUSED) { + this.paused = true; + socket.unshift(data.slice(offset)); + } else if (ret !== constants3.ERROR.OK) { + const ptr = llhttp.llhttp_get_error_reason(this.ptr); + let message = ""; + if (ptr) { + const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); + message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; } + throw new HTTPParserError(message, constants3.ERROR[ret], data.slice(offset)); } } catch (err) { util.destroy(socket, err); } } - finish() { - assert(currentParser === null); - assert(this.ptr != null); - assert(!this.paused); - const { llhttp } = this; - let ret; - try { - currentParser = this; - ret = llhttp.llhttp_finish(this.ptr); - } finally { - currentParser = null; - } - if (ret === constants3.ERROR.OK) { - return null; - } - if (ret === constants3.ERROR.PAUSED || ret === constants3.ERROR.PAUSED_UPGRADE) { - this.paused = true; - return null; - } - return this.createError(ret, EMPTY_BUF); - } - createError(ret, data) { - const { llhttp, contentLength, bytesRead } = this; - if (contentLength && bytesRead !== parseInt(contentLength, 10)) { - return new ResponseContentLengthMismatchError(); - } - const ptr = llhttp.llhttp_get_error_reason(this.ptr); - let message = ""; - if (ptr) { - const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); - message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; - } - return new HTTPParserError(message, constants3.ERROR[ret], data); - } destroy() { assert(this.ptr != null); assert(currentParser == null); @@ -6018,10 +5912,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6065,7 +5955,7 @@ var require_client_h1 = __commonJS({ } } onUpgrade(head) { - const { upgrade, client, socket, headers, statusCode, statusText } = this; + const { upgrade, client, socket, headers, statusCode } = this; assert(upgrade); assert(client[kSocket] === socket); assert(!socket.destroyed); @@ -6090,10 +5980,9 @@ var require_client_h1 = __commonJS({ client[kQueue][client[kRunningIdx]++] = null; client.emit("disconnect", client[kUrl], [client], new InformationalError("upgrade")); try { - request2.onUpgrade(statusCode, headers, socket, statusText); - } catch (error2) { - util.errorRequest(client, request2, error2); - util.destroy(socket, error2); + request2.onUpgrade(statusCode, headers, socket); + } catch (err) { + util.destroy(socket, err); } client[kResume](); } @@ -6102,10 +5991,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6231,7 +6116,6 @@ var require_client_h1 = __commonJS({ } request2.onComplete(headers); client[kQueue][client[kRunningIdx]++] = null; - socket[kSocketUsed] = true; if (socket[kWriting]) { assert(client[kRunning] === 0); util.destroy(socket, new InformationalError("reset")); @@ -6275,19 +6159,12 @@ var require_client_h1 = __commonJS({ socket[kWriting] = false; socket[kReset] = false; socket[kBlocking] = false; - socket[kIdleSocketValidation] = 0; - socket[kIdleSocketValidationTimeout] = null; - socket[kSocketUsed] = false; socket[kParser] = new Parser(client, socket, llhttpInstance); addListener(socket, "error", function(err) { assert(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID"); const parser = this[kParser]; if (err.code === "ECONNRESET" && parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - this[kError] = parserErr; - this[kClient][kOnError](parserErr); - } + parser.onMessageComplete(); return; } this[kError] = err; @@ -6302,10 +6179,7 @@ var require_client_h1 = __commonJS({ addListener(socket, "end", function() { const parser = this[kParser]; if (parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - util.destroy(this, parserErr); - } + parser.onMessageComplete(); return; } util.destroy(this, new SocketError("other side closed", util.getSocketInfo(this))); @@ -6313,10 +6187,9 @@ var require_client_h1 = __commonJS({ addListener(socket, "close", function() { const client2 = this[kClient]; const parser = this[kParser]; - clearIdleSocketValidation(this); if (parser) { if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { - this[kError] = parser.finish() || this[kError]; + parser.onMessageComplete(); } this[kParser].destroy(); this[kParser] = null; @@ -6365,7 +6238,7 @@ var require_client_h1 = __commonJS({ return socket.destroyed; }, busy(request2) { - if (socket[kWriting] || socket[kReset] || socket[kBlocking] || socket[kIdleSocketValidation] === 1) { + if (socket[kWriting] || socket[kReset] || socket[kBlocking]) { return true; } if (request2) { @@ -6383,23 +6256,6 @@ var require_client_h1 = __commonJS({ } }; } - function clearIdleSocketValidation(socket) { - if (socket[kIdleSocketValidationTimeout]) { - clearImmediate(socket[kIdleSocketValidationTimeout]); - socket[kIdleSocketValidationTimeout] = null; - } - socket[kIdleSocketValidation] = 0; - } - function scheduleIdleSocketValidation(client, socket) { - socket[kIdleSocketValidation] = 1; - socket[kIdleSocketValidationTimeout] = setImmediate(() => { - socket[kIdleSocketValidationTimeout] = null; - socket[kIdleSocketValidation] = 2; - if (client[kSocket] === socket && !socket.destroyed) { - client[kResume](); - } - }); - } function resumeH1(client) { const socket = client[kSocket]; if (socket && !socket.destroyed) { @@ -6412,29 +6268,6 @@ var require_client_h1 = __commonJS({ socket.ref(); socket[kNoRef] = false; } - if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) { - if (socket[kIdleSocketValidation] === 0) { - scheduleIdleSocketValidation(client, socket); - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - if (socket[kIdleSocketValidation] === 1) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - } - if (client[kRunning] === 0) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - } if (client[kSize] === 0) { if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) { socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE); @@ -6465,16 +6298,8 @@ var require_client_h1 = __commonJS({ } body = bodyStream.stream; contentLength = bodyStream.length; - } else if (util.isBlobLike(body) && request2.contentType == null) { - const contentType = body.type; - if (contentType) { - const contentTypeValue = `${contentType}`; - if (!util.isValidHeaderValue(contentTypeValue)) { - util.errorRequest(client, request2, new InvalidArgumentError("invalid content-type header")); - return false; - } - headers.push("content-type", contentTypeValue); - } + } else if (util.isBlobLike(body) && request2.contentType == null && body.type) { + headers.push("content-type", body.type); } if (body && typeof body.read === "function") { body.read(0); @@ -6495,18 +6320,11 @@ var require_client_h1 = __commonJS({ process.emitWarning(new RequestContentLengthMismatchError()); } const socket = client[kSocket]; - clearIdleSocketValidation(socket); - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (request2.upgrade || request2.method === "CONNECT") { - util.destroy(socket, new InformationalError("aborted")); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - util.errorRequest(client, request2, error2 || new RequestAbortedError()); + util.errorRequest(client, request2, err || new RequestAbortedError()); util.destroy(body); util.destroy(socket, new InformationalError("aborted")); }; @@ -6862,7 +6680,6 @@ var require_client_h2 = __commonJS({ "node_modules/undici/lib/dispatcher/client-h2.js"(exports, module) { "use strict"; var assert = __require("node:assert"); - var { errorMonitor } = __require("node:events"); var { pipeline } = __require("node:stream"); var util = require_util(); var { @@ -6923,10 +6740,6 @@ var require_client_h2 = __commonJS({ } return result; } - function parseH2ResponseHeaders(headers) { - const { [HTTP2_HEADER_STATUS]: _statusCode, ...realHeaders } = headers; - return parseH2Headers(realHeaders); - } async function connectH2(client, socket) { client[kSocket] = socket; if (!h2ExperimentalWarned) { @@ -7090,22 +6903,16 @@ var require_client_h2 = __commonJS({ const { hostname, port } = client[kUrl]; headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ""}`; headers[HTTP2_HEADER_METHOD] = method; - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (method === "CONNECT" && stream != null) { - util.destroy(stream, error2 || new RequestAbortedError()); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - error2 = error2 || new RequestAbortedError(); - util.errorRequest(client, request2, error2); + err = err || new RequestAbortedError(); + util.errorRequest(client, request2, err); if (stream != null) { - util.destroy(stream, error2); + util.destroy(stream, err); } - util.destroy(body, error2); + util.destroy(body, err); client[kQueue][client[kRunningIdx]++] = null; client[kResume](); }; @@ -7120,42 +6927,18 @@ var require_client_h2 = __commonJS({ if (method === "CONNECT") { session.ref(); stream = session.request(headers, { endStream: false, signal }); - let upgradeResponseFinished = false; - const onResponse = (headers2) => { - upgradeResponseFinished = true; - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeResponse(Number(headers2[HTTP2_HEADER_STATUS]), headers2, parseH2ResponseHeaders); - }; - const onUpgradeError = (error2) => { - upgradeResponseFinished = true; - stream.off("response", onResponse); - request2.onUpgradeError(error2); - }; - const onReady = () => { - try { - request2.onUpgrade(null, null, stream); - } catch (error2) { - stream.off("response", onResponse); - abort(error2); - return; - } - if (request2.aborted) { - return; - } - stream.off("error", abort); - stream.once(errorMonitor, onUpgradeError); + if (stream.id && !stream.pending) { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; client[kQueue][client[kRunningIdx]++] = null; - }; - stream.once("response", onResponse); - stream.once("error", abort); - ++session[kOpenStreams]; - onReady(); + } else { + stream.once("ready", () => { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; + client[kQueue][client[kRunningIdx]++] = null; + }); + } stream.once("close", () => { - if (!upgradeResponseFinished && request2.completed) { - stream.off("response", onResponse); - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeError(new InformationalError(`HTTP/2: "stream error" received - code ${stream.rstCode}`)); - } session[kOpenStreams] -= 1; if (session[kOpenStreams] === 0) session.unref(); }); @@ -7716,10 +7499,9 @@ var require_client = __commonJS({ autoSelectFamilyAttemptTimeout, // h2 maxConcurrentStreams, - allowH2, - webSocket + allowH2 } = {}) { - super({ webSocket }); + super(); if (keepAlive !== void 0) { throw new InvalidArgumentError("unsupported keepAlive, use pipelining=0 instead"); } @@ -8225,8 +8007,8 @@ var require_pool_base = __commonJS({ var kRemoveClient = /* @__PURE__ */ Symbol("remove client"); var kStats = /* @__PURE__ */ Symbol("stats"); var PoolBase = class extends DispatcherBase { - constructor(opts) { - super(opts); + constructor() { + super(); this[kQueue] = new FixedQueue(); this[kClients] = []; this[kQueued] = 0; @@ -8397,6 +8179,7 @@ var require_pool = __commonJS({ allowH2, ...options } = {}) { + super(); if (connections != null && (!Number.isFinite(connections) || connections < 0)) { throw new InvalidArgumentError("invalid connections"); } @@ -8417,7 +8200,6 @@ var require_pool = __commonJS({ ...connect }); } - super(options); this[kInterceptors] = options.interceptors?.Pool && Array.isArray(options.interceptors.Pool) ? options.interceptors.Pool : []; this[kConnections] = connections || null; this[kUrl] = util.parseOrigin(origin); @@ -8617,6 +8399,7 @@ var require_agent = __commonJS({ } var Agent = class extends DispatcherBase { constructor({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { + super(); if (typeof factory !== "function") { throw new InvalidArgumentError("factory must be a function."); } @@ -8626,7 +8409,6 @@ var require_agent = __commonJS({ if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { throw new InvalidArgumentError("maxRedirections must be a positive number"); } - super(options); if (connect && typeof connect !== "function") { connect = { ...connect }; } @@ -9067,24 +8849,6 @@ var require_retry_handler = __commonJS({ const current = Date.now(); return new Date(retryAfter).getTime() - current; } - function validatePartialResponseContentLength(headers, range, statusCode, retryCount) { - const contentLength = headers["content-length"]; - if (contentLength == null) { - return null; - } - if (!Number.isFinite(range.start) || !Number.isFinite(range.end)) { - return null; - } - const length = Number(contentLength); - const expectedLength = range.end - range.start + 1; - if (!Number.isFinite(length) || length !== expectedLength) { - return new RequestRetryError("Content-Length mismatch", statusCode, { - headers, - data: { count: retryCount } - }); - } - return null; - } var RetryHandler = class _RetryHandler { constructor(opts, handlers) { const { retryOptions, ...dispatchOpts } = opts; @@ -9138,7 +8902,6 @@ var require_retry_handler = __commonJS({ this.end = null; this.etag = null; this.resume = null; - this.headersSent = false; this.handler.onConnect((reason) => { this.aborted = true; if (this.abort) { @@ -9148,17 +8911,6 @@ var require_retry_handler = __commonJS({ } }); } - 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(); @@ -9220,9 +8972,7 @@ var require_retry_handler = __commonJS({ const headers = parseHeaders(rawHeaders); this.retryCount += 1; if (statusCode >= 300) { - if (!this.headersSent && this.retryOpts.statusCodes.includes(statusCode) === false) { - this.headersSent = true; - this.checkpointResponseEnd(headers, resume); + if (this.retryOpts.statusCodes.includes(statusCode) === false) { return this.handler.onHeaders( statusCode, rawHeaders, @@ -9271,21 +9021,9 @@ var require_retry_handler = __commonJS({ ); return false; } - const contentLengthError = validatePartialResponseContentLength(headers, contentRange, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = contentRange; - 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; - } + assert(this.start === start, "content-range mismatch"); + assert(this.end == null || this.end === end, "content-range mismatch"); this.resume = resume; return true; } @@ -9293,7 +9031,6 @@ var require_retry_handler = __commonJS({ if (statusCode === 206) { const range = parseRangeHeader(headers["content-range"]); if (range == null) { - this.headersSent = true; return this.handler.onHeaders( statusCode, rawHeaders, @@ -9301,11 +9038,6 @@ var require_retry_handler = __commonJS({ statusMessage ); } - const contentLengthError = validatePartialResponseContentLength(headers, range, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = range; assert( start != null && Number.isFinite(start), @@ -9325,7 +9057,6 @@ var require_retry_handler = __commonJS({ "invalid content-length" ); this.resume = resume; - this.headersSent = true; this.etag = headers.etag != null ? headers.etag : null; if (this.etag != null && this.etag.startsWith("W/")) { this.etag = null; @@ -9353,7 +9084,7 @@ var require_retry_handler = __commonJS({ return this.handler.onComplete(rawTrailers); } onError(err) { - if (this.aborted || isDisturbed(this.opts.body) || this.headersSent && this.resume == null) { + if (this.aborted || isDisturbed(this.opts.body)) { return this.handler.onError(err); } if (this.retryCount - this.retryCountCheckpoint > 0) { @@ -16152,48 +15883,14 @@ var require_util6 = __commonJS({ for (let i = 0; i < path.length; ++i) { const code = path.charCodeAt(i); if (code < 32 || // exclude CTLs (0-31) - code > 126 || // exclude DEL and non-ascii + code === 127 || // DEL code === 59) { throw new Error("Invalid cookie path"); } } } - function isLetterOrDigit(code) { - return code >= 48 && code <= 57 || // 0-9 - code >= 65 && code <= 90 || // A-Z - code >= 97 && code <= 122; - } function validateCookieDomain(domain) { - if (domain === " ") { - return; - } - if (domain.length > 255) { - throw new Error("Invalid cookie domain"); - } - let labelLength = 0; - for (let i = 0; i < domain.length; ++i) { - const code = domain.charCodeAt(i); - if (code === 46) { - if (labelLength === 0) { - throw new Error("Invalid cookie domain"); - } - if (domain.charCodeAt(i - 1) === 45) { - throw new Error("Invalid cookie domain"); - } - labelLength = 0; - continue; - } - if (labelLength === 0 && !isLetterOrDigit(code)) { - throw new Error("Invalid cookie domain"); - } - if (!isLetterOrDigit(code) && code !== 45) { - throw new Error("Invalid cookie domain"); - } - if (++labelLength > 63) { - throw new Error("Invalid cookie domain"); - } - } - if (labelLength === 0 || domain.charCodeAt(domain.length - 1) === 45) { + if (domain.startsWith("-") || domain.endsWith(".") || domain.endsWith("-")) { throw new Error("Invalid cookie domain"); } } @@ -16276,11 +15973,7 @@ var require_util6 = __commonJS({ throw new Error("Invalid unparsed"); } const [key, ...value] = part.split("="); - const trimmedKey = key.trim(); - const joinedValue = value.join("="); - validateCookieName(trimmedKey); - validateCookieValue(joinedValue); - out.push(`${trimmedKey}=${joinedValue}`); + out.push(`${key.trim()}=${value.join("=")}`); } return out.join("; "); } @@ -16410,14 +16103,18 @@ var require_parse = __commonJS({ } else if (attributeNameLowercase === "httponly") { cookieAttributeList.httpOnly = true; } else if (attributeNameLowercase === "samesite") { + let enforcement = "Default"; const attributeValueLowercase = attributeValue.toLowerCase(); - if (attributeValueLowercase === "none") { - cookieAttributeList.sameSite = "None"; - } else if (attributeValueLowercase === "strict") { - cookieAttributeList.sameSite = "Strict"; - } else if (attributeValueLowercase === "lax") { - cookieAttributeList.sameSite = "Lax"; + if (attributeValueLowercase.includes("none")) { + enforcement = "None"; + } + if (attributeValueLowercase.includes("strict")) { + enforcement = "Strict"; + } + if (attributeValueLowercase.includes("lax")) { + enforcement = "Lax"; } + cookieAttributeList.sameSite = enforcement; } else { cookieAttributeList.unparsed ??= []; cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`); @@ -17239,7 +16936,7 @@ var require_connection = __commonJS({ const secProtocol = response.headersList.get("Sec-WebSocket-Protocol"); if (secProtocol !== null) { const requestProtocols = getDecodeSplit("sec-websocket-protocol", request2.headersList); - if (requestProtocols === null || !requestProtocols.includes(secProtocol)) { + if (!requestProtocols.includes(secProtocol)) { failWebsocketConnection(ws, "Protocol was not set in the opening handshake."); return; } @@ -17345,26 +17042,31 @@ var require_permessage_deflate = __commonJS({ var tail = Buffer.from([0, 0, 255, 255]); var kBuffer = /* @__PURE__ */ Symbol("kBuffer"); var kLength = /* @__PURE__ */ Symbol("kLength"); + var kDefaultMaxDecompressedSize = 4 * 1024 * 1024; var PerMessageDeflate = class { /** @type {import('node:zlib').InflateRaw} */ #inflate; #options = {}; - #maxPayloadSize = 0; + /** @type {number} */ + #maxDecompressedSize; + /** @type {boolean} */ + #aborted = false; + /** @type {Function|null} */ + #currentCallback = null; /** * @param {Map} extensions + * @param {{ maxDecompressedMessageSize?: number }} [options] */ - constructor(extensions, options) { + constructor(extensions, options = {}) { this.#options.serverNoContextTakeover = extensions.has("server_no_context_takeover"); this.#options.serverMaxWindowBits = extensions.get("server_max_window_bits"); - this.#maxPayloadSize = options.maxPayloadSize; + this.#maxDecompressedSize = options.maxDecompressedMessageSize ?? kDefaultMaxDecompressedSize; } - /** - * Decompress a compressed payload. - * @param {Buffer} chunk Compressed data - * @param {boolean} fin Final fragment flag - * @param {Function} callback Callback function - */ decompress(chunk, fin, callback) { + if (this.#aborted) { + callback(new MessageSizeExceededError()); + return; + } if (!this.#inflate) { let windowBits = Z_DEFAULT_WINDOWBITS; if (this.#options.serverMaxWindowBits) { @@ -17383,12 +17085,20 @@ var require_permessage_deflate = __commonJS({ this.#inflate[kBuffer] = []; this.#inflate[kLength] = 0; this.#inflate.on("data", (data) => { + if (this.#aborted) { + return; + } this.#inflate[kLength] += data.length; - if (this.#maxPayloadSize > 0 && this.#inflate[kLength] > this.#maxPayloadSize) { - callback(new MessageSizeExceededError()); + if (this.#inflate[kLength] > this.#maxDecompressedSize) { + this.#aborted = true; this.#inflate.removeAllListeners(); this.#inflate.destroy(); this.#inflate = null; + if (this.#currentCallback) { + const cb = this.#currentCallback; + this.#currentCallback = null; + cb(new MessageSizeExceededError()); + } return; } this.#inflate[kBuffer].push(data); @@ -17398,17 +17108,19 @@ var require_permessage_deflate = __commonJS({ callback(err); }); } + this.#currentCallback = callback; this.#inflate.write(chunk); if (fin) { this.#inflate.write(tail); } this.#inflate.flush(() => { - if (!this.#inflate) { + if (this.#aborted || !this.#inflate) { return; } const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]); this.#inflate[kBuffer].length = 0; this.#inflate[kLength] = 0; + this.#currentCallback = null; callback(null, full); }); } @@ -17439,14 +17151,8 @@ var require_receiver = __commonJS({ var { WebsocketFrameSend } = require_frame(); var { closeWebSocketConnection } = require_connection(); var { PerMessageDeflate } = require_permessage_deflate(); - var { MessageSizeExceededError } = require_errors(); - function failWebsocketConnectionWithCode(ws, code, reason) { - closeWebSocketConnection(ws, code, reason, Buffer.byteLength(reason)); - failWebsocketConnection(ws, reason); - } var ByteParser = class extends Writable { #buffers = []; - #fragmentsBytes = 0; #byteOffset = 0; #loop = false; #state = parserStates.INFO; @@ -17454,21 +17160,18 @@ var require_receiver = __commonJS({ #fragments = []; /** @type {Map} */ #extensions; - /** @type {number} */ - #maxFragments; - /** @type {number} */ - #maxPayloadSize; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {import('./websocket').WebSocket} ws * @param {Map|null} extensions - * @param {{ maxFragments?: number, maxPayloadSize?: number }} [options] + * @param {{ maxDecompressedMessageSize?: number }} [options] */ constructor(ws, extensions, options = {}) { super(); this.ws = ws; this.#extensions = extensions == null ? /* @__PURE__ */ new Map() : extensions; - this.#maxFragments = options.maxFragments ?? 0; - this.#maxPayloadSize = options.maxPayloadSize ?? 0; + this.#options = options; if (this.#extensions.has("permessage-deflate")) { this.#extensions.set("permessage-deflate", new PerMessageDeflate(extensions, options)); } @@ -17483,13 +17186,6 @@ var require_receiver = __commonJS({ this.#loop = true; this.run(callback); } - #validatePayloadLength() { - if (this.#maxPayloadSize > 0 && !isControlFrame(this.#info.opcode) && this.#info.payloadLength + this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, "Payload size exceeds maximum allowed size"); - return false; - } - return true; - } /** * Runs whenever a new chunk is received. * Callback is called whenever there are no more chunks buffering, @@ -17549,9 +17245,6 @@ var require_receiver = __commonJS({ if (payloadLength <= 125) { this.#info.payloadLength = payloadLength; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (payloadLength === 126) { this.#state = parserStates.PAYLOADLENGTH_16; } else if (payloadLength === 127) { @@ -17572,9 +17265,6 @@ var require_receiver = __commonJS({ const buffer = this.consume(2); this.#info.payloadLength = buffer.readUInt16BE(0); this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.PAYLOADLENGTH_64) { if (this.#byteOffset < 8) { return callback(); @@ -17588,9 +17278,6 @@ var require_receiver = __commonJS({ } this.#info.payloadLength = lower; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.READ_DATA) { if (this.#byteOffset < this.#info.payloadLength) { return callback(); @@ -17601,46 +17288,32 @@ var require_receiver = __commonJS({ this.#state = parserStates.INFO; } else { if (!this.#info.compressed) { - if (!this.writeFragments(body)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } + this.#fragments.push(body); if (!this.#info.fragmented && this.#info.fin) { - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); + const fullMessage = Buffer.concat(this.#fragments); + websocketMessageReceived(this.ws, this.#info.binaryType, fullMessage); + this.#fragments.length = 0; } this.#state = parserStates.INFO; } else { - this.#extensions.get("permessage-deflate").decompress( - body, - this.#info.fin, - (error2, data) => { - if (error2) { - const code = error2 instanceof MessageSizeExceededError ? 1009 : 1007; - failWebsocketConnectionWithCode(this.ws, code, error2.message); - return; - } - if (!this.writeFragments(data)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } - if (!this.#info.fin) { - this.#state = parserStates.INFO; - this.#loop = true; - this.run(callback); - return; - } - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); - this.#loop = true; + this.#extensions.get("permessage-deflate").decompress(body, this.#info.fin, (error2, data) => { + if (error2) { + failWebsocketConnection(this.ws, error2.message); + return; + } + this.#fragments.push(data); + if (!this.#info.fin) { this.#state = parserStates.INFO; + this.#loop = true; this.run(callback); + return; } - ); + websocketMessageReceived(this.ws, this.#info.binaryType, Buffer.concat(this.#fragments)); + this.#loop = true; + this.#state = parserStates.INFO; + this.#fragments.length = 0; + this.run(callback); + }); this.#loop = false; break; } @@ -17683,26 +17356,6 @@ var require_receiver = __commonJS({ this.#byteOffset -= n; return buffer; } - writeFragments(fragment) { - if (this.#maxFragments > 0 && this.#fragments.length === this.#maxFragments) { - failWebsocketConnectionWithCode(this.ws, 1008, "Too many message fragments"); - return false; - } - this.#fragmentsBytes += fragment.length; - this.#fragments.push(fragment); - return true; - } - consumeFragments() { - const fragments = this.#fragments; - if (fragments.length === 1) { - this.#fragmentsBytes = 0; - return fragments.shift(); - } - const output = Buffer.concat(fragments, this.#fragmentsBytes); - this.#fragments = []; - this.#fragmentsBytes = 0; - return output; - } parseCloseBody(data) { assert(data.length !== 1); let code; @@ -17914,6 +17567,8 @@ var require_websocket = __commonJS({ #extensions = ""; /** @type {SendQueue} */ #sendQueue; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {string} url * @param {string|string[]} protocols @@ -17957,6 +17612,9 @@ var require_websocket = __commonJS({ throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError"); } this[kWebSocketURL] = new URL(urlRecord.href); + this.#options = { + maxDecompressedMessageSize: options.maxDecompressedMessageSize + }; const client = environmentSettingsObject.settingsObject; this[kController] = establishWebSocketConnection( urlRecord, @@ -18140,13 +17798,7 @@ var require_websocket = __commonJS({ */ #onConnectionEstablished(response, parsedExtensions) { this[kResponse] = response; - const webSocketOptions = this[kController]?.dispatcher?.webSocketOptions; - const maxFragments = webSocketOptions?.maxFragments; - const maxPayloadSize = webSocketOptions?.maxPayloadSize; - const parser = new ByteParser(this, parsedExtensions, { - maxFragments, - maxPayloadSize - }); + const parser = new ByteParser(this, parsedExtensions, this.#options); parser.on("drain", onParserDrain); parser.on("error", onParserError.bind(this)); response.socket.ws = this; @@ -18221,6 +17873,19 @@ var require_websocket = __commonJS({ { key: "headers", converter: webidl.nullableConverter(webidl.converters.HeadersInit) + }, + { + key: "maxDecompressedMessageSize", + converter: webidl.nullableConverter((V) => { + V = webidl.converters["unsigned long long"](V); + if (V <= 0) { + throw webidl.errors.exception({ + header: "WebSocket constructor", + message: "maxDecompressedMessageSize must be greater than 0" + }); + } + return V; + }) } ]); webidl.converters["DOMString or sequence or WebSocketInit"] = function(V) { @@ -18299,40 +17964,6 @@ 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; - } - function isValidLastEventIdBytes(buffer, start) { - for (let i = start; i < buffer.length; i++) { - if (buffer[i] === 0) { - 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; - } var EventSourceStream = class extends Transform { /** * @type {eventSourceSettings} @@ -18352,13 +17983,10 @@ var require_eventsource_stream = __commonJS({ */ eventEndCheck = false; /** - * @type {Buffer[]} + * @type {Buffer} */ - chunks = []; - chunkIndex = 0; + buffer = null; pos = 0; - lineChunkIndex = 0; - linePos = 0; event = { data: void 0, event: void 0, @@ -18389,30 +18017,63 @@ var require_eventsource_stream = __commonJS({ callback(); return; } - this.chunks.push(chunk); + if (this.buffer) { + this.buffer = Buffer.concat([this.buffer, chunk]); + } else { + this.buffer = chunk; + } if (this.checkBOM) { - if (this.handleBOM()) { - callback(); - return; + 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; } } - while (this.hasCurrentByte()) { - const byte = this.currentByte(); + while (this.pos < this.buffer.length) { if (this.eventEndCheck) { if (this.crlfCheck) { - if (byte === LF) { + if (this.buffer[this.pos] === LF) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.crlfCheck = false; - this.consumeCurrentByte(); continue; } this.crlfCheck = false; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.consumeCurrentByte(); - if (this.hasPendingEvent()) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; + if (this.event.data !== void 0 || this.event.event || this.event.id || this.event.retry) { this.processEvent(this.event); } this.clearEvent(); @@ -18421,16 +18082,17 @@ var require_eventsource_stream = __commonJS({ this.eventEndCheck = false; continue; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.parseLine(this.readLine(), this.event); - this.consumeCurrentByte(); + this.parseLine(this.buffer.subarray(0, this.pos), this.event); + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.eventEndCheck = true; continue; } - this.advanceCursor(); + this.pos++; } callback(); } @@ -18446,42 +18108,43 @@ var require_eventsource_stream = __commonJS({ if (colonPosition === 0) { return; } - let fieldLength = line.length; - let valueStart = line.length; + let field = ""; + let value = ""; if (colonPosition !== -1) { - fieldLength = colonPosition; - valueStart = colonPosition + 1; + field = line.subarray(0, colonPosition).toString("utf8"); + let valueStart = colonPosition + 1; if (line[valueStart] === SPACE) { ++valueStart; } + value = line.subarray(valueStart).toString("utf8"); + } else { + field = line.toString("utf8"); + value = ""; } - if (isFieldName(line, fieldLength, DATA)) { - const value = line.toString("utf8", valueStart); - if (event.data === void 0) { - event.data = value; - } else { - event.data += ` + switch (field) { + case "data": + if (event[field] === void 0) { + event[field] = value; + } else { + event[field] += ` ${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; - } + } + 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; } } /** @@ -18506,120 +18169,12 @@ ${value}`; } } clearEvent() { - 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(); + this.event = { + data: void 0, + event: void 0, + id: void 0, + retry: void 0 + }; } }; module.exports = { diff --git a/.github/actions/javascript/validateReassureOutput/index.js b/.github/actions/javascript/validateReassureOutput/index.js index e511f56ffd08..b26522496b9c 100644 --- a/.github/actions/javascript/validateReassureOutput/index.js +++ b/.github/actions/javascript/validateReassureOutput/index.js @@ -1863,66 +1863,10 @@ var require_request = __commonJS({ return false; } } - /** - * @param {number|null} statusCode - * @param {Buffer[]|null} headers - * @param {import('node:stream').Duplex} socket - * @param {string} [statusText] - */ - onUpgrade(statusCode, headers, socket, statusText = "") { - this.onFinally(); + onUpgrade(statusCode, headers, socket) { assert(!this.aborted); assert(!this.completed); - 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(error2) { - assert(!this.aborted); - assert(this.completed); - if (channels.error.hasSubscribers) { - channels.error.publish({ request: this, error: error2 }); - } - } - /** - * @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: [] }); - } + return this[kHandler].onUpgrade(statusCode, headers, socket); } onComplete(trailers) { this.onFinally(); @@ -1989,11 +1933,7 @@ var require_request = __commonJS({ } else if (typeof val[i] === "object") { throw new InvalidArgumentError(`invalid ${key} header`); } else { - const str = `${val[i]}`; - if (!isValidHeaderValue(str)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } - arr.push(str); + arr.push(`${val[i]}`); } } val = arr; @@ -2005,9 +1945,6 @@ var require_request = __commonJS({ val = ""; } else { val = `${val}`; - if (!isValidHeaderValue(val)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } } if (headerName === "host") { if (request.host !== null) { @@ -2117,21 +2054,13 @@ var require_dispatcher_base = __commonJS({ var kOnDestroyed = /* @__PURE__ */ Symbol("onDestroyed"); var kOnClosed = /* @__PURE__ */ Symbol("onClosed"); var kInterceptedDispatch = /* @__PURE__ */ Symbol("Intercepted Dispatch"); - var kWebSocketOptions = /* @__PURE__ */ Symbol("webSocketOptions"); var DispatcherBase = class extends Dispatcher { - constructor(opts) { + constructor() { super(); this[kDestroyed] = false; this[kOnDestroyed] = null; this[kClosed] = false; this[kOnClosed] = []; - this[kWebSocketOptions] = opts?.webSocket ?? {}; - } - get webSocketOptions() { - return { - maxFragments: this[kWebSocketOptions].maxFragments ?? 131072, - maxPayloadSize: this[kWebSocketOptions].maxPayloadSize ?? 128 * 1024 * 1024 - }; } get destroyed() { return this[kDestroyed]; @@ -5738,7 +5667,6 @@ var require_client_h1 = __commonJS({ RequestContentLengthMismatchError, ResponseContentLengthMismatchError, RequestAbortedError, - InvalidArgumentError, HeadersTimeoutError, HeadersOverflowError, SocketError, @@ -5785,9 +5713,6 @@ var require_client_h1 = __commonJS({ var FastBuffer = Buffer[Symbol.species]; var addListener = util.addListener; var removeAllListeners = util.removeAllListeners; - var kIdleSocketValidation = /* @__PURE__ */ Symbol("kIdleSocketValidation"); - var kIdleSocketValidationTimeout = /* @__PURE__ */ Symbol("kIdleSocketValidationTimeout"); - var kSocketUsed = /* @__PURE__ */ Symbol("kSocketUsed"); var extractBody; async function lazyllhttp() { const llhttpWasmData = process.env.JEST_WORKER_ID ? require_llhttp_wasm() : void 0; @@ -5950,55 +5875,24 @@ var require_client_h1 = __commonJS({ currentBufferRef = null; } const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr; - if (ret !== constants3.ERROR.OK) { - const body = data.subarray(offset); - if (ret === constants3.ERROR.PAUSED_UPGRADE) { - this.onUpgrade(body); - } else if (ret === constants3.ERROR.PAUSED) { - this.paused = true; - socket.unshift(body); - } else { - throw this.createError(ret, body); + if (ret === constants3.ERROR.PAUSED_UPGRADE) { + this.onUpgrade(data.slice(offset)); + } else if (ret === constants3.ERROR.PAUSED) { + this.paused = true; + socket.unshift(data.slice(offset)); + } else if (ret !== constants3.ERROR.OK) { + const ptr = llhttp.llhttp_get_error_reason(this.ptr); + let message = ""; + if (ptr) { + const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); + message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; } + throw new HTTPParserError(message, constants3.ERROR[ret], data.slice(offset)); } } catch (err) { util.destroy(socket, err); } } - finish() { - assert(currentParser === null); - assert(this.ptr != null); - assert(!this.paused); - const { llhttp } = this; - let ret; - try { - currentParser = this; - ret = llhttp.llhttp_finish(this.ptr); - } finally { - currentParser = null; - } - if (ret === constants3.ERROR.OK) { - return null; - } - if (ret === constants3.ERROR.PAUSED || ret === constants3.ERROR.PAUSED_UPGRADE) { - this.paused = true; - return null; - } - return this.createError(ret, EMPTY_BUF); - } - createError(ret, data) { - const { llhttp, contentLength, bytesRead } = this; - if (contentLength && bytesRead !== parseInt(contentLength, 10)) { - return new ResponseContentLengthMismatchError(); - } - const ptr = llhttp.llhttp_get_error_reason(this.ptr); - let message = ""; - if (ptr) { - const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); - message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; - } - return new HTTPParserError(message, constants3.ERROR[ret], data); - } destroy() { assert(this.ptr != null); assert(currentParser == null); @@ -6018,10 +5912,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request = client[kQueue][client[kRunningIdx]]; if (!request) { return -1; @@ -6065,7 +5955,7 @@ var require_client_h1 = __commonJS({ } } onUpgrade(head) { - const { upgrade, client, socket, headers, statusCode, statusText } = this; + const { upgrade, client, socket, headers, statusCode } = this; assert(upgrade); assert(client[kSocket] === socket); assert(!socket.destroyed); @@ -6090,10 +5980,9 @@ var require_client_h1 = __commonJS({ client[kQueue][client[kRunningIdx]++] = null; client.emit("disconnect", client[kUrl], [client], new InformationalError("upgrade")); try { - request.onUpgrade(statusCode, headers, socket, statusText); - } catch (error2) { - util.errorRequest(client, request, error2); - util.destroy(socket, error2); + request.onUpgrade(statusCode, headers, socket); + } catch (err) { + util.destroy(socket, err); } client[kResume](); } @@ -6102,10 +5991,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request = client[kQueue][client[kRunningIdx]]; if (!request) { return -1; @@ -6231,7 +6116,6 @@ var require_client_h1 = __commonJS({ } request.onComplete(headers); client[kQueue][client[kRunningIdx]++] = null; - socket[kSocketUsed] = true; if (socket[kWriting]) { assert(client[kRunning] === 0); util.destroy(socket, new InformationalError("reset")); @@ -6275,19 +6159,12 @@ var require_client_h1 = __commonJS({ socket[kWriting] = false; socket[kReset] = false; socket[kBlocking] = false; - socket[kIdleSocketValidation] = 0; - socket[kIdleSocketValidationTimeout] = null; - socket[kSocketUsed] = false; socket[kParser] = new Parser(client, socket, llhttpInstance); addListener(socket, "error", function(err) { assert(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID"); const parser = this[kParser]; if (err.code === "ECONNRESET" && parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - this[kError] = parserErr; - this[kClient][kOnError](parserErr); - } + parser.onMessageComplete(); return; } this[kError] = err; @@ -6302,10 +6179,7 @@ var require_client_h1 = __commonJS({ addListener(socket, "end", function() { const parser = this[kParser]; if (parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - util.destroy(this, parserErr); - } + parser.onMessageComplete(); return; } util.destroy(this, new SocketError("other side closed", util.getSocketInfo(this))); @@ -6313,10 +6187,9 @@ var require_client_h1 = __commonJS({ addListener(socket, "close", function() { const client2 = this[kClient]; const parser = this[kParser]; - clearIdleSocketValidation(this); if (parser) { if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { - this[kError] = parser.finish() || this[kError]; + parser.onMessageComplete(); } this[kParser].destroy(); this[kParser] = null; @@ -6365,7 +6238,7 @@ var require_client_h1 = __commonJS({ return socket.destroyed; }, busy(request) { - if (socket[kWriting] || socket[kReset] || socket[kBlocking] || socket[kIdleSocketValidation] === 1) { + if (socket[kWriting] || socket[kReset] || socket[kBlocking]) { return true; } if (request) { @@ -6383,23 +6256,6 @@ var require_client_h1 = __commonJS({ } }; } - function clearIdleSocketValidation(socket) { - if (socket[kIdleSocketValidationTimeout]) { - clearImmediate(socket[kIdleSocketValidationTimeout]); - socket[kIdleSocketValidationTimeout] = null; - } - socket[kIdleSocketValidation] = 0; - } - function scheduleIdleSocketValidation(client, socket) { - socket[kIdleSocketValidation] = 1; - socket[kIdleSocketValidationTimeout] = setImmediate(() => { - socket[kIdleSocketValidationTimeout] = null; - socket[kIdleSocketValidation] = 2; - if (client[kSocket] === socket && !socket.destroyed) { - client[kResume](); - } - }); - } function resumeH1(client) { const socket = client[kSocket]; if (socket && !socket.destroyed) { @@ -6412,29 +6268,6 @@ var require_client_h1 = __commonJS({ socket.ref(); socket[kNoRef] = false; } - if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) { - if (socket[kIdleSocketValidation] === 0) { - scheduleIdleSocketValidation(client, socket); - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - if (socket[kIdleSocketValidation] === 1) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - } - if (client[kRunning] === 0) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - } if (client[kSize] === 0) { if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) { socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE); @@ -6465,16 +6298,8 @@ var require_client_h1 = __commonJS({ } body = bodyStream.stream; contentLength = bodyStream.length; - } else if (util.isBlobLike(body) && request.contentType == null) { - const contentType = body.type; - if (contentType) { - const contentTypeValue = `${contentType}`; - if (!util.isValidHeaderValue(contentTypeValue)) { - util.errorRequest(client, request, new InvalidArgumentError("invalid content-type header")); - return false; - } - headers.push("content-type", contentTypeValue); - } + } else if (util.isBlobLike(body) && request.contentType == null && body.type) { + headers.push("content-type", body.type); } if (body && typeof body.read === "function") { body.read(0); @@ -6495,18 +6320,11 @@ var require_client_h1 = __commonJS({ process.emitWarning(new RequestContentLengthMismatchError()); } const socket = client[kSocket]; - clearIdleSocketValidation(socket); - const abort = (error2) => { - if (request.aborted) { + const abort = (err) => { + if (request.aborted || request.completed) { return; } - if (request.completed) { - if (request.upgrade || request.method === "CONNECT") { - util.destroy(socket, new InformationalError("aborted")); - } - return; - } - util.errorRequest(client, request, error2 || new RequestAbortedError()); + util.errorRequest(client, request, err || new RequestAbortedError()); util.destroy(body); util.destroy(socket, new InformationalError("aborted")); }; @@ -6862,7 +6680,6 @@ var require_client_h2 = __commonJS({ "node_modules/undici/lib/dispatcher/client-h2.js"(exports, module) { "use strict"; var assert = __require("node:assert"); - var { errorMonitor } = __require("node:events"); var { pipeline } = __require("node:stream"); var util = require_util(); var { @@ -6923,10 +6740,6 @@ var require_client_h2 = __commonJS({ } return result; } - function parseH2ResponseHeaders(headers) { - const { [HTTP2_HEADER_STATUS]: _statusCode, ...realHeaders } = headers; - return parseH2Headers(realHeaders); - } async function connectH2(client, socket) { client[kSocket] = socket; if (!h2ExperimentalWarned) { @@ -7090,22 +6903,16 @@ var require_client_h2 = __commonJS({ const { hostname, port } = client[kUrl]; headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ""}`; headers[HTTP2_HEADER_METHOD] = method; - const abort = (error2) => { - if (request.aborted) { + const abort = (err) => { + if (request.aborted || request.completed) { return; } - if (request.completed) { - if (method === "CONNECT" && stream != null) { - util.destroy(stream, error2 || new RequestAbortedError()); - } - return; - } - error2 = error2 || new RequestAbortedError(); - util.errorRequest(client, request, error2); + err = err || new RequestAbortedError(); + util.errorRequest(client, request, err); if (stream != null) { - util.destroy(stream, error2); + util.destroy(stream, err); } - util.destroy(body, error2); + util.destroy(body, err); client[kQueue][client[kRunningIdx]++] = null; client[kResume](); }; @@ -7120,42 +6927,18 @@ var require_client_h2 = __commonJS({ if (method === "CONNECT") { session.ref(); stream = session.request(headers, { endStream: false, signal }); - let upgradeResponseFinished = false; - const onResponse = (headers2) => { - upgradeResponseFinished = true; - stream.off(errorMonitor, onUpgradeError); - request.onUpgradeResponse(Number(headers2[HTTP2_HEADER_STATUS]), headers2, parseH2ResponseHeaders); - }; - const onUpgradeError = (error2) => { - upgradeResponseFinished = true; - stream.off("response", onResponse); - request.onUpgradeError(error2); - }; - const onReady = () => { - try { - request.onUpgrade(null, null, stream); - } catch (error2) { - stream.off("response", onResponse); - abort(error2); - return; - } - if (request.aborted) { - return; - } - stream.off("error", abort); - stream.once(errorMonitor, onUpgradeError); + if (stream.id && !stream.pending) { + request.onUpgrade(null, null, stream); + ++session[kOpenStreams]; client[kQueue][client[kRunningIdx]++] = null; - }; - stream.once("response", onResponse); - stream.once("error", abort); - ++session[kOpenStreams]; - onReady(); + } else { + stream.once("ready", () => { + request.onUpgrade(null, null, stream); + ++session[kOpenStreams]; + client[kQueue][client[kRunningIdx]++] = null; + }); + } 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(); }); @@ -7716,10 +7499,9 @@ var require_client = __commonJS({ autoSelectFamilyAttemptTimeout, // h2 maxConcurrentStreams, - allowH2, - webSocket + allowH2 } = {}) { - super({ webSocket }); + super(); if (keepAlive !== void 0) { throw new InvalidArgumentError("unsupported keepAlive, use pipelining=0 instead"); } @@ -8225,8 +8007,8 @@ var require_pool_base = __commonJS({ var kRemoveClient = /* @__PURE__ */ Symbol("remove client"); var kStats = /* @__PURE__ */ Symbol("stats"); var PoolBase = class extends DispatcherBase { - constructor(opts) { - super(opts); + constructor() { + super(); this[kQueue] = new FixedQueue(); this[kClients] = []; this[kQueued] = 0; @@ -8397,6 +8179,7 @@ var require_pool = __commonJS({ allowH2, ...options } = {}) { + super(); if (connections != null && (!Number.isFinite(connections) || connections < 0)) { throw new InvalidArgumentError("invalid connections"); } @@ -8417,7 +8200,6 @@ var require_pool = __commonJS({ ...connect }); } - super(options); this[kInterceptors] = options.interceptors?.Pool && Array.isArray(options.interceptors.Pool) ? options.interceptors.Pool : []; this[kConnections] = connections || null; this[kUrl] = util.parseOrigin(origin); @@ -8617,6 +8399,7 @@ var require_agent = __commonJS({ } var Agent = class extends DispatcherBase { constructor({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { + super(); if (typeof factory !== "function") { throw new InvalidArgumentError("factory must be a function."); } @@ -8626,7 +8409,6 @@ var require_agent = __commonJS({ if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { throw new InvalidArgumentError("maxRedirections must be a positive number"); } - super(options); if (connect && typeof connect !== "function") { connect = { ...connect }; } @@ -9067,24 +8849,6 @@ var require_retry_handler = __commonJS({ const current = Date.now(); return new Date(retryAfter).getTime() - current; } - function validatePartialResponseContentLength(headers, range, statusCode, retryCount) { - const contentLength = headers["content-length"]; - if (contentLength == null) { - return null; - } - if (!Number.isFinite(range.start) || !Number.isFinite(range.end)) { - return null; - } - const length = Number(contentLength); - const expectedLength = range.end - range.start + 1; - if (!Number.isFinite(length) || length !== expectedLength) { - return new RequestRetryError("Content-Length mismatch", statusCode, { - headers, - data: { count: retryCount } - }); - } - return null; - } var RetryHandler = class _RetryHandler { constructor(opts, handlers) { const { retryOptions, ...dispatchOpts } = opts; @@ -9138,7 +8902,6 @@ var require_retry_handler = __commonJS({ this.end = null; this.etag = null; this.resume = null; - this.headersSent = false; this.handler.onConnect((reason) => { this.aborted = true; if (this.abort) { @@ -9148,17 +8911,6 @@ var require_retry_handler = __commonJS({ } }); } - 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(); @@ -9220,9 +8972,7 @@ var require_retry_handler = __commonJS({ const headers = parseHeaders(rawHeaders); this.retryCount += 1; if (statusCode >= 300) { - if (!this.headersSent && this.retryOpts.statusCodes.includes(statusCode) === false) { - this.headersSent = true; - this.checkpointResponseEnd(headers, resume); + if (this.retryOpts.statusCodes.includes(statusCode) === false) { return this.handler.onHeaders( statusCode, rawHeaders, @@ -9271,21 +9021,9 @@ var require_retry_handler = __commonJS({ ); return false; } - const contentLengthError = validatePartialResponseContentLength(headers, contentRange, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = contentRange; - 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; - } + assert(this.start === start, "content-range mismatch"); + assert(this.end == null || this.end === end, "content-range mismatch"); this.resume = resume; return true; } @@ -9293,7 +9031,6 @@ var require_retry_handler = __commonJS({ if (statusCode === 206) { const range = parseRangeHeader(headers["content-range"]); if (range == null) { - this.headersSent = true; return this.handler.onHeaders( statusCode, rawHeaders, @@ -9301,11 +9038,6 @@ var require_retry_handler = __commonJS({ statusMessage ); } - const contentLengthError = validatePartialResponseContentLength(headers, range, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = range; assert( start != null && Number.isFinite(start), @@ -9325,7 +9057,6 @@ var require_retry_handler = __commonJS({ "invalid content-length" ); this.resume = resume; - this.headersSent = true; this.etag = headers.etag != null ? headers.etag : null; if (this.etag != null && this.etag.startsWith("W/")) { this.etag = null; @@ -9353,7 +9084,7 @@ var require_retry_handler = __commonJS({ return this.handler.onComplete(rawTrailers); } onError(err) { - if (this.aborted || isDisturbed(this.opts.body) || this.headersSent && this.resume == null) { + if (this.aborted || isDisturbed(this.opts.body)) { return this.handler.onError(err); } if (this.retryCount - this.retryCountCheckpoint > 0) { @@ -16152,48 +15883,14 @@ var require_util6 = __commonJS({ for (let i = 0; i < path.length; ++i) { const code = path.charCodeAt(i); if (code < 32 || // exclude CTLs (0-31) - code > 126 || // exclude DEL and non-ascii + code === 127 || // DEL code === 59) { throw new Error("Invalid cookie path"); } } } - function isLetterOrDigit(code) { - return code >= 48 && code <= 57 || // 0-9 - code >= 65 && code <= 90 || // A-Z - code >= 97 && code <= 122; - } function validateCookieDomain(domain) { - if (domain === " ") { - return; - } - if (domain.length > 255) { - throw new Error("Invalid cookie domain"); - } - let labelLength = 0; - for (let i = 0; i < domain.length; ++i) { - const code = domain.charCodeAt(i); - if (code === 46) { - if (labelLength === 0) { - throw new Error("Invalid cookie domain"); - } - if (domain.charCodeAt(i - 1) === 45) { - throw new Error("Invalid cookie domain"); - } - labelLength = 0; - continue; - } - if (labelLength === 0 && !isLetterOrDigit(code)) { - throw new Error("Invalid cookie domain"); - } - if (!isLetterOrDigit(code) && code !== 45) { - throw new Error("Invalid cookie domain"); - } - if (++labelLength > 63) { - throw new Error("Invalid cookie domain"); - } - } - if (labelLength === 0 || domain.charCodeAt(domain.length - 1) === 45) { + if (domain.startsWith("-") || domain.endsWith(".") || domain.endsWith("-")) { throw new Error("Invalid cookie domain"); } } @@ -16276,11 +15973,7 @@ var require_util6 = __commonJS({ throw new Error("Invalid unparsed"); } const [key, ...value] = part.split("="); - const trimmedKey = key.trim(); - const joinedValue = value.join("="); - validateCookieName(trimmedKey); - validateCookieValue(joinedValue); - out.push(`${trimmedKey}=${joinedValue}`); + out.push(`${key.trim()}=${value.join("=")}`); } return out.join("; "); } @@ -16410,14 +16103,18 @@ var require_parse = __commonJS({ } else if (attributeNameLowercase === "httponly") { cookieAttributeList.httpOnly = true; } else if (attributeNameLowercase === "samesite") { + let enforcement = "Default"; const attributeValueLowercase = attributeValue.toLowerCase(); - if (attributeValueLowercase === "none") { - cookieAttributeList.sameSite = "None"; - } else if (attributeValueLowercase === "strict") { - cookieAttributeList.sameSite = "Strict"; - } else if (attributeValueLowercase === "lax") { - cookieAttributeList.sameSite = "Lax"; + if (attributeValueLowercase.includes("none")) { + enforcement = "None"; + } + if (attributeValueLowercase.includes("strict")) { + enforcement = "Strict"; + } + if (attributeValueLowercase.includes("lax")) { + enforcement = "Lax"; } + cookieAttributeList.sameSite = enforcement; } else { cookieAttributeList.unparsed ??= []; cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`); @@ -17239,7 +16936,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 === null || !requestProtocols.includes(secProtocol)) { + if (!requestProtocols.includes(secProtocol)) { failWebsocketConnection(ws, "Protocol was not set in the opening handshake."); return; } @@ -17345,26 +17042,31 @@ var require_permessage_deflate = __commonJS({ var tail = Buffer.from([0, 0, 255, 255]); var kBuffer = /* @__PURE__ */ Symbol("kBuffer"); var kLength = /* @__PURE__ */ Symbol("kLength"); + var kDefaultMaxDecompressedSize = 4 * 1024 * 1024; var PerMessageDeflate = class { /** @type {import('node:zlib').InflateRaw} */ #inflate; #options = {}; - #maxPayloadSize = 0; + /** @type {number} */ + #maxDecompressedSize; + /** @type {boolean} */ + #aborted = false; + /** @type {Function|null} */ + #currentCallback = null; /** * @param {Map} extensions + * @param {{ maxDecompressedMessageSize?: number }} [options] */ - constructor(extensions, options) { + constructor(extensions, options = {}) { this.#options.serverNoContextTakeover = extensions.has("server_no_context_takeover"); this.#options.serverMaxWindowBits = extensions.get("server_max_window_bits"); - this.#maxPayloadSize = options.maxPayloadSize; + this.#maxDecompressedSize = options.maxDecompressedMessageSize ?? kDefaultMaxDecompressedSize; } - /** - * Decompress a compressed payload. - * @param {Buffer} chunk Compressed data - * @param {boolean} fin Final fragment flag - * @param {Function} callback Callback function - */ decompress(chunk, fin, callback) { + if (this.#aborted) { + callback(new MessageSizeExceededError()); + return; + } if (!this.#inflate) { let windowBits = Z_DEFAULT_WINDOWBITS; if (this.#options.serverMaxWindowBits) { @@ -17383,12 +17085,20 @@ var require_permessage_deflate = __commonJS({ this.#inflate[kBuffer] = []; this.#inflate[kLength] = 0; this.#inflate.on("data", (data) => { + if (this.#aborted) { + return; + } this.#inflate[kLength] += data.length; - if (this.#maxPayloadSize > 0 && this.#inflate[kLength] > this.#maxPayloadSize) { - callback(new MessageSizeExceededError()); + if (this.#inflate[kLength] > this.#maxDecompressedSize) { + this.#aborted = true; this.#inflate.removeAllListeners(); this.#inflate.destroy(); this.#inflate = null; + if (this.#currentCallback) { + const cb = this.#currentCallback; + this.#currentCallback = null; + cb(new MessageSizeExceededError()); + } return; } this.#inflate[kBuffer].push(data); @@ -17398,17 +17108,19 @@ var require_permessage_deflate = __commonJS({ callback(err); }); } + this.#currentCallback = callback; this.#inflate.write(chunk); if (fin) { this.#inflate.write(tail); } this.#inflate.flush(() => { - if (!this.#inflate) { + if (this.#aborted || !this.#inflate) { return; } const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]); this.#inflate[kBuffer].length = 0; this.#inflate[kLength] = 0; + this.#currentCallback = null; callback(null, full); }); } @@ -17439,14 +17151,8 @@ var require_receiver = __commonJS({ var { WebsocketFrameSend } = require_frame(); var { closeWebSocketConnection } = require_connection(); var { PerMessageDeflate } = require_permessage_deflate(); - var { MessageSizeExceededError } = require_errors(); - function failWebsocketConnectionWithCode(ws, code, reason) { - closeWebSocketConnection(ws, code, reason, Buffer.byteLength(reason)); - failWebsocketConnection(ws, reason); - } var ByteParser = class extends Writable { #buffers = []; - #fragmentsBytes = 0; #byteOffset = 0; #loop = false; #state = parserStates.INFO; @@ -17454,21 +17160,18 @@ var require_receiver = __commonJS({ #fragments = []; /** @type {Map} */ #extensions; - /** @type {number} */ - #maxFragments; - /** @type {number} */ - #maxPayloadSize; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {import('./websocket').WebSocket} ws * @param {Map|null} extensions - * @param {{ maxFragments?: number, maxPayloadSize?: number }} [options] + * @param {{ maxDecompressedMessageSize?: number }} [options] */ constructor(ws, extensions, options = {}) { super(); this.ws = ws; this.#extensions = extensions == null ? /* @__PURE__ */ new Map() : extensions; - this.#maxFragments = options.maxFragments ?? 0; - this.#maxPayloadSize = options.maxPayloadSize ?? 0; + this.#options = options; if (this.#extensions.has("permessage-deflate")) { this.#extensions.set("permessage-deflate", new PerMessageDeflate(extensions, options)); } @@ -17483,13 +17186,6 @@ var require_receiver = __commonJS({ this.#loop = true; this.run(callback); } - #validatePayloadLength() { - if (this.#maxPayloadSize > 0 && !isControlFrame(this.#info.opcode) && this.#info.payloadLength + this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, "Payload size exceeds maximum allowed size"); - return false; - } - return true; - } /** * Runs whenever a new chunk is received. * Callback is called whenever there are no more chunks buffering, @@ -17549,9 +17245,6 @@ var require_receiver = __commonJS({ if (payloadLength <= 125) { this.#info.payloadLength = payloadLength; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (payloadLength === 126) { this.#state = parserStates.PAYLOADLENGTH_16; } else if (payloadLength === 127) { @@ -17572,9 +17265,6 @@ var require_receiver = __commonJS({ const buffer = this.consume(2); this.#info.payloadLength = buffer.readUInt16BE(0); this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.PAYLOADLENGTH_64) { if (this.#byteOffset < 8) { return callback(); @@ -17588,9 +17278,6 @@ var require_receiver = __commonJS({ } this.#info.payloadLength = lower; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.READ_DATA) { if (this.#byteOffset < this.#info.payloadLength) { return callback(); @@ -17601,46 +17288,32 @@ var require_receiver = __commonJS({ this.#state = parserStates.INFO; } else { if (!this.#info.compressed) { - if (!this.writeFragments(body)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } + this.#fragments.push(body); if (!this.#info.fragmented && this.#info.fin) { - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); + const fullMessage = Buffer.concat(this.#fragments); + websocketMessageReceived(this.ws, this.#info.binaryType, fullMessage); + this.#fragments.length = 0; } this.#state = parserStates.INFO; } else { - this.#extensions.get("permessage-deflate").decompress( - body, - this.#info.fin, - (error2, data) => { - if (error2) { - const code = error2 instanceof MessageSizeExceededError ? 1009 : 1007; - failWebsocketConnectionWithCode(this.ws, code, error2.message); - return; - } - if (!this.writeFragments(data)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } - if (!this.#info.fin) { - this.#state = parserStates.INFO; - this.#loop = true; - this.run(callback); - return; - } - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); - this.#loop = true; + this.#extensions.get("permessage-deflate").decompress(body, this.#info.fin, (error2, data) => { + if (error2) { + failWebsocketConnection(this.ws, error2.message); + return; + } + this.#fragments.push(data); + if (!this.#info.fin) { this.#state = parserStates.INFO; + this.#loop = true; this.run(callback); + return; } - ); + websocketMessageReceived(this.ws, this.#info.binaryType, Buffer.concat(this.#fragments)); + this.#loop = true; + this.#state = parserStates.INFO; + this.#fragments.length = 0; + this.run(callback); + }); this.#loop = false; break; } @@ -17683,26 +17356,6 @@ var require_receiver = __commonJS({ this.#byteOffset -= n; return buffer; } - writeFragments(fragment) { - if (this.#maxFragments > 0 && this.#fragments.length === this.#maxFragments) { - failWebsocketConnectionWithCode(this.ws, 1008, "Too many message fragments"); - return false; - } - this.#fragmentsBytes += fragment.length; - this.#fragments.push(fragment); - return true; - } - consumeFragments() { - const fragments = this.#fragments; - if (fragments.length === 1) { - this.#fragmentsBytes = 0; - return fragments.shift(); - } - const output = Buffer.concat(fragments, this.#fragmentsBytes); - this.#fragments = []; - this.#fragmentsBytes = 0; - return output; - } parseCloseBody(data) { assert(data.length !== 1); let code; @@ -17914,6 +17567,8 @@ var require_websocket = __commonJS({ #extensions = ""; /** @type {SendQueue} */ #sendQueue; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {string} url * @param {string|string[]} protocols @@ -17957,6 +17612,9 @@ var require_websocket = __commonJS({ throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError"); } this[kWebSocketURL] = new URL(urlRecord.href); + this.#options = { + maxDecompressedMessageSize: options.maxDecompressedMessageSize + }; const client = environmentSettingsObject.settingsObject; this[kController] = establishWebSocketConnection( urlRecord, @@ -18140,13 +17798,7 @@ var require_websocket = __commonJS({ */ #onConnectionEstablished(response, parsedExtensions) { this[kResponse] = response; - const webSocketOptions = this[kController]?.dispatcher?.webSocketOptions; - const maxFragments = webSocketOptions?.maxFragments; - const maxPayloadSize = webSocketOptions?.maxPayloadSize; - const parser = new ByteParser(this, parsedExtensions, { - maxFragments, - maxPayloadSize - }); + const parser = new ByteParser(this, parsedExtensions, this.#options); parser.on("drain", onParserDrain); parser.on("error", onParserError.bind(this)); response.socket.ws = this; @@ -18221,6 +17873,19 @@ var require_websocket = __commonJS({ { key: "headers", converter: webidl.nullableConverter(webidl.converters.HeadersInit) + }, + { + key: "maxDecompressedMessageSize", + converter: webidl.nullableConverter((V) => { + V = webidl.converters["unsigned long long"](V); + if (V <= 0) { + throw webidl.errors.exception({ + header: "WebSocket constructor", + message: "maxDecompressedMessageSize must be greater than 0" + }); + } + return V; + }) } ]); webidl.converters["DOMString or sequence or WebSocketInit"] = function(V) { @@ -18299,40 +17964,6 @@ 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; - } - function isValidLastEventIdBytes(buffer, start) { - for (let i = start; i < buffer.length; i++) { - if (buffer[i] === 0) { - 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; - } var EventSourceStream = class extends Transform { /** * @type {eventSourceSettings} @@ -18352,13 +17983,10 @@ var require_eventsource_stream = __commonJS({ */ eventEndCheck = false; /** - * @type {Buffer[]} + * @type {Buffer} */ - chunks = []; - chunkIndex = 0; + buffer = null; pos = 0; - lineChunkIndex = 0; - linePos = 0; event = { data: void 0, event: void 0, @@ -18389,30 +18017,63 @@ var require_eventsource_stream = __commonJS({ callback(); return; } - this.chunks.push(chunk); + if (this.buffer) { + this.buffer = Buffer.concat([this.buffer, chunk]); + } else { + this.buffer = chunk; + } if (this.checkBOM) { - if (this.handleBOM()) { - callback(); - return; + 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; } } - while (this.hasCurrentByte()) { - const byte = this.currentByte(); + while (this.pos < this.buffer.length) { if (this.eventEndCheck) { if (this.crlfCheck) { - if (byte === LF) { + if (this.buffer[this.pos] === LF) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.crlfCheck = false; - this.consumeCurrentByte(); continue; } this.crlfCheck = false; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.consumeCurrentByte(); - if (this.hasPendingEvent()) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; + if (this.event.data !== void 0 || this.event.event || this.event.id || this.event.retry) { this.processEvent(this.event); } this.clearEvent(); @@ -18421,16 +18082,17 @@ var require_eventsource_stream = __commonJS({ this.eventEndCheck = false; continue; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.parseLine(this.readLine(), this.event); - this.consumeCurrentByte(); + this.parseLine(this.buffer.subarray(0, this.pos), this.event); + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.eventEndCheck = true; continue; } - this.advanceCursor(); + this.pos++; } callback(); } @@ -18446,42 +18108,43 @@ var require_eventsource_stream = __commonJS({ if (colonPosition === 0) { return; } - let fieldLength = line.length; - let valueStart = line.length; + let field = ""; + let value = ""; if (colonPosition !== -1) { - fieldLength = colonPosition; - valueStart = colonPosition + 1; + field = line.subarray(0, colonPosition).toString("utf8"); + let valueStart = colonPosition + 1; if (line[valueStart] === SPACE) { ++valueStart; } + value = line.subarray(valueStart).toString("utf8"); + } else { + field = line.toString("utf8"); + value = ""; } - if (isFieldName(line, fieldLength, DATA)) { - const value = line.toString("utf8", valueStart); - if (event.data === void 0) { - event.data = value; - } else { - event.data += ` + switch (field) { + case "data": + if (event[field] === void 0) { + event[field] = value; + } else { + event[field] += ` ${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; - } + } + 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; } } /** @@ -18506,120 +18169,12 @@ ${value}`; } } clearEvent() { - 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(); + this.event = { + data: void 0, + event: void 0, + id: void 0, + retry: void 0 + }; } }; module.exports = { diff --git a/.github/actions/javascript/verifySignedCommits/index.js b/.github/actions/javascript/verifySignedCommits/index.js index d982728230d3..087b5df387fd 100644 --- a/.github/actions/javascript/verifySignedCommits/index.js +++ b/.github/actions/javascript/verifySignedCommits/index.js @@ -1863,66 +1863,10 @@ var require_request = __commonJS({ return false; } } - /** - * @param {number|null} statusCode - * @param {Buffer[]|null} headers - * @param {import('node:stream').Duplex} socket - * @param {string} [statusText] - */ - onUpgrade(statusCode, headers, socket, statusText = "") { - this.onFinally(); + onUpgrade(statusCode, headers, socket) { assert(!this.aborted); assert(!this.completed); - 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(error2) { - assert(!this.aborted); - assert(this.completed); - if (channels.error.hasSubscribers) { - channels.error.publish({ request: this, error: error2 }); - } - } - /** - * @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: [] }); - } + return this[kHandler].onUpgrade(statusCode, headers, socket); } onComplete(trailers) { this.onFinally(); @@ -1989,11 +1933,7 @@ var require_request = __commonJS({ } else if (typeof val[i] === "object") { throw new InvalidArgumentError(`invalid ${key} header`); } else { - const str = `${val[i]}`; - if (!isValidHeaderValue(str)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } - arr.push(str); + arr.push(`${val[i]}`); } } val = arr; @@ -2005,9 +1945,6 @@ var require_request = __commonJS({ val = ""; } else { val = `${val}`; - if (!isValidHeaderValue(val)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } } if (headerName === "host") { if (request2.host !== null) { @@ -2117,21 +2054,13 @@ var require_dispatcher_base = __commonJS({ var kOnDestroyed = /* @__PURE__ */ Symbol("onDestroyed"); var kOnClosed = /* @__PURE__ */ Symbol("onClosed"); var kInterceptedDispatch = /* @__PURE__ */ Symbol("Intercepted Dispatch"); - var kWebSocketOptions = /* @__PURE__ */ Symbol("webSocketOptions"); var DispatcherBase = class extends Dispatcher { - constructor(opts) { + constructor() { super(); this[kDestroyed] = false; this[kOnDestroyed] = null; this[kClosed] = false; this[kOnClosed] = []; - this[kWebSocketOptions] = opts?.webSocket ?? {}; - } - get webSocketOptions() { - return { - maxFragments: this[kWebSocketOptions].maxFragments ?? 131072, - maxPayloadSize: this[kWebSocketOptions].maxPayloadSize ?? 128 * 1024 * 1024 - }; } get destroyed() { return this[kDestroyed]; @@ -5738,7 +5667,6 @@ var require_client_h1 = __commonJS({ RequestContentLengthMismatchError, ResponseContentLengthMismatchError, RequestAbortedError, - InvalidArgumentError, HeadersTimeoutError, HeadersOverflowError, SocketError, @@ -5785,9 +5713,6 @@ var require_client_h1 = __commonJS({ var FastBuffer = Buffer[Symbol.species]; var addListener = util.addListener; var removeAllListeners = util.removeAllListeners; - var kIdleSocketValidation = /* @__PURE__ */ Symbol("kIdleSocketValidation"); - var kIdleSocketValidationTimeout = /* @__PURE__ */ Symbol("kIdleSocketValidationTimeout"); - var kSocketUsed = /* @__PURE__ */ Symbol("kSocketUsed"); var extractBody; async function lazyllhttp() { const llhttpWasmData = process.env.JEST_WORKER_ID ? require_llhttp_wasm() : void 0; @@ -5950,55 +5875,24 @@ var require_client_h1 = __commonJS({ currentBufferRef = null; } const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr; - if (ret !== constants3.ERROR.OK) { - const body = data.subarray(offset); - if (ret === constants3.ERROR.PAUSED_UPGRADE) { - this.onUpgrade(body); - } else if (ret === constants3.ERROR.PAUSED) { - this.paused = true; - socket.unshift(body); - } else { - throw this.createError(ret, body); + if (ret === constants3.ERROR.PAUSED_UPGRADE) { + this.onUpgrade(data.slice(offset)); + } else if (ret === constants3.ERROR.PAUSED) { + this.paused = true; + socket.unshift(data.slice(offset)); + } else if (ret !== constants3.ERROR.OK) { + const ptr = llhttp.llhttp_get_error_reason(this.ptr); + let message = ""; + if (ptr) { + const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); + message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; } + throw new HTTPParserError(message, constants3.ERROR[ret], data.slice(offset)); } } catch (err) { util.destroy(socket, err); } } - finish() { - assert(currentParser === null); - assert(this.ptr != null); - assert(!this.paused); - const { llhttp } = this; - let ret; - try { - currentParser = this; - ret = llhttp.llhttp_finish(this.ptr); - } finally { - currentParser = null; - } - if (ret === constants3.ERROR.OK) { - return null; - } - if (ret === constants3.ERROR.PAUSED || ret === constants3.ERROR.PAUSED_UPGRADE) { - this.paused = true; - return null; - } - return this.createError(ret, EMPTY_BUF); - } - createError(ret, data) { - const { llhttp, contentLength, bytesRead } = this; - if (contentLength && bytesRead !== parseInt(contentLength, 10)) { - return new ResponseContentLengthMismatchError(); - } - const ptr = llhttp.llhttp_get_error_reason(this.ptr); - let message = ""; - if (ptr) { - const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); - message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; - } - return new HTTPParserError(message, constants3.ERROR[ret], data); - } destroy() { assert(this.ptr != null); assert(currentParser == null); @@ -6018,10 +5912,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6065,7 +5955,7 @@ var require_client_h1 = __commonJS({ } } onUpgrade(head) { - const { upgrade, client, socket, headers, statusCode, statusText } = this; + const { upgrade, client, socket, headers, statusCode } = this; assert(upgrade); assert(client[kSocket] === socket); assert(!socket.destroyed); @@ -6090,10 +5980,9 @@ var require_client_h1 = __commonJS({ client[kQueue][client[kRunningIdx]++] = null; client.emit("disconnect", client[kUrl], [client], new InformationalError("upgrade")); try { - request2.onUpgrade(statusCode, headers, socket, statusText); - } catch (error2) { - util.errorRequest(client, request2, error2); - util.destroy(socket, error2); + request2.onUpgrade(statusCode, headers, socket); + } catch (err) { + util.destroy(socket, err); } client[kResume](); } @@ -6102,10 +5991,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6231,7 +6116,6 @@ var require_client_h1 = __commonJS({ } request2.onComplete(headers); client[kQueue][client[kRunningIdx]++] = null; - socket[kSocketUsed] = true; if (socket[kWriting]) { assert(client[kRunning] === 0); util.destroy(socket, new InformationalError("reset")); @@ -6275,19 +6159,12 @@ var require_client_h1 = __commonJS({ socket[kWriting] = false; socket[kReset] = false; socket[kBlocking] = false; - socket[kIdleSocketValidation] = 0; - socket[kIdleSocketValidationTimeout] = null; - socket[kSocketUsed] = false; socket[kParser] = new Parser(client, socket, llhttpInstance); addListener(socket, "error", function(err) { assert(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID"); const parser = this[kParser]; if (err.code === "ECONNRESET" && parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - this[kError] = parserErr; - this[kClient][kOnError](parserErr); - } + parser.onMessageComplete(); return; } this[kError] = err; @@ -6302,10 +6179,7 @@ var require_client_h1 = __commonJS({ addListener(socket, "end", function() { const parser = this[kParser]; if (parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - util.destroy(this, parserErr); - } + parser.onMessageComplete(); return; } util.destroy(this, new SocketError("other side closed", util.getSocketInfo(this))); @@ -6313,10 +6187,9 @@ var require_client_h1 = __commonJS({ addListener(socket, "close", function() { const client2 = this[kClient]; const parser = this[kParser]; - clearIdleSocketValidation(this); if (parser) { if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { - this[kError] = parser.finish() || this[kError]; + parser.onMessageComplete(); } this[kParser].destroy(); this[kParser] = null; @@ -6365,7 +6238,7 @@ var require_client_h1 = __commonJS({ return socket.destroyed; }, busy(request2) { - if (socket[kWriting] || socket[kReset] || socket[kBlocking] || socket[kIdleSocketValidation] === 1) { + if (socket[kWriting] || socket[kReset] || socket[kBlocking]) { return true; } if (request2) { @@ -6383,23 +6256,6 @@ var require_client_h1 = __commonJS({ } }; } - function clearIdleSocketValidation(socket) { - if (socket[kIdleSocketValidationTimeout]) { - clearImmediate(socket[kIdleSocketValidationTimeout]); - socket[kIdleSocketValidationTimeout] = null; - } - socket[kIdleSocketValidation] = 0; - } - function scheduleIdleSocketValidation(client, socket) { - socket[kIdleSocketValidation] = 1; - socket[kIdleSocketValidationTimeout] = setImmediate(() => { - socket[kIdleSocketValidationTimeout] = null; - socket[kIdleSocketValidation] = 2; - if (client[kSocket] === socket && !socket.destroyed) { - client[kResume](); - } - }); - } function resumeH1(client) { const socket = client[kSocket]; if (socket && !socket.destroyed) { @@ -6412,29 +6268,6 @@ var require_client_h1 = __commonJS({ socket.ref(); socket[kNoRef] = false; } - if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) { - if (socket[kIdleSocketValidation] === 0) { - scheduleIdleSocketValidation(client, socket); - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - if (socket[kIdleSocketValidation] === 1) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - } - if (client[kRunning] === 0) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - } if (client[kSize] === 0) { if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) { socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE); @@ -6465,16 +6298,8 @@ var require_client_h1 = __commonJS({ } body = bodyStream.stream; contentLength = bodyStream.length; - } else if (util.isBlobLike(body) && request2.contentType == null) { - const contentType = body.type; - if (contentType) { - const contentTypeValue = `${contentType}`; - if (!util.isValidHeaderValue(contentTypeValue)) { - util.errorRequest(client, request2, new InvalidArgumentError("invalid content-type header")); - return false; - } - headers.push("content-type", contentTypeValue); - } + } else if (util.isBlobLike(body) && request2.contentType == null && body.type) { + headers.push("content-type", body.type); } if (body && typeof body.read === "function") { body.read(0); @@ -6495,18 +6320,11 @@ var require_client_h1 = __commonJS({ process.emitWarning(new RequestContentLengthMismatchError()); } const socket = client[kSocket]; - clearIdleSocketValidation(socket); - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (request2.upgrade || request2.method === "CONNECT") { - util.destroy(socket, new InformationalError("aborted")); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - util.errorRequest(client, request2, error2 || new RequestAbortedError()); + util.errorRequest(client, request2, err || new RequestAbortedError()); util.destroy(body); util.destroy(socket, new InformationalError("aborted")); }; @@ -6862,7 +6680,6 @@ var require_client_h2 = __commonJS({ "node_modules/undici/lib/dispatcher/client-h2.js"(exports, module) { "use strict"; var assert = __require("node:assert"); - var { errorMonitor } = __require("node:events"); var { pipeline } = __require("node:stream"); var util = require_util(); var { @@ -6923,10 +6740,6 @@ var require_client_h2 = __commonJS({ } return result; } - function parseH2ResponseHeaders(headers) { - const { [HTTP2_HEADER_STATUS]: _statusCode, ...realHeaders } = headers; - return parseH2Headers(realHeaders); - } async function connectH2(client, socket) { client[kSocket] = socket; if (!h2ExperimentalWarned) { @@ -7090,22 +6903,16 @@ var require_client_h2 = __commonJS({ const { hostname, port } = client[kUrl]; headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ""}`; headers[HTTP2_HEADER_METHOD] = method; - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (method === "CONNECT" && stream != null) { - util.destroy(stream, error2 || new RequestAbortedError()); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - error2 = error2 || new RequestAbortedError(); - util.errorRequest(client, request2, error2); + err = err || new RequestAbortedError(); + util.errorRequest(client, request2, err); if (stream != null) { - util.destroy(stream, error2); + util.destroy(stream, err); } - util.destroy(body, error2); + util.destroy(body, err); client[kQueue][client[kRunningIdx]++] = null; client[kResume](); }; @@ -7120,42 +6927,18 @@ var require_client_h2 = __commonJS({ if (method === "CONNECT") { session.ref(); stream = session.request(headers, { endStream: false, signal }); - let upgradeResponseFinished = false; - const onResponse = (headers2) => { - upgradeResponseFinished = true; - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeResponse(Number(headers2[HTTP2_HEADER_STATUS]), headers2, parseH2ResponseHeaders); - }; - const onUpgradeError = (error2) => { - upgradeResponseFinished = true; - stream.off("response", onResponse); - request2.onUpgradeError(error2); - }; - const onReady = () => { - try { - request2.onUpgrade(null, null, stream); - } catch (error2) { - stream.off("response", onResponse); - abort(error2); - return; - } - if (request2.aborted) { - return; - } - stream.off("error", abort); - stream.once(errorMonitor, onUpgradeError); + if (stream.id && !stream.pending) { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; client[kQueue][client[kRunningIdx]++] = null; - }; - stream.once("response", onResponse); - stream.once("error", abort); - ++session[kOpenStreams]; - onReady(); + } else { + stream.once("ready", () => { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; + client[kQueue][client[kRunningIdx]++] = null; + }); + } stream.once("close", () => { - if (!upgradeResponseFinished && request2.completed) { - stream.off("response", onResponse); - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeError(new InformationalError(`HTTP/2: "stream error" received - code ${stream.rstCode}`)); - } session[kOpenStreams] -= 1; if (session[kOpenStreams] === 0) session.unref(); }); @@ -7716,10 +7499,9 @@ var require_client = __commonJS({ autoSelectFamilyAttemptTimeout, // h2 maxConcurrentStreams, - allowH2, - webSocket + allowH2 } = {}) { - super({ webSocket }); + super(); if (keepAlive !== void 0) { throw new InvalidArgumentError("unsupported keepAlive, use pipelining=0 instead"); } @@ -8225,8 +8007,8 @@ var require_pool_base = __commonJS({ var kRemoveClient = /* @__PURE__ */ Symbol("remove client"); var kStats = /* @__PURE__ */ Symbol("stats"); var PoolBase = class extends DispatcherBase { - constructor(opts) { - super(opts); + constructor() { + super(); this[kQueue] = new FixedQueue(); this[kClients] = []; this[kQueued] = 0; @@ -8397,6 +8179,7 @@ var require_pool = __commonJS({ allowH2, ...options } = {}) { + super(); if (connections != null && (!Number.isFinite(connections) || connections < 0)) { throw new InvalidArgumentError("invalid connections"); } @@ -8417,7 +8200,6 @@ var require_pool = __commonJS({ ...connect }); } - super(options); this[kInterceptors] = options.interceptors?.Pool && Array.isArray(options.interceptors.Pool) ? options.interceptors.Pool : []; this[kConnections] = connections || null; this[kUrl] = util.parseOrigin(origin); @@ -8617,6 +8399,7 @@ var require_agent = __commonJS({ } var Agent = class extends DispatcherBase { constructor({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { + super(); if (typeof factory !== "function") { throw new InvalidArgumentError("factory must be a function."); } @@ -8626,7 +8409,6 @@ var require_agent = __commonJS({ if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { throw new InvalidArgumentError("maxRedirections must be a positive number"); } - super(options); if (connect && typeof connect !== "function") { connect = { ...connect }; } @@ -9067,24 +8849,6 @@ var require_retry_handler = __commonJS({ const current = Date.now(); return new Date(retryAfter).getTime() - current; } - function validatePartialResponseContentLength(headers, range, statusCode, retryCount) { - const contentLength = headers["content-length"]; - if (contentLength == null) { - return null; - } - if (!Number.isFinite(range.start) || !Number.isFinite(range.end)) { - return null; - } - const length = Number(contentLength); - const expectedLength = range.end - range.start + 1; - if (!Number.isFinite(length) || length !== expectedLength) { - return new RequestRetryError("Content-Length mismatch", statusCode, { - headers, - data: { count: retryCount } - }); - } - return null; - } var RetryHandler = class _RetryHandler { constructor(opts, handlers) { const { retryOptions, ...dispatchOpts } = opts; @@ -9138,7 +8902,6 @@ var require_retry_handler = __commonJS({ this.end = null; this.etag = null; this.resume = null; - this.headersSent = false; this.handler.onConnect((reason) => { this.aborted = true; if (this.abort) { @@ -9148,17 +8911,6 @@ var require_retry_handler = __commonJS({ } }); } - 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(); @@ -9220,9 +8972,7 @@ var require_retry_handler = __commonJS({ const headers = parseHeaders(rawHeaders); this.retryCount += 1; if (statusCode >= 300) { - if (!this.headersSent && this.retryOpts.statusCodes.includes(statusCode) === false) { - this.headersSent = true; - this.checkpointResponseEnd(headers, resume); + if (this.retryOpts.statusCodes.includes(statusCode) === false) { return this.handler.onHeaders( statusCode, rawHeaders, @@ -9271,21 +9021,9 @@ var require_retry_handler = __commonJS({ ); return false; } - const contentLengthError = validatePartialResponseContentLength(headers, contentRange, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = contentRange; - 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; - } + assert(this.start === start, "content-range mismatch"); + assert(this.end == null || this.end === end, "content-range mismatch"); this.resume = resume; return true; } @@ -9293,7 +9031,6 @@ var require_retry_handler = __commonJS({ if (statusCode === 206) { const range = parseRangeHeader(headers["content-range"]); if (range == null) { - this.headersSent = true; return this.handler.onHeaders( statusCode, rawHeaders, @@ -9301,11 +9038,6 @@ var require_retry_handler = __commonJS({ statusMessage ); } - const contentLengthError = validatePartialResponseContentLength(headers, range, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = range; assert( start != null && Number.isFinite(start), @@ -9325,7 +9057,6 @@ var require_retry_handler = __commonJS({ "invalid content-length" ); this.resume = resume; - this.headersSent = true; this.etag = headers.etag != null ? headers.etag : null; if (this.etag != null && this.etag.startsWith("W/")) { this.etag = null; @@ -9353,7 +9084,7 @@ var require_retry_handler = __commonJS({ return this.handler.onComplete(rawTrailers); } onError(err) { - if (this.aborted || isDisturbed(this.opts.body) || this.headersSent && this.resume == null) { + if (this.aborted || isDisturbed(this.opts.body)) { return this.handler.onError(err); } if (this.retryCount - this.retryCountCheckpoint > 0) { @@ -16152,48 +15883,14 @@ var require_util6 = __commonJS({ for (let i = 0; i < path.length; ++i) { const code = path.charCodeAt(i); if (code < 32 || // exclude CTLs (0-31) - code > 126 || // exclude DEL and non-ascii + code === 127 || // DEL code === 59) { throw new Error("Invalid cookie path"); } } } - function isLetterOrDigit(code) { - return code >= 48 && code <= 57 || // 0-9 - code >= 65 && code <= 90 || // A-Z - code >= 97 && code <= 122; - } function validateCookieDomain(domain) { - if (domain === " ") { - return; - } - if (domain.length > 255) { - throw new Error("Invalid cookie domain"); - } - let labelLength = 0; - for (let i = 0; i < domain.length; ++i) { - const code = domain.charCodeAt(i); - if (code === 46) { - if (labelLength === 0) { - throw new Error("Invalid cookie domain"); - } - if (domain.charCodeAt(i - 1) === 45) { - throw new Error("Invalid cookie domain"); - } - labelLength = 0; - continue; - } - if (labelLength === 0 && !isLetterOrDigit(code)) { - throw new Error("Invalid cookie domain"); - } - if (!isLetterOrDigit(code) && code !== 45) { - throw new Error("Invalid cookie domain"); - } - if (++labelLength > 63) { - throw new Error("Invalid cookie domain"); - } - } - if (labelLength === 0 || domain.charCodeAt(domain.length - 1) === 45) { + if (domain.startsWith("-") || domain.endsWith(".") || domain.endsWith("-")) { throw new Error("Invalid cookie domain"); } } @@ -16276,11 +15973,7 @@ var require_util6 = __commonJS({ throw new Error("Invalid unparsed"); } const [key, ...value] = part.split("="); - const trimmedKey = key.trim(); - const joinedValue = value.join("="); - validateCookieName(trimmedKey); - validateCookieValue(joinedValue); - out.push(`${trimmedKey}=${joinedValue}`); + out.push(`${key.trim()}=${value.join("=")}`); } return out.join("; "); } @@ -16410,14 +16103,18 @@ var require_parse = __commonJS({ } else if (attributeNameLowercase === "httponly") { cookieAttributeList.httpOnly = true; } else if (attributeNameLowercase === "samesite") { + let enforcement = "Default"; const attributeValueLowercase = attributeValue.toLowerCase(); - if (attributeValueLowercase === "none") { - cookieAttributeList.sameSite = "None"; - } else if (attributeValueLowercase === "strict") { - cookieAttributeList.sameSite = "Strict"; - } else if (attributeValueLowercase === "lax") { - cookieAttributeList.sameSite = "Lax"; + if (attributeValueLowercase.includes("none")) { + enforcement = "None"; + } + if (attributeValueLowercase.includes("strict")) { + enforcement = "Strict"; + } + if (attributeValueLowercase.includes("lax")) { + enforcement = "Lax"; } + cookieAttributeList.sameSite = enforcement; } else { cookieAttributeList.unparsed ??= []; cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`); @@ -17239,7 +16936,7 @@ var require_connection = __commonJS({ const secProtocol = response.headersList.get("Sec-WebSocket-Protocol"); if (secProtocol !== null) { const requestProtocols = getDecodeSplit("sec-websocket-protocol", request2.headersList); - if (requestProtocols === null || !requestProtocols.includes(secProtocol)) { + if (!requestProtocols.includes(secProtocol)) { failWebsocketConnection(ws, "Protocol was not set in the opening handshake."); return; } @@ -17345,26 +17042,31 @@ var require_permessage_deflate = __commonJS({ var tail = Buffer.from([0, 0, 255, 255]); var kBuffer = /* @__PURE__ */ Symbol("kBuffer"); var kLength = /* @__PURE__ */ Symbol("kLength"); + var kDefaultMaxDecompressedSize = 4 * 1024 * 1024; var PerMessageDeflate = class { /** @type {import('node:zlib').InflateRaw} */ #inflate; #options = {}; - #maxPayloadSize = 0; + /** @type {number} */ + #maxDecompressedSize; + /** @type {boolean} */ + #aborted = false; + /** @type {Function|null} */ + #currentCallback = null; /** * @param {Map} extensions + * @param {{ maxDecompressedMessageSize?: number }} [options] */ - constructor(extensions, options) { + constructor(extensions, options = {}) { this.#options.serverNoContextTakeover = extensions.has("server_no_context_takeover"); this.#options.serverMaxWindowBits = extensions.get("server_max_window_bits"); - this.#maxPayloadSize = options.maxPayloadSize; + this.#maxDecompressedSize = options.maxDecompressedMessageSize ?? kDefaultMaxDecompressedSize; } - /** - * Decompress a compressed payload. - * @param {Buffer} chunk Compressed data - * @param {boolean} fin Final fragment flag - * @param {Function} callback Callback function - */ decompress(chunk, fin, callback) { + if (this.#aborted) { + callback(new MessageSizeExceededError()); + return; + } if (!this.#inflate) { let windowBits = Z_DEFAULT_WINDOWBITS; if (this.#options.serverMaxWindowBits) { @@ -17383,12 +17085,20 @@ var require_permessage_deflate = __commonJS({ this.#inflate[kBuffer] = []; this.#inflate[kLength] = 0; this.#inflate.on("data", (data) => { + if (this.#aborted) { + return; + } this.#inflate[kLength] += data.length; - if (this.#maxPayloadSize > 0 && this.#inflate[kLength] > this.#maxPayloadSize) { - callback(new MessageSizeExceededError()); + if (this.#inflate[kLength] > this.#maxDecompressedSize) { + this.#aborted = true; this.#inflate.removeAllListeners(); this.#inflate.destroy(); this.#inflate = null; + if (this.#currentCallback) { + const cb = this.#currentCallback; + this.#currentCallback = null; + cb(new MessageSizeExceededError()); + } return; } this.#inflate[kBuffer].push(data); @@ -17398,17 +17108,19 @@ var require_permessage_deflate = __commonJS({ callback(err); }); } + this.#currentCallback = callback; this.#inflate.write(chunk); if (fin) { this.#inflate.write(tail); } this.#inflate.flush(() => { - if (!this.#inflate) { + if (this.#aborted || !this.#inflate) { return; } const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]); this.#inflate[kBuffer].length = 0; this.#inflate[kLength] = 0; + this.#currentCallback = null; callback(null, full); }); } @@ -17439,14 +17151,8 @@ var require_receiver = __commonJS({ var { WebsocketFrameSend } = require_frame(); var { closeWebSocketConnection } = require_connection(); var { PerMessageDeflate } = require_permessage_deflate(); - var { MessageSizeExceededError } = require_errors(); - function failWebsocketConnectionWithCode(ws, code, reason) { - closeWebSocketConnection(ws, code, reason, Buffer.byteLength(reason)); - failWebsocketConnection(ws, reason); - } var ByteParser = class extends Writable { #buffers = []; - #fragmentsBytes = 0; #byteOffset = 0; #loop = false; #state = parserStates.INFO; @@ -17454,21 +17160,18 @@ var require_receiver = __commonJS({ #fragments = []; /** @type {Map} */ #extensions; - /** @type {number} */ - #maxFragments; - /** @type {number} */ - #maxPayloadSize; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {import('./websocket').WebSocket} ws * @param {Map|null} extensions - * @param {{ maxFragments?: number, maxPayloadSize?: number }} [options] + * @param {{ maxDecompressedMessageSize?: number }} [options] */ constructor(ws, extensions, options = {}) { super(); this.ws = ws; this.#extensions = extensions == null ? /* @__PURE__ */ new Map() : extensions; - this.#maxFragments = options.maxFragments ?? 0; - this.#maxPayloadSize = options.maxPayloadSize ?? 0; + this.#options = options; if (this.#extensions.has("permessage-deflate")) { this.#extensions.set("permessage-deflate", new PerMessageDeflate(extensions, options)); } @@ -17483,13 +17186,6 @@ var require_receiver = __commonJS({ this.#loop = true; this.run(callback); } - #validatePayloadLength() { - if (this.#maxPayloadSize > 0 && !isControlFrame(this.#info.opcode) && this.#info.payloadLength + this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, "Payload size exceeds maximum allowed size"); - return false; - } - return true; - } /** * Runs whenever a new chunk is received. * Callback is called whenever there are no more chunks buffering, @@ -17549,9 +17245,6 @@ var require_receiver = __commonJS({ if (payloadLength <= 125) { this.#info.payloadLength = payloadLength; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (payloadLength === 126) { this.#state = parserStates.PAYLOADLENGTH_16; } else if (payloadLength === 127) { @@ -17572,9 +17265,6 @@ var require_receiver = __commonJS({ const buffer = this.consume(2); this.#info.payloadLength = buffer.readUInt16BE(0); this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.PAYLOADLENGTH_64) { if (this.#byteOffset < 8) { return callback(); @@ -17588,9 +17278,6 @@ var require_receiver = __commonJS({ } this.#info.payloadLength = lower; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.READ_DATA) { if (this.#byteOffset < this.#info.payloadLength) { return callback(); @@ -17601,46 +17288,32 @@ var require_receiver = __commonJS({ this.#state = parserStates.INFO; } else { if (!this.#info.compressed) { - if (!this.writeFragments(body)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } + this.#fragments.push(body); if (!this.#info.fragmented && this.#info.fin) { - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); + const fullMessage = Buffer.concat(this.#fragments); + websocketMessageReceived(this.ws, this.#info.binaryType, fullMessage); + this.#fragments.length = 0; } this.#state = parserStates.INFO; } else { - this.#extensions.get("permessage-deflate").decompress( - body, - this.#info.fin, - (error2, data) => { - if (error2) { - const code = error2 instanceof MessageSizeExceededError ? 1009 : 1007; - failWebsocketConnectionWithCode(this.ws, code, error2.message); - return; - } - if (!this.writeFragments(data)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } - if (!this.#info.fin) { - this.#state = parserStates.INFO; - this.#loop = true; - this.run(callback); - return; - } - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); - this.#loop = true; + this.#extensions.get("permessage-deflate").decompress(body, this.#info.fin, (error2, data) => { + if (error2) { + failWebsocketConnection(this.ws, error2.message); + return; + } + this.#fragments.push(data); + if (!this.#info.fin) { this.#state = parserStates.INFO; + this.#loop = true; this.run(callback); + return; } - ); + websocketMessageReceived(this.ws, this.#info.binaryType, Buffer.concat(this.#fragments)); + this.#loop = true; + this.#state = parserStates.INFO; + this.#fragments.length = 0; + this.run(callback); + }); this.#loop = false; break; } @@ -17683,26 +17356,6 @@ var require_receiver = __commonJS({ this.#byteOffset -= n; return buffer; } - writeFragments(fragment) { - if (this.#maxFragments > 0 && this.#fragments.length === this.#maxFragments) { - failWebsocketConnectionWithCode(this.ws, 1008, "Too many message fragments"); - return false; - } - this.#fragmentsBytes += fragment.length; - this.#fragments.push(fragment); - return true; - } - consumeFragments() { - const fragments = this.#fragments; - if (fragments.length === 1) { - this.#fragmentsBytes = 0; - return fragments.shift(); - } - const output = Buffer.concat(fragments, this.#fragmentsBytes); - this.#fragments = []; - this.#fragmentsBytes = 0; - return output; - } parseCloseBody(data) { assert(data.length !== 1); let code; @@ -17914,6 +17567,8 @@ var require_websocket = __commonJS({ #extensions = ""; /** @type {SendQueue} */ #sendQueue; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {string} url * @param {string|string[]} protocols @@ -17957,6 +17612,9 @@ var require_websocket = __commonJS({ throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError"); } this[kWebSocketURL] = new URL(urlRecord.href); + this.#options = { + maxDecompressedMessageSize: options.maxDecompressedMessageSize + }; const client = environmentSettingsObject.settingsObject; this[kController] = establishWebSocketConnection( urlRecord, @@ -18140,13 +17798,7 @@ var require_websocket = __commonJS({ */ #onConnectionEstablished(response, parsedExtensions) { this[kResponse] = response; - const webSocketOptions = this[kController]?.dispatcher?.webSocketOptions; - const maxFragments = webSocketOptions?.maxFragments; - const maxPayloadSize = webSocketOptions?.maxPayloadSize; - const parser = new ByteParser(this, parsedExtensions, { - maxFragments, - maxPayloadSize - }); + const parser = new ByteParser(this, parsedExtensions, this.#options); parser.on("drain", onParserDrain); parser.on("error", onParserError.bind(this)); response.socket.ws = this; @@ -18221,6 +17873,19 @@ var require_websocket = __commonJS({ { key: "headers", converter: webidl.nullableConverter(webidl.converters.HeadersInit) + }, + { + key: "maxDecompressedMessageSize", + converter: webidl.nullableConverter((V) => { + V = webidl.converters["unsigned long long"](V); + if (V <= 0) { + throw webidl.errors.exception({ + header: "WebSocket constructor", + message: "maxDecompressedMessageSize must be greater than 0" + }); + } + return V; + }) } ]); webidl.converters["DOMString or sequence or WebSocketInit"] = function(V) { @@ -18299,40 +17964,6 @@ 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; - } - function isValidLastEventIdBytes(buffer, start) { - for (let i = start; i < buffer.length; i++) { - if (buffer[i] === 0) { - 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; - } var EventSourceStream = class extends Transform { /** * @type {eventSourceSettings} @@ -18352,13 +17983,10 @@ var require_eventsource_stream = __commonJS({ */ eventEndCheck = false; /** - * @type {Buffer[]} + * @type {Buffer} */ - chunks = []; - chunkIndex = 0; + buffer = null; pos = 0; - lineChunkIndex = 0; - linePos = 0; event = { data: void 0, event: void 0, @@ -18389,30 +18017,63 @@ var require_eventsource_stream = __commonJS({ callback(); return; } - this.chunks.push(chunk); + if (this.buffer) { + this.buffer = Buffer.concat([this.buffer, chunk]); + } else { + this.buffer = chunk; + } if (this.checkBOM) { - if (this.handleBOM()) { - callback(); - return; + 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; } } - while (this.hasCurrentByte()) { - const byte = this.currentByte(); + while (this.pos < this.buffer.length) { if (this.eventEndCheck) { if (this.crlfCheck) { - if (byte === LF) { + if (this.buffer[this.pos] === LF) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.crlfCheck = false; - this.consumeCurrentByte(); continue; } this.crlfCheck = false; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.consumeCurrentByte(); - if (this.hasPendingEvent()) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; + if (this.event.data !== void 0 || this.event.event || this.event.id || this.event.retry) { this.processEvent(this.event); } this.clearEvent(); @@ -18421,16 +18082,17 @@ var require_eventsource_stream = __commonJS({ this.eventEndCheck = false; continue; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.parseLine(this.readLine(), this.event); - this.consumeCurrentByte(); + this.parseLine(this.buffer.subarray(0, this.pos), this.event); + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.eventEndCheck = true; continue; } - this.advanceCursor(); + this.pos++; } callback(); } @@ -18446,42 +18108,43 @@ var require_eventsource_stream = __commonJS({ if (colonPosition === 0) { return; } - let fieldLength = line.length; - let valueStart = line.length; + let field = ""; + let value = ""; if (colonPosition !== -1) { - fieldLength = colonPosition; - valueStart = colonPosition + 1; + field = line.subarray(0, colonPosition).toString("utf8"); + let valueStart = colonPosition + 1; if (line[valueStart] === SPACE) { ++valueStart; } + value = line.subarray(valueStart).toString("utf8"); + } else { + field = line.toString("utf8"); + value = ""; } - if (isFieldName(line, fieldLength, DATA)) { - const value = line.toString("utf8", valueStart); - if (event.data === void 0) { - event.data = value; - } else { - event.data += ` + switch (field) { + case "data": + if (event[field] === void 0) { + event[field] = value; + } else { + event[field] += ` ${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; - } + } + 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; } } /** @@ -18506,120 +18169,12 @@ ${value}`; } } clearEvent() { - 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(); + this.event = { + data: void 0, + event: void 0, + id: void 0, + retry: void 0 + }; } }; module.exports = { diff --git a/.github/actions/javascript/verifyStagingBuildsSucceeded/index.js b/.github/actions/javascript/verifyStagingBuildsSucceeded/index.js index d5508591a07b..1e9b71a5c3e0 100644 --- a/.github/actions/javascript/verifyStagingBuildsSucceeded/index.js +++ b/.github/actions/javascript/verifyStagingBuildsSucceeded/index.js @@ -1863,66 +1863,10 @@ var require_request = __commonJS({ return false; } } - /** - * @param {number|null} statusCode - * @param {Buffer[]|null} headers - * @param {import('node:stream').Duplex} socket - * @param {string} [statusText] - */ - onUpgrade(statusCode, headers, socket, statusText = "") { - this.onFinally(); + onUpgrade(statusCode, headers, socket) { assert(!this.aborted); assert(!this.completed); - 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(error2) { - assert(!this.aborted); - assert(this.completed); - if (channels.error.hasSubscribers) { - channels.error.publish({ request: this, error: error2 }); - } - } - /** - * @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: [] }); - } + return this[kHandler].onUpgrade(statusCode, headers, socket); } onComplete(trailers) { this.onFinally(); @@ -1989,11 +1933,7 @@ var require_request = __commonJS({ } else if (typeof val[i] === "object") { throw new InvalidArgumentError(`invalid ${key} header`); } else { - const str = `${val[i]}`; - if (!isValidHeaderValue(str)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } - arr.push(str); + arr.push(`${val[i]}`); } } val = arr; @@ -2005,9 +1945,6 @@ var require_request = __commonJS({ val = ""; } else { val = `${val}`; - if (!isValidHeaderValue(val)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } } if (headerName === "host") { if (request2.host !== null) { @@ -2117,21 +2054,13 @@ var require_dispatcher_base = __commonJS({ var kOnDestroyed = /* @__PURE__ */ Symbol("onDestroyed"); var kOnClosed = /* @__PURE__ */ Symbol("onClosed"); var kInterceptedDispatch = /* @__PURE__ */ Symbol("Intercepted Dispatch"); - var kWebSocketOptions = /* @__PURE__ */ Symbol("webSocketOptions"); var DispatcherBase = class extends Dispatcher { - constructor(opts) { + constructor() { super(); this[kDestroyed] = false; this[kOnDestroyed] = null; this[kClosed] = false; this[kOnClosed] = []; - this[kWebSocketOptions] = opts?.webSocket ?? {}; - } - get webSocketOptions() { - return { - maxFragments: this[kWebSocketOptions].maxFragments ?? 131072, - maxPayloadSize: this[kWebSocketOptions].maxPayloadSize ?? 128 * 1024 * 1024 - }; } get destroyed() { return this[kDestroyed]; @@ -5738,7 +5667,6 @@ var require_client_h1 = __commonJS({ RequestContentLengthMismatchError, ResponseContentLengthMismatchError, RequestAbortedError, - InvalidArgumentError, HeadersTimeoutError, HeadersOverflowError, SocketError, @@ -5785,9 +5713,6 @@ var require_client_h1 = __commonJS({ var FastBuffer = Buffer[Symbol.species]; var addListener = util.addListener; var removeAllListeners = util.removeAllListeners; - var kIdleSocketValidation = /* @__PURE__ */ Symbol("kIdleSocketValidation"); - var kIdleSocketValidationTimeout = /* @__PURE__ */ Symbol("kIdleSocketValidationTimeout"); - var kSocketUsed = /* @__PURE__ */ Symbol("kSocketUsed"); var extractBody; async function lazyllhttp() { const llhttpWasmData = process.env.JEST_WORKER_ID ? require_llhttp_wasm() : void 0; @@ -5950,55 +5875,24 @@ var require_client_h1 = __commonJS({ currentBufferRef = null; } const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr; - if (ret !== constants3.ERROR.OK) { - const body = data.subarray(offset); - if (ret === constants3.ERROR.PAUSED_UPGRADE) { - this.onUpgrade(body); - } else if (ret === constants3.ERROR.PAUSED) { - this.paused = true; - socket.unshift(body); - } else { - throw this.createError(ret, body); + if (ret === constants3.ERROR.PAUSED_UPGRADE) { + this.onUpgrade(data.slice(offset)); + } else if (ret === constants3.ERROR.PAUSED) { + this.paused = true; + socket.unshift(data.slice(offset)); + } else if (ret !== constants3.ERROR.OK) { + const ptr = llhttp.llhttp_get_error_reason(this.ptr); + let message = ""; + if (ptr) { + const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); + message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; } + throw new HTTPParserError(message, constants3.ERROR[ret], data.slice(offset)); } } catch (err) { util.destroy(socket, err); } } - finish() { - assert(currentParser === null); - assert(this.ptr != null); - assert(!this.paused); - const { llhttp } = this; - let ret; - try { - currentParser = this; - ret = llhttp.llhttp_finish(this.ptr); - } finally { - currentParser = null; - } - if (ret === constants3.ERROR.OK) { - return null; - } - if (ret === constants3.ERROR.PAUSED || ret === constants3.ERROR.PAUSED_UPGRADE) { - this.paused = true; - return null; - } - return this.createError(ret, EMPTY_BUF); - } - createError(ret, data) { - const { llhttp, contentLength, bytesRead } = this; - if (contentLength && bytesRead !== parseInt(contentLength, 10)) { - return new ResponseContentLengthMismatchError(); - } - const ptr = llhttp.llhttp_get_error_reason(this.ptr); - let message = ""; - if (ptr) { - const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); - message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; - } - return new HTTPParserError(message, constants3.ERROR[ret], data); - } destroy() { assert(this.ptr != null); assert(currentParser == null); @@ -6018,10 +5912,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6065,7 +5955,7 @@ var require_client_h1 = __commonJS({ } } onUpgrade(head) { - const { upgrade, client, socket, headers, statusCode, statusText } = this; + const { upgrade, client, socket, headers, statusCode } = this; assert(upgrade); assert(client[kSocket] === socket); assert(!socket.destroyed); @@ -6090,10 +5980,9 @@ var require_client_h1 = __commonJS({ client[kQueue][client[kRunningIdx]++] = null; client.emit("disconnect", client[kUrl], [client], new InformationalError("upgrade")); try { - request2.onUpgrade(statusCode, headers, socket, statusText); - } catch (error2) { - util.errorRequest(client, request2, error2); - util.destroy(socket, error2); + request2.onUpgrade(statusCode, headers, socket); + } catch (err) { + util.destroy(socket, err); } client[kResume](); } @@ -6102,10 +5991,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6231,7 +6116,6 @@ var require_client_h1 = __commonJS({ } request2.onComplete(headers); client[kQueue][client[kRunningIdx]++] = null; - socket[kSocketUsed] = true; if (socket[kWriting]) { assert(client[kRunning] === 0); util.destroy(socket, new InformationalError("reset")); @@ -6275,19 +6159,12 @@ var require_client_h1 = __commonJS({ socket[kWriting] = false; socket[kReset] = false; socket[kBlocking] = false; - socket[kIdleSocketValidation] = 0; - socket[kIdleSocketValidationTimeout] = null; - socket[kSocketUsed] = false; socket[kParser] = new Parser(client, socket, llhttpInstance); addListener(socket, "error", function(err) { assert(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID"); const parser = this[kParser]; if (err.code === "ECONNRESET" && parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - this[kError] = parserErr; - this[kClient][kOnError](parserErr); - } + parser.onMessageComplete(); return; } this[kError] = err; @@ -6302,10 +6179,7 @@ var require_client_h1 = __commonJS({ addListener(socket, "end", function() { const parser = this[kParser]; if (parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - util.destroy(this, parserErr); - } + parser.onMessageComplete(); return; } util.destroy(this, new SocketError("other side closed", util.getSocketInfo(this))); @@ -6313,10 +6187,9 @@ var require_client_h1 = __commonJS({ addListener(socket, "close", function() { const client2 = this[kClient]; const parser = this[kParser]; - clearIdleSocketValidation(this); if (parser) { if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { - this[kError] = parser.finish() || this[kError]; + parser.onMessageComplete(); } this[kParser].destroy(); this[kParser] = null; @@ -6365,7 +6238,7 @@ var require_client_h1 = __commonJS({ return socket.destroyed; }, busy(request2) { - if (socket[kWriting] || socket[kReset] || socket[kBlocking] || socket[kIdleSocketValidation] === 1) { + if (socket[kWriting] || socket[kReset] || socket[kBlocking]) { return true; } if (request2) { @@ -6383,23 +6256,6 @@ var require_client_h1 = __commonJS({ } }; } - function clearIdleSocketValidation(socket) { - if (socket[kIdleSocketValidationTimeout]) { - clearImmediate(socket[kIdleSocketValidationTimeout]); - socket[kIdleSocketValidationTimeout] = null; - } - socket[kIdleSocketValidation] = 0; - } - function scheduleIdleSocketValidation(client, socket) { - socket[kIdleSocketValidation] = 1; - socket[kIdleSocketValidationTimeout] = setImmediate(() => { - socket[kIdleSocketValidationTimeout] = null; - socket[kIdleSocketValidation] = 2; - if (client[kSocket] === socket && !socket.destroyed) { - client[kResume](); - } - }); - } function resumeH1(client) { const socket = client[kSocket]; if (socket && !socket.destroyed) { @@ -6412,29 +6268,6 @@ var require_client_h1 = __commonJS({ socket.ref(); socket[kNoRef] = false; } - if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) { - if (socket[kIdleSocketValidation] === 0) { - scheduleIdleSocketValidation(client, socket); - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - if (socket[kIdleSocketValidation] === 1) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - } - if (client[kRunning] === 0) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - } if (client[kSize] === 0) { if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) { socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE); @@ -6465,16 +6298,8 @@ var require_client_h1 = __commonJS({ } body = bodyStream.stream; contentLength = bodyStream.length; - } else if (util.isBlobLike(body) && request2.contentType == null) { - const contentType = body.type; - if (contentType) { - const contentTypeValue = `${contentType}`; - if (!util.isValidHeaderValue(contentTypeValue)) { - util.errorRequest(client, request2, new InvalidArgumentError("invalid content-type header")); - return false; - } - headers.push("content-type", contentTypeValue); - } + } else if (util.isBlobLike(body) && request2.contentType == null && body.type) { + headers.push("content-type", body.type); } if (body && typeof body.read === "function") { body.read(0); @@ -6495,18 +6320,11 @@ var require_client_h1 = __commonJS({ process.emitWarning(new RequestContentLengthMismatchError()); } const socket = client[kSocket]; - clearIdleSocketValidation(socket); - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (request2.upgrade || request2.method === "CONNECT") { - util.destroy(socket, new InformationalError("aborted")); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - util.errorRequest(client, request2, error2 || new RequestAbortedError()); + util.errorRequest(client, request2, err || new RequestAbortedError()); util.destroy(body); util.destroy(socket, new InformationalError("aborted")); }; @@ -6862,7 +6680,6 @@ var require_client_h2 = __commonJS({ "node_modules/undici/lib/dispatcher/client-h2.js"(exports, module) { "use strict"; var assert = __require("node:assert"); - var { errorMonitor } = __require("node:events"); var { pipeline } = __require("node:stream"); var util = require_util(); var { @@ -6923,10 +6740,6 @@ var require_client_h2 = __commonJS({ } return result; } - function parseH2ResponseHeaders(headers) { - const { [HTTP2_HEADER_STATUS]: _statusCode, ...realHeaders } = headers; - return parseH2Headers(realHeaders); - } async function connectH2(client, socket) { client[kSocket] = socket; if (!h2ExperimentalWarned) { @@ -7090,22 +6903,16 @@ var require_client_h2 = __commonJS({ const { hostname, port } = client[kUrl]; headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ""}`; headers[HTTP2_HEADER_METHOD] = method; - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (method === "CONNECT" && stream != null) { - util.destroy(stream, error2 || new RequestAbortedError()); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - error2 = error2 || new RequestAbortedError(); - util.errorRequest(client, request2, error2); + err = err || new RequestAbortedError(); + util.errorRequest(client, request2, err); if (stream != null) { - util.destroy(stream, error2); + util.destroy(stream, err); } - util.destroy(body, error2); + util.destroy(body, err); client[kQueue][client[kRunningIdx]++] = null; client[kResume](); }; @@ -7120,42 +6927,18 @@ var require_client_h2 = __commonJS({ if (method === "CONNECT") { session.ref(); stream = session.request(headers, { endStream: false, signal }); - let upgradeResponseFinished = false; - const onResponse = (headers2) => { - upgradeResponseFinished = true; - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeResponse(Number(headers2[HTTP2_HEADER_STATUS]), headers2, parseH2ResponseHeaders); - }; - const onUpgradeError = (error2) => { - upgradeResponseFinished = true; - stream.off("response", onResponse); - request2.onUpgradeError(error2); - }; - const onReady = () => { - try { - request2.onUpgrade(null, null, stream); - } catch (error2) { - stream.off("response", onResponse); - abort(error2); - return; - } - if (request2.aborted) { - return; - } - stream.off("error", abort); - stream.once(errorMonitor, onUpgradeError); + if (stream.id && !stream.pending) { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; client[kQueue][client[kRunningIdx]++] = null; - }; - stream.once("response", onResponse); - stream.once("error", abort); - ++session[kOpenStreams]; - onReady(); + } else { + stream.once("ready", () => { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; + client[kQueue][client[kRunningIdx]++] = null; + }); + } stream.once("close", () => { - if (!upgradeResponseFinished && request2.completed) { - stream.off("response", onResponse); - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeError(new InformationalError(`HTTP/2: "stream error" received - code ${stream.rstCode}`)); - } session[kOpenStreams] -= 1; if (session[kOpenStreams] === 0) session.unref(); }); @@ -7716,10 +7499,9 @@ var require_client = __commonJS({ autoSelectFamilyAttemptTimeout, // h2 maxConcurrentStreams, - allowH2, - webSocket + allowH2 } = {}) { - super({ webSocket }); + super(); if (keepAlive !== void 0) { throw new InvalidArgumentError("unsupported keepAlive, use pipelining=0 instead"); } @@ -8225,8 +8007,8 @@ var require_pool_base = __commonJS({ var kRemoveClient = /* @__PURE__ */ Symbol("remove client"); var kStats = /* @__PURE__ */ Symbol("stats"); var PoolBase = class extends DispatcherBase { - constructor(opts) { - super(opts); + constructor() { + super(); this[kQueue] = new FixedQueue(); this[kClients] = []; this[kQueued] = 0; @@ -8397,6 +8179,7 @@ var require_pool = __commonJS({ allowH2, ...options } = {}) { + super(); if (connections != null && (!Number.isFinite(connections) || connections < 0)) { throw new InvalidArgumentError("invalid connections"); } @@ -8417,7 +8200,6 @@ var require_pool = __commonJS({ ...connect }); } - super(options); this[kInterceptors] = options.interceptors?.Pool && Array.isArray(options.interceptors.Pool) ? options.interceptors.Pool : []; this[kConnections] = connections || null; this[kUrl] = util.parseOrigin(origin); @@ -8617,6 +8399,7 @@ var require_agent = __commonJS({ } var Agent = class extends DispatcherBase { constructor({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { + super(); if (typeof factory !== "function") { throw new InvalidArgumentError("factory must be a function."); } @@ -8626,7 +8409,6 @@ var require_agent = __commonJS({ if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { throw new InvalidArgumentError("maxRedirections must be a positive number"); } - super(options); if (connect && typeof connect !== "function") { connect = { ...connect }; } @@ -9067,24 +8849,6 @@ var require_retry_handler = __commonJS({ const current = Date.now(); return new Date(retryAfter).getTime() - current; } - function validatePartialResponseContentLength(headers, range, statusCode, retryCount) { - const contentLength = headers["content-length"]; - if (contentLength == null) { - return null; - } - if (!Number.isFinite(range.start) || !Number.isFinite(range.end)) { - return null; - } - const length = Number(contentLength); - const expectedLength = range.end - range.start + 1; - if (!Number.isFinite(length) || length !== expectedLength) { - return new RequestRetryError("Content-Length mismatch", statusCode, { - headers, - data: { count: retryCount } - }); - } - return null; - } var RetryHandler = class _RetryHandler { constructor(opts, handlers) { const { retryOptions, ...dispatchOpts } = opts; @@ -9138,7 +8902,6 @@ var require_retry_handler = __commonJS({ this.end = null; this.etag = null; this.resume = null; - this.headersSent = false; this.handler.onConnect((reason) => { this.aborted = true; if (this.abort) { @@ -9148,17 +8911,6 @@ var require_retry_handler = __commonJS({ } }); } - 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(); @@ -9220,9 +8972,7 @@ var require_retry_handler = __commonJS({ const headers = parseHeaders(rawHeaders); this.retryCount += 1; if (statusCode >= 300) { - if (!this.headersSent && this.retryOpts.statusCodes.includes(statusCode) === false) { - this.headersSent = true; - this.checkpointResponseEnd(headers, resume); + if (this.retryOpts.statusCodes.includes(statusCode) === false) { return this.handler.onHeaders( statusCode, rawHeaders, @@ -9271,21 +9021,9 @@ var require_retry_handler = __commonJS({ ); return false; } - const contentLengthError = validatePartialResponseContentLength(headers, contentRange, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = contentRange; - 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; - } + assert(this.start === start, "content-range mismatch"); + assert(this.end == null || this.end === end, "content-range mismatch"); this.resume = resume; return true; } @@ -9293,7 +9031,6 @@ var require_retry_handler = __commonJS({ if (statusCode === 206) { const range = parseRangeHeader(headers["content-range"]); if (range == null) { - this.headersSent = true; return this.handler.onHeaders( statusCode, rawHeaders, @@ -9301,11 +9038,6 @@ var require_retry_handler = __commonJS({ statusMessage ); } - const contentLengthError = validatePartialResponseContentLength(headers, range, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = range; assert( start != null && Number.isFinite(start), @@ -9325,7 +9057,6 @@ var require_retry_handler = __commonJS({ "invalid content-length" ); this.resume = resume; - this.headersSent = true; this.etag = headers.etag != null ? headers.etag : null; if (this.etag != null && this.etag.startsWith("W/")) { this.etag = null; @@ -9353,7 +9084,7 @@ var require_retry_handler = __commonJS({ return this.handler.onComplete(rawTrailers); } onError(err) { - if (this.aborted || isDisturbed(this.opts.body) || this.headersSent && this.resume == null) { + if (this.aborted || isDisturbed(this.opts.body)) { return this.handler.onError(err); } if (this.retryCount - this.retryCountCheckpoint > 0) { @@ -16152,48 +15883,14 @@ var require_util6 = __commonJS({ for (let i = 0; i < path.length; ++i) { const code = path.charCodeAt(i); if (code < 32 || // exclude CTLs (0-31) - code > 126 || // exclude DEL and non-ascii + code === 127 || // DEL code === 59) { throw new Error("Invalid cookie path"); } } } - function isLetterOrDigit(code) { - return code >= 48 && code <= 57 || // 0-9 - code >= 65 && code <= 90 || // A-Z - code >= 97 && code <= 122; - } function validateCookieDomain(domain) { - if (domain === " ") { - return; - } - if (domain.length > 255) { - throw new Error("Invalid cookie domain"); - } - let labelLength = 0; - for (let i = 0; i < domain.length; ++i) { - const code = domain.charCodeAt(i); - if (code === 46) { - if (labelLength === 0) { - throw new Error("Invalid cookie domain"); - } - if (domain.charCodeAt(i - 1) === 45) { - throw new Error("Invalid cookie domain"); - } - labelLength = 0; - continue; - } - if (labelLength === 0 && !isLetterOrDigit(code)) { - throw new Error("Invalid cookie domain"); - } - if (!isLetterOrDigit(code) && code !== 45) { - throw new Error("Invalid cookie domain"); - } - if (++labelLength > 63) { - throw new Error("Invalid cookie domain"); - } - } - if (labelLength === 0 || domain.charCodeAt(domain.length - 1) === 45) { + if (domain.startsWith("-") || domain.endsWith(".") || domain.endsWith("-")) { throw new Error("Invalid cookie domain"); } } @@ -16276,11 +15973,7 @@ var require_util6 = __commonJS({ throw new Error("Invalid unparsed"); } const [key, ...value] = part.split("="); - const trimmedKey = key.trim(); - const joinedValue = value.join("="); - validateCookieName(trimmedKey); - validateCookieValue(joinedValue); - out.push(`${trimmedKey}=${joinedValue}`); + out.push(`${key.trim()}=${value.join("=")}`); } return out.join("; "); } @@ -16410,14 +16103,18 @@ var require_parse = __commonJS({ } else if (attributeNameLowercase === "httponly") { cookieAttributeList.httpOnly = true; } else if (attributeNameLowercase === "samesite") { + let enforcement = "Default"; const attributeValueLowercase = attributeValue.toLowerCase(); - if (attributeValueLowercase === "none") { - cookieAttributeList.sameSite = "None"; - } else if (attributeValueLowercase === "strict") { - cookieAttributeList.sameSite = "Strict"; - } else if (attributeValueLowercase === "lax") { - cookieAttributeList.sameSite = "Lax"; + if (attributeValueLowercase.includes("none")) { + enforcement = "None"; + } + if (attributeValueLowercase.includes("strict")) { + enforcement = "Strict"; + } + if (attributeValueLowercase.includes("lax")) { + enforcement = "Lax"; } + cookieAttributeList.sameSite = enforcement; } else { cookieAttributeList.unparsed ??= []; cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`); @@ -17239,7 +16936,7 @@ var require_connection = __commonJS({ const secProtocol = response.headersList.get("Sec-WebSocket-Protocol"); if (secProtocol !== null) { const requestProtocols = getDecodeSplit("sec-websocket-protocol", request2.headersList); - if (requestProtocols === null || !requestProtocols.includes(secProtocol)) { + if (!requestProtocols.includes(secProtocol)) { failWebsocketConnection(ws, "Protocol was not set in the opening handshake."); return; } @@ -17345,26 +17042,31 @@ var require_permessage_deflate = __commonJS({ var tail = Buffer.from([0, 0, 255, 255]); var kBuffer = /* @__PURE__ */ Symbol("kBuffer"); var kLength = /* @__PURE__ */ Symbol("kLength"); + var kDefaultMaxDecompressedSize = 4 * 1024 * 1024; var PerMessageDeflate = class { /** @type {import('node:zlib').InflateRaw} */ #inflate; #options = {}; - #maxPayloadSize = 0; + /** @type {number} */ + #maxDecompressedSize; + /** @type {boolean} */ + #aborted = false; + /** @type {Function|null} */ + #currentCallback = null; /** * @param {Map} extensions + * @param {{ maxDecompressedMessageSize?: number }} [options] */ - constructor(extensions, options) { + constructor(extensions, options = {}) { this.#options.serverNoContextTakeover = extensions.has("server_no_context_takeover"); this.#options.serverMaxWindowBits = extensions.get("server_max_window_bits"); - this.#maxPayloadSize = options.maxPayloadSize; + this.#maxDecompressedSize = options.maxDecompressedMessageSize ?? kDefaultMaxDecompressedSize; } - /** - * Decompress a compressed payload. - * @param {Buffer} chunk Compressed data - * @param {boolean} fin Final fragment flag - * @param {Function} callback Callback function - */ decompress(chunk, fin, callback) { + if (this.#aborted) { + callback(new MessageSizeExceededError()); + return; + } if (!this.#inflate) { let windowBits = Z_DEFAULT_WINDOWBITS; if (this.#options.serverMaxWindowBits) { @@ -17383,12 +17085,20 @@ var require_permessage_deflate = __commonJS({ this.#inflate[kBuffer] = []; this.#inflate[kLength] = 0; this.#inflate.on("data", (data) => { + if (this.#aborted) { + return; + } this.#inflate[kLength] += data.length; - if (this.#maxPayloadSize > 0 && this.#inflate[kLength] > this.#maxPayloadSize) { - callback(new MessageSizeExceededError()); + if (this.#inflate[kLength] > this.#maxDecompressedSize) { + this.#aborted = true; this.#inflate.removeAllListeners(); this.#inflate.destroy(); this.#inflate = null; + if (this.#currentCallback) { + const cb = this.#currentCallback; + this.#currentCallback = null; + cb(new MessageSizeExceededError()); + } return; } this.#inflate[kBuffer].push(data); @@ -17398,17 +17108,19 @@ var require_permessage_deflate = __commonJS({ callback(err); }); } + this.#currentCallback = callback; this.#inflate.write(chunk); if (fin) { this.#inflate.write(tail); } this.#inflate.flush(() => { - if (!this.#inflate) { + if (this.#aborted || !this.#inflate) { return; } const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]); this.#inflate[kBuffer].length = 0; this.#inflate[kLength] = 0; + this.#currentCallback = null; callback(null, full); }); } @@ -17439,14 +17151,8 @@ var require_receiver = __commonJS({ var { WebsocketFrameSend } = require_frame(); var { closeWebSocketConnection } = require_connection(); var { PerMessageDeflate } = require_permessage_deflate(); - var { MessageSizeExceededError } = require_errors(); - function failWebsocketConnectionWithCode(ws, code, reason) { - closeWebSocketConnection(ws, code, reason, Buffer.byteLength(reason)); - failWebsocketConnection(ws, reason); - } var ByteParser = class extends Writable { #buffers = []; - #fragmentsBytes = 0; #byteOffset = 0; #loop = false; #state = parserStates.INFO; @@ -17454,21 +17160,18 @@ var require_receiver = __commonJS({ #fragments = []; /** @type {Map} */ #extensions; - /** @type {number} */ - #maxFragments; - /** @type {number} */ - #maxPayloadSize; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {import('./websocket').WebSocket} ws * @param {Map|null} extensions - * @param {{ maxFragments?: number, maxPayloadSize?: number }} [options] + * @param {{ maxDecompressedMessageSize?: number }} [options] */ constructor(ws, extensions, options = {}) { super(); this.ws = ws; this.#extensions = extensions == null ? /* @__PURE__ */ new Map() : extensions; - this.#maxFragments = options.maxFragments ?? 0; - this.#maxPayloadSize = options.maxPayloadSize ?? 0; + this.#options = options; if (this.#extensions.has("permessage-deflate")) { this.#extensions.set("permessage-deflate", new PerMessageDeflate(extensions, options)); } @@ -17483,13 +17186,6 @@ var require_receiver = __commonJS({ this.#loop = true; this.run(callback); } - #validatePayloadLength() { - if (this.#maxPayloadSize > 0 && !isControlFrame(this.#info.opcode) && this.#info.payloadLength + this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, "Payload size exceeds maximum allowed size"); - return false; - } - return true; - } /** * Runs whenever a new chunk is received. * Callback is called whenever there are no more chunks buffering, @@ -17549,9 +17245,6 @@ var require_receiver = __commonJS({ if (payloadLength <= 125) { this.#info.payloadLength = payloadLength; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (payloadLength === 126) { this.#state = parserStates.PAYLOADLENGTH_16; } else if (payloadLength === 127) { @@ -17572,9 +17265,6 @@ var require_receiver = __commonJS({ const buffer = this.consume(2); this.#info.payloadLength = buffer.readUInt16BE(0); this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.PAYLOADLENGTH_64) { if (this.#byteOffset < 8) { return callback(); @@ -17588,9 +17278,6 @@ var require_receiver = __commonJS({ } this.#info.payloadLength = lower; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.READ_DATA) { if (this.#byteOffset < this.#info.payloadLength) { return callback(); @@ -17601,46 +17288,32 @@ var require_receiver = __commonJS({ this.#state = parserStates.INFO; } else { if (!this.#info.compressed) { - if (!this.writeFragments(body)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } + this.#fragments.push(body); if (!this.#info.fragmented && this.#info.fin) { - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); + const fullMessage = Buffer.concat(this.#fragments); + websocketMessageReceived(this.ws, this.#info.binaryType, fullMessage); + this.#fragments.length = 0; } this.#state = parserStates.INFO; } else { - this.#extensions.get("permessage-deflate").decompress( - body, - this.#info.fin, - (error2, data) => { - if (error2) { - const code = error2 instanceof MessageSizeExceededError ? 1009 : 1007; - failWebsocketConnectionWithCode(this.ws, code, error2.message); - return; - } - if (!this.writeFragments(data)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } - if (!this.#info.fin) { - this.#state = parserStates.INFO; - this.#loop = true; - this.run(callback); - return; - } - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); - this.#loop = true; + this.#extensions.get("permessage-deflate").decompress(body, this.#info.fin, (error2, data) => { + if (error2) { + failWebsocketConnection(this.ws, error2.message); + return; + } + this.#fragments.push(data); + if (!this.#info.fin) { this.#state = parserStates.INFO; + this.#loop = true; this.run(callback); + return; } - ); + websocketMessageReceived(this.ws, this.#info.binaryType, Buffer.concat(this.#fragments)); + this.#loop = true; + this.#state = parserStates.INFO; + this.#fragments.length = 0; + this.run(callback); + }); this.#loop = false; break; } @@ -17683,26 +17356,6 @@ var require_receiver = __commonJS({ this.#byteOffset -= n; return buffer; } - writeFragments(fragment) { - if (this.#maxFragments > 0 && this.#fragments.length === this.#maxFragments) { - failWebsocketConnectionWithCode(this.ws, 1008, "Too many message fragments"); - return false; - } - this.#fragmentsBytes += fragment.length; - this.#fragments.push(fragment); - return true; - } - consumeFragments() { - const fragments = this.#fragments; - if (fragments.length === 1) { - this.#fragmentsBytes = 0; - return fragments.shift(); - } - const output = Buffer.concat(fragments, this.#fragmentsBytes); - this.#fragments = []; - this.#fragmentsBytes = 0; - return output; - } parseCloseBody(data) { assert(data.length !== 1); let code; @@ -17914,6 +17567,8 @@ var require_websocket = __commonJS({ #extensions = ""; /** @type {SendQueue} */ #sendQueue; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {string} url * @param {string|string[]} protocols @@ -17957,6 +17612,9 @@ var require_websocket = __commonJS({ throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError"); } this[kWebSocketURL] = new URL(urlRecord.href); + this.#options = { + maxDecompressedMessageSize: options.maxDecompressedMessageSize + }; const client = environmentSettingsObject.settingsObject; this[kController] = establishWebSocketConnection( urlRecord, @@ -18140,13 +17798,7 @@ var require_websocket = __commonJS({ */ #onConnectionEstablished(response, parsedExtensions) { this[kResponse] = response; - const webSocketOptions = this[kController]?.dispatcher?.webSocketOptions; - const maxFragments = webSocketOptions?.maxFragments; - const maxPayloadSize = webSocketOptions?.maxPayloadSize; - const parser = new ByteParser(this, parsedExtensions, { - maxFragments, - maxPayloadSize - }); + const parser = new ByteParser(this, parsedExtensions, this.#options); parser.on("drain", onParserDrain); parser.on("error", onParserError.bind(this)); response.socket.ws = this; @@ -18221,6 +17873,19 @@ var require_websocket = __commonJS({ { key: "headers", converter: webidl.nullableConverter(webidl.converters.HeadersInit) + }, + { + key: "maxDecompressedMessageSize", + converter: webidl.nullableConverter((V) => { + V = webidl.converters["unsigned long long"](V); + if (V <= 0) { + throw webidl.errors.exception({ + header: "WebSocket constructor", + message: "maxDecompressedMessageSize must be greater than 0" + }); + } + return V; + }) } ]); webidl.converters["DOMString or sequence or WebSocketInit"] = function(V) { @@ -18299,40 +17964,6 @@ 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; - } - function isValidLastEventIdBytes(buffer, start) { - for (let i = start; i < buffer.length; i++) { - if (buffer[i] === 0) { - 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; - } var EventSourceStream = class extends Transform { /** * @type {eventSourceSettings} @@ -18352,13 +17983,10 @@ var require_eventsource_stream = __commonJS({ */ eventEndCheck = false; /** - * @type {Buffer[]} + * @type {Buffer} */ - chunks = []; - chunkIndex = 0; + buffer = null; pos = 0; - lineChunkIndex = 0; - linePos = 0; event = { data: void 0, event: void 0, @@ -18389,30 +18017,63 @@ var require_eventsource_stream = __commonJS({ callback(); return; } - this.chunks.push(chunk); + if (this.buffer) { + this.buffer = Buffer.concat([this.buffer, chunk]); + } else { + this.buffer = chunk; + } if (this.checkBOM) { - if (this.handleBOM()) { - callback(); - return; + 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; } } - while (this.hasCurrentByte()) { - const byte = this.currentByte(); + while (this.pos < this.buffer.length) { if (this.eventEndCheck) { if (this.crlfCheck) { - if (byte === LF) { + if (this.buffer[this.pos] === LF) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.crlfCheck = false; - this.consumeCurrentByte(); continue; } this.crlfCheck = false; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.consumeCurrentByte(); - if (this.hasPendingEvent()) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; + if (this.event.data !== void 0 || this.event.event || this.event.id || this.event.retry) { this.processEvent(this.event); } this.clearEvent(); @@ -18421,16 +18082,17 @@ var require_eventsource_stream = __commonJS({ this.eventEndCheck = false; continue; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.parseLine(this.readLine(), this.event); - this.consumeCurrentByte(); + this.parseLine(this.buffer.subarray(0, this.pos), this.event); + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.eventEndCheck = true; continue; } - this.advanceCursor(); + this.pos++; } callback(); } @@ -18446,42 +18108,43 @@ var require_eventsource_stream = __commonJS({ if (colonPosition === 0) { return; } - let fieldLength = line.length; - let valueStart = line.length; + let field = ""; + let value = ""; if (colonPosition !== -1) { - fieldLength = colonPosition; - valueStart = colonPosition + 1; + field = line.subarray(0, colonPosition).toString("utf8"); + let valueStart = colonPosition + 1; if (line[valueStart] === SPACE) { ++valueStart; } + value = line.subarray(valueStart).toString("utf8"); + } else { + field = line.toString("utf8"); + value = ""; } - if (isFieldName(line, fieldLength, DATA)) { - const value = line.toString("utf8", valueStart); - if (event.data === void 0) { - event.data = value; - } else { - event.data += ` + switch (field) { + case "data": + if (event[field] === void 0) { + event[field] = value; + } else { + event[field] += ` ${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; - } + } + 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; } } /** @@ -18506,120 +18169,12 @@ ${value}`; } } clearEvent() { - 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(); + this.event = { + data: void 0, + event: void 0, + id: void 0, + retry: void 0 + }; } }; module.exports = { diff --git a/__mocks__/react-native-onyx.ts b/__mocks__/react-native-onyx.ts index 6db22ac1b627..f5b09f2949da 100644 --- a/__mocks__/react-native-onyx.ts +++ b/__mocks__/react-native-onyx.ts @@ -5,7 +5,7 @@ import type {ConnectOptions, OnyxKey} from 'react-native-onyx'; // eslint-disable-next-line no-restricted-imports -import Onyx, {useOnyx} from 'react-native-onyx'; +import Onyx, {useOnyx, useOnyxState} from 'react-native-onyx'; let connectCallbackDelay = 0; function addDelayToConnectCallback(delay: number) { @@ -41,4 +41,4 @@ const reactNativeOnyxMock: ReactNativeOnyxMock = { export default reactNativeOnyxMock; -export {useOnyx}; +export {useOnyx, useOnyxState}; diff --git a/src/ONYXKEYS.ts b/src/ONYXKEYS.ts index 9aceaf15c17e..e9b07bbcf0d9 100755 --- a/src/ONYXKEYS.ts +++ b/src/ONYXKEYS.ts @@ -1438,7 +1438,6 @@ const ONYXKEYS = { OUTSTANDING_REPORTS_BY_POLICY_ID: 'outstandingReportsByPolicyID', VISIBLE_REPORT_ACTIONS: 'visibleReportActions', NON_PERSONAL_AND_WORKSPACE_CARD_LIST: 'nonPersonalAndWorkspaceCardList', - PERSONAL_AND_WORKSPACE_CARD_LIST: 'personalAndWorkspaceCardList', CARD_FEED_ERRORS: 'cardFeedErrors', RAM_ONLY_SORTED_REPORT_ACTIONS: 'sortedReportActions', LOGIN_TO_ACCOUNT_ID_MAP: 'loginToAccountIDMap', @@ -2021,7 +2020,6 @@ type OnyxDerivedValuesMapping = { [ONYXKEYS.DERIVED.OUTSTANDING_REPORTS_BY_POLICY_ID]: OnyxTypes.OutstandingReportsByPolicyIDDerivedValue; [ONYXKEYS.DERIVED.VISIBLE_REPORT_ACTIONS]: OnyxTypes.VisibleReportActionsDerivedValue; [ONYXKEYS.DERIVED.NON_PERSONAL_AND_WORKSPACE_CARD_LIST]: OnyxTypes.NonPersonalAndWorkspaceCardListDerivedValue; - [ONYXKEYS.DERIVED.PERSONAL_AND_WORKSPACE_CARD_LIST]: OnyxTypes.PersonalAndWorkspaceCardListDerivedValue; [ONYXKEYS.DERIVED.CARD_FEED_ERRORS]: OnyxTypes.CardFeedErrorsDerivedValue; [ONYXKEYS.DERIVED.RAM_ONLY_SORTED_REPORT_ACTIONS]: OnyxTypes.SortedReportActionsDerivedValue; [ONYXKEYS.DERIVED.LOGIN_TO_ACCOUNT_ID_MAP]: OnyxTypes.LoginToAccountIDMapDerivedValue; diff --git a/src/components/Search/SearchAutocompleteList.tsx b/src/components/Search/SearchAutocompleteList.tsx index 413871add079..debcb69f5fa0 100644 --- a/src/components/Search/SearchAutocompleteList.tsx +++ b/src/components/Search/SearchAutocompleteList.tsx @@ -19,6 +19,7 @@ import {useMemoizedLazyExpensifyIcons} from '@hooks/useLazyAsset'; import useLocalize from '@hooks/useLocalize'; import useOnyx from '@hooks/useOnyx'; import usePermissions from '@hooks/usePermissions'; +import usePersonalAndWorkspaceCardList from '@hooks/usePersonalAndWorkspaceCardList'; import useReportAttributes from '@hooks/useReportAttributes'; import useResponsiveLayout from '@hooks/useResponsiveLayout'; import useSortedReportActionsData from '@hooks/useSortedReportActionsData'; @@ -223,7 +224,7 @@ function SearchAutocompleteList({ const lastActions = sortedReportActionsData?.lastActions; const personalDetails = usePersonalDetails(); const [reports] = useOnyx(ONYXKEYS.COLLECTION.REPORT); - const [personalAndWorkspaceCards] = useOnyx(ONYXKEYS.DERIVED.PERSONAL_AND_WORKSPACE_CARD_LIST); + const personalAndWorkspaceCards = usePersonalAndWorkspaceCardList(); const [allFeeds] = useOnyx(ONYXKEYS.COLLECTION.SHARED_NVP_PRIVATE_DOMAIN_MEMBER); const [bankAccountList] = useOnyx(ONYXKEYS.BANK_ACCOUNT_LIST); const allCards = personalAndWorkspaceCards ?? CONST.EMPTY_OBJECT; diff --git a/src/components/Search/SearchRouter/SearchRouter.tsx b/src/components/Search/SearchRouter/SearchRouter.tsx index 3a4ebdd856cd..e2561f4ca555 100644 --- a/src/components/Search/SearchRouter/SearchRouter.tsx +++ b/src/components/Search/SearchRouter/SearchRouter.tsx @@ -19,6 +19,7 @@ import useKeyboardShortcut from '@hooks/useKeyboardShortcut'; import {useMemoizedLazyExpensifyIcons} from '@hooks/useLazyAsset'; import useLocalize from '@hooks/useLocalize'; import useOnyx from '@hooks/useOnyx'; +import usePersonalAndWorkspaceCardList from '@hooks/usePersonalAndWorkspaceCardList'; import {useGetPersonalDetailsByLogin} from '@hooks/usePersonalDetailByLogin'; import useReportAttributes from '@hooks/useReportAttributes'; import useReportOrReportDraft from '@hooks/useReportOrReportDraft'; @@ -124,7 +125,7 @@ function SearchRouter({onRouterClose, shouldHideInputCaret, isSearchRouterDispla const {currentSearchQueryJSON, currentSearchHash, currentSearchKey} = useSearchQueryContext(); const [reports] = useOnyx(ONYXKEYS.COLLECTION.REPORT); const [policies] = useOnyx(ONYXKEYS.COLLECTION.POLICY); - const [personalAndWorkspaceCards] = useOnyx(ONYXKEYS.DERIVED.PERSONAL_AND_WORKSPACE_CARD_LIST); + const personalAndWorkspaceCards = usePersonalAndWorkspaceCardList(); const [allFeeds] = useOnyx(ONYXKEYS.COLLECTION.SHARED_NVP_PRIVATE_DOMAIN_MEMBER); const [bankAccountList] = useOnyx(ONYXKEYS.BANK_ACCOUNT_LIST); const getPersonalDetailsByLogin = useGetPersonalDetailsByLogin(); diff --git a/src/components/Search/hooks/useFilterCardValue.tsx b/src/components/Search/hooks/useFilterCardValue.tsx index a0b2510cbb20..d84c95ddad88 100644 --- a/src/components/Search/hooks/useFilterCardValue.tsx +++ b/src/components/Search/hooks/useFilterCardValue.tsx @@ -1,14 +1,13 @@ import useLocalize from '@hooks/useLocalize'; -import useOnyx from '@hooks/useOnyx'; +import usePersonalAndWorkspaceCardList from '@hooks/usePersonalAndWorkspaceCardList'; import {getCardDescription} from '@libs/CardUtils'; -import ONYXKEYS from '@src/ONYXKEYS'; import {filterCardsHiddenFromSearch} from '@src/selectors/Card'; function useFilterCardValue(value: string[]): string { const {translate} = useLocalize(); - const [searchCards] = useOnyx(ONYXKEYS.DERIVED.PERSONAL_AND_WORKSPACE_CARD_LIST, {selector: filterCardsHiddenFromSearch}); + const searchCards = usePersonalAndWorkspaceCardList(filterCardsHiddenFromSearch); const cardNames = Object.values(searchCards ?? {}) .filter((card) => value.includes(card.cardID.toString())) diff --git a/src/components/Search/hooks/useFilterFeedData.tsx b/src/components/Search/hooks/useFilterFeedData.tsx index 8e73e3676312..0a852357dd53 100644 --- a/src/components/Search/hooks/useFilterFeedData.tsx +++ b/src/components/Search/hooks/useFilterFeedData.tsx @@ -1,6 +1,7 @@ import useFeedKeysWithAssignedCards from '@hooks/useFeedKeysWithAssignedCards'; import useLocalize from '@hooks/useLocalize'; import useOnyx from '@hooks/useOnyx'; +import usePersonalAndWorkspaceCardList from '@hooks/usePersonalAndWorkspaceCardList'; import {getFeedOptions} from '@libs/SearchUIUtils'; @@ -9,7 +10,7 @@ import ONYXKEYS from '@src/ONYXKEYS'; function useFilterFeedData(value: string[] | undefined) { const {translate, localeCompare} = useLocalize(); const [allFeeds] = useOnyx(ONYXKEYS.COLLECTION.SHARED_NVP_PRIVATE_DOMAIN_MEMBER); - const [personalAndWorkspaceCards] = useOnyx(ONYXKEYS.DERIVED.PERSONAL_AND_WORKSPACE_CARD_LIST); + const personalAndWorkspaceCards = usePersonalAndWorkspaceCardList(); const [policies] = useOnyx(ONYXKEYS.COLLECTION.POLICY); const [domains] = useOnyx(ONYXKEYS.COLLECTION.DOMAIN); const [expensifyCardSettings] = useOnyx(ONYXKEYS.COLLECTION.PRIVATE_EXPENSIFY_CARD_SETTINGS); diff --git a/src/components/Search/hooks/useSearchSnapshot.ts b/src/components/Search/hooks/useSearchSnapshot.ts index e889874c1b1d..1717c92b9933 100644 --- a/src/components/Search/hooks/useSearchSnapshot.ts +++ b/src/components/Search/hooks/useSearchSnapshot.ts @@ -9,6 +9,7 @@ import useLocalize from '@hooks/useLocalize'; import useMultipleSnapshots from '@hooks/useMultipleSnapshots'; import useNetwork from '@hooks/useNetwork'; import useOnyx from '@hooks/useOnyx'; +import usePersonalAndWorkspaceCardList from '@hooks/usePersonalAndWorkspaceCardList'; import {useAllPersonalDetails} from '@hooks/usePersonalDetails'; import usePolicyForMovingExpenses from '@hooks/usePolicyForMovingExpenses'; import useReportAttributes from '@hooks/useReportAttributes'; @@ -139,7 +140,7 @@ function useSearchSnapshot({queryJSON, searchResults, transactions, reportAction const [bankAccountList] = useOnyx(ONYXKEYS.BANK_ACCOUNT_LIST); const [onyxPersonalDetailsList] = useAllPersonalDetails(); const [cardFeeds] = useOnyx(ONYXKEYS.COLLECTION.SHARED_NVP_PRIVATE_DOMAIN_MEMBER); - const [personalAndWorkspaceCards] = useOnyx(ONYXKEYS.DERIVED.PERSONAL_AND_WORKSPACE_CARD_LIST); + const personalAndWorkspaceCards = usePersonalAndWorkspaceCardList(); const [nonPersonalAndWorkspaceCards] = useOnyx(ONYXKEYS.DERIVED.NON_PERSONAL_AND_WORKSPACE_CARD_LIST); const [customCardNames] = useOnyx(ONYXKEYS.NVP_EXPENSIFY_COMPANY_CARDS_CUSTOM_NAMES); const [conciergeReportID] = useOnyx(ONYXKEYS.CONCIERGE_REPORT_ID); diff --git a/src/components/Table/TableBody.tsx b/src/components/Table/TableBody.tsx index 9a4db2f7aead..faa96b4da20f 100644 --- a/src/components/Table/TableBody.tsx +++ b/src/components/Table/TableBody.tsx @@ -164,6 +164,7 @@ function TableBodyList({contentContainerStyle, emptyMessage, onLayout, style, .. noResultsStateElement, tableListMetadata, isEmptyResult, + isDefaultViewEmpty, scrollWidth, tableWidth, } = useTableContext(); @@ -337,8 +338,10 @@ function TableBodyList({contentContainerStyle, emptyMessage, onLayout, style, .. ); - const emptyStateContent = - tableListMetadata.hasPageHeader && isEmptyResult ? (noResultsStateElement ?? EmptyResultComponent) : (emptyStateElement ?? renderListComponent(ListEmptyComponent)); + // When the default view hides every row (e.g. all workspaces are archived), no search or filter is active, + // so show the empty state rather than "No results". + const shouldShowNoResultsState = tableListMetadata.hasPageHeader && isEmptyResult && !isDefaultViewEmpty; + const emptyStateContent = shouldShowNoResultsState ? (noResultsStateElement ?? EmptyResultComponent) : (emptyStateElement ?? renderListComponent(ListEmptyComponent)); const footerElement = renderListComponent(ListFooterComponent); // Consumer footer flex growth is useful below normal rows, but inside the combined empty-state // footer it can expand over the page header. Preserve the remaining style while disabling growth. diff --git a/src/components/Table/TableEmptyStates/TableNoResultsState.tsx b/src/components/Table/TableEmptyStates/TableNoResultsState.tsx index 60a93ca4a2c6..30c49a66fe35 100644 --- a/src/components/Table/TableEmptyStates/TableNoResultsState.tsx +++ b/src/components/Table/TableEmptyStates/TableNoResultsState.tsx @@ -21,10 +21,11 @@ type TableNoResultsStateProps = Omit) { } function useAdvancedSearchFilters(type: SearchDataTypes | undefined) { - const [shouldDisplayCardFilter] = useOnyx(ONYXKEYS.DERIVED.PERSONAL_AND_WORKSPACE_CARD_LIST, {selector: shouldDisplayCardFilterSelector}); + const shouldDisplayCardFilter = usePersonalAndWorkspaceCardList(shouldDisplayCardFilterSelector); const [policies = getEmptyObject>>()] = useOnyx(ONYXKEYS.COLLECTION.POLICY, {selector: advancedSearchPoliciesSelector}); const [policyDerived] = useOnyx(ONYXKEYS.COLLECTION.POLICY, {selector: policyDerivedSelector}); const [bankAccountList] = useOnyx(ONYXKEYS.BANK_ACCOUNT_LIST); diff --git a/src/hooks/usePersonalAndWorkspaceCardList.ts b/src/hooks/usePersonalAndWorkspaceCardList.ts new file mode 100644 index 000000000000..086aaeb279a7 --- /dev/null +++ b/src/hooks/usePersonalAndWorkspaceCardList.ts @@ -0,0 +1,42 @@ +import ONYXKEYS from '@src/ONYXKEYS'; +import type {CardList, WorkspaceCardsList} from '@src/types/onyx'; + +import type {OnyxCollection} from 'react-native-onyx'; + +import {personalAndWorkspaceCardListSelector} from '@selectors/Card'; +import {useOnyxState} from 'react-native-onyx'; + +type CardListSelector = (cardList: CardList) => TReturn; + +const dependencies = [ONYXKEYS.CARD_LIST, ONYXKEYS.COLLECTION.WORKSPACE_CARDS_LIST]; + +// useOnyxState runs the selector on every write to either key, so each selector's output is kept per merged list +const selectedValues = new WeakMap, {cardList: CardList; value: unknown}>(); + +function select(selector: CardListSelector, cardList: CardList): TReturn { + const cached = selectedValues.get(selector); + if (cached?.cardList === cardList) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion + return cached.value as TReturn; + } + const value = selector(cardList); + selectedValues.set(selector, {cardList, value}); + return value; +} + +function usePersonalAndWorkspaceCardList(): CardList; +function usePersonalAndWorkspaceCardList(selector: CardListSelector): TReturn; +function usePersonalAndWorkspaceCardList(selector?: CardListSelector) { + return useOnyxState( + (state) => { + // useOnyxState's state view types a collection key as one member, but at runtime it returns the whole collection + // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion + const workspaceCardFeeds = state[ONYXKEYS.COLLECTION.WORKSPACE_CARDS_LIST] as OnyxCollection; + const cardList = personalAndWorkspaceCardListSelector(state[ONYXKEYS.CARD_LIST], workspaceCardFeeds); + return selector ? select(selector, cardList) : cardList; + }, + {dependencies}, + ); +} + +export default usePersonalAndWorkspaceCardList; diff --git a/src/hooks/useSearchSections.ts b/src/hooks/useSearchSections.ts index 19733b0ac474..f3e9960b3a18 100644 --- a/src/hooks/useSearchSections.ts +++ b/src/hooks/useSearchSections.ts @@ -11,6 +11,7 @@ import useCurrentUserPersonalDetails from './useCurrentUserPersonalDetails'; import useFilterPendingDeleteReports from './useFilterPendingDeleteReports'; import useLocalize from './useLocalize'; import useOnyx from './useOnyx'; +import usePersonalAndWorkspaceCardList from './usePersonalAndWorkspaceCardList'; import useReportAttributes from './useReportAttributes'; type UseSearchSectionsResult = { @@ -28,7 +29,7 @@ function useSearchSections(): UseSearchSectionsResult { const {convertToDisplayString} = useCurrencyListActions(); const [cardFeeds] = useOnyx(ONYXKEYS.COLLECTION.SHARED_NVP_PRIVATE_DOMAIN_MEMBER); - const [personalAndWorkspaceCards] = useOnyx(ONYXKEYS.DERIVED.PERSONAL_AND_WORKSPACE_CARD_LIST); + const personalAndWorkspaceCards = usePersonalAndWorkspaceCardList(); const [nonPersonalAndWorkspaceCards] = useOnyx(ONYXKEYS.DERIVED.NON_PERSONAL_AND_WORKSPACE_CARD_LIST); const [bankAccountList] = useOnyx(ONYXKEYS.BANK_ACCOUNT_LIST); diff --git a/src/libs/actions/OnyxDerived/ONYX_DERIVED_VALUES.ts b/src/libs/actions/OnyxDerived/ONYX_DERIVED_VALUES.ts index 4ea4fabd9560..d01d9759f785 100644 --- a/src/libs/actions/OnyxDerived/ONYX_DERIVED_VALUES.ts +++ b/src/libs/actions/OnyxDerived/ONYX_DERIVED_VALUES.ts @@ -10,7 +10,6 @@ import loginToAccountIDMapConfig from './configs/loginToAccountIDMap'; import nonPersonalAndWorkspaceCardListConfig from './configs/nonPersonalAndWorkspaceCardList'; import oneOnOneChatReportIDsConfig from './configs/oneOnOneChatReportIDs'; import outstandingReportsByPolicyIDConfig from './configs/outstandingReportsByPolicyID'; -import personalAndWorkspaceCardListConfig from './configs/personalAndWorkspaceCardList'; import reportAttributesConfig from './configs/reportAttributes'; import reportTransactionsAndViolationsConfig from './configs/reportTransactionsAndViolations'; import sortedReportActionsConfig from './configs/sortedReportActions'; @@ -27,7 +26,6 @@ const ONYX_DERIVED_VALUES = { [ONYXKEYS.DERIVED.OUTSTANDING_REPORTS_BY_POLICY_ID]: outstandingReportsByPolicyIDConfig, [ONYXKEYS.DERIVED.VISIBLE_REPORT_ACTIONS]: visibleReportActionsConfig, [ONYXKEYS.DERIVED.NON_PERSONAL_AND_WORKSPACE_CARD_LIST]: nonPersonalAndWorkspaceCardListConfig, - [ONYXKEYS.DERIVED.PERSONAL_AND_WORKSPACE_CARD_LIST]: personalAndWorkspaceCardListConfig, [ONYXKEYS.DERIVED.CARD_FEED_ERRORS]: cardFeedErrorsConfig, [ONYXKEYS.DERIVED.RAM_ONLY_SORTED_REPORT_ACTIONS]: sortedReportActionsConfig, [ONYXKEYS.DERIVED.LOGIN_TO_ACCOUNT_ID_MAP]: loginToAccountIDMapConfig, diff --git a/src/libs/actions/OnyxDerived/configs/personalAndWorkspaceCardList.ts b/src/libs/actions/OnyxDerived/configs/personalAndWorkspaceCardList.ts deleted file mode 100644 index fe52455ddc82..000000000000 --- a/src/libs/actions/OnyxDerived/configs/personalAndWorkspaceCardList.ts +++ /dev/null @@ -1,14 +0,0 @@ -import {mergeCardListWithWorkspaceFeeds} from '@libs/CardUtils'; - -import createOnyxDerivedValueConfig from '@userActions/OnyxDerived/createOnyxDerivedValueConfig'; - -import CONST from '@src/CONST'; -import ONYXKEYS from '@src/ONYXKEYS'; - -export default createOnyxDerivedValueConfig({ - key: ONYXKEYS.DERIVED.PERSONAL_AND_WORKSPACE_CARD_LIST, - dependencies: [ONYXKEYS.CARD_LIST, ONYXKEYS.COLLECTION.WORKSPACE_CARDS_LIST], - compute: ([cardList, workspaceCardFeeds]) => { - return mergeCardListWithWorkspaceFeeds(workspaceCardFeeds ?? CONST.EMPTY_OBJECT, cardList); - }, -}); diff --git a/src/selectors/Card.ts b/src/selectors/Card.ts index 7a75744ff56c..64dfff36e0e4 100644 --- a/src/selectors/Card.ts +++ b/src/selectors/Card.ts @@ -1,5 +1,15 @@ import {getExpensifyCardFeedsForDisplay} from '@libs/CardFeedUtils'; -import {hasActiveExpensifyCard, hasAssignedCardMatching, isActiveCard, isCard, isCardHiddenFromSearch, isCSVFeedOrExpensifyCard, isExpensifyCard, isPersonalCard} from '@libs/CardUtils'; +import { + hasActiveExpensifyCard, + hasAssignedCardMatching, + isActiveCard, + isCard, + isCardHiddenFromSearch, + isCSVFeedOrExpensifyCard, + isExpensifyCard, + isPersonalCard, + mergeCardListWithWorkspaceFeeds, +} from '@libs/CardUtils'; import {filterObject} from '@libs/ObjectUtils'; import CONST from '@src/CONST'; @@ -8,6 +18,8 @@ import type {CardFeeds, CardList, NonPersonalAndWorkspaceCardListDerivedValue, W import type {OnyxCollection, OnyxEntry} from 'react-native-onyx'; +import {deepEqual} from 'fast-equals'; + /** * Builds a lightweight map of "${domainID}_${feedName}" keys that have card entries. * A feed counts as having cards when: @@ -87,6 +99,33 @@ const defaultExpensifyCardSelector = (allCards: OnyxEntry { + let lastCardList: OnyxEntry; + let lastWorkspaceCardFeeds: OnyxCollection; + let lastResult: CardList | undefined; + + return (cardList: OnyxEntry, workspaceCardFeeds: OnyxCollection): CardList => { + if (lastResult && cardList === lastCardList && workspaceCardFeeds === lastWorkspaceCardFeeds) { + return lastResult; + } + lastCardList = cardList; + lastWorkspaceCardFeeds = workspaceCardFeeds; + const result = mergeCardListWithWorkspaceFeeds(workspaceCardFeeds ?? CONST.EMPTY_OBJECT, cardList, shouldFilterOutPersonalCards); + if (!lastResult || !deepEqual(result, lastResult)) { + lastResult = result; + } + return lastResult; + }; +}; + +/** The user's cards, personal ones included, plus every workspace feed card. */ +const personalAndWorkspaceCardListSelector = createCardListWithWorkspaceFeedsSelector(false); + /** * Returns a selector that picks a single card from the card list by card ID. */ @@ -135,4 +174,5 @@ export { companyCardCustomNamesSelector, hasIssuedExpensifyCardSelector, hasActiveExpensifyCardSelector, + personalAndWorkspaceCardListSelector, }; diff --git a/src/types/onyx/DerivedValues.ts b/src/types/onyx/DerivedValues.ts index 3f5e2a136157..dcf793f69d28 100644 --- a/src/types/onyx/DerivedValues.ts +++ b/src/types/onyx/DerivedValues.ts @@ -206,11 +206,6 @@ type SortedReportActionsDerivedValue = { transactionThreadIDs: Record; }; -/** - * The derived value for merged personal and workspace card feeds. - */ -type PersonalAndWorkspaceCardListDerivedValue = CardList; - /** * The derived value mapping each user's login (lowercased) to their accountID. * @@ -253,7 +248,6 @@ export type { VisibleReportActionsDerivedValue, SortedReportActionsDerivedValue, NonPersonalAndWorkspaceCardListDerivedValue, - PersonalAndWorkspaceCardListDerivedValue, CardFeedErrorsDerivedValue, LoginToAccountIDMapDerivedValue, GuideAccountIDsDerivedValue, diff --git a/src/types/onyx/index.ts b/src/types/onyx/index.ts index a86e9d85adb5..18f3fe0839d1 100644 --- a/src/types/onyx/index.ts +++ b/src/types/onyx/index.ts @@ -66,7 +66,6 @@ import type { NonPersonalAndWorkspaceCardListDerivedValue, OneOnOneChatReportIDsDerivedValue, OutstandingReportsByPolicyIDDerivedValue, - PersonalAndWorkspaceCardListDerivedValue, ReportAttributesDerivedValue, ReportTransactionsAndViolationsDerivedValue, SortedReportActionsDerivedValue, @@ -499,7 +498,6 @@ export type { VisibleReportActionsDerivedValue, SortedReportActionsDerivedValue, NonPersonalAndWorkspaceCardListDerivedValue, - PersonalAndWorkspaceCardListDerivedValue, CardFeedErrorsDerivedValue, LoginToAccountIDMapDerivedValue, GuideAccountIDsDerivedValue, diff --git a/tests/perf-test/PersonalAndWorkspaceCardList.perf-test.tsx b/tests/perf-test/PersonalAndWorkspaceCardList.perf-test.tsx new file mode 100644 index 000000000000..47ef5f002ecd --- /dev/null +++ b/tests/perf-test/PersonalAndWorkspaceCardList.perf-test.tsx @@ -0,0 +1,305 @@ +import {render, screen} from '@testing-library/react-native'; + +import useFilterCardValue from '@components/Search/hooks/useFilterCardValue'; +import useFilterFeedData from '@components/Search/hooks/useFilterFeedData'; + +import useAdvancedSearchFilters from '@hooks/useAdvancedSearchFilters'; +import useSearchSections from '@hooks/useSearchSections'; + +import CONST from '@src/CONST'; +import ONYXKEYS from '@src/ONYXKEYS'; +import type {Card, CardList, WorkspaceCardsList} from '@src/types/onyx'; + +import type * as Navigation from '@react-navigation/native'; + +import React from 'react'; +import {View} from 'react-native'; +import Onyx from 'react-native-onyx'; +import {measureAsyncFunction, measureRenders} from 'reassure'; + +import createMock from '../utils/createMock'; +import * as TestHelper from '../utils/TestHelper'; +import waitForBatchedUpdates from '../utils/waitForBatchedUpdates'; +import wrapOnyxWithWaitForBatchedUpdates from '../utils/wrapOnyxWithWaitForBatchedUpdates'; + +jest.mock('@libs/Permissions'); +jest.mock('../../src/libs/Navigation/Navigation', () => ({ + navigate: jest.fn(), + isActiveRoute: jest.fn(), + getTopmostReportId: jest.fn(), + getActiveRoute: jest.fn(), + getTopmostReportActionId: jest.fn(), + isNavigationReady: jest.fn(() => Promise.resolve()), + isDisplayedInModal: jest.fn(() => false), + getActiveRouteWithoutParams: jest.fn(() => ''), +})); +jest.mock('../../src/libs/Navigation/navigationRef', () => ({ + getState: () => ({ + routes: [{name: 'Report'}], + }), + getRootState: () => ({ + routes: [], + }), + addListener: () => () => {}, + isReady: () => true, +})); +jest.mock('@react-navigation/native', () => { + const actualNav = jest.requireActual('@react-navigation/native'); + return { + ...actualNav, + useNavigationState: () => true, + useRoute: jest.fn(() => ({key: '', name: '', params: {reportID: '1'}})), + useFocusEffect: jest.fn(), + useIsFocused: () => true, + useNavigation: () => ({ + navigate: jest.fn(), + addListener: jest.fn(() => jest.fn()), + }), + createNavigationContainerRef: jest.fn(), + }; +}); +const CURRENT_USER_ACCOUNT_ID = 1; +const CURRENT_USER_EMAIL = 'email1@test.com'; +const WORKSPACE_ACCOUNT_ID = 777; +const HOOK_CONSUMER_COUNT = 3; +const SMALL_CARD_COUNT = 20; +const LARGE_CARD_COUNT = 3000; +const WRITES_PER_SCENARIO = 10; +const RENAMED_CARD_ID = 1; + +const WORKSPACE_FEED_KEYS = [ + `${ONYXKEYS.COLLECTION.WORKSPACE_CARDS_LIST}${WORKSPACE_ACCOUNT_ID}_${CONST.EXPENSIFY_CARD.BANK}`, + `${ONYXKEYS.COLLECTION.WORKSPACE_CARDS_LIST}${WORKSPACE_ACCOUNT_ID}_${CONST.COMPANY_CARD.FEED_BANK_NAME.VISA}`, +] as const; + +function createCard(cardID: number, bank: Card['bank'], fundID: string | undefined): Card { + return createMock({ + cardID, + bank, + fundID, + state: CONST.EXPENSIFY_CARD.STATE.OPEN, + lastFourPAN: String(1000 + (cardID % 9000)), + cardName: `Card ${cardID}`, + accountID: CURRENT_USER_ACCOUNT_ID, + domainName: 'expensify-policy.exfy', + }); +} + +function buildCards(count: number) { + const cardList: CardList = {}; + const expensifyFeed: WorkspaceCardsList = {}; + const companyFeed: WorkspaceCardsList = {}; + for (let index = 0; index < count; index++) { + const userCardID = index + 1; + cardList[userCardID] = index % 2 === 0 ? createCard(userCardID, CONST.COMPANY_CARD.FEED_BANK_NAME.VISA, '0') : createCard(userCardID, CONST.EXPENSIFY_CARD.BANK, '5000'); + const expensifyCardID = 100000 + index; + expensifyFeed[expensifyCardID] = createCard(expensifyCardID, CONST.EXPENSIFY_CARD.BANK, '5000'); + const companyCardID = 200000 + index; + companyFeed[companyCardID] = createCard(companyCardID, CONST.COMPANY_CARD.FEED_BANK_NAME.VISA, undefined); + } + return {cardList, workspaceFeeds: [expensifyFeed, companyFeed]}; +} + +const smallCards = buildCards(SMALL_CARD_COUNT); +const largeCards = buildCards(LARGE_CARD_COUNT); + +const SELECTED_CARD_IDS = ['1', '2']; + +function SearchSectionsConsumer() { + useSearchSections(); + return ; +} + +function FeedDataConsumer() { + useFilterFeedData(undefined); + return ; +} + +function CardValueConsumer() { + useFilterCardValue(SELECTED_CARD_IDS); + return ; +} + +function AdvancedFiltersConsumer() { + useAdvancedSearchFilters(CONST.SEARCH.DATA_TYPES.EXPENSE); + return ; +} + +/** Search filter surfaces that read the card list through selectors and nothing else of the cards, so their re-renders isolate card list churn */ +function CardFilterConsumers() { + return ( + <> + {Array.from({length: HOOK_CONSUMER_COUNT}, (value, index) => ( + + + + + ))} + + ); +} + +/** Every Search surface that reads the merged card list, mounted together as on the Search page with its filters open */ +function AllCardConsumers() { + return ( + <> + {Array.from({length: HOOK_CONSUMER_COUNT}, (value, index) => ( + + + + + ))} + + + ); +} + +async function seed(cards: ReturnType) { + await Onyx.multiSet({ + [ONYXKEYS.CARD_LIST]: cards.cardList, + [WORKSPACE_FEED_KEYS[0]]: cards.workspaceFeeds.at(0), + [WORKSPACE_FEED_KEYS[1]]: cards.workspaceFeeds.at(1), + }); + await waitForBatchedUpdates(); +} + +/** Writes to a workspace feed's list of cards still to assign, which are not cards, so the merged list keeps its content */ +async function writeUnassignedCards(label: string) { + for (let index = 0; index < WRITES_PER_SCENARIO; index++) { + await Onyx.merge(WORKSPACE_FEED_KEYS[1], {cardList: {[`account ${label}-${index}`]: 'encrypted'}}); + await waitForBatchedUpdates(); + } +} + +describe('Personal and workspace card list consumers on card writes', () => { + beforeAll(() => { + Onyx.init({ + keys: ONYXKEYS, + evictableKeys: [ONYXKEYS.COLLECTION.REPORT_ACTIONS], + }); + // Required lazily so the navigation mocks above are registered before the engine's imports load it + // eslint-disable-next-line @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access + require('@userActions/OnyxDerived').default(); + }); + + beforeEach(async () => { + global.fetch = TestHelper.getGlobalFetchMock(); + wrapOnyxWithWaitForBatchedUpdates(Onyx); + await TestHelper.signInWithTestUser(CURRENT_USER_ACCOUNT_ID, CURRENT_USER_EMAIL, undefined, undefined, 'One'); + await waitForBatchedUpdates(); + }); + + afterEach(async () => { + await Onyx.clear(); + await waitForBatchedUpdates(); + }); + + test('[PersonalCardList] should re-render Search surfaces when unassigned workspace cards change', async () => { + // Given every Search surface that reads the card list, mounted over a small card list + await seed(smallCards); + + // Reassure runs the scenario several times against one seeded Onyx, so every run writes keys that don't exist yet + let run = 0; + const scenario = async () => { + await screen.findAllByTestId('feed-data-consumer'); + + // When the unassigned cards of a workspace feed change repeatedly, which leaves the merged list unchanged + await writeUnassignedCards(`small ${run}`); + run++; + }; + + // Then reassure measures what the unchanged merges cost the consumers + await measureRenders(, {scenario}); + }); + + test('[PersonalCardList] should not re-render card filters when unassigned workspace cards change', async () => { + // Given only the card filters, which read the merged list through selectors and nothing else of the cards + await seed(smallCards); + + let run = 0; + const scenario = async () => { + await screen.findAllByTestId('card-value-consumer'); + + // When the unassigned cards of a workspace feed change repeatedly, which leaves the merged list unchanged + await writeUnassignedCards(`isolated ${run}`); + run++; + }; + + // Then every render here comes from the merged list or a selected value changing reference without changing content + await measureRenders(, {scenario}); + }); + + test('[PersonalCardList] should re-render Search surfaces when a personal card is renamed', async () => { + // Given every Search surface that reads the card list, mounted over a small card list + await seed(smallCards); + + let run = 0; + const scenario = async () => { + await screen.findAllByTestId('feed-data-consumer'); + + // When a personal card is renamed on every write, so the merged list really changes + for (let index = 0; index < WRITES_PER_SCENARIO; index++) { + await Onyx.merge(ONYXKEYS.CARD_LIST, {[RENAMED_CARD_ID]: {cardName: `Renamed ${run}-${index}`}}); + await waitForBatchedUpdates(); + } + run++; + }; + + // Then reassure measures the cost of a real change, which both versions have to pay + await measureRenders(, {scenario}); + }); + + test('[PersonalCardList] should re-render Search surfaces when unassigned workspace cards change in a large card list', async () => { + // Given the same consumers over 9000 cards + await seed(largeCards); + + let run = 0; + const scenario = async () => { + await screen.findAllByTestId('feed-data-consumer'); + + // When the unassigned cards of a workspace feed change repeatedly, so every write merges the whole list again + await writeUnassignedCards(`large ${run}`); + run++; + }; + + // Then reassure measures the render cost, which grows if each consumer scans the list during render + await measureRenders(, {scenario}); + }); + + test('[PersonalCardList] should process unassigned workspace card writes in a large card list', async () => { + // Given the consumers mounted over 9000 cards + await seed(largeCards); + render(); + await screen.findAllByTestId('feed-data-consumer'); + + // When the unassigned cards of a workspace feed change repeatedly + let run = 0; + const writeLoop = async () => { + await writeUnassignedCards(`timed ${run}`); + run++; + }; + + // Then reassure times the whole write loop, including work done outside React renders such as derived computes and their writes + await measureAsyncFunction(writeLoop); + }); + + test('[PersonalCardList] should process personal card renames in a large card list', async () => { + // Given the consumers mounted over 9000 cards + await seed(largeCards); + render(); + await screen.findAllByTestId('feed-data-consumer'); + + // When a personal card is renamed on every write + let run = 0; + const writeLoop = async () => { + for (let index = 0; index < WRITES_PER_SCENARIO; index++) { + await Onyx.merge(ONYXKEYS.CARD_LIST, {[RENAMED_CARD_ID]: {cardName: `Timed rename ${run}-${index}`}}); + await waitForBatchedUpdates(); + } + run++; + }; + + // Then reassure times the loop when both versions must merge and deliver a new list + await measureAsyncFunction(writeLoop); + }); +}); diff --git a/tests/ui/TableTest.tsx b/tests/ui/TableTest.tsx index 29825bdc490c..4570ad085b50 100644 --- a/tests/ui/TableTest.tsx +++ b/tests/ui/TableTest.tsx @@ -2621,6 +2621,44 @@ describe('Table', () => { expect(screen.queryByTestId('row-2')).toBeNull(); expect(screen.getByTestId('generic-empty-state')).toBeTruthy(); }); + + it('renders the empty state instead of "No results" when a page-header table hides every row by default', () => { + // Given a page-header table (like the Workspaces list) whose default filter hides every row, with both + // a no-results state and an empty state declared + const props = createDefaultProps(); + const data: TestItem[] = [ + {keyForList: '1', id: '1', name: 'Archived A', category: 'archived', value: 1}, + {keyForList: '2', id: '2', name: 'Archived B', category: 'archived', value: 2}, + ]; + + // When the table renders with no search or filter selected + render( + + data={data} + columns={props.columns} + renderItem={props.renderItem} + keyExtractor={props.keyExtractor} + filters={statusFilterConfig} + isItemInFilter={isItemInStatusFilter} + > + + Page header + + + + + + , + ); + + // Then the empty state shows inside the list with the page header still visible, because the user did + // not search or filter, so "No results found" would be misleading + expect(screen.getByTestId('flash-list')).toBeTruthy(); + expect(screen.getByTestId('table-header-component')).toBeTruthy(); + expect(screen.getAllByTestId('generic-empty-state')).toHaveLength(1); + expect(screen.getByText('No workspaces')).toBeTruthy(); + expect(screen.queryByText('common.noResultsFound')).toBeNull(); + }); }); describe('immediate filter', () => { diff --git a/tests/unit/OnyxDerivedTest.tsx b/tests/unit/OnyxDerivedTest.tsx index 629837bb5080..e7b775bfe95f 100644 --- a/tests/unit/OnyxDerivedTest.tsx +++ b/tests/unit/OnyxDerivedTest.tsx @@ -1012,83 +1012,6 @@ describe('OnyxDerived', () => { }); }); - describe('personalAndWorkspaceCardList', () => { - it('merges cardList and workspaceCardFeeds when dependencies are set', async () => { - // Non-personal cards (fundID !== '0') from cardList are kept, workspace cards are always included - const nonPersonalCard1 = createRandomExpensifyCard(1, {fundID: '123'}); - const nonPersonalCard2 = createRandomExpensifyCard(2, {fundID: '456'}); - const personalCard = createRandomExpensifyCard(3, {fundID: '0'}); - const workspaceCard3 = createRandomCompanyCard(4, {bank: 'vcf'}); - - await Onyx.set(ONYXKEYS.CARD_LIST, { - '1': nonPersonalCard1, - '2': nonPersonalCard2, - '3': personalCard, - }); - await Onyx.set(`${ONYXKEYS.COLLECTION.WORKSPACE_CARDS_LIST}workspace_123`, { - '4': workspaceCard3, - }); - await waitForBatchedUpdates(); - const derivedCardList = await OnyxUtils.get(ONYXKEYS.DERIVED.PERSONAL_AND_WORKSPACE_CARD_LIST); - - expect(derivedCardList).toMatchObject({ - '1': expect.objectContaining({cardID: 1}), - '2': expect.objectContaining({cardID: 2}), - '3': expect.objectContaining({cardID: 3}), - '4': expect.objectContaining({cardID: 4}), - }); - }); - - it('handles empty cardList when workspaceCardFeeds are set', async () => { - const workspaceCard = createRandomCompanyCard(1, {bank: 'vcf'}); - - await Onyx.set(ONYXKEYS.CARD_LIST, {}); - await Onyx.set(`${ONYXKEYS.COLLECTION.WORKSPACE_CARDS_LIST}workspace_123`, { - '1': workspaceCard, - }); - await waitForBatchedUpdates(); - const derivedCardList = await OnyxUtils.get(ONYXKEYS.DERIVED.PERSONAL_AND_WORKSPACE_CARD_LIST); - - expect(derivedCardList).toMatchObject({ - '1': expect.objectContaining({cardID: 1}), - }); - }); - - it('handles empty workspaceCardFeeds when cardList is set', async () => { - const nonPersonalCard = createRandomExpensifyCard(1, {fundID: '123'}); - - await Onyx.set(ONYXKEYS.CARD_LIST, { - '1': nonPersonalCard, - }); - await waitForBatchedUpdates(); - const derivedCardList = await OnyxUtils.get(ONYXKEYS.DERIVED.PERSONAL_AND_WORKSPACE_CARD_LIST); - - expect(derivedCardList).toMatchObject({ - '1': expect.objectContaining({cardID: 1}), - }); - }); - - it('includes cards from multiple workspace feeds when dependencies are set', async () => { - const card1 = createRandomCompanyCard(1, {bank: 'vcf'}); - const card2 = createRandomCompanyCard(2, {bank: 'stripe'}); - - await Onyx.set(ONYXKEYS.CARD_LIST, {}); - await Onyx.set(`${ONYXKEYS.COLLECTION.WORKSPACE_CARDS_LIST}workspace_123`, { - '1': card1, - }); - await Onyx.set(`${ONYXKEYS.COLLECTION.WORKSPACE_CARDS_LIST}workspace_456`, { - '2': card2, - }); - await waitForBatchedUpdates(); - const derivedCardList = await OnyxUtils.get(ONYXKEYS.DERIVED.PERSONAL_AND_WORKSPACE_CARD_LIST); - - expect(derivedCardList).toMatchObject({ - '1': expect.objectContaining({cardID: 1}), - '2': expect.objectContaining({cardID: 2}), - }); - }); - }); - describe('skipping the write when compute returns the current value', () => { beforeEach(async () => { jest.restoreAllMocks(); diff --git a/tests/unit/hooks/useFilterFeedDataTest.ts b/tests/unit/hooks/useFilterFeedDataTest.ts index 17a88f4dc38f..a2acd8bd8d7e 100644 --- a/tests/unit/hooks/useFilterFeedDataTest.ts +++ b/tests/unit/hooks/useFilterFeedDataTest.ts @@ -110,15 +110,19 @@ describe('useFilterFeedData', () => { }); it('should include Expensify Card feeds from allCards', async () => { - await Onyx.merge(ONYXKEYS.DERIVED.PERSONAL_AND_WORKSPACE_CARD_LIST, { + // Given an Expensify Card in the user's card list + await Onyx.merge(ONYXKEYS.CARD_LIST, { card1: { + cardID: 1, bank: 'Expensify Card', fundID: '999', }, }); + // When the feed options are built const {result} = renderHook(() => useFilterFeedData(undefined)); + // Then the card's feed is offered, since the merged card list is read live from the card list and workspace feeds expect(result.current.feedOptions).toHaveLength(1); expect(result.current.feedOptions.at(0)?.value).toBe('999_Expensify Card'); }); diff --git a/tests/unit/pages/Search/SearchSavePageTest.tsx b/tests/unit/pages/Search/SearchSavePageTest.tsx index 258c06a1d59e..eca76ede2c4a 100644 --- a/tests/unit/pages/Search/SearchSavePageTest.tsx +++ b/tests/unit/pages/Search/SearchSavePageTest.tsx @@ -5,6 +5,7 @@ import useFilterTaxRateValue from '@components/Search/hooks/useFilterTaxRateValu import useLocalize from '@hooks/useLocalize'; import useOnyx from '@hooks/useOnyx'; +import usePersonalAndWorkspaceCardList from '@hooks/usePersonalAndWorkspaceCardList'; import * as SearchUIUtils from '@libs/SearchUIUtils'; @@ -35,6 +36,7 @@ jest.mock('@hooks/useAutoFocusInput', () => jest.fn(() => ({inputCallbackRef: je jest.mock('@hooks/useCurrencyList', () => ({useCurrencyListActions: jest.fn(() => ({convertToDisplayStringWithoutCurrency: jest.fn()}))})); jest.mock('@hooks/useLocalize'); jest.mock('@hooks/useOnyx'); +jest.mock('@hooks/usePersonalAndWorkspaceCardList'); jest.mock('@hooks/useThemeStyles', () => jest.fn(() => ({}))); const cards = createMock({}); cards[12] = createMock({cardID: 12, bank: CONST.COMPANY_CARD.FEED_BANK_NAME.UPLOAD, state: CONST.EXPENSIFY_CARD.STATE.OPEN, nameValuePairs: {cardTitle: 'Selected Alpha'}}); @@ -48,12 +50,11 @@ jest.mocked(useOnyx).mockImplementation((key) => { switch (key) { case ONYXKEYS.FORMS.SEARCH_ADVANCED_FILTERS_FORM: return [form, {status: 'loaded'}]; - case ONYXKEYS.DERIVED.PERSONAL_AND_WORKSPACE_CARD_LIST: - return [cards, {status: 'loaded'}]; default: return [undefined, {status: 'loaded'}]; } }); +jest.mocked(usePersonalAndWorkspaceCardList).mockImplementation((selector) => selector(cards)); // Without a loaded locale, translate returns key paths and translated filter values never show the user's text. beforeAll(() => IntlStore.load(CONST.LOCALES.EN)); beforeEach(() => jest.clearAllMocks()); diff --git a/tests/unit/selectors/CardTest.ts b/tests/unit/selectors/CardTest.ts index 836a9a0c81ce..0a1b7454fb29 100644 --- a/tests/unit/selectors/CardTest.ts +++ b/tests/unit/selectors/CardTest.ts @@ -1,9 +1,10 @@ import {isCard, isCardPendingActivate, isCardPendingIssue, isCardWithPotentialFraud, isExpensifyCard} from '@libs/CardUtils'; import CONST from '@src/CONST'; +import ONYXKEYS from '@src/ONYXKEYS'; import type {Card, CardList, WorkspaceCardsList} from '@src/types/onyx'; -import type {OnyxEntry} from 'react-native-onyx'; +import type {OnyxCollection, OnyxEntry} from 'react-native-onyx'; import type {ValueOf} from 'type-fest'; /* eslint-disable @typescript-eslint/naming-convention */ @@ -14,6 +15,7 @@ import { filterOutPersonalCards, hasActiveExpensifyCardSelector, hasIssuedExpensifyCardSelector, + personalAndWorkspaceCardListSelector, } from '@selectors/Card'; import createRandomCard, {createRandomCompanyCard, createRandomExpensifyCard} from '../../utils/collections/card'; @@ -1000,3 +1002,90 @@ describe('hasActiveExpensifyCardSelector', () => { expect(hasActiveExpensifyCardSelector(undefined)).toBe(false); }); }); + +describe('personalAndWorkspaceCardListSelector', () => { + const workspaceFeedKey = `${ONYXKEYS.COLLECTION.WORKSPACE_CARDS_LIST}workspace_123`; + const otherWorkspaceFeedKey = `${ONYXKEYS.COLLECTION.WORKSPACE_CARDS_LIST}workspace_456`; + + it('should return an empty list when neither input is set', () => { + // Given no card list and no workspace feeds, as before they are loaded + // When the merged list is selected + // Then it is an empty list rather than undefined, so consumers can look cards up right away + expect(personalAndWorkspaceCardListSelector(undefined, undefined)).toEqual({}); + }); + + it('should merge every card of the card list, personal ones included, with the workspace feed cards', () => { + // Given two non-personal cards, a personal card (fundID '0') and a workspace feed card + const cardList: CardList = { + '1': createRandomExpensifyCard(1, {fundID: '123'}), + '2': createRandomExpensifyCard(2, {fundID: '456'}), + '3': createRandomExpensifyCard(3, {fundID: '0'}), + }; + const workspaceCardFeeds: OnyxCollection = {[workspaceFeedKey]: {'4': createRandomCompanyCard(4, {bank: 'vcf'})}}; + + // When the merged list is selected + // Then every card is in it, since Search filters on personal cards too + expect(personalAndWorkspaceCardListSelector(cardList, workspaceCardFeeds)).toMatchObject({ + '1': expect.objectContaining({cardID: 1}), + '2': expect.objectContaining({cardID: 2}), + '3': expect.objectContaining({cardID: 3}), + '4': expect.objectContaining({cardID: 4}), + }); + }); + + it('should keep the workspace feed cards when the card list is empty', () => { + // Given an empty card list and one workspace feed card + const workspaceCardFeeds: OnyxCollection = {[workspaceFeedKey]: {'1': createRandomCompanyCard(1, {bank: 'vcf'})}}; + + // When the merged list is selected + // Then the workspace card is still there, since the two sources are independent + expect(personalAndWorkspaceCardListSelector({}, workspaceCardFeeds)).toMatchObject({'1': expect.objectContaining({cardID: 1})}); + }); + + it('should keep the card list cards when there are no workspace feeds', () => { + // Given one card and no workspace feeds + const cardList: CardList = {'1': createRandomExpensifyCard(1, {fundID: '123'})}; + + // When the merged list is selected + // Then the card is there, since a missing feed collection must not hide the user's own cards + expect(personalAndWorkspaceCardListSelector(cardList, undefined)).toMatchObject({'1': expect.objectContaining({cardID: 1})}); + }); + + it('should include the cards of every workspace feed', () => { + // Given two workspace feeds with one card each + const workspaceCardFeeds: OnyxCollection = { + [workspaceFeedKey]: {'1': createRandomCompanyCard(1, {bank: 'vcf'})}, + [otherWorkspaceFeedKey]: {'2': createRandomCompanyCard(2, {bank: 'stripe'})}, + }; + + // When the merged list is selected + // Then cards from both feeds are in it + expect(personalAndWorkspaceCardListSelector({}, workspaceCardFeeds)).toMatchObject({ + '1': expect.objectContaining({cardID: 1}), + '2': expect.objectContaining({cardID: 2}), + }); + }); + + it('should return the same list while the merged content is unchanged and a new one when it changes', () => { + // Given a card list and a workspace feed collection + const cardList: CardList = {'1': createRandomExpensifyCard(1, {fundID: '0'})}; + const workspaceCard = createRandomCompanyCard(2, {bank: 'vcf'}); + const workspaceCardFeeds: OnyxCollection = {[workspaceFeedKey]: {'2': workspaceCard}}; + const first = personalAndWorkspaceCardListSelector(cardList, workspaceCardFeeds); + const feedWithCardsToAssign: WorkspaceCardsList = {'2': workspaceCard}; + Object.assign(feedWithCardsToAssign, {cardList: {'Visa 1234': 'encrypted'}}); + + // When the list is selected again from the same inputs, from new feeds that only add a card still to assign, + // and from a new card list with another card + const fromSameInputs = personalAndWorkspaceCardListSelector(cardList, workspaceCardFeeds); + const afterUnassignedCardAdded = personalAndWorkspaceCardListSelector(cardList, {[workspaceFeedKey]: feedWithCardsToAssign}); + const afterCardAdded = personalAndWorkspaceCardListSelector({...cardList, '3': createRandomExpensifyCard(3, {fundID: '0'})}, workspaceCardFeeds); + + // Then the first two reuse the same object, so consumers skip their selectors and re-renders, + // and only a real change gives a new list + expect(fromSameInputs).toBe(first); + expect(afterUnassignedCardAdded).toBe(first); + expect(afterCardAdded).not.toBe(first); + expect(afterCardAdded['3']).toMatchObject({cardID: 3}); + }); +}); diff --git a/tests/unit/usePersonalAndWorkspaceCardListTest.tsx b/tests/unit/usePersonalAndWorkspaceCardListTest.tsx new file mode 100644 index 000000000000..e489e34713ed --- /dev/null +++ b/tests/unit/usePersonalAndWorkspaceCardListTest.tsx @@ -0,0 +1,137 @@ +import {act, renderHook} from '@testing-library/react-native'; + +import usePersonalAndWorkspaceCardList from '@hooks/usePersonalAndWorkspaceCardList'; + +import ONYXKEYS from '@src/ONYXKEYS'; +import type {CardList, WorkspaceCardsList} from '@src/types/onyx'; + +/* eslint-disable @typescript-eslint/naming-convention */ +import Onyx from 'react-native-onyx'; + +import {createRandomCompanyCard, createRandomExpensifyCard} from '../utils/collections/card'; +import waitForBatchedUpdatesWithAct from '../utils/waitForBatchedUpdatesWithAct'; + +// `cardList` clashes with the WorkspaceCardsList index signature in a typed literal, so it is attached with Object.assign +function createCardsToAssign(): WorkspaceCardsList { + const feed: WorkspaceCardsList = {}; + Object.assign(feed, {cardList: {'Visa 1234': 'encrypted'}}); + return feed; +} + +const WORKSPACE_FEED_KEY = `${ONYXKEYS.COLLECTION.WORKSPACE_CARDS_LIST}workspace_123` as const; + +describe('usePersonalAndWorkspaceCardList', () => { + beforeAll(() => { + Onyx.init({keys: ONYXKEYS}); + }); + + beforeEach(async () => { + await act(async () => { + await Onyx.clear(); + }); + }); + + it('should follow writes to the card list and the workspace feeds', async () => { + // Given a personal card in the card list + await act(async () => { + await Onyx.set(ONYXKEYS.CARD_LIST, {'1': createRandomExpensifyCard(1, {fundID: '0'})}); + }); + const {result} = renderHook(() => usePersonalAndWorkspaceCardList()); + await waitForBatchedUpdatesWithAct(); + expect(Object.keys(result.current)).toEqual(['1']); + + // When a workspace feed with another card arrives + await act(async () => { + await Onyx.set(WORKSPACE_FEED_KEY, {'2': createRandomCompanyCard(2, {bank: 'vcf'})}); + }); + await waitForBatchedUpdatesWithAct(); + + // Then the hook returns both cards, since it reads its inputs live instead of a stored derived value + expect(Object.keys(result.current).sort()).toEqual(['1', '2']); + }); + + it('should not re-render when a write leaves the merged list unchanged', async () => { + // Given a non-personal card and a workspace feed card + await act(async () => { + await Onyx.set(ONYXKEYS.CARD_LIST, {'1': createRandomExpensifyCard(1, {fundID: '123'})}); + await Onyx.set(WORKSPACE_FEED_KEY, {'2': createRandomCompanyCard(2, {bank: 'vcf'})}); + }); + let renderCount = 0; + const {result} = renderHook(() => { + renderCount++; + return usePersonalAndWorkspaceCardList(); + }); + await waitForBatchedUpdatesWithAct(); + const listBeforeWrite = result.current; + const renderCountBeforeWrite = renderCount; + + // When a card still to assign is added to the workspace feed, which is not a card of the list + await act(async () => { + await Onyx.merge(WORKSPACE_FEED_KEY, createCardsToAssign()); + }); + await waitForBatchedUpdatesWithAct(); + + // Then the consumer keeps the same list and does not re-render + expect(result.current).toBe(listBeforeWrite); + expect(renderCount).toBe(renderCountBeforeWrite); + }); + + it('should give every mounted consumer the same list', async () => { + // Given two consumers mounted over the same inputs + await act(async () => { + await Onyx.set(ONYXKEYS.CARD_LIST, {'1': createRandomExpensifyCard(1, {fundID: '123'})}); + }); + const {result: first} = renderHook(() => usePersonalAndWorkspaceCardList()); + const {result: second} = renderHook(() => usePersonalAndWorkspaceCardList()); + await waitForBatchedUpdatesWithAct(); + + // When a workspace feed card arrives + await act(async () => { + await Onyx.set(WORKSPACE_FEED_KEY, {'2': createRandomCompanyCard(2, {bank: 'vcf'})}); + }); + await waitForBatchedUpdatesWithAct(); + + // Then both get the same object, because the merge runs once per pair of inputs, not once per consumer + expect(second.current).toBe(first.current); + }); + + it('should apply the selector to the merged list', async () => { + // Given a non-personal card and a workspace feed card + await act(async () => { + await Onyx.set(ONYXKEYS.CARD_LIST, {'1': createRandomExpensifyCard(1, {fundID: '123'})}); + await Onyx.set(WORKSPACE_FEED_KEY, {'2': createRandomCompanyCard(2, {bank: 'vcf'})}); + }); + + // When a consumer selects only the card count + const {result} = renderHook(() => usePersonalAndWorkspaceCardList((cardList) => Object.keys(cardList).length)); + await waitForBatchedUpdatesWithAct(); + + // Then it gets the count of the merged list, so selector consumers see the same cards as everyone else + expect(result.current).toBe(2); + }); + + it('should run each selector once per merged list, however many consumers use it', async () => { + // Given two consumers mounted with the same selector + await act(async () => { + await Onyx.set(ONYXKEYS.CARD_LIST, {'1': createRandomExpensifyCard(1, {fundID: '123'})}); + }); + const countCards = jest.fn((cardList: CardList) => Object.keys(cardList).length); + renderHook(() => usePersonalAndWorkspaceCardList(countCards)); + renderHook(() => usePersonalAndWorkspaceCardList(countCards)); + await waitForBatchedUpdatesWithAct(); + countCards.mockClear(); + + // When a workspace feed card arrives, and then a card still to assign that leaves the merged list unchanged + await act(async () => { + await Onyx.set(WORKSPACE_FEED_KEY, {'2': createRandomCompanyCard(2, {bank: 'vcf'})}); + }); + await waitForBatchedUpdatesWithAct(); + await act(async () => { + await Onyx.merge(WORKSPACE_FEED_KEY, createCardsToAssign()); + }); + await waitForBatchedUpdatesWithAct(); + + // Then the selector ran once for the one new merged list, since a big card list makes every run cost a full scan + expect(countCards).toHaveBeenCalledTimes(1); + }); +});