From 2860631359ee49388b5873b7a8c5ad1e00ebf319 Mon Sep 17 00:00:00 2001 From: Matteo Collina Date: Thu, 12 Oct 2023 10:42:04 +0100 Subject: [PATCH] deps: update undici to v5.26.3 Signed-off-by: Matteo Collina PR-URL: https://github.com/nodejs/node/pull/50153 Reviewed-By: Yagiz Nizipli Reviewed-By: Rafael Gonzaga Reviewed-By: Filip Skokan Reviewed-By: Matthew Aitken Reviewed-By: Marco Ippolito CVE-ID: CVE-2023-45143 --- deps/undici/src/docs/api/Client.md | 2 +- deps/undici/src/lib/client.js | 21 +- .../src/lib/compat/dispatcher-weakref.js | 12 +- deps/undici/src/lib/core/request.js | 3 +- deps/undici/src/lib/fetch/index.js | 8 +- deps/undici/src/package.json | 16 +- deps/undici/src/scripts/esbuild-build.mjs | 24 + deps/undici/src/types/agent.d.ts | 2 +- deps/undici/src/types/client.d.ts | 2 +- deps/undici/src/types/connector.d.ts | 1 + deps/undici/undici.js | 6156 ++++++----------- .../maintaining/maintaining-dependencies.md | 6 +- src/undici_version.h | 2 +- tools/dep_updaters/update-undici.sh | 3 + 14 files changed, 2233 insertions(+), 4025 deletions(-) create mode 100644 deps/undici/src/scripts/esbuild-build.mjs diff --git a/deps/undici/src/docs/api/Client.md b/deps/undici/src/docs/api/Client.md index c0987713a328c5..42668389a94225 100644 --- a/deps/undici/src/docs/api/Client.md +++ b/deps/undici/src/docs/api/Client.md @@ -24,7 +24,7 @@ Returns: `Client` * **keepAliveMaxTimeout** `number | null` (optional) - Default: `600e3` - The maximum allowed `keepAliveTimeout`, in milliseconds, when overridden by *keep-alive* hints from the server. Defaults to 10 minutes. * **keepAliveTimeout** `number | null` (optional) - Default: `4e3` - The timeout, in milliseconds, after which a socket without active requests will time out. Monitors time between activity on a connected socket. This value may be overridden by *keep-alive* hints from the server. See [MDN: HTTP - Headers - Keep-Alive directives](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Keep-Alive#directives) for more details. Defaults to 4 seconds. * **keepAliveTimeoutThreshold** `number | null` (optional) - Default: `1e3` - A number of milliseconds subtracted from server *keep-alive* hints when overriding `keepAliveTimeout` to account for timing inaccuracies caused by e.g. transport latency. Defaults to 1 second. -* **maxHeaderSize** `number | null` (optional) - Default: `16384` - The maximum length of request headers in bytes. Defaults to 16KiB. +* **maxHeaderSize** `number | null` (optional) - Default: `--max-http-header-size` or `16384` - The maximum length of request headers in bytes. Defaults to Node.js' --max-http-header-size or 16KiB. * **maxResponseSize** `number | null` (optional) - Default: `-1` - The maximum length of response body in bytes. Set to `-1` to disable. * **pipelining** `number | null` (optional) - Default: `1` - The amount of concurrent requests to be sent over the single TCP/TLS connection according to [RFC7230](https://tools.ietf.org/html/rfc7230#section-6.3.2). Carefully consider your workload and environment before enabling concurrent requests as pipelining may reduce performance if used incorrectly. Pipelining is sensitive to network stack settings as well as head of line blocking caused by e.g. long running requests. Set to `0` to disable keep-alive connections. * **connect** `ConnectOptions | Function | null` (optional) - Default: `null`. diff --git a/deps/undici/src/lib/client.js b/deps/undici/src/lib/client.js index b5170d4f88da9b..065fb563380dcc 100644 --- a/deps/undici/src/lib/client.js +++ b/deps/undici/src/lib/client.js @@ -6,6 +6,7 @@ const assert = require('assert') const net = require('net') +const http = require('http') const { pipeline } = require('stream') const util = require('./core/util') const timers = require('./timers') @@ -93,6 +94,7 @@ const { HTTP2_HEADER_AUTHORITY, HTTP2_HEADER_METHOD, HTTP2_HEADER_PATH, + HTTP2_HEADER_SCHEME, HTTP2_HEADER_CONTENT_LENGTH, HTTP2_HEADER_EXPECT, HTTP2_HEADER_STATUS @@ -269,7 +271,7 @@ class Client extends DispatcherBase { this[kConnector] = connect this[kSocket] = null this[kPipelining] = pipelining != null ? pipelining : 1 - this[kMaxHeadersSize] = maxHeaderSize || 16384 + this[kMaxHeadersSize] = maxHeaderSize || http.maxHeaderSize this[kKeepAliveDefaultTimeout] = keepAliveTimeout == null ? 4e3 : keepAliveTimeout this[kKeepAliveMaxTimeout] = keepAliveMaxTimeout == null ? 600e3 : keepAliveMaxTimeout this[kKeepAliveTimeoutThreshold] = keepAliveTimeoutThreshold == null ? 1e3 : keepAliveTimeoutThreshold @@ -1689,7 +1691,7 @@ function writeH2 (client, session, request) { const h2State = client[kHTTP2SessionState] headers[HTTP2_HEADER_AUTHORITY] = host || client[kHost] - headers[HTTP2_HEADER_PATH] = path + headers[HTTP2_HEADER_METHOD] = method if (method === 'CONNECT') { session.ref() @@ -1716,10 +1718,14 @@ function writeH2 (client, session, request) { }) return true - } else { - headers[HTTP2_HEADER_METHOD] = method } + // https://tools.ietf.org/html/rfc7540#section-8.3 + // :path and :scheme headers must be omited when sending CONNECT + + headers[HTTP2_HEADER_PATH] = path + headers[HTTP2_HEADER_SCHEME] = 'https' + // https://tools.ietf.org/html/rfc7231#section-4.3.1 // https://tools.ietf.org/html/rfc7231#section-4.3.2 // https://tools.ietf.org/html/rfc7231#section-4.3.5 @@ -1856,6 +1862,7 @@ function writeH2 (client, session, request) { stream.cork() stream.write(body) stream.uncork() + stream.end() request.onBodySent(body) request.onRequestSent() } else if (util.isBlobLike(body)) { @@ -2090,13 +2097,17 @@ async function writeIterable ({ h2stream, body, client, request, socket, content throw socket[kError] } - if (!h2stream.write(chunk)) { + const res = h2stream.write(chunk) + request.onBodySent(chunk) + if (!res) { await waitForDrain() } } } catch (err) { h2stream.destroy(err) } finally { + request.onRequestSent() + h2stream.end() h2stream .off('close', onDrain) .off('drain', onDrain) diff --git a/deps/undici/src/lib/compat/dispatcher-weakref.js b/deps/undici/src/lib/compat/dispatcher-weakref.js index dbca8580404ebf..aaaa53ee4af57a 100644 --- a/deps/undici/src/lib/compat/dispatcher-weakref.js +++ b/deps/undici/src/lib/compat/dispatcher-weakref.js @@ -22,11 +22,13 @@ class CompatFinalizer { } register (dispatcher, key) { - dispatcher.on('disconnect', () => { - if (dispatcher[kConnected] === 0 && dispatcher[kSize] === 0) { - this.finalizer(key) - } - }) + if (dispatcher.on) { + dispatcher.on('disconnect', () => { + if (dispatcher[kConnected] === 0 && dispatcher[kSize] === 0) { + this.finalizer(key) + } + }) + } } } diff --git a/deps/undici/src/lib/core/request.js b/deps/undici/src/lib/core/request.js index e3b0c7b9dbf06c..50be01c0dc8355 100644 --- a/deps/undici/src/lib/core/request.js +++ b/deps/undici/src/lib/core/request.js @@ -381,7 +381,8 @@ function processHeader (request, key, val, skipAppend = false) { key.toLowerCase() === 'content-type' ) { request.contentType = val - request.headers += processHeaderValue(key, val) + if (skipAppend) request.headers[key] = processHeaderValue(key, val, skipAppend) + else request.headers += processHeaderValue(key, val) } else if ( key.length === 17 && key.toLowerCase() === 'transfer-encoding' diff --git a/deps/undici/src/lib/fetch/index.js b/deps/undici/src/lib/fetch/index.js index 50f1b9f3fcdcc1..5323c30abc8791 100644 --- a/deps/undici/src/lib/fetch/index.js +++ b/deps/undici/src/lib/fetch/index.js @@ -1200,6 +1200,10 @@ async function httpRedirectFetch (fetchParams, response) { if (!sameOrigin(requestCurrentURL(request), locationURL)) { // https://fetch.spec.whatwg.org/#cors-non-wildcard-request-header-name request.headersList.delete('authorization') + + // "Cookie" and "Host" are forbidden request-headers, which undici doesn't implement. + request.headersList.delete('cookie') + request.headersList.delete('host') } // 14. If request’s body is non-null, then set request’s body to the first return @@ -1344,7 +1348,7 @@ async function httpNetworkOrCacheFetch ( // user agents should append `User-Agent`/default `User-Agent` value to // httpRequest’s header list. if (!httpRequest.headersList.contains('user-agent')) { - httpRequest.headersList.append('user-agent', 'undici') + httpRequest.headersList.append('user-agent', typeof esbuildDetection === 'undefined' ? 'undici' : 'node') } // 15. If httpRequest’s cache mode is "default" and httpRequest’s header @@ -1406,6 +1410,8 @@ async function httpNetworkOrCacheFetch ( } } + httpRequest.headersList.delete('host') + // 20. If includeCredentials is true, then: if (includeCredentials) { // 1. If the user agent is not configured to block cookies for httpRequest diff --git a/deps/undici/src/package.json b/deps/undici/src/package.json index 3846b9dc3988c5..67046ad68a3541 100644 --- a/deps/undici/src/package.json +++ b/deps/undici/src/package.json @@ -1,6 +1,6 @@ { "name": "undici", - "version": "5.25.2", + "version": "5.26.3", "description": "An HTTP/1.1 client, written from scratch for Node.js", "homepage": "https://undici.nodejs.org", "bugs": { @@ -67,15 +67,16 @@ "index-fetch.js", "lib", "types", - "docs" + "docs", + "scripts/esbuild-build.mjs" ], "scripts": { - "build:node": "npx esbuild@0.14.38 index-fetch.js --bundle --platform=node --outfile=undici-fetch.js", + "build:node": "node scripts/esbuild-build.mjs", "prebuild:wasm": "node build/wasm.js --prebuild", "build:wasm": "node build/wasm.js --docker", "lint": "standard | snazzy", "lint:fix": "standard --fix | snazzy", - "test": "npm run test:tap && npm run test:node-fetch && npm run test:fetch && npm run test:cookies && npm run test:wpt && npm run test:websocket && npm run test:jest && npm run test:typescript", + "test": "node scripts/generate-pem && npm run test:tap && npm run test:node-fetch && npm run test:fetch && npm run test:cookies && npm run test:wpt && npm run test:websocket && npm run test:jest && npm run test:typescript", "test:cookies": "node scripts/verifyVersion 16 || tap test/cookie/*.js", "test:node-fetch": "node scripts/verifyVersion.js 16 || mocha --exit test/node-fetch", "test:fetch": "node scripts/verifyVersion.js 16 || (npm run build:node && tap --expose-gc test/fetch/*.js && tap test/webidl/*.js)", @@ -93,7 +94,6 @@ "bench:run": "CONNECTIONS=1 node benchmarks/benchmark.js; CONNECTIONS=50 node benchmarks/benchmark.js", "serve:website": "docsify serve .", "prepare": "husky install", - "postpublish": "node scripts/update-undici-types-version.js && cd types && npm publish", "fuzz": "jsfuzz test/fuzzing/fuzz.js corpus" }, "devDependencies": { @@ -110,6 +110,7 @@ "delay": "^5.0.0", "dns-packet": "^5.4.0", "docsify-cli": "^4.4.3", + "esbuild": "^0.19.4", "form-data": "^4.0.0", "formdata-node": "^4.3.1", "https-pem": "^3.0.0", @@ -123,7 +124,8 @@ "pre-commit": "^1.2.2", "proxy": "^1.0.2", "proxyquire": "^2.1.3", - "sinon": "^15.0.0", + "semver": "^7.5.4", + "sinon": "^16.1.0", "snazzy": "^9.0.0", "standard": "^17.0.0", "table": "^6.8.0", @@ -161,6 +163,6 @@ ] }, "dependencies": { - "busboy": "^1.6.0" + "@fastify/busboy": "^2.0.0" } } diff --git a/deps/undici/src/scripts/esbuild-build.mjs b/deps/undici/src/scripts/esbuild-build.mjs new file mode 100644 index 00000000000000..ca5886c1a2b861 --- /dev/null +++ b/deps/undici/src/scripts/esbuild-build.mjs @@ -0,0 +1,24 @@ +import * as esbuild from 'esbuild' +import fs from 'node:fs' + +const bundle = { + name: 'bundle', + setup (build) { + build.onLoad({ filter: /lib(\/|\\)fetch(\/|\\)index.js/ }, async (args) => { + const text = await fs.promises.readFile(args.path, 'utf8') + + return { + contents: `var esbuildDetection = 1;${text}`, + loader: 'js' + } + }) + } +} + +await esbuild.build({ + entryPoints: ['index-fetch.js'], + bundle: true, + outfile: 'undici-fetch.js', + plugins: [bundle], + platform: 'node' +}) diff --git a/deps/undici/src/types/agent.d.ts b/deps/undici/src/types/agent.d.ts index 0813735805824e..58081ce9372633 100644 --- a/deps/undici/src/types/agent.d.ts +++ b/deps/undici/src/types/agent.d.ts @@ -17,7 +17,7 @@ declare class Agent extends Dispatcher{ declare namespace Agent { export interface Options extends Pool.Options { /** Default: `(origin, opts) => new Pool(origin, opts)`. */ - factory?(origin: URL, opts: Object): Dispatcher; + factory?(origin: string | URL, opts: Object): Dispatcher; /** Integer. Default: `0` */ maxRedirections?: number; diff --git a/deps/undici/src/types/client.d.ts b/deps/undici/src/types/client.d.ts index ac1779721f6a2c..74948b15f3841f 100644 --- a/deps/undici/src/types/client.d.ts +++ b/deps/undici/src/types/client.d.ts @@ -23,7 +23,7 @@ export declare namespace Client { export interface Options { /** TODO */ interceptors?: OptionsInterceptors; - /** The maximum length of request headers in bytes. Default: `16384` (16KiB). */ + /** The maximum length of request headers in bytes. Default: Node.js' `--max-http-header-size` or `16384` (16KiB). */ maxHeaderSize?: number; /** The amount of time, in milliseconds, the parser will wait to receive the complete HTTP headers (Node 14 and above only). Default: `300e3` milliseconds (300s). */ headersTimeout?: number; diff --git a/deps/undici/src/types/connector.d.ts b/deps/undici/src/types/connector.d.ts index 847284a1f2b503..bd924339eb3986 100644 --- a/deps/undici/src/types/connector.d.ts +++ b/deps/undici/src/types/connector.d.ts @@ -6,6 +6,7 @@ declare function buildConnector (options?: buildConnector.BuildOptions): buildCo declare namespace buildConnector { export type BuildOptions = (ConnectionOptions | TcpNetConnectOpts | IpcNetConnectOpts) & { + allowH2?: boolean; maxCachedSessions?: number | null; socketPath?: string | null; timeout?: number | null; diff --git a/deps/undici/undici.js b/deps/undici/undici.js index cd6308f9f3cc2d..0c3dc7ebfc149b 100644 --- a/deps/undici/undici.js +++ b/deps/undici/undici.js @@ -97,46 +97,46 @@ var require_errors = __commonJS({ this.code = "UND_ERR"; } }; - var ConnectTimeoutError = class extends UndiciError { + var ConnectTimeoutError = class _ConnectTimeoutError extends UndiciError { constructor(message) { super(message); - Error.captureStackTrace(this, ConnectTimeoutError); + Error.captureStackTrace(this, _ConnectTimeoutError); this.name = "ConnectTimeoutError"; this.message = message || "Connect Timeout Error"; this.code = "UND_ERR_CONNECT_TIMEOUT"; } }; - var HeadersTimeoutError = class extends UndiciError { + var HeadersTimeoutError = class _HeadersTimeoutError extends UndiciError { constructor(message) { super(message); - Error.captureStackTrace(this, HeadersTimeoutError); + Error.captureStackTrace(this, _HeadersTimeoutError); this.name = "HeadersTimeoutError"; this.message = message || "Headers Timeout Error"; this.code = "UND_ERR_HEADERS_TIMEOUT"; } }; - var HeadersOverflowError = class extends UndiciError { + var HeadersOverflowError = class _HeadersOverflowError extends UndiciError { constructor(message) { super(message); - Error.captureStackTrace(this, HeadersOverflowError); + Error.captureStackTrace(this, _HeadersOverflowError); this.name = "HeadersOverflowError"; this.message = message || "Headers Overflow Error"; this.code = "UND_ERR_HEADERS_OVERFLOW"; } }; - var BodyTimeoutError = class extends UndiciError { + var BodyTimeoutError = class _BodyTimeoutError extends UndiciError { constructor(message) { super(message); - Error.captureStackTrace(this, BodyTimeoutError); + Error.captureStackTrace(this, _BodyTimeoutError); this.name = "BodyTimeoutError"; this.message = message || "Body Timeout Error"; this.code = "UND_ERR_BODY_TIMEOUT"; } }; - var ResponseStatusCodeError = class extends UndiciError { + var ResponseStatusCodeError = class _ResponseStatusCodeError extends UndiciError { constructor(message, statusCode, headers, body) { super(message); - Error.captureStackTrace(this, ResponseStatusCodeError); + Error.captureStackTrace(this, _ResponseStatusCodeError); this.name = "ResponseStatusCodeError"; this.message = message || "Response Status Code Error"; this.code = "UND_ERR_RESPONSE_STATUS_CODE"; @@ -146,92 +146,92 @@ var require_errors = __commonJS({ this.headers = headers; } }; - var InvalidArgumentError = class extends UndiciError { + var InvalidArgumentError = class _InvalidArgumentError extends UndiciError { constructor(message) { super(message); - Error.captureStackTrace(this, InvalidArgumentError); + Error.captureStackTrace(this, _InvalidArgumentError); this.name = "InvalidArgumentError"; this.message = message || "Invalid Argument Error"; this.code = "UND_ERR_INVALID_ARG"; } }; - var InvalidReturnValueError = class extends UndiciError { + var InvalidReturnValueError = class _InvalidReturnValueError extends UndiciError { constructor(message) { super(message); - Error.captureStackTrace(this, InvalidReturnValueError); + Error.captureStackTrace(this, _InvalidReturnValueError); this.name = "InvalidReturnValueError"; this.message = message || "Invalid Return Value Error"; this.code = "UND_ERR_INVALID_RETURN_VALUE"; } }; - var RequestAbortedError = class extends UndiciError { + var RequestAbortedError = class _RequestAbortedError extends UndiciError { constructor(message) { super(message); - Error.captureStackTrace(this, RequestAbortedError); + Error.captureStackTrace(this, _RequestAbortedError); this.name = "AbortError"; this.message = message || "Request aborted"; this.code = "UND_ERR_ABORTED"; } }; - var InformationalError = class extends UndiciError { + var InformationalError = class _InformationalError extends UndiciError { constructor(message) { super(message); - Error.captureStackTrace(this, InformationalError); + Error.captureStackTrace(this, _InformationalError); this.name = "InformationalError"; this.message = message || "Request information"; this.code = "UND_ERR_INFO"; } }; - var RequestContentLengthMismatchError = class extends UndiciError { + var RequestContentLengthMismatchError = class _RequestContentLengthMismatchError extends UndiciError { constructor(message) { super(message); - Error.captureStackTrace(this, RequestContentLengthMismatchError); + Error.captureStackTrace(this, _RequestContentLengthMismatchError); this.name = "RequestContentLengthMismatchError"; this.message = message || "Request body length does not match content-length header"; this.code = "UND_ERR_REQ_CONTENT_LENGTH_MISMATCH"; } }; - var ResponseContentLengthMismatchError = class extends UndiciError { + var ResponseContentLengthMismatchError = class _ResponseContentLengthMismatchError extends UndiciError { constructor(message) { super(message); - Error.captureStackTrace(this, ResponseContentLengthMismatchError); + Error.captureStackTrace(this, _ResponseContentLengthMismatchError); this.name = "ResponseContentLengthMismatchError"; this.message = message || "Response body length does not match content-length header"; this.code = "UND_ERR_RES_CONTENT_LENGTH_MISMATCH"; } }; - var ClientDestroyedError = class extends UndiciError { + var ClientDestroyedError = class _ClientDestroyedError extends UndiciError { constructor(message) { super(message); - Error.captureStackTrace(this, ClientDestroyedError); + Error.captureStackTrace(this, _ClientDestroyedError); this.name = "ClientDestroyedError"; this.message = message || "The client is destroyed"; this.code = "UND_ERR_DESTROYED"; } }; - var ClientClosedError = class extends UndiciError { + var ClientClosedError = class _ClientClosedError extends UndiciError { constructor(message) { super(message); - Error.captureStackTrace(this, ClientClosedError); + Error.captureStackTrace(this, _ClientClosedError); this.name = "ClientClosedError"; this.message = message || "The client is closed"; this.code = "UND_ERR_CLOSED"; } }; - var SocketError = class extends UndiciError { + var SocketError = class _SocketError extends UndiciError { constructor(message, socket) { super(message); - Error.captureStackTrace(this, SocketError); + Error.captureStackTrace(this, _SocketError); this.name = "SocketError"; this.message = message || "Socket error"; this.code = "UND_ERR_SOCKET"; this.socket = socket; } }; - var NotSupportedError = class extends UndiciError { + var NotSupportedError = class _NotSupportedError extends UndiciError { constructor(message) { super(message); - Error.captureStackTrace(this, NotSupportedError); + Error.captureStackTrace(this, _NotSupportedError); this.name = "NotSupportedError"; this.message = message || "Not supported error"; this.code = "UND_ERR_NOT_SUPPORTED"; @@ -246,19 +246,19 @@ var require_errors = __commonJS({ this.code = "UND_ERR_BPL_MISSING_UPSTREAM"; } }; - var HTTPParserError = class extends Error { + var HTTPParserError = class _HTTPParserError extends Error { constructor(message, code, data) { super(message); - Error.captureStackTrace(this, HTTPParserError); + Error.captureStackTrace(this, _HTTPParserError); this.name = "HTTPParserError"; this.code = code ? `HPE_${code}` : void 0; this.data = data ? data.toString() : void 0; } }; - var ResponseExceededMaxSizeError = class extends UndiciError { + var ResponseExceededMaxSizeError = class _ResponseExceededMaxSizeError extends UndiciError { constructor(message) { super(message); - Error.captureStackTrace(this, ResponseExceededMaxSizeError); + Error.captureStackTrace(this, _ResponseExceededMaxSizeError); this.name = "ResponseExceededMaxSizeError"; this.message = message || "Response content exceeded max size"; this.code = "UND_ERR_RES_EXCEEDED_MAX_SIZE"; @@ -331,25 +331,25 @@ var require_util = __commonJS({ if (!url || typeof url !== "object") { throw new InvalidArgumentError("Invalid URL: The URL argument must be a non-null object."); } - if (url.port != null && url.port !== "" && !Number.isFinite(parseInt(url.port))) { - throw new InvalidArgumentError("Invalid URL: port must be a valid integer or a string representation of an integer."); - } - if (url.path != null && typeof url.path !== "string") { - throw new InvalidArgumentError("Invalid URL path: the path must be a string or null/undefined."); - } - if (url.pathname != null && typeof url.pathname !== "string") { - throw new InvalidArgumentError("Invalid URL pathname: the pathname must be a string or null/undefined."); - } - if (url.hostname != null && typeof url.hostname !== "string") { - throw new InvalidArgumentError("Invalid URL hostname: the hostname must be a string or null/undefined."); - } - if (url.origin != null && typeof url.origin !== "string") { - throw new InvalidArgumentError("Invalid URL origin: the origin must be a string or null/undefined."); - } if (!/^https?:/.test(url.origin || url.protocol)) { throw new InvalidArgumentError("Invalid URL protocol: the URL must start with `http:` or `https:`."); } if (!(url instanceof URL)) { + if (url.port != null && url.port !== "" && !Number.isFinite(parseInt(url.port))) { + throw new InvalidArgumentError("Invalid URL: port must be a valid integer or a string representation of an integer."); + } + if (url.path != null && typeof url.path !== "string") { + throw new InvalidArgumentError("Invalid URL path: the path must be a string or null/undefined."); + } + if (url.pathname != null && typeof url.pathname !== "string") { + throw new InvalidArgumentError("Invalid URL pathname: the pathname must be a string or null/undefined."); + } + if (url.hostname != null && typeof url.hostname !== "string") { + throw new InvalidArgumentError("Invalid URL hostname: the hostname must be a string or null/undefined."); + } + if (url.origin != null && typeof url.origin !== "string") { + throw new InvalidArgumentError("Invalid URL origin: the origin must be a string or null/undefined."); + } const port = url.port != null ? url.port : url.protocol === "https:" ? 443 : 80; let origin = url.origin != null ? url.origin : `${url.protocol}//${url.hostname}:${port}`; let path = url.path != null ? url.path : `${url.pathname || ""}${url.search || ""}`; @@ -526,10 +526,14 @@ var require_util = __commonJS({ return !!(body && (stream.isDisturbed ? stream.isDisturbed(body) || body[kBodyUsed] : body[kBodyUsed] || body.readableDidRead || body._readableState && body._readableState.dataEmitted || isReadableAborted(body))); } function isErrored(body) { - return !!(body && (stream.isErrored ? stream.isErrored(body) : /state: 'errored'/.test(nodeUtil.inspect(body)))); + return !!(body && (stream.isErrored ? stream.isErrored(body) : /state: 'errored'/.test( + nodeUtil.inspect(body) + ))); } function isReadable(body) { - return !!(body && (stream.isReadable ? stream.isReadable(body) : /state: 'readable'/.test(nodeUtil.inspect(body)))); + return !!(body && (stream.isReadable ? stream.isReadable(body) : /state: 'readable'/.test( + nodeUtil.inspect(body) + ))); } function getSocketInfo(socket) { return { @@ -557,26 +561,29 @@ var require_util = __commonJS({ return ReadableStream.from(convertIterableToBuffer(iterable)); } let iterator; - return new ReadableStream({ - async start() { - iterator = iterable[Symbol.asyncIterator](); - }, - async pull(controller) { - const { done, value } = await iterator.next(); - if (done) { - queueMicrotask(() => { - controller.close(); - }); - } else { - const buf = Buffer.isBuffer(value) ? value : Buffer.from(value); - controller.enqueue(new Uint8Array(buf)); + return new ReadableStream( + { + async start() { + iterator = iterable[Symbol.asyncIterator](); + }, + async pull(controller) { + const { done, value } = await iterator.next(); + if (done) { + queueMicrotask(() => { + controller.close(); + }); + } else { + const buf = Buffer.isBuffer(value) ? value : Buffer.from(value); + controller.enqueue(new Uint8Array(buf)); + } + return controller.desiredSize > 0; + }, + async cancel(reason) { + await iterator.return(); } - return controller.desiredSize > 0; }, - async cancel(reason) { - await iterator.return(); - } - }, 0); + 0 + ); } function isFormDataLike(object) { return object && typeof object === "object" && typeof object.append === "function" && typeof object.delete === "function" && typeof object.get === "function" && typeof object.getAll === "function" && typeof object.has === "function" && typeof object.set === "function" && object[Symbol.toStringTag] === "FormData"; @@ -778,6 +785,10 @@ var require_constants = __commonJS({ "content-language", "content-location", "content-type", + // See https://github.com/nodejs/undici/issues/2021 + // 'Content-Length' is a forbidden header name, which is typically + // removed in the Headers implementation. However, undici doesn't + // filter out headers, so we add it here. "content-length" ]; var requestDuplex = [ @@ -806,7 +817,9 @@ var require_constants = __commonJS({ } })(); var channel; - var structuredClone = globalThis.structuredClone ?? function structuredClone2(value, options = void 0) { + var structuredClone = globalThis.structuredClone ?? // https://github.com/nodejs/node/blob/b27ae24dcc4251bad726d9d84baf678d1f707fed/lib/internal/structured_clone.js + // structuredClone was added in v17.0.0, but fetch supports v16.8 + function structuredClone2(value, options = void 0) { if (arguments.length === 0) { throw new TypeError("missing argument"); } @@ -848,9 +861,6 @@ var require_global = __commonJS({ return globalThis[globalOrigin]; } function setGlobalOrigin(newOrigin) { - if (newOrigin !== void 0 && typeof newOrigin !== "string" && !(newOrigin instanceof URL)) { - throw new Error("Invalid base url"); - } if (newOrigin === void 0) { Object.defineProperty(globalThis, globalOrigin, { value: void 0, @@ -927,7 +937,9 @@ var require_util2 = __commonJS({ function isValidReasonPhrase(statusText) { for (let i = 0; i < statusText.length; ++i) { const c = statusText.charCodeAt(i); - if (!(c === 9 || c >= 32 && c <= 126 || c >= 128 && c <= 255)) { + if (!(c === 9 || // HTAB + c >= 32 && c <= 126 || // SP / VCHAR + c >= 128 && c <= 255)) { return false; } } @@ -1241,7 +1253,9 @@ var require_util2 = __commonJS({ const i = { next() { if (Object.getPrototypeOf(this) !== i) { - throw new TypeError(`'next' called on an object that does not implement interface ${name} Iterator.`); + throw new TypeError( + `'next' called on an object that does not implement interface ${name} Iterator.` + ); } const { index, kind: kind2, target } = object; const values = target(); @@ -1253,6 +1267,8 @@ var require_util2 = __commonJS({ object.index = index + 1; return iteratorResult(pair, kind2); }, + // The class string of an iterator prototype object for a given interface is the + // result of concatenating the identifier of the interface and the string " Iterator". [Symbol.toStringTag]: `${name} Iterator` }; Object.setPrototypeOf(i, esIteratorPrototype); @@ -1666,7 +1682,9 @@ var require_webidl = __commonJS({ for (let index = 0; index < x.length; index++) { const charCode = x.charCodeAt(index); if (charCode > 255) { - throw new TypeError(`Cannot convert argument to a ByteString because the character at index ${index} has a value of ${charCode} which is greater than 255.`); + throw new TypeError( + `Cannot convert argument to a ByteString because the character at index ${index} has a value of ${charCode} which is greater than 255.` + ); } } return x; @@ -1754,9 +1772,16 @@ var require_webidl = __commonJS({ } throw new TypeError(`Could not convert ${V} to a BufferSource.`); }; - webidl.converters["sequence"] = webidl.sequenceConverter(webidl.converters.ByteString); - webidl.converters["sequence>"] = webidl.sequenceConverter(webidl.converters["sequence"]); - webidl.converters["record"] = webidl.recordConverter(webidl.converters.ByteString, webidl.converters.ByteString); + webidl.converters["sequence"] = webidl.sequenceConverter( + webidl.converters.ByteString + ); + webidl.converters["sequence>"] = webidl.sequenceConverter( + webidl.converters["sequence"] + ); + webidl.converters["record"] = webidl.recordConverter( + webidl.converters.ByteString, + webidl.converters.ByteString + ); module2.exports = { webidl }; @@ -1808,10 +1833,11 @@ var require_headers = __commonJS({ }); } } - var HeadersList = class { + var HeadersList = class _HeadersList { + /** @type {[string, string][]|null} */ cookies = null; constructor(init) { - if (init instanceof HeadersList) { + if (init instanceof _HeadersList) { this[kHeadersMap] = new Map(init[kHeadersMap]); this[kHeadersSortedMap] = init[kHeadersSortedMap]; this.cookies = init.cookies; @@ -1820,6 +1846,7 @@ var require_headers = __commonJS({ this[kHeadersSortedMap] = null; } } + // https://fetch.spec.whatwg.org/#header-list-contains contains(name) { name = name.toLowerCase(); return this[kHeadersMap].has(name); @@ -1829,6 +1856,7 @@ var require_headers = __commonJS({ this[kHeadersSortedMap] = null; this.cookies = null; } + // https://fetch.spec.whatwg.org/#concept-header-list-append append(name, value) { this[kHeadersSortedMap] = null; const lowercaseName = name.toLowerCase(); @@ -1847,6 +1875,7 @@ var require_headers = __commonJS({ this.cookies.push(value); } } + // https://fetch.spec.whatwg.org/#concept-header-list-set set(name, value) { this[kHeadersSortedMap] = null; const lowercaseName = name.toLowerCase(); @@ -1855,6 +1884,7 @@ var require_headers = __commonJS({ } return this[kHeadersMap].set(lowercaseName, { name, value }); } + // https://fetch.spec.whatwg.org/#concept-header-list-delete delete(name) { this[kHeadersSortedMap] = null; name = name.toLowerCase(); @@ -1863,6 +1893,7 @@ var require_headers = __commonJS({ } return this[kHeadersMap].delete(name); } + // https://fetch.spec.whatwg.org/#concept-header-list-get get(name) { if (!this.contains(name)) { return null; @@ -1884,7 +1915,7 @@ var require_headers = __commonJS({ return headers; } }; - var Headers = class { + var Headers = class _Headers { constructor(init = void 0) { this[kHeadersList] = new HeadersList(); this[kGuard] = "none"; @@ -1893,8 +1924,9 @@ var require_headers = __commonJS({ fill(this, init); } } + // https://fetch.spec.whatwg.org/#dom-headers-append append(name, value) { - webidl.brandCheck(this, Headers); + webidl.brandCheck(this, _Headers); webidl.argumentLengthCheck(arguments, 2, { header: "Headers.append" }); name = webidl.converters.ByteString(name); value = webidl.converters.ByteString(value); @@ -1918,8 +1950,9 @@ var require_headers = __commonJS({ } return this[kHeadersList].append(name, value); } + // https://fetch.spec.whatwg.org/#dom-headers-delete delete(name) { - webidl.brandCheck(this, Headers); + webidl.brandCheck(this, _Headers); webidl.argumentLengthCheck(arguments, 1, { header: "Headers.delete" }); name = webidl.converters.ByteString(name); if (!isValidHeaderName(name)) { @@ -1938,8 +1971,9 @@ var require_headers = __commonJS({ } return this[kHeadersList].delete(name); } + // https://fetch.spec.whatwg.org/#dom-headers-get get(name) { - webidl.brandCheck(this, Headers); + webidl.brandCheck(this, _Headers); webidl.argumentLengthCheck(arguments, 1, { header: "Headers.get" }); name = webidl.converters.ByteString(name); if (!isValidHeaderName(name)) { @@ -1951,8 +1985,9 @@ var require_headers = __commonJS({ } return this[kHeadersList].get(name); } + // https://fetch.spec.whatwg.org/#dom-headers-has has(name) { - webidl.brandCheck(this, Headers); + webidl.brandCheck(this, _Headers); webidl.argumentLengthCheck(arguments, 1, { header: "Headers.has" }); name = webidl.converters.ByteString(name); if (!isValidHeaderName(name)) { @@ -1964,8 +1999,9 @@ var require_headers = __commonJS({ } return this[kHeadersList].contains(name); } + // https://fetch.spec.whatwg.org/#dom-headers-set set(name, value) { - webidl.brandCheck(this, Headers); + webidl.brandCheck(this, _Headers); webidl.argumentLengthCheck(arguments, 2, { header: "Headers.set" }); name = webidl.converters.ByteString(name); value = webidl.converters.ByteString(value); @@ -1989,14 +2025,16 @@ var require_headers = __commonJS({ } return this[kHeadersList].set(name, value); } + // https://fetch.spec.whatwg.org/#dom-headers-getsetcookie getSetCookie() { - webidl.brandCheck(this, Headers); + webidl.brandCheck(this, _Headers); const list = this[kHeadersList].cookies; if (list) { return [...list]; } return []; } + // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine get [kHeadersSortedMap]() { if (this[kHeadersList][kHeadersSortedMap]) { return this[kHeadersList][kHeadersSortedMap]; @@ -2018,29 +2056,47 @@ var require_headers = __commonJS({ return headers; } keys() { - webidl.brandCheck(this, Headers); - return makeIterator(() => [...this[kHeadersSortedMap].values()], "Headers", "key"); + webidl.brandCheck(this, _Headers); + return makeIterator( + () => [...this[kHeadersSortedMap].values()], + "Headers", + "key" + ); } values() { - webidl.brandCheck(this, Headers); - return makeIterator(() => [...this[kHeadersSortedMap].values()], "Headers", "value"); + webidl.brandCheck(this, _Headers); + return makeIterator( + () => [...this[kHeadersSortedMap].values()], + "Headers", + "value" + ); } entries() { - webidl.brandCheck(this, Headers); - return makeIterator(() => [...this[kHeadersSortedMap].values()], "Headers", "key+value"); - } + webidl.brandCheck(this, _Headers); + return makeIterator( + () => [...this[kHeadersSortedMap].values()], + "Headers", + "key+value" + ); + } + /** + * @param {(value: string, key: string, self: Headers) => void} callbackFn + * @param {unknown} thisArg + */ forEach(callbackFn, thisArg = globalThis) { - webidl.brandCheck(this, Headers); + webidl.brandCheck(this, _Headers); webidl.argumentLengthCheck(arguments, 1, { header: "Headers.forEach" }); if (typeof callbackFn !== "function") { - throw new TypeError("Failed to execute 'forEach' on 'Headers': parameter 1 is not of type 'Function'."); + throw new TypeError( + "Failed to execute 'forEach' on 'Headers': parameter 1 is not of type 'Function'." + ); } for (const [key, value] of this) { callbackFn.apply(thisArg, [value, key, this]); } } [Symbol.for("nodejs.util.inspect.custom")]() { - webidl.brandCheck(this, Headers); + webidl.brandCheck(this, _Headers); return this[kHeadersList]; } }; @@ -2083,383 +2139,666 @@ var require_headers = __commonJS({ } }); -// node_modules/busboy/lib/utils.js -var require_utils = __commonJS({ - "node_modules/busboy/lib/utils.js"(exports2, module2) { +// node_modules/@fastify/busboy/deps/streamsearch/sbmh.js +var require_sbmh = __commonJS({ + "node_modules/@fastify/busboy/deps/streamsearch/sbmh.js"(exports2, module2) { "use strict"; - function parseContentType(str) { - if (str.length === 0) - return; - const params = /* @__PURE__ */ Object.create(null); - let i = 0; - for (; i < str.length; ++i) { - const code = str.charCodeAt(i); - if (TOKEN[code] !== 1) { - if (code !== 47 || i === 0) - return; - break; - } + var EventEmitter = require("node:events").EventEmitter; + var inherits = require("node:util").inherits; + function SBMH(needle) { + if (typeof needle === "string") { + needle = Buffer.from(needle); + } + if (!Buffer.isBuffer(needle)) { + throw new TypeError("The needle has to be a String or a Buffer."); + } + const needleLength = needle.length; + if (needleLength === 0) { + throw new Error("The needle cannot be an empty String/Buffer."); + } + if (needleLength > 256) { + throw new Error("The needle cannot have a length bigger than 256."); + } + this.maxMatches = Infinity; + this.matches = 0; + this._occ = new Array(256).fill(needleLength); + this._lookbehind_size = 0; + this._needle = needle; + this._bufpos = 0; + this._lookbehind = Buffer.alloc(needleLength); + for (var i = 0; i < needleLength - 1; ++i) { + this._occ[needle[i]] = needleLength - 1 - i; + } + } + inherits(SBMH, EventEmitter); + SBMH.prototype.reset = function() { + this._lookbehind_size = 0; + this.matches = 0; + this._bufpos = 0; + }; + SBMH.prototype.push = function(chunk, pos) { + if (!Buffer.isBuffer(chunk)) { + chunk = Buffer.from(chunk, "binary"); } - if (i === str.length) - return; - const type = str.slice(0, i).toLowerCase(); - const subtypeStart = ++i; - for (; i < str.length; ++i) { - const code = str.charCodeAt(i); - if (TOKEN[code] !== 1) { - if (i === subtypeStart) - return; - if (parseContentTypeParams(str, i, params) === void 0) - return; - break; - } + const chlen = chunk.length; + this._bufpos = pos || 0; + let r; + while (r !== chlen && this.matches < this.maxMatches) { + r = this._sbmh_feed(chunk); } - if (i === subtypeStart) - return; - const subtype = str.slice(subtypeStart, i).toLowerCase(); - return { type, subtype, params }; - } - function parseContentTypeParams(str, i, params) { - while (i < str.length) { - for (; i < str.length; ++i) { - const code = str.charCodeAt(i); - if (code !== 32 && code !== 9) - break; - } - if (i === str.length) - break; - if (str.charCodeAt(i++) !== 59) - return; - for (; i < str.length; ++i) { - const code = str.charCodeAt(i); - if (code !== 32 && code !== 9) - break; - } - if (i === str.length) - return; - let name; - const nameStart = i; - for (; i < str.length; ++i) { - const code = str.charCodeAt(i); - if (TOKEN[code] !== 1) { - if (code !== 61) - return; - break; + return r; + }; + SBMH.prototype._sbmh_feed = function(data) { + const len = data.length; + const needle = this._needle; + const needleLength = needle.length; + const lastNeedleChar = needle[needleLength - 1]; + let pos = -this._lookbehind_size; + let ch; + if (pos < 0) { + while (pos < 0 && pos <= len - needleLength) { + ch = this._sbmh_lookup_char(data, pos + needleLength - 1); + if (ch === lastNeedleChar && this._sbmh_memcmp(data, pos, needleLength - 1)) { + this._lookbehind_size = 0; + ++this.matches; + this.emit("info", true); + return this._bufpos = pos + needleLength; } + pos += this._occ[ch]; } - if (i === str.length) - return; - name = str.slice(nameStart, i); - ++i; - if (i === str.length) - return; - let value = ""; - let valueStart; - if (str.charCodeAt(i) === 34) { - valueStart = ++i; - let escaping = false; - for (; i < str.length; ++i) { - const code = str.charCodeAt(i); - if (code === 92) { - if (escaping) { - valueStart = i; - escaping = false; - } else { - value += str.slice(valueStart, i); - escaping = true; - } - continue; - } - if (code === 34) { - if (escaping) { - valueStart = i; - escaping = false; - continue; - } - value += str.slice(valueStart, i); - break; - } - if (escaping) { - valueStart = i - 1; - escaping = false; - } - if (QDTEXT[code] !== 1) - return; + if (pos < 0) { + while (pos < 0 && !this._sbmh_memcmp(data, pos, len - pos)) { + ++pos; } - if (i === str.length) - return; - ++i; + } + if (pos >= 0) { + this.emit("info", false, this._lookbehind, 0, this._lookbehind_size); + this._lookbehind_size = 0; } else { - valueStart = i; - for (; i < str.length; ++i) { - const code = str.charCodeAt(i); - if (TOKEN[code] !== 1) { - if (i === valueStart) - return; - break; - } - } - value = str.slice(valueStart, i); + const bytesToCutOff = this._lookbehind_size + pos; + if (bytesToCutOff > 0) { + this.emit("info", false, this._lookbehind, 0, bytesToCutOff); + } + this._lookbehind.copy( + this._lookbehind, + 0, + bytesToCutOff, + this._lookbehind_size - bytesToCutOff + ); + this._lookbehind_size -= bytesToCutOff; + data.copy(this._lookbehind, this._lookbehind_size); + this._lookbehind_size += len; + this._bufpos = len; + return len; } - name = name.toLowerCase(); - if (params[name] === void 0) - params[name] = value; } - return params; + pos += (pos >= 0) * this._bufpos; + if (data.indexOf(needle, pos) !== -1) { + pos = data.indexOf(needle, pos); + ++this.matches; + if (pos > 0) { + this.emit("info", true, data, this._bufpos, pos); + } else { + this.emit("info", true); + } + return this._bufpos = pos + needleLength; + } else { + pos = len - needleLength; + } + while (pos < len && (data[pos] !== needle[0] || Buffer.compare( + data.subarray(pos, pos + len - pos), + needle.subarray(0, len - pos) + ) !== 0)) { + ++pos; + } + if (pos < len) { + data.copy(this._lookbehind, 0, pos, pos + (len - pos)); + this._lookbehind_size = len - pos; + } + if (pos > 0) { + this.emit("info", false, data, this._bufpos, pos < len ? pos : len); + } + this._bufpos = len; + return len; + }; + SBMH.prototype._sbmh_lookup_char = function(data, pos) { + return pos < 0 ? this._lookbehind[this._lookbehind_size + pos] : data[pos]; + }; + SBMH.prototype._sbmh_memcmp = function(data, pos, len) { + for (var i = 0; i < len; ++i) { + if (this._sbmh_lookup_char(data, pos + i) !== this._needle[i]) { + return false; + } + } + return true; + }; + module2.exports = SBMH; + } +}); + +// node_modules/@fastify/busboy/deps/dicer/lib/PartStream.js +var require_PartStream = __commonJS({ + "node_modules/@fastify/busboy/deps/dicer/lib/PartStream.js"(exports2, module2) { + "use strict"; + var inherits = require("node:util").inherits; + var ReadableStream = require("node:stream").Readable; + function PartStream(opts) { + ReadableStream.call(this, opts); + } + inherits(PartStream, ReadableStream); + PartStream.prototype._read = function(n) { + }; + module2.exports = PartStream; + } +}); + +// node_modules/@fastify/busboy/lib/utils/getLimit.js +var require_getLimit = __commonJS({ + "node_modules/@fastify/busboy/lib/utils/getLimit.js"(exports2, module2) { + "use strict"; + module2.exports = function getLimit(limits, name, defaultLimit) { + if (!limits || limits[name] === void 0 || limits[name] === null) { + return defaultLimit; + } + if (typeof limits[name] !== "number" || isNaN(limits[name])) { + throw new TypeError("Limit " + name + " is not a valid number"); + } + return limits[name]; + }; + } +}); + +// node_modules/@fastify/busboy/deps/dicer/lib/HeaderParser.js +var require_HeaderParser = __commonJS({ + "node_modules/@fastify/busboy/deps/dicer/lib/HeaderParser.js"(exports2, module2) { + "use strict"; + var EventEmitter = require("node:events").EventEmitter; + var inherits = require("node:util").inherits; + var getLimit = require_getLimit(); + var StreamSearch = require_sbmh(); + var B_DCRLF = Buffer.from("\r\n\r\n"); + var RE_CRLF = /\r\n/g; + var RE_HDR = /^([^:]+):[ \t]?([\x00-\xFF]+)?$/; + function HeaderParser(cfg) { + EventEmitter.call(this); + cfg = cfg || {}; + const self = this; + this.nread = 0; + this.maxed = false; + this.npairs = 0; + this.maxHeaderPairs = getLimit(cfg, "maxHeaderPairs", 2e3); + this.maxHeaderSize = getLimit(cfg, "maxHeaderSize", 80 * 1024); + this.buffer = ""; + this.header = {}; + this.finished = false; + this.ss = new StreamSearch(B_DCRLF); + this.ss.on("info", function(isMatch, data, start, end) { + if (data && !self.maxed) { + if (self.nread + end - start >= self.maxHeaderSize) { + end = self.maxHeaderSize - self.nread + start; + self.nread = self.maxHeaderSize; + self.maxed = true; + } else { + self.nread += end - start; + } + self.buffer += data.toString("binary", start, end); + } + if (isMatch) { + self._finish(); + } + }); } - function parseDisposition(str, defDecoder) { - if (str.length === 0) + inherits(HeaderParser, EventEmitter); + HeaderParser.prototype.push = function(data) { + const r = this.ss.push(data); + if (this.finished) { + return r; + } + }; + HeaderParser.prototype.reset = function() { + this.finished = false; + this.buffer = ""; + this.header = {}; + this.ss.reset(); + }; + HeaderParser.prototype._finish = function() { + if (this.buffer) { + this._parseHeader(); + } + this.ss.matches = this.ss.maxMatches; + const header = this.header; + this.header = {}; + this.buffer = ""; + this.finished = true; + this.nread = this.npairs = 0; + this.maxed = false; + this.emit("header", header); + }; + HeaderParser.prototype._parseHeader = function() { + if (this.npairs === this.maxHeaderPairs) { return; - const params = /* @__PURE__ */ Object.create(null); - let i = 0; - for (; i < str.length; ++i) { - const code = str.charCodeAt(i); - if (TOKEN[code] !== 1) { - if (parseDispositionParams(str, i, params, defDecoder) === void 0) - return; + } + const lines = this.buffer.split(RE_CRLF); + const len = lines.length; + let m, h; + for (var i = 0; i < len; ++i) { + if (lines[i].length === 0) { + continue; + } + if (lines[i][0] === " " || lines[i][0] === " ") { + if (h) { + this.header[h][this.header[h].length - 1] += lines[i]; + continue; + } + } + const posColon = lines[i].indexOf(":"); + if (posColon === -1 || posColon === 0) { + return; + } + m = RE_HDR.exec(lines[i]); + h = m[1].toLowerCase(); + this.header[h] = this.header[h] || []; + this.header[h].push(m[2] || ""); + if (++this.npairs === this.maxHeaderPairs) { break; } } - const type = str.slice(0, i).toLowerCase(); - return { type, params }; + }; + module2.exports = HeaderParser; + } +}); + +// node_modules/@fastify/busboy/deps/dicer/lib/Dicer.js +var require_Dicer = __commonJS({ + "node_modules/@fastify/busboy/deps/dicer/lib/Dicer.js"(exports2, module2) { + "use strict"; + var WritableStream = require("node:stream").Writable; + var inherits = require("node:util").inherits; + var StreamSearch = require_sbmh(); + var PartStream = require_PartStream(); + var HeaderParser = require_HeaderParser(); + var DASH = 45; + var B_ONEDASH = Buffer.from("-"); + var B_CRLF = Buffer.from("\r\n"); + var EMPTY_FN = function() { + }; + function Dicer(cfg) { + if (!(this instanceof Dicer)) { + return new Dicer(cfg); + } + WritableStream.call(this, cfg); + if (!cfg || !cfg.headerFirst && typeof cfg.boundary !== "string") { + throw new TypeError("Boundary required"); + } + if (typeof cfg.boundary === "string") { + this.setBoundary(cfg.boundary); + } else { + this._bparser = void 0; + } + this._headerFirst = cfg.headerFirst; + this._dashes = 0; + this._parts = 0; + this._finished = false; + this._realFinish = false; + this._isPreamble = true; + this._justMatched = false; + this._firstWrite = true; + this._inHeader = true; + this._part = void 0; + this._cb = void 0; + this._ignoreData = false; + this._partOpts = { highWaterMark: cfg.partHwm }; + this._pause = false; + const self = this; + this._hparser = new HeaderParser(cfg); + this._hparser.on("header", function(header) { + self._inHeader = false; + self._part.emit("header", header); + }); } - function parseDispositionParams(str, i, params, defDecoder) { - while (i < str.length) { - for (; i < str.length; ++i) { - const code = str.charCodeAt(i); - if (code !== 32 && code !== 9) - break; + inherits(Dicer, WritableStream); + Dicer.prototype.emit = function(ev) { + if (ev === "finish" && !this._realFinish) { + if (!this._finished) { + const self = this; + process.nextTick(function() { + self.emit("error", new Error("Unexpected end of multipart data")); + if (self._part && !self._ignoreData) { + const type = self._isPreamble ? "Preamble" : "Part"; + self._part.emit("error", new Error(type + " terminated early due to unexpected end of multipart data")); + self._part.push(null); + process.nextTick(function() { + self._realFinish = true; + self.emit("finish"); + self._realFinish = false; + }); + return; + } + self._realFinish = true; + self.emit("finish"); + self._realFinish = false; + }); } - if (i === str.length) - break; - if (str.charCodeAt(i++) !== 59) - return; - for (; i < str.length; ++i) { - const code = str.charCodeAt(i); - if (code !== 32 && code !== 9) + } else { + WritableStream.prototype.emit.apply(this, arguments); + } + }; + Dicer.prototype._write = function(data, encoding, cb) { + if (!this._hparser && !this._bparser) { + return cb(); + } + if (this._headerFirst && this._isPreamble) { + if (!this._part) { + this._part = new PartStream(this._partOpts); + if (this._events.preamble) { + this.emit("preamble", this._part); + } else { + this._ignore(); + } + } + const r = this._hparser.push(data); + if (!this._inHeader && r !== void 0 && r < data.length) { + data = data.slice(r); + } else { + return cb(); + } + } + if (this._firstWrite) { + this._bparser.push(B_CRLF); + this._firstWrite = false; + } + this._bparser.push(data); + if (this._pause) { + this._cb = cb; + } else { + cb(); + } + }; + Dicer.prototype.reset = function() { + this._part = void 0; + this._bparser = void 0; + this._hparser = void 0; + }; + Dicer.prototype.setBoundary = function(boundary) { + const self = this; + this._bparser = new StreamSearch("\r\n--" + boundary); + this._bparser.on("info", function(isMatch, data, start, end) { + self._oninfo(isMatch, data, start, end); + }); + }; + Dicer.prototype._ignore = function() { + if (this._part && !this._ignoreData) { + this._ignoreData = true; + this._part.on("error", EMPTY_FN); + this._part.resume(); + } + }; + Dicer.prototype._oninfo = function(isMatch, data, start, end) { + let buf; + const self = this; + let i = 0; + let r; + let shouldWriteMore = true; + if (!this._part && this._justMatched && data) { + while (this._dashes < 2 && start + i < end) { + if (data[start + i] === DASH) { + ++i; + ++this._dashes; + } else { + if (this._dashes) { + buf = B_ONEDASH; + } + this._dashes = 0; break; + } } - if (i === str.length) - return; - let name; - const nameStart = i; - for (; i < str.length; ++i) { - const code = str.charCodeAt(i); - if (TOKEN[code] !== 1) { - if (code === 61) - break; - return; + if (this._dashes === 2) { + if (start + i < end && this._events.trailer) { + this.emit("trailer", data.slice(start + i, end)); + } + this.reset(); + this._finished = true; + if (self._parts === 0) { + self._realFinish = true; + self.emit("finish"); + self._realFinish = false; } } - if (i === str.length) + if (this._dashes) { return; - let value = ""; - let valueStart; - let charset; - name = str.slice(nameStart, i); - if (name.charCodeAt(name.length - 1) === 42) { - const charsetStart = ++i; - for (; i < str.length; ++i) { - const code = str.charCodeAt(i); - if (CHARSET[code] !== 1) { - if (code !== 39) - return; - break; - } + } + } + if (this._justMatched) { + this._justMatched = false; + } + if (!this._part) { + this._part = new PartStream(this._partOpts); + this._part._read = function(n) { + self._unpause(); + }; + if (this._isPreamble && this._events.preamble) { + this.emit("preamble", this._part); + } else if (this._isPreamble !== true && this._events.part) { + this.emit("part", this._part); + } else { + this._ignore(); + } + if (!this._isPreamble) { + this._inHeader = true; + } + } + if (data && start < end && !this._ignoreData) { + if (this._isPreamble || !this._inHeader) { + if (buf) { + shouldWriteMore = this._part.push(buf); } - if (i === str.length) - return; - charset = str.slice(charsetStart, i); - ++i; - for (; i < str.length; ++i) { - const code = str.charCodeAt(i); - if (code === 39) - break; + shouldWriteMore = this._part.push(data.slice(start, end)); + if (!shouldWriteMore) { + this._pause = true; } - if (i === str.length) - return; - ++i; - if (i === str.length) - return; - valueStart = i; - let encode = 0; - for (; i < str.length; ++i) { - const code = str.charCodeAt(i); - if (EXTENDED_VALUE[code] !== 1) { - if (code === 37) { - let hexUpper; - let hexLower; - if (i + 2 < str.length && (hexUpper = HEX_VALUES[str.charCodeAt(i + 1)]) !== -1 && (hexLower = HEX_VALUES[str.charCodeAt(i + 2)]) !== -1) { - const byteVal = (hexUpper << 4) + hexLower; - value += str.slice(valueStart, i); - value += String.fromCharCode(byteVal); - i += 2; - valueStart = i + 1; - if (byteVal >= 128) - encode = 2; - else if (encode === 0) - encode = 1; - continue; - } - return; - } - break; - } + } else if (!this._isPreamble && this._inHeader) { + if (buf) { + this._hparser.push(buf); } - value += str.slice(valueStart, i); - value = convertToUTF8(value, charset, encode); - if (value === void 0) - return; + r = this._hparser.push(data.slice(start, end)); + if (!this._inHeader && r !== void 0 && r < end) { + this._oninfo(false, data, start + r, end); + } + } + } + if (isMatch) { + this._hparser.reset(); + if (this._isPreamble) { + this._isPreamble = false; } else { - ++i; - if (i === str.length) - return; - if (str.charCodeAt(i) === 34) { - valueStart = ++i; - let escaping = false; - for (; i < str.length; ++i) { - const code = str.charCodeAt(i); - if (code === 92) { - if (escaping) { - valueStart = i; - escaping = false; + if (start !== end) { + ++this._parts; + this._part.on("end", function() { + if (--self._parts === 0) { + if (self._finished) { + self._realFinish = true; + self.emit("finish"); + self._realFinish = false; } else { - value += str.slice(valueStart, i); - escaping = true; - } - continue; - } - if (code === 34) { - if (escaping) { - valueStart = i; - escaping = false; - continue; + self._unpause(); } - value += str.slice(valueStart, i); - break; } - if (escaping) { - valueStart = i - 1; - escaping = false; - } - if (QDTEXT[code] !== 1) - return; - } - if (i === str.length) - return; - ++i; - } else { - valueStart = i; - for (; i < str.length; ++i) { - const code = str.charCodeAt(i); - if (TOKEN[code] !== 1) { - if (i === valueStart) - return; - break; - } - } - value = str.slice(valueStart, i); + }); } - value = defDecoder(value, 2); - if (value === void 0) - return; } - name = name.toLowerCase(); - if (params[name] === void 0) - params[name] = value; + this._part.push(null); + this._part = void 0; + this._ignoreData = false; + this._justMatched = true; + this._dashes = 0; } - return params; - } - function getDecoder(charset) { - let lc; - while (true) { - switch (charset) { - case "utf-8": - case "utf8": - return decoders.utf8; - case "latin1": - case "ascii": - case "us-ascii": - case "iso-8859-1": - case "iso8859-1": - case "iso88591": - case "iso_8859-1": - case "windows-1252": - case "iso_8859-1:1987": - case "cp1252": - case "x-cp1252": - return decoders.latin1; - case "utf16le": - case "utf-16le": - case "ucs2": - case "ucs-2": - return decoders.utf16le; - case "base64": - return decoders.base64; - default: - if (lc === void 0) { - lc = true; - charset = charset.toLowerCase(); - continue; - } - return decoders.other.bind(charset); - } + }; + Dicer.prototype._unpause = function() { + if (!this._pause) { + return; } - } - var decoders = { - utf8: (data, hint) => { - if (data.length === 0) - return ""; - if (typeof data === "string") { - if (hint < 2) - return data; - data = Buffer.from(data, "latin1"); - } - return data.utf8Slice(0, data.length); - }, - latin1: (data, hint) => { - if (data.length === 0) - return ""; - if (typeof data === "string") - return data; - return data.latin1Slice(0, data.length); - }, - utf16le: (data, hint) => { - if (data.length === 0) - return ""; - if (typeof data === "string") - data = Buffer.from(data, "latin1"); - return data.ucs2Slice(0, data.length); - }, - base64: (data, hint) => { - if (data.length === 0) - return ""; - if (typeof data === "string") - data = Buffer.from(data, "latin1"); - return data.base64Slice(0, data.length); - }, - other: (data, hint) => { - if (data.length === 0) - return ""; - if (typeof data === "string") - data = Buffer.from(data, "latin1"); - try { - const decoder = new TextDecoder(exports2); - return decoder.decode(data); - } catch { - } + this._pause = false; + if (this._cb) { + const cb = this._cb; + this._cb = void 0; + cb(); } }; - function convertToUTF8(data, charset, hint) { - const decode = getDecoder(charset); - if (decode) - return decode(data, hint); + module2.exports = Dicer; + } +}); + +// node_modules/@fastify/busboy/lib/utils/decodeText.js +var require_decodeText = __commonJS({ + "node_modules/@fastify/busboy/lib/utils/decodeText.js"(exports2, module2) { + "use strict"; + var utf8Decoder = new TextDecoder("utf-8"); + var textDecoders = /* @__PURE__ */ new Map([ + ["utf-8", utf8Decoder], + ["utf8", utf8Decoder] + ]); + function decodeText(text, textEncoding, destEncoding) { + if (text) { + if (textDecoders.has(destEncoding)) { + try { + return textDecoders.get(destEncoding).decode(Buffer.from(text, textEncoding)); + } catch (e) { + } + } else { + try { + textDecoders.set(destEncoding, new TextDecoder(destEncoding)); + return textDecoders.get(destEncoding).decode(Buffer.from(text, textEncoding)); + } catch (e) { + } + } + } + return text; } - function basename(path) { - if (typeof path !== "string") - return ""; - for (let i = path.length - 1; i >= 0; --i) { - switch (path.charCodeAt(i)) { + module2.exports = decodeText; + } +}); + +// node_modules/@fastify/busboy/lib/utils/parseParams.js +var require_parseParams = __commonJS({ + "node_modules/@fastify/busboy/lib/utils/parseParams.js"(exports2, module2) { + "use strict"; + var decodeText = require_decodeText(); + var RE_ENCODED = /%([a-fA-F0-9]{2})/g; + function encodedReplacer(match, byte) { + return String.fromCharCode(parseInt(byte, 16)); + } + function parseParams(str) { + const res = []; + let state = "key"; + let charset = ""; + let inquote = false; + let escaping = false; + let p = 0; + let tmp = ""; + for (var i = 0, len = str.length; i < len; ++i) { + const char = str[i]; + if (char === "\\" && inquote) { + if (escaping) { + escaping = false; + } else { + escaping = true; + continue; + } + } else if (char === '"') { + if (!escaping) { + if (inquote) { + inquote = false; + state = "key"; + } else { + inquote = true; + } + continue; + } else { + escaping = false; + } + } else { + if (escaping && inquote) { + tmp += "\\"; + } + escaping = false; + if ((state === "charset" || state === "lang") && char === "'") { + if (state === "charset") { + state = "lang"; + charset = tmp.substring(1); + } else { + state = "value"; + } + tmp = ""; + continue; + } else if (state === "key" && (char === "*" || char === "=") && res.length) { + if (char === "*") { + state = "charset"; + } else { + state = "value"; + } + res[p] = [tmp, void 0]; + tmp = ""; + continue; + } else if (!inquote && char === ";") { + state = "key"; + if (charset) { + if (tmp.length) { + tmp = decodeText( + tmp.replace(RE_ENCODED, encodedReplacer), + "binary", + charset + ); + } + charset = ""; + } else if (tmp.length) { + tmp = decodeText(tmp, "binary", "utf8"); + } + if (res[p] === void 0) { + res[p] = tmp; + } else { + res[p][1] = tmp; + } + tmp = ""; + ++p; + continue; + } else if (!inquote && (char === " " || char === " ")) { + continue; + } + } + tmp += char; + } + if (charset && tmp.length) { + tmp = decodeText( + tmp.replace(RE_ENCODED, encodedReplacer), + "binary", + charset + ); + } else if (tmp) { + tmp = decodeText(tmp, "binary", "utf8"); + } + if (res[p] === void 0) { + if (tmp) { + res[p] = tmp; + } + } else { + res[p][1] = tmp; + } + return res; + } + module2.exports = parseParams; + } +}); + +// node_modules/@fastify/busboy/lib/utils/basename.js +var require_basename = __commonJS({ + "node_modules/@fastify/busboy/lib/utils/basename.js"(exports2, module2) { + "use strict"; + module2.exports = function basename(path) { + if (typeof path !== "string") { + return ""; + } + for (var i = path.length - 1; i >= 0; --i) { + switch (path.charCodeAt(i)) { case 47: case 92: path = path.slice(i + 1); @@ -2467,146 +2806,296 @@ var require_utils = __commonJS({ } } return path === ".." || path === "." ? "" : path; + }; + } +}); + +// node_modules/@fastify/busboy/lib/types/multipart.js +var require_multipart = __commonJS({ + "node_modules/@fastify/busboy/lib/types/multipart.js"(exports2, module2) { + "use strict"; + var { Readable } = require("node:stream"); + var { inherits } = require("node:util"); + var Dicer = require_Dicer(); + var parseParams = require_parseParams(); + var decodeText = require_decodeText(); + var basename = require_basename(); + var getLimit = require_getLimit(); + var RE_BOUNDARY = /^boundary$/i; + var RE_FIELD = /^form-data$/i; + var RE_CHARSET = /^charset$/i; + var RE_FILENAME = /^filename$/i; + var RE_NAME = /^name$/i; + Multipart.detect = /^multipart\/form-data/i; + function Multipart(boy, cfg) { + let i; + let len; + const self = this; + let boundary; + const limits = cfg.limits; + const isPartAFile = cfg.isPartAFile || ((fieldName, contentType, fileName) => contentType === "application/octet-stream" || fileName !== void 0); + const parsedConType = cfg.parsedConType || []; + const defCharset = cfg.defCharset || "utf8"; + const preservePath = cfg.preservePath; + const fileOpts = { highWaterMark: cfg.fileHwm }; + for (i = 0, len = parsedConType.length; i < len; ++i) { + if (Array.isArray(parsedConType[i]) && RE_BOUNDARY.test(parsedConType[i][0])) { + boundary = parsedConType[i][1]; + break; + } + } + function checkFinished() { + if (nends === 0 && finished && !boy._done) { + finished = false; + self.end(); + } + } + if (typeof boundary !== "string") { + throw new Error("Multipart: Boundary not found"); + } + const fieldSizeLimit = getLimit(limits, "fieldSize", 1 * 1024 * 1024); + const fileSizeLimit = getLimit(limits, "fileSize", Infinity); + const filesLimit = getLimit(limits, "files", Infinity); + const fieldsLimit = getLimit(limits, "fields", Infinity); + const partsLimit = getLimit(limits, "parts", Infinity); + const headerPairsLimit = getLimit(limits, "headerPairs", 2e3); + const headerSizeLimit = getLimit(limits, "headerSize", 80 * 1024); + let nfiles = 0; + let nfields = 0; + let nends = 0; + let curFile; + let curField; + let finished = false; + this._needDrain = false; + this._pause = false; + this._cb = void 0; + this._nparts = 0; + this._boy = boy; + const parserCfg = { + boundary, + maxHeaderPairs: headerPairsLimit, + maxHeaderSize: headerSizeLimit, + partHwm: fileOpts.highWaterMark, + highWaterMark: cfg.highWaterMark + }; + this.parser = new Dicer(parserCfg); + this.parser.on("drain", function() { + self._needDrain = false; + if (self._cb && !self._pause) { + const cb = self._cb; + self._cb = void 0; + cb(); + } + }).on("part", function onPart(part) { + if (++self._nparts > partsLimit) { + self.parser.removeListener("part", onPart); + self.parser.on("part", skipPart); + boy.hitPartsLimit = true; + boy.emit("partsLimit"); + return skipPart(part); + } + if (curField) { + const field = curField; + field.emit("end"); + field.removeAllListeners("end"); + } + part.on("header", function(header) { + let contype; + let fieldname; + let parsed; + let charset; + let encoding; + let filename; + let nsize = 0; + if (header["content-type"]) { + parsed = parseParams(header["content-type"][0]); + if (parsed[0]) { + contype = parsed[0].toLowerCase(); + for (i = 0, len = parsed.length; i < len; ++i) { + if (RE_CHARSET.test(parsed[i][0])) { + charset = parsed[i][1].toLowerCase(); + break; + } + } + } + } + if (contype === void 0) { + contype = "text/plain"; + } + if (charset === void 0) { + charset = defCharset; + } + if (header["content-disposition"]) { + parsed = parseParams(header["content-disposition"][0]); + if (!RE_FIELD.test(parsed[0])) { + return skipPart(part); + } + for (i = 0, len = parsed.length; i < len; ++i) { + if (RE_NAME.test(parsed[i][0])) { + fieldname = parsed[i][1]; + } else if (RE_FILENAME.test(parsed[i][0])) { + filename = parsed[i][1]; + if (!preservePath) { + filename = basename(filename); + } + } + } + } else { + return skipPart(part); + } + if (header["content-transfer-encoding"]) { + encoding = header["content-transfer-encoding"][0].toLowerCase(); + } else { + encoding = "7bit"; + } + let onData, onEnd; + if (isPartAFile(fieldname, contype, filename)) { + if (nfiles === filesLimit) { + if (!boy.hitFilesLimit) { + boy.hitFilesLimit = true; + boy.emit("filesLimit"); + } + return skipPart(part); + } + ++nfiles; + if (!boy._events.file) { + self.parser._ignore(); + return; + } + ++nends; + const file = new FileStream(fileOpts); + curFile = file; + file.on("end", function() { + --nends; + self._pause = false; + checkFinished(); + if (self._cb && !self._needDrain) { + const cb = self._cb; + self._cb = void 0; + cb(); + } + }); + file._read = function(n) { + if (!self._pause) { + return; + } + self._pause = false; + if (self._cb && !self._needDrain) { + const cb = self._cb; + self._cb = void 0; + cb(); + } + }; + boy.emit("file", fieldname, file, filename, encoding, contype); + onData = function(data) { + if ((nsize += data.length) > fileSizeLimit) { + const extralen = fileSizeLimit - nsize + data.length; + if (extralen > 0) { + file.push(data.slice(0, extralen)); + } + file.truncated = true; + file.bytesRead = fileSizeLimit; + part.removeAllListeners("data"); + file.emit("limit"); + return; + } else if (!file.push(data)) { + self._pause = true; + } + file.bytesRead = nsize; + }; + onEnd = function() { + curFile = void 0; + file.push(null); + }; + } else { + if (nfields === fieldsLimit) { + if (!boy.hitFieldsLimit) { + boy.hitFieldsLimit = true; + boy.emit("fieldsLimit"); + } + return skipPart(part); + } + ++nfields; + ++nends; + let buffer = ""; + let truncated = false; + curField = part; + onData = function(data) { + if ((nsize += data.length) > fieldSizeLimit) { + const extralen = fieldSizeLimit - (nsize - data.length); + buffer += data.toString("binary", 0, extralen); + truncated = true; + part.removeAllListeners("data"); + } else { + buffer += data.toString("binary"); + } + }; + onEnd = function() { + curField = void 0; + if (buffer.length) { + buffer = decodeText(buffer, "binary", charset); + } + boy.emit("field", fieldname, buffer, false, truncated, encoding, contype); + --nends; + checkFinished(); + }; + } + part._readableState.sync = false; + part.on("data", onData); + part.on("end", onEnd); + }).on("error", function(err) { + if (curFile) { + curFile.emit("error", err); + } + }); + }).on("error", function(err) { + boy.emit("error", err); + }).on("finish", function() { + finished = true; + checkFinished(); + }); } - var TOKEN = [ - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 1, - 0, - 1, - 1, - 1, - 1, - 1, - 0, - 0, - 1, - 1, - 0, - 1, - 1, - 0, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 0, - 0, - 0, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 0, - 1, - 0, - 1, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, + Multipart.prototype.write = function(chunk, cb) { + const r = this.parser.write(chunk); + if (r && !this._pause) { + cb(); + } else { + this._needDrain = !r; + this._cb = cb; + } + }; + Multipart.prototype.end = function() { + const self = this; + if (self.parser.writable) { + self.parser.end(); + } else if (!self._boy._done) { + process.nextTick(function() { + self._boy._done = true; + self._boy.emit("finish"); + }); + } + }; + function skipPart(part) { + part.resume(); + } + function FileStream(opts) { + Readable.call(this, opts); + this.bytesRead = 0; + this.truncated = false; + } + inherits(FileStream, Readable); + FileStream.prototype._read = function(n) { + }; + module2.exports = Multipart; + } +}); + +// node_modules/@fastify/busboy/lib/utils/Decoder.js +var require_Decoder = __commonJS({ + "node_modules/@fastify/busboy/lib/utils/Decoder.js"(exports2, module2) { + "use strict"; + var RE_PLUS = /\+/g; + var HEX = [ 0, 0, 0, @@ -2655,2515 +3144,6 @@ var require_utils = __commonJS({ 0, 0, 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0 - ]; - var QDTEXT = [ - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 1, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 1, - 1, - 0, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 0, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 0, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1 - ]; - var CHARSET = [ - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 1, - 0, - 1, - 1, - 1, - 1, - 0, - 0, - 0, - 0, - 1, - 0, - 1, - 0, - 0, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 0, - 0, - 0, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 0, - 1, - 1, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0 - ]; - var EXTENDED_VALUE = [ - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 1, - 0, - 1, - 1, - 0, - 1, - 0, - 0, - 0, - 0, - 1, - 0, - 1, - 1, - 0, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 0, - 0, - 0, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 0, - 1, - 0, - 1, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0 - ]; - var HEX_VALUES = [ - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - 0, - 1, - 2, - 3, - 4, - 5, - 6, - 7, - 8, - 9, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - 10, - 11, - 12, - 13, - 14, - 15, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - 10, - 11, - 12, - 13, - 14, - 15, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1 - ]; - module2.exports = { - basename, - convertToUTF8, - getDecoder, - parseContentType, - parseDisposition - }; - } -}); - -// node_modules/streamsearch/lib/sbmh.js -var require_sbmh = __commonJS({ - "node_modules/streamsearch/lib/sbmh.js"(exports2, module2) { - "use strict"; - function memcmp(buf1, pos1, buf2, pos2, num) { - for (let i = 0; i < num; ++i) { - if (buf1[pos1 + i] !== buf2[pos2 + i]) - return false; - } - return true; - } - var SBMH = class { - constructor(needle, cb) { - if (typeof cb !== "function") - throw new Error("Missing match callback"); - if (typeof needle === "string") - needle = Buffer.from(needle); - else if (!Buffer.isBuffer(needle)) - throw new Error(`Expected Buffer for needle, got ${typeof needle}`); - const needleLen = needle.length; - this.maxMatches = Infinity; - this.matches = 0; - this._cb = cb; - this._lookbehindSize = 0; - this._needle = needle; - this._bufPos = 0; - this._lookbehind = Buffer.allocUnsafe(needleLen); - this._occ = [ - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen - ]; - if (needleLen > 1) { - for (let i = 0; i < needleLen - 1; ++i) - this._occ[needle[i]] = needleLen - 1 - i; - } - } - reset() { - this.matches = 0; - this._lookbehindSize = 0; - this._bufPos = 0; - } - push(chunk, pos) { - let result; - if (!Buffer.isBuffer(chunk)) - chunk = Buffer.from(chunk, "latin1"); - const chunkLen = chunk.length; - this._bufPos = pos || 0; - while (result !== chunkLen && this.matches < this.maxMatches) - result = feed(this, chunk); - return result; - } - destroy() { - const lbSize = this._lookbehindSize; - if (lbSize) - this._cb(false, this._lookbehind, 0, lbSize, false); - this.reset(); - } - }; - function feed(self, data) { - const len = data.length; - const needle = self._needle; - const needleLen = needle.length; - let pos = -self._lookbehindSize; - const lastNeedleCharPos = needleLen - 1; - const lastNeedleChar = needle[lastNeedleCharPos]; - const end = len - needleLen; - const occ = self._occ; - const lookbehind = self._lookbehind; - if (pos < 0) { - while (pos < 0 && pos <= end) { - const nextPos = pos + lastNeedleCharPos; - const ch = nextPos < 0 ? lookbehind[self._lookbehindSize + nextPos] : data[nextPos]; - if (ch === lastNeedleChar && matchNeedle(self, data, pos, lastNeedleCharPos)) { - self._lookbehindSize = 0; - ++self.matches; - if (pos > -self._lookbehindSize) - self._cb(true, lookbehind, 0, self._lookbehindSize + pos, false); - else - self._cb(true, void 0, 0, 0, true); - return self._bufPos = pos + needleLen; - } - pos += occ[ch]; - } - while (pos < 0 && !matchNeedle(self, data, pos, len - pos)) - ++pos; - if (pos < 0) { - const bytesToCutOff = self._lookbehindSize + pos; - if (bytesToCutOff > 0) { - self._cb(false, lookbehind, 0, bytesToCutOff, false); - } - self._lookbehindSize -= bytesToCutOff; - lookbehind.copy(lookbehind, 0, bytesToCutOff, self._lookbehindSize); - lookbehind.set(data, self._lookbehindSize); - self._lookbehindSize += len; - self._bufPos = len; - return len; - } - self._cb(false, lookbehind, 0, self._lookbehindSize, false); - self._lookbehindSize = 0; - } - pos += self._bufPos; - const firstNeedleChar = needle[0]; - while (pos <= end) { - const ch = data[pos + lastNeedleCharPos]; - if (ch === lastNeedleChar && data[pos] === firstNeedleChar && memcmp(needle, 0, data, pos, lastNeedleCharPos)) { - ++self.matches; - if (pos > 0) - self._cb(true, data, self._bufPos, pos, true); - else - self._cb(true, void 0, 0, 0, true); - return self._bufPos = pos + needleLen; - } - pos += occ[ch]; - } - while (pos < len) { - if (data[pos] !== firstNeedleChar || !memcmp(data, pos, needle, 0, len - pos)) { - ++pos; - continue; - } - data.copy(lookbehind, 0, pos, len); - self._lookbehindSize = len - pos; - break; - } - if (pos > 0) - self._cb(false, data, self._bufPos, pos < len ? pos : len, true); - self._bufPos = len; - return len; - } - function matchNeedle(self, data, pos, len) { - const lb = self._lookbehind; - const lbSize = self._lookbehindSize; - const needle = self._needle; - for (let i = 0; i < len; ++i, ++pos) { - const ch = pos < 0 ? lb[lbSize + pos] : data[pos]; - if (ch !== needle[i]) - return false; - } - return true; - } - module2.exports = SBMH; - } -}); - -// node_modules/busboy/lib/types/multipart.js -var require_multipart = __commonJS({ - "node_modules/busboy/lib/types/multipart.js"(exports2, module2) { - "use strict"; - var { Readable, Writable } = require("stream"); - var StreamSearch = require_sbmh(); - var { - basename, - convertToUTF8, - getDecoder, - parseContentType, - parseDisposition - } = require_utils(); - var BUF_CRLF = Buffer.from("\r\n"); - var BUF_CR = Buffer.from("\r"); - var BUF_DASH = Buffer.from("-"); - function noop() { - } - var MAX_HEADER_PAIRS = 2e3; - var MAX_HEADER_SIZE = 16 * 1024; - var HPARSER_NAME = 0; - var HPARSER_PRE_OWS = 1; - var HPARSER_VALUE = 2; - var HeaderParser = class { - constructor(cb) { - this.header = /* @__PURE__ */ Object.create(null); - this.pairCount = 0; - this.byteCount = 0; - this.state = HPARSER_NAME; - this.name = ""; - this.value = ""; - this.crlf = 0; - this.cb = cb; - } - reset() { - this.header = /* @__PURE__ */ Object.create(null); - this.pairCount = 0; - this.byteCount = 0; - this.state = HPARSER_NAME; - this.name = ""; - this.value = ""; - this.crlf = 0; - } - push(chunk, pos, end) { - let start = pos; - while (pos < end) { - switch (this.state) { - case HPARSER_NAME: { - let done = false; - for (; pos < end; ++pos) { - if (this.byteCount === MAX_HEADER_SIZE) - return -1; - ++this.byteCount; - const code = chunk[pos]; - if (TOKEN[code] !== 1) { - if (code !== 58) - return -1; - this.name += chunk.latin1Slice(start, pos); - if (this.name.length === 0) - return -1; - ++pos; - done = true; - this.state = HPARSER_PRE_OWS; - break; - } - } - if (!done) { - this.name += chunk.latin1Slice(start, pos); - break; - } - } - case HPARSER_PRE_OWS: { - let done = false; - for (; pos < end; ++pos) { - if (this.byteCount === MAX_HEADER_SIZE) - return -1; - ++this.byteCount; - const code = chunk[pos]; - if (code !== 32 && code !== 9) { - start = pos; - done = true; - this.state = HPARSER_VALUE; - break; - } - } - if (!done) - break; - } - case HPARSER_VALUE: - switch (this.crlf) { - case 0: - for (; pos < end; ++pos) { - if (this.byteCount === MAX_HEADER_SIZE) - return -1; - ++this.byteCount; - const code = chunk[pos]; - if (FIELD_VCHAR[code] !== 1) { - if (code !== 13) - return -1; - ++this.crlf; - break; - } - } - this.value += chunk.latin1Slice(start, pos++); - break; - case 1: - if (this.byteCount === MAX_HEADER_SIZE) - return -1; - ++this.byteCount; - if (chunk[pos++] !== 10) - return -1; - ++this.crlf; - break; - case 2: { - if (this.byteCount === MAX_HEADER_SIZE) - return -1; - ++this.byteCount; - const code = chunk[pos]; - if (code === 32 || code === 9) { - start = pos; - this.crlf = 0; - } else { - if (++this.pairCount < MAX_HEADER_PAIRS) { - this.name = this.name.toLowerCase(); - if (this.header[this.name] === void 0) - this.header[this.name] = [this.value]; - else - this.header[this.name].push(this.value); - } - if (code === 13) { - ++this.crlf; - ++pos; - } else { - start = pos; - this.crlf = 0; - this.state = HPARSER_NAME; - this.name = ""; - this.value = ""; - } - } - break; - } - case 3: { - if (this.byteCount === MAX_HEADER_SIZE) - return -1; - ++this.byteCount; - if (chunk[pos++] !== 10) - return -1; - const header = this.header; - this.reset(); - this.cb(header); - return pos; - } - } - break; - } - } - return pos; - } - }; - var FileStream = class extends Readable { - constructor(opts, owner) { - super(opts); - this.truncated = false; - this._readcb = null; - this.once("end", () => { - this._read(); - if (--owner._fileEndsLeft === 0 && owner._finalcb) { - const cb = owner._finalcb; - owner._finalcb = null; - process.nextTick(cb); - } - }); - } - _read(n) { - const cb = this._readcb; - if (cb) { - this._readcb = null; - cb(); - } - } - }; - var ignoreData = { - push: (chunk, pos) => { - }, - destroy: () => { - } - }; - function callAndUnsetCb(self, err) { - const cb = self._writecb; - self._writecb = null; - if (err) - self.destroy(err); - else if (cb) - cb(); - } - function nullDecoder(val, hint) { - return val; - } - var Multipart = class extends Writable { - constructor(cfg) { - const streamOpts = { - autoDestroy: true, - emitClose: true, - highWaterMark: typeof cfg.highWaterMark === "number" ? cfg.highWaterMark : void 0 - }; - super(streamOpts); - if (!cfg.conType.params || typeof cfg.conType.params.boundary !== "string") - throw new Error("Multipart: Boundary not found"); - const boundary = cfg.conType.params.boundary; - const paramDecoder = typeof cfg.defParamCharset === "string" && cfg.defParamCharset ? getDecoder(cfg.defParamCharset) : nullDecoder; - const defCharset = cfg.defCharset || "utf8"; - const preservePath = cfg.preservePath; - const fileOpts = { - autoDestroy: true, - emitClose: true, - highWaterMark: typeof cfg.fileHwm === "number" ? cfg.fileHwm : void 0 - }; - const limits = cfg.limits; - const fieldSizeLimit = limits && typeof limits.fieldSize === "number" ? limits.fieldSize : 1 * 1024 * 1024; - const fileSizeLimit = limits && typeof limits.fileSize === "number" ? limits.fileSize : Infinity; - const filesLimit = limits && typeof limits.files === "number" ? limits.files : Infinity; - const fieldsLimit = limits && typeof limits.fields === "number" ? limits.fields : Infinity; - const partsLimit = limits && typeof limits.parts === "number" ? limits.parts : Infinity; - let parts = -1; - let fields = 0; - let files = 0; - let skipPart = false; - this._fileEndsLeft = 0; - this._fileStream = void 0; - this._complete = false; - let fileSize = 0; - let field; - let fieldSize = 0; - let partCharset; - let partEncoding; - let partType; - let partName; - let partTruncated = false; - let hitFilesLimit = false; - let hitFieldsLimit = false; - this._hparser = null; - const hparser = new HeaderParser((header) => { - this._hparser = null; - skipPart = false; - partType = "text/plain"; - partCharset = defCharset; - partEncoding = "7bit"; - partName = void 0; - partTruncated = false; - let filename; - if (!header["content-disposition"]) { - skipPart = true; - return; - } - const disp = parseDisposition(header["content-disposition"][0], paramDecoder); - if (!disp || disp.type !== "form-data") { - skipPart = true; - return; - } - if (disp.params) { - if (disp.params.name) - partName = disp.params.name; - if (disp.params["filename*"]) - filename = disp.params["filename*"]; - else if (disp.params.filename) - filename = disp.params.filename; - if (filename !== void 0 && !preservePath) - filename = basename(filename); - } - if (header["content-type"]) { - const conType = parseContentType(header["content-type"][0]); - if (conType) { - partType = `${conType.type}/${conType.subtype}`; - if (conType.params && typeof conType.params.charset === "string") - partCharset = conType.params.charset.toLowerCase(); - } - } - if (header["content-transfer-encoding"]) - partEncoding = header["content-transfer-encoding"][0].toLowerCase(); - if (partType === "application/octet-stream" || filename !== void 0) { - if (files === filesLimit) { - if (!hitFilesLimit) { - hitFilesLimit = true; - this.emit("filesLimit"); - } - skipPart = true; - return; - } - ++files; - if (this.listenerCount("file") === 0) { - skipPart = true; - return; - } - fileSize = 0; - this._fileStream = new FileStream(fileOpts, this); - ++this._fileEndsLeft; - this.emit("file", partName, this._fileStream, { - filename, - encoding: partEncoding, - mimeType: partType - }); - } else { - if (fields === fieldsLimit) { - if (!hitFieldsLimit) { - hitFieldsLimit = true; - this.emit("fieldsLimit"); - } - skipPart = true; - return; - } - ++fields; - if (this.listenerCount("field") === 0) { - skipPart = true; - return; - } - field = []; - fieldSize = 0; - } - }); - let matchPostBoundary = 0; - const ssCb = (isMatch, data, start, end, isDataSafe) => { - retrydata: - while (data) { - if (this._hparser !== null) { - const ret = this._hparser.push(data, start, end); - if (ret === -1) { - this._hparser = null; - hparser.reset(); - this.emit("error", new Error("Malformed part header")); - break; - } - start = ret; - } - if (start === end) - break; - if (matchPostBoundary !== 0) { - if (matchPostBoundary === 1) { - switch (data[start]) { - case 45: - matchPostBoundary = 2; - ++start; - break; - case 13: - matchPostBoundary = 3; - ++start; - break; - default: - matchPostBoundary = 0; - } - if (start === end) - return; - } - if (matchPostBoundary === 2) { - matchPostBoundary = 0; - if (data[start] === 45) { - this._complete = true; - this._bparser = ignoreData; - return; - } - const writecb = this._writecb; - this._writecb = noop; - ssCb(false, BUF_DASH, 0, 1, false); - this._writecb = writecb; - } else if (matchPostBoundary === 3) { - matchPostBoundary = 0; - if (data[start] === 10) { - ++start; - if (parts >= partsLimit) - break; - this._hparser = hparser; - if (start === end) - break; - continue retrydata; - } else { - const writecb = this._writecb; - this._writecb = noop; - ssCb(false, BUF_CR, 0, 1, false); - this._writecb = writecb; - } - } - } - if (!skipPart) { - if (this._fileStream) { - let chunk; - const actualLen = Math.min(end - start, fileSizeLimit - fileSize); - if (!isDataSafe) { - chunk = Buffer.allocUnsafe(actualLen); - data.copy(chunk, 0, start, start + actualLen); - } else { - chunk = data.slice(start, start + actualLen); - } - fileSize += chunk.length; - if (fileSize === fileSizeLimit) { - if (chunk.length > 0) - this._fileStream.push(chunk); - this._fileStream.emit("limit"); - this._fileStream.truncated = true; - skipPart = true; - } else if (!this._fileStream.push(chunk)) { - if (this._writecb) - this._fileStream._readcb = this._writecb; - this._writecb = null; - } - } else if (field !== void 0) { - let chunk; - const actualLen = Math.min(end - start, fieldSizeLimit - fieldSize); - if (!isDataSafe) { - chunk = Buffer.allocUnsafe(actualLen); - data.copy(chunk, 0, start, start + actualLen); - } else { - chunk = data.slice(start, start + actualLen); - } - fieldSize += actualLen; - field.push(chunk); - if (fieldSize === fieldSizeLimit) { - skipPart = true; - partTruncated = true; - } - } - } - break; - } - if (isMatch) { - matchPostBoundary = 1; - if (this._fileStream) { - this._fileStream.push(null); - this._fileStream = null; - } else if (field !== void 0) { - let data2; - switch (field.length) { - case 0: - data2 = ""; - break; - case 1: - data2 = convertToUTF8(field[0], partCharset, 0); - break; - default: - data2 = convertToUTF8(Buffer.concat(field, fieldSize), partCharset, 0); - } - field = void 0; - fieldSize = 0; - this.emit("field", partName, data2, { - nameTruncated: false, - valueTruncated: partTruncated, - encoding: partEncoding, - mimeType: partType - }); - } - if (++parts === partsLimit) - this.emit("partsLimit"); - } - }; - this._bparser = new StreamSearch(`\r ---${boundary}`, ssCb); - this._writecb = null; - this._finalcb = null; - this.write(BUF_CRLF); - } - static detect(conType) { - return conType.type === "multipart" && conType.subtype === "form-data"; - } - _write(chunk, enc, cb) { - this._writecb = cb; - this._bparser.push(chunk, 0); - if (this._writecb) - callAndUnsetCb(this); - } - _destroy(err, cb) { - this._hparser = null; - this._bparser = ignoreData; - if (!err) - err = checkEndState(this); - const fileStream = this._fileStream; - if (fileStream) { - this._fileStream = null; - fileStream.destroy(err); - } - cb(err); - } - _final(cb) { - this._bparser.destroy(); - if (!this._complete) - return cb(new Error("Unexpected end of form")); - if (this._fileEndsLeft) - this._finalcb = finalcb.bind(null, this, cb); - else - finalcb(this, cb); - } - }; - function finalcb(self, cb, err) { - if (err) - return cb(err); - err = checkEndState(self); - cb(err); - } - function checkEndState(self) { - if (self._hparser) - return new Error("Malformed part header"); - const fileStream = self._fileStream; - if (fileStream) { - self._fileStream = null; - fileStream.destroy(new Error("Unexpected end of file")); - } - if (!self._complete) - return new Error("Unexpected end of form"); - } - var TOKEN = [ - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 1, - 0, - 1, - 1, - 1, - 1, - 1, - 0, - 0, - 1, - 1, - 0, - 1, - 1, - 0, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 0, - 0, - 0, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 0, - 1, - 0, - 1, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0 - ]; - var FIELD_VCHAR = [ - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 1, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 0, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, 1, 1, 1, @@ -5174,605 +3154,412 @@ var require_multipart = __commonJS({ 1, 1, 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, 1, 1, 1, 1, 1, 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, 1, 1, 1, 1, 1, 1, - 1 + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0 ]; - module2.exports = Multipart; + function Decoder() { + this.buffer = void 0; + } + Decoder.prototype.write = function(str) { + str = str.replace(RE_PLUS, " "); + let res = ""; + let i = 0; + let p = 0; + const len = str.length; + for (; i < len; ++i) { + if (this.buffer !== void 0) { + if (!HEX[str.charCodeAt(i)]) { + res += "%" + this.buffer; + this.buffer = void 0; + --i; + } else { + this.buffer += str[i]; + ++p; + if (this.buffer.length === 2) { + res += String.fromCharCode(parseInt(this.buffer, 16)); + this.buffer = void 0; + } + } + } else if (str[i] === "%") { + if (i > p) { + res += str.substring(p, i); + p = i; + } + this.buffer = ""; + ++p; + } + } + if (p < len && this.buffer === void 0) { + res += str.substring(p); + } + return res; + }; + Decoder.prototype.reset = function() { + this.buffer = void 0; + }; + module2.exports = Decoder; } }); -// node_modules/busboy/lib/types/urlencoded.js +// node_modules/@fastify/busboy/lib/types/urlencoded.js var require_urlencoded = __commonJS({ - "node_modules/busboy/lib/types/urlencoded.js"(exports2, module2) { + "node_modules/@fastify/busboy/lib/types/urlencoded.js"(exports2, module2) { "use strict"; - var { Writable } = require("stream"); - var { getDecoder } = require_utils(); - var URLEncoded = class extends Writable { - constructor(cfg) { - const streamOpts = { - autoDestroy: true, - emitClose: true, - highWaterMark: typeof cfg.highWaterMark === "number" ? cfg.highWaterMark : void 0 - }; - super(streamOpts); - let charset = cfg.defCharset || "utf8"; - if (cfg.conType.params && typeof cfg.conType.params.charset === "string") - charset = cfg.conType.params.charset; - this.charset = charset; - const limits = cfg.limits; - this.fieldSizeLimit = limits && typeof limits.fieldSize === "number" ? limits.fieldSize : 1 * 1024 * 1024; - this.fieldsLimit = limits && typeof limits.fields === "number" ? limits.fields : Infinity; - this.fieldNameSizeLimit = limits && typeof limits.fieldNameSize === "number" ? limits.fieldNameSize : 100; - this._inKey = true; - this._keyTrunc = false; - this._valTrunc = false; - this._bytesKey = 0; - this._bytesVal = 0; - this._fields = 0; - this._key = ""; - this._val = ""; - this._byte = -2; - this._lastPos = 0; - this._encode = 0; - this._decoder = getDecoder(charset); - } - static detect(conType) { - return conType.type === "application" && conType.subtype === "x-www-form-urlencoded"; - } - _write(chunk, enc, cb) { - if (this._fields >= this.fieldsLimit) - return cb(); - let i = 0; - const len = chunk.length; - this._lastPos = 0; - if (this._byte !== -2) { - i = readPctEnc(this, chunk, i, len); - if (i === -1) - return cb(new Error("Malformed urlencoded form")); - if (i >= len) - return cb(); - if (this._inKey) - ++this._bytesKey; - else - ++this._bytesVal; - } - main: - while (i < len) { - if (this._inKey) { - i = skipKeyBytes(this, chunk, i, len); - while (i < len) { - switch (chunk[i]) { - case 61: - if (this._lastPos < i) - this._key += chunk.latin1Slice(this._lastPos, i); - this._lastPos = ++i; - this._key = this._decoder(this._key, this._encode); - this._encode = 0; - this._inKey = false; - continue main; - case 38: - if (this._lastPos < i) - this._key += chunk.latin1Slice(this._lastPos, i); - this._lastPos = ++i; - this._key = this._decoder(this._key, this._encode); - this._encode = 0; - if (this._bytesKey > 0) { - this.emit("field", this._key, "", { - nameTruncated: this._keyTrunc, - valueTruncated: false, - encoding: this.charset, - mimeType: "text/plain" - }); - } - this._key = ""; - this._val = ""; - this._keyTrunc = false; - this._valTrunc = false; - this._bytesKey = 0; - this._bytesVal = 0; - if (++this._fields >= this.fieldsLimit) { - this.emit("fieldsLimit"); - return cb(); - } - continue; - case 43: - if (this._lastPos < i) - this._key += chunk.latin1Slice(this._lastPos, i); - this._key += " "; - this._lastPos = i + 1; - break; - case 37: - if (this._encode === 0) - this._encode = 1; - if (this._lastPos < i) - this._key += chunk.latin1Slice(this._lastPos, i); - this._lastPos = i + 1; - this._byte = -1; - i = readPctEnc(this, chunk, i + 1, len); - if (i === -1) - return cb(new Error("Malformed urlencoded form")); - if (i >= len) - return cb(); - ++this._bytesKey; - i = skipKeyBytes(this, chunk, i, len); - continue; - } - ++i; - ++this._bytesKey; - i = skipKeyBytes(this, chunk, i, len); - } - if (this._lastPos < i) - this._key += chunk.latin1Slice(this._lastPos, i); + var Decoder = require_Decoder(); + var decodeText = require_decodeText(); + var getLimit = require_getLimit(); + var RE_CHARSET = /^charset$/i; + UrlEncoded.detect = /^application\/x-www-form-urlencoded/i; + function UrlEncoded(boy, cfg) { + const limits = cfg.limits; + const parsedConType = cfg.parsedConType; + this.boy = boy; + this.fieldSizeLimit = getLimit(limits, "fieldSize", 1 * 1024 * 1024); + this.fieldNameSizeLimit = getLimit(limits, "fieldNameSize", 100); + this.fieldsLimit = getLimit(limits, "fields", Infinity); + let charset; + for (var i = 0, len = parsedConType.length; i < len; ++i) { + if (Array.isArray(parsedConType[i]) && RE_CHARSET.test(parsedConType[i][0])) { + charset = parsedConType[i][1].toLowerCase(); + break; + } + } + if (charset === void 0) { + charset = cfg.defCharset || "utf8"; + } + this.decoder = new Decoder(); + this.charset = charset; + this._fields = 0; + this._state = "key"; + this._checkingBytes = true; + this._bytesKey = 0; + this._bytesVal = 0; + this._key = ""; + this._val = ""; + this._keyTrunc = false; + this._valTrunc = false; + this._hitLimit = false; + } + UrlEncoded.prototype.write = function(data, cb) { + if (this._fields === this.fieldsLimit) { + if (!this.boy.hitFieldsLimit) { + this.boy.hitFieldsLimit = true; + this.boy.emit("fieldsLimit"); + } + return cb(); + } + let idxeq; + let idxamp; + let i; + let p = 0; + const len = data.length; + while (p < len) { + if (this._state === "key") { + idxeq = idxamp = void 0; + for (i = p; i < len; ++i) { + if (!this._checkingBytes) { + ++p; + } + if (data[i] === 61) { + idxeq = i; + break; + } else if (data[i] === 38) { + idxamp = i; + break; + } + if (this._checkingBytes && this._bytesKey === this.fieldNameSizeLimit) { + this._hitLimit = true; + break; + } else if (this._checkingBytes) { + ++this._bytesKey; + } + } + if (idxeq !== void 0) { + if (idxeq > p) { + this._key += this.decoder.write(data.toString("binary", p, idxeq)); + } + this._state = "val"; + this._hitLimit = false; + this._checkingBytes = true; + this._val = ""; + this._bytesVal = 0; + this._valTrunc = false; + this.decoder.reset(); + p = idxeq + 1; + } else if (idxamp !== void 0) { + ++this._fields; + let key; + const keyTrunc = this._keyTrunc; + if (idxamp > p) { + key = this._key += this.decoder.write(data.toString("binary", p, idxamp)); } else { - i = skipValBytes(this, chunk, i, len); - while (i < len) { - switch (chunk[i]) { - case 38: - if (this._lastPos < i) - this._val += chunk.latin1Slice(this._lastPos, i); - this._lastPos = ++i; - this._inKey = true; - this._val = this._decoder(this._val, this._encode); - this._encode = 0; - if (this._bytesKey > 0 || this._bytesVal > 0) { - this.emit("field", this._key, this._val, { - nameTruncated: this._keyTrunc, - valueTruncated: this._valTrunc, - encoding: this.charset, - mimeType: "text/plain" - }); - } - this._key = ""; - this._val = ""; - this._keyTrunc = false; - this._valTrunc = false; - this._bytesKey = 0; - this._bytesVal = 0; - if (++this._fields >= this.fieldsLimit) { - this.emit("fieldsLimit"); - return cb(); - } - continue main; - case 43: - if (this._lastPos < i) - this._val += chunk.latin1Slice(this._lastPos, i); - this._val += " "; - this._lastPos = i + 1; - break; - case 37: - if (this._encode === 0) - this._encode = 1; - if (this._lastPos < i) - this._val += chunk.latin1Slice(this._lastPos, i); - this._lastPos = i + 1; - this._byte = -1; - i = readPctEnc(this, chunk, i + 1, len); - if (i === -1) - return cb(new Error("Malformed urlencoded form")); - if (i >= len) - return cb(); - ++this._bytesVal; - i = skipValBytes(this, chunk, i, len); - continue; - } - ++i; - ++this._bytesVal; - i = skipValBytes(this, chunk, i, len); - } - if (this._lastPos < i) - this._val += chunk.latin1Slice(this._lastPos, i); + key = this._key; + } + this._hitLimit = false; + this._checkingBytes = true; + this._key = ""; + this._bytesKey = 0; + this._keyTrunc = false; + this.decoder.reset(); + if (key.length) { + this.boy.emit( + "field", + decodeText(key, "binary", this.charset), + "", + keyTrunc, + false + ); + } + p = idxamp + 1; + if (this._fields === this.fieldsLimit) { + return cb(); + } + } else if (this._hitLimit) { + if (i > p) { + this._key += this.decoder.write(data.toString("binary", p, i)); } + p = i; + if ((this._bytesKey = this._key.length) === this.fieldNameSizeLimit) { + this._checkingBytes = false; + this._keyTrunc = true; + } + } else { + if (p < len) { + this._key += this.decoder.write(data.toString("binary", p)); + } + p = len; + } + } else { + idxamp = void 0; + for (i = p; i < len; ++i) { + if (!this._checkingBytes) { + ++p; + } + if (data[i] === 38) { + idxamp = i; + break; + } + if (this._checkingBytes && this._bytesVal === this.fieldSizeLimit) { + this._hitLimit = true; + break; + } else if (this._checkingBytes) { + ++this._bytesVal; + } + } + if (idxamp !== void 0) { + ++this._fields; + if (idxamp > p) { + this._val += this.decoder.write(data.toString("binary", p, idxamp)); + } + this.boy.emit( + "field", + decodeText(this._key, "binary", this.charset), + decodeText(this._val, "binary", this.charset), + this._keyTrunc, + this._valTrunc + ); + this._state = "key"; + this._hitLimit = false; + this._checkingBytes = true; + this._key = ""; + this._bytesKey = 0; + this._keyTrunc = false; + this.decoder.reset(); + p = idxamp + 1; + if (this._fields === this.fieldsLimit) { + return cb(); + } + } else if (this._hitLimit) { + if (i > p) { + this._val += this.decoder.write(data.toString("binary", p, i)); + } + p = i; + if (this._val === "" && this.fieldSizeLimit === 0 || (this._bytesVal = this._val.length) === this.fieldSizeLimit) { + this._checkingBytes = false; + this._valTrunc = true; + } + } else { + if (p < len) { + this._val += this.decoder.write(data.toString("binary", p)); + } + p = len; } - cb(); - } - _final(cb) { - if (this._byte !== -2) - return cb(new Error("Malformed urlencoded form")); - if (!this._inKey || this._bytesKey > 0 || this._bytesVal > 0) { - if (this._inKey) - this._key = this._decoder(this._key, this._encode); - else - this._val = this._decoder(this._val, this._encode); - this.emit("field", this._key, this._val, { - nameTruncated: this._keyTrunc, - valueTruncated: this._valTrunc, - encoding: this.charset, - mimeType: "text/plain" - }); } - cb(); } + cb(); }; - function readPctEnc(self, chunk, pos, len) { - if (pos >= len) - return len; - if (self._byte === -1) { - const hexUpper = HEX_VALUES[chunk[pos++]]; - if (hexUpper === -1) - return -1; - if (hexUpper >= 8) - self._encode = 2; - if (pos < len) { - const hexLower = HEX_VALUES[chunk[pos++]]; - if (hexLower === -1) - return -1; - if (self._inKey) - self._key += String.fromCharCode((hexUpper << 4) + hexLower); - else - self._val += String.fromCharCode((hexUpper << 4) + hexLower); - self._byte = -2; - self._lastPos = pos; - } else { - self._byte = hexUpper; - } - } else { - const hexLower = HEX_VALUES[chunk[pos++]]; - if (hexLower === -1) - return -1; - if (self._inKey) - self._key += String.fromCharCode((self._byte << 4) + hexLower); - else - self._val += String.fromCharCode((self._byte << 4) + hexLower); - self._byte = -2; - self._lastPos = pos; - } - return pos; - } - function skipKeyBytes(self, chunk, pos, len) { - if (self._bytesKey > self.fieldNameSizeLimit) { - if (!self._keyTrunc) { - if (self._lastPos < pos) - self._key += chunk.latin1Slice(self._lastPos, pos - 1); - } - self._keyTrunc = true; - for (; pos < len; ++pos) { - const code = chunk[pos]; - if (code === 61 || code === 38) - break; - ++self._bytesKey; - } - self._lastPos = pos; + UrlEncoded.prototype.end = function() { + if (this.boy._done) { + return; } - return pos; - } - function skipValBytes(self, chunk, pos, len) { - if (self._bytesVal > self.fieldSizeLimit) { - if (!self._valTrunc) { - if (self._lastPos < pos) - self._val += chunk.latin1Slice(self._lastPos, pos - 1); - } - self._valTrunc = true; - for (; pos < len; ++pos) { - if (chunk[pos] === 38) - break; - ++self._bytesVal; - } - self._lastPos = pos; - } - return pos; - } - var HEX_VALUES = [ - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - 0, - 1, - 2, - 3, - 4, - 5, - 6, - 7, - 8, - 9, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - 10, - 11, - 12, - 13, - 14, - 15, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - 10, - 11, - 12, - 13, - 14, - 15, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1 - ]; - module2.exports = URLEncoded; + if (this._state === "key" && this._key.length > 0) { + this.boy.emit( + "field", + decodeText(this._key, "binary", this.charset), + "", + this._keyTrunc, + false + ); + } else if (this._state === "val") { + this.boy.emit( + "field", + decodeText(this._key, "binary", this.charset), + decodeText(this._val, "binary", this.charset), + this._keyTrunc, + this._valTrunc + ); + } + this.boy._done = true; + this.boy.emit("finish"); + }; + module2.exports = UrlEncoded; } }); -// node_modules/busboy/lib/index.js -var require_lib = __commonJS({ - "node_modules/busboy/lib/index.js"(exports2, module2) { +// node_modules/@fastify/busboy/lib/main.js +var require_main = __commonJS({ + "node_modules/@fastify/busboy/lib/main.js"(exports2, module2) { "use strict"; - var { parseContentType } = require_utils(); - function getInstance(cfg) { - const headers = cfg.headers; - const conType = parseContentType(headers["content-type"]); - if (!conType) - throw new Error("Malformed content type"); - for (const type of TYPES) { - const matched = type.detect(conType); - if (!matched) - continue; - const instanceCfg = { - limits: cfg.limits, - headers, - conType, - highWaterMark: void 0, - fileHwm: void 0, - defCharset: void 0, - defParamCharset: void 0, - preservePath: false - }; - if (cfg.highWaterMark) - instanceCfg.highWaterMark = cfg.highWaterMark; - if (cfg.fileHwm) - instanceCfg.fileHwm = cfg.fileHwm; - instanceCfg.defCharset = cfg.defCharset; - instanceCfg.defParamCharset = cfg.defParamCharset; - instanceCfg.preservePath = cfg.preservePath; - return new type(instanceCfg); - } - throw new Error(`Unsupported content type: ${headers["content-type"]}`); - } - var TYPES = [ - require_multipart(), - require_urlencoded() - ].filter(function(typemod) { - return typeof typemod.detect === "function"; - }); - module2.exports = (cfg) => { - if (typeof cfg !== "object" || cfg === null) - cfg = {}; - if (typeof cfg.headers !== "object" || cfg.headers === null || typeof cfg.headers["content-type"] !== "string") { - throw new Error("Missing Content-Type"); + var WritableStream = require("node:stream").Writable; + var { inherits } = require("node:util"); + var Dicer = require_Dicer(); + var MultipartParser = require_multipart(); + var UrlencodedParser = require_urlencoded(); + var parseParams = require_parseParams(); + function Busboy(opts) { + if (!(this instanceof Busboy)) { + return new Busboy(opts); + } + if (typeof opts !== "object") { + throw new TypeError("Busboy expected an options-Object."); + } + if (typeof opts.headers !== "object") { + throw new TypeError("Busboy expected an options-Object with headers-attribute."); + } + if (typeof opts.headers["content-type"] !== "string") { + throw new TypeError("Missing Content-Type-header."); + } + const { + headers, + ...streamOptions + } = opts; + this.opts = { + autoDestroy: false, + ...streamOptions + }; + WritableStream.call(this, this.opts); + this._done = false; + this._parser = this.getParserByHeaders(headers); + this._finished = false; + } + inherits(Busboy, WritableStream); + Busboy.prototype.emit = function(ev) { + if (ev === "finish") { + if (!this._done) { + this._parser?.end(); + return; + } else if (this._finished) { + return; + } + this._finished = true; + } + WritableStream.prototype.emit.apply(this, arguments); + }; + Busboy.prototype.getParserByHeaders = function(headers) { + const parsed = parseParams(headers["content-type"]); + const cfg = { + defCharset: this.opts.defCharset, + fileHwm: this.opts.fileHwm, + headers, + highWaterMark: this.opts.highWaterMark, + isPartAFile: this.opts.isPartAFile, + limits: this.opts.limits, + parsedConType: parsed, + preservePath: this.opts.preservePath + }; + if (MultipartParser.detect.test(parsed[0])) { + return new MultipartParser(this, cfg); + } + if (UrlencodedParser.detect.test(parsed[0])) { + return new UrlencodedParser(this, cfg); } - return getInstance(cfg); + throw new Error("Unsupported Content-Type."); }; + Busboy.prototype._write = function(chunk, encoding, cb) { + this._parser.write(chunk, cb); + }; + module2.exports = Busboy; + module2.exports.default = Busboy; + module2.exports.Busboy = Busboy; + module2.exports.Dicer = Dicer; } }); @@ -5791,7 +3578,11 @@ var require_dataURL = __commonJS({ let input = URLSerializer(dataURL, true); input = input.slice(5); const position = { position: 0 }; - let mimeType = collectASequenceOfCodePointsFast(",", input, position); + let mimeType = collectASequenceOfCodePointsFast( + ",", + input, + position + ); const mimeTypeLength = mimeType.length; mimeType = removeASCIIWhitespace(mimeType, true, true); if (position.position >= input.length) { @@ -5872,7 +3663,11 @@ var require_dataURL = __commonJS({ function parseMIMEType(input) { input = removeHTTPWhitespace(input, true, true); const position = { position: 0 }; - const type = collectASequenceOfCodePointsFast("/", input, position); + const type = collectASequenceOfCodePointsFast( + "/", + input, + position + ); if (type.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(type)) { return "failure"; } @@ -5880,7 +3675,11 @@ var require_dataURL = __commonJS({ return "failure"; } position.position++; - let subtype = collectASequenceOfCodePointsFast(";", input, position); + let subtype = collectASequenceOfCodePointsFast( + ";", + input, + position + ); subtype = removeHTTPWhitespace(subtype, false, true); if (subtype.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(subtype)) { return "failure"; @@ -5890,13 +3689,24 @@ var require_dataURL = __commonJS({ const mimeType = { type: typeLowercase, subtype: subtypeLowercase, + /** @type {Map} */ parameters: /* @__PURE__ */ new Map(), + // https://mimesniff.spec.whatwg.org/#mime-type-essence essence: `${typeLowercase}/${subtypeLowercase}` }; while (position.position < input.length) { position.position++; - collectASequenceOfCodePoints((char) => HTTP_WHITESPACE_REGEX.test(char), input, position); - let parameterName = collectASequenceOfCodePoints((char) => char !== ";" && char !== "=", input, position); + collectASequenceOfCodePoints( + // https://fetch.spec.whatwg.org/#http-whitespace + (char) => HTTP_WHITESPACE_REGEX.test(char), + input, + position + ); + let parameterName = collectASequenceOfCodePoints( + (char) => char !== ";" && char !== "=", + input, + position + ); parameterName = parameterName.toLowerCase(); if (position.position < input.length) { if (input[position.position] === ";") { @@ -5910,9 +3720,17 @@ var require_dataURL = __commonJS({ let parameterValue = null; if (input[position.position] === '"') { parameterValue = collectAnHTTPQuotedString(input, position, true); - collectASequenceOfCodePointsFast(";", input, position); + collectASequenceOfCodePointsFast( + ";", + input, + position + ); } else { - parameterValue = collectASequenceOfCodePointsFast(";", input, position); + parameterValue = collectASequenceOfCodePointsFast( + ";", + input, + position + ); parameterValue = removeHTTPWhitespace(parameterValue, false, true); if (parameterValue.length === 0) { continue; @@ -5948,7 +3766,11 @@ var require_dataURL = __commonJS({ assert(input[position.position] === '"'); position.position++; while (true) { - value += collectASequenceOfCodePoints((char) => char !== '"' && char !== "\\", input, position); + value += collectASequenceOfCodePoints( + (char) => char !== '"' && char !== "\\", + input, + position + ); if (position.position >= input.length) { break; } @@ -6044,7 +3866,7 @@ var require_file = __commonJS({ var { webidl } = require_webidl(); var { parseMIMEType, serializeAMimeType } = require_dataURL(); var { kEnumerableProperty } = require_util(); - var File = class extends Blob2 { + var File = class _File extends Blob2 { constructor(fileBits, fileName, options = {}) { webidl.argumentLengthCheck(arguments, 2, { header: "File constructor" }); fileBits = webidl.converters["sequence"](fileBits); @@ -6072,19 +3894,19 @@ var require_file = __commonJS({ }; } get name() { - webidl.brandCheck(this, File); + webidl.brandCheck(this, _File); return this[kState].name; } get lastModified() { - webidl.brandCheck(this, File); + webidl.brandCheck(this, _File); return this[kState].lastModified; } get type() { - webidl.brandCheck(this, File); + webidl.brandCheck(this, _File); return this[kState].type; } }; - var FileLike = class { + var FileLike = class _FileLike { constructor(blobLike, fileName, options = {}) { const n = fileName; const t = options.type; @@ -6097,35 +3919,35 @@ var require_file = __commonJS({ }; } stream(...args) { - webidl.brandCheck(this, FileLike); + webidl.brandCheck(this, _FileLike); return this[kState].blobLike.stream(...args); } arrayBuffer(...args) { - webidl.brandCheck(this, FileLike); + webidl.brandCheck(this, _FileLike); return this[kState].blobLike.arrayBuffer(...args); } slice(...args) { - webidl.brandCheck(this, FileLike); + webidl.brandCheck(this, _FileLike); return this[kState].blobLike.slice(...args); } text(...args) { - webidl.brandCheck(this, FileLike); + webidl.brandCheck(this, _FileLike); return this[kState].blobLike.text(...args); } get size() { - webidl.brandCheck(this, FileLike); + webidl.brandCheck(this, _FileLike); return this[kState].blobLike.size; } get type() { - webidl.brandCheck(this, FileLike); + webidl.brandCheck(this, _FileLike); return this[kState].blobLike.type; } get name() { - webidl.brandCheck(this, FileLike); + webidl.brandCheck(this, _FileLike); return this[kState].name; } get lastModified() { - webidl.brandCheck(this, FileLike); + webidl.brandCheck(this, _FileLike); return this[kState].lastModified; } get [Symbol.toStringTag]() { @@ -6152,7 +3974,9 @@ var require_file = __commonJS({ } return webidl.converters.USVString(V, opts); }; - webidl.converters["sequence"] = webidl.sequenceConverter(webidl.converters.BlobPart); + webidl.converters["sequence"] = webidl.sequenceConverter( + webidl.converters.BlobPart + ); webidl.converters.FilePropertyBag = webidl.dictionaryConverter([ { key: "lastModified", @@ -6192,7 +4016,9 @@ var require_file = __commonJS({ if (!element.buffer) { bytes.push(new Uint8Array(element)); } else { - bytes.push(new Uint8Array(element.buffer, element.byteOffset, element.byteLength)); + bytes.push( + new Uint8Array(element.buffer, element.byteOffset, element.byteLength) + ); } } else if (isBlobLike(element)) { bytes.push(element); @@ -6224,7 +4050,7 @@ var require_formdata = __commonJS({ var { webidl } = require_webidl(); var { Blob: Blob2, File: NativeFile } = require("buffer"); var File = NativeFile ?? UndiciFile; - var FormData = class { + var FormData = class _FormData { constructor(form) { if (form !== void 0) { throw webidl.errors.conversionFailed({ @@ -6236,10 +4062,12 @@ var require_formdata = __commonJS({ this[kState] = []; } append(name, value, filename = void 0) { - webidl.brandCheck(this, FormData); + webidl.brandCheck(this, _FormData); webidl.argumentLengthCheck(arguments, 2, { header: "FormData.append" }); if (arguments.length === 3 && !isBlobLike(value)) { - throw new TypeError("Failed to execute 'append' on 'FormData': parameter 2 is not of type 'Blob'"); + throw new TypeError( + "Failed to execute 'append' on 'FormData': parameter 2 is not of type 'Blob'" + ); } name = webidl.converters.USVString(name); value = isBlobLike(value) ? webidl.converters.Blob(value, { strict: false }) : webidl.converters.USVString(value); @@ -6248,13 +4076,13 @@ var require_formdata = __commonJS({ this[kState].push(entry); } delete(name) { - webidl.brandCheck(this, FormData); + webidl.brandCheck(this, _FormData); webidl.argumentLengthCheck(arguments, 1, { header: "FormData.delete" }); name = webidl.converters.USVString(name); this[kState] = this[kState].filter((entry) => entry.name !== name); } get(name) { - webidl.brandCheck(this, FormData); + webidl.brandCheck(this, _FormData); webidl.argumentLengthCheck(arguments, 1, { header: "FormData.get" }); name = webidl.converters.USVString(name); const idx = this[kState].findIndex((entry) => entry.name === name); @@ -6264,22 +4092,24 @@ var require_formdata = __commonJS({ return this[kState][idx].value; } getAll(name) { - webidl.brandCheck(this, FormData); + webidl.brandCheck(this, _FormData); webidl.argumentLengthCheck(arguments, 1, { header: "FormData.getAll" }); name = webidl.converters.USVString(name); return this[kState].filter((entry) => entry.name === name).map((entry) => entry.value); } has(name) { - webidl.brandCheck(this, FormData); + webidl.brandCheck(this, _FormData); webidl.argumentLengthCheck(arguments, 1, { header: "FormData.has" }); name = webidl.converters.USVString(name); return this[kState].findIndex((entry) => entry.name === name) !== -1; } set(name, value, filename = void 0) { - webidl.brandCheck(this, FormData); + webidl.brandCheck(this, _FormData); webidl.argumentLengthCheck(arguments, 2, { header: "FormData.set" }); if (arguments.length === 3 && !isBlobLike(value)) { - throw new TypeError("Failed to execute 'set' on 'FormData': parameter 2 is not of type 'Blob'"); + throw new TypeError( + "Failed to execute 'set' on 'FormData': parameter 2 is not of type 'Blob'" + ); } name = webidl.converters.USVString(name); value = isBlobLike(value) ? webidl.converters.Blob(value, { strict: false }) : webidl.converters.USVString(value); @@ -6297,22 +4127,40 @@ var require_formdata = __commonJS({ } } entries() { - webidl.brandCheck(this, FormData); - return makeIterator(() => this[kState].map((pair) => [pair.name, pair.value]), "FormData", "key+value"); + webidl.brandCheck(this, _FormData); + return makeIterator( + () => this[kState].map((pair) => [pair.name, pair.value]), + "FormData", + "key+value" + ); } keys() { - webidl.brandCheck(this, FormData); - return makeIterator(() => this[kState].map((pair) => [pair.name, pair.value]), "FormData", "key"); + webidl.brandCheck(this, _FormData); + return makeIterator( + () => this[kState].map((pair) => [pair.name, pair.value]), + "FormData", + "key" + ); } values() { - webidl.brandCheck(this, FormData); - return makeIterator(() => this[kState].map((pair) => [pair.name, pair.value]), "FormData", "value"); - } + webidl.brandCheck(this, _FormData); + return makeIterator( + () => this[kState].map((pair) => [pair.name, pair.value]), + "FormData", + "value" + ); + } + /** + * @param {(value: string, key: string, self: FormData) => void} callbackFn + * @param {unknown} thisArg + */ forEach(callbackFn, thisArg = globalThis) { - webidl.brandCheck(this, FormData); + webidl.brandCheck(this, _FormData); webidl.argumentLengthCheck(arguments, 1, { header: "FormData.forEach" }); if (typeof callbackFn !== "function") { - throw new TypeError("Failed to execute 'forEach' on 'FormData': parameter 1 is not of type 'Function'."); + throw new TypeError( + "Failed to execute 'forEach' on 'FormData': parameter 1 is not of type 'Function'." + ); } for (const [key, value] of this) { callbackFn.apply(thisArg, [value, key, this]); @@ -6352,7 +4200,7 @@ var require_formdata = __commonJS({ var require_body = __commonJS({ "lib/fetch/body.js"(exports2, module2) { "use strict"; - var Busboy = require_lib(); + var Busboy = require_main(); var util = require_util(); var { ReadableStreamFrom, @@ -6387,7 +4235,9 @@ var require_body = __commonJS({ } else { stream = new ReadableStream({ async pull(controller) { - controller.enqueue(typeof source === "string" ? new TextEncoder().encode(source) : source); + controller.enqueue( + typeof source === "string" ? new TextEncoder().encode(source) : source + ); queueMicrotask(() => readableStreamClose(controller)); }, start() { @@ -6470,7 +4320,9 @@ Content-Type: ${value.type || "application/octet-stream"}\r throw new TypeError("keepalive"); } if (util.isDisturbed(object) || object.locked) { - throw new TypeError("Response body object should not be disturbed or locked"); + throw new TypeError( + "Response body object should not be disturbed or locked" + ); } stream = object instanceof ReadableStream ? object : ReadableStreamFrom(object); } @@ -6583,10 +4435,9 @@ Content-Type: ${value.type || "application/octet-stream"}\r const responseFormData = new FormData(); let busboy; try { - busboy = Busboy({ + busboy = new Busboy({ headers, - preservePath: true, - defParamCharset: "utf8" + preservePath: true }); } catch (err) { throw new DOMException(`${err}`, "AbortError"); @@ -6594,8 +4445,7 @@ Content-Type: ${value.type || "application/octet-stream"}\r busboy.on("field", (name, value) => { responseFormData.append(name, value); }); - busboy.on("file", (name, value, info) => { - const { filename, encoding, mimeType } = info; + busboy.on("file", (name, value, filename, encoding, mimeType) => { const chunks = []; if (encoding === "base64" || encoding.toLowerCase() === "base64") { let base64chunk = ""; @@ -6750,10 +4600,11 @@ var require_response = __commonJS({ var assert = require("assert"); var { types } = require("util"); var ReadableStream = globalThis.ReadableStream || require("stream/web").ReadableStream; - var Response = class { + var Response = class _Response { + // Creates network error Response. static error() { const relevantRealm = { settingsObject: {} }; - const responseObject = new Response(); + const responseObject = new _Response(); responseObject[kState] = makeNetworkError(); responseObject[kRealm] = relevantRealm; responseObject[kHeaders][kHeadersList] = responseObject[kState].headersList; @@ -6761,21 +4612,25 @@ var require_response = __commonJS({ responseObject[kHeaders][kRealm] = relevantRealm; return responseObject; } + // https://fetch.spec.whatwg.org/#dom-response-json static json(data, init = {}) { webidl.argumentLengthCheck(arguments, 1, { header: "Response.json" }); if (init !== null) { init = webidl.converters.ResponseInit(init); } - const bytes = new TextEncoder("utf-8").encode(serializeJavascriptValueToJSONString(data)); + const bytes = new TextEncoder("utf-8").encode( + serializeJavascriptValueToJSONString(data) + ); const body = extractBody(bytes); const relevantRealm = { settingsObject: {} }; - const responseObject = new Response(); + const responseObject = new _Response(); responseObject[kRealm] = relevantRealm; responseObject[kHeaders][kGuard] = "response"; responseObject[kHeaders][kRealm] = relevantRealm; initializeResponse(responseObject, init, { body: body[0], type: "application/json" }); return responseObject; } + // Creates a redirect Response that redirects to url with status status. static redirect(url, status = 302) { const relevantRealm = { settingsObject: {} }; webidl.argumentLengthCheck(arguments, 1, { header: "Response.redirect" }); @@ -6792,7 +4647,7 @@ var require_response = __commonJS({ if (!redirectStatus.includes(status)) { throw new RangeError("Invalid status code " + status); } - const responseObject = new Response(); + const responseObject = new _Response(); responseObject[kRealm] = relevantRealm; responseObject[kHeaders][kGuard] = "immutable"; responseObject[kHeaders][kRealm] = relevantRealm; @@ -6801,6 +4656,7 @@ var require_response = __commonJS({ responseObject[kState].headersList.append("location", value); return responseObject; } + // https://fetch.spec.whatwg.org/#dom-response constructor(body = null, init = {}) { if (body !== null) { body = webidl.converters.BodyInit(body); @@ -6819,12 +4675,14 @@ var require_response = __commonJS({ } initializeResponse(this, init, bodyWithType); } + // Returns response’s type, e.g., "cors". get type() { - webidl.brandCheck(this, Response); + webidl.brandCheck(this, _Response); return this[kState].type; } + // Returns response’s URL, if it has one; otherwise the empty string. get url() { - webidl.brandCheck(this, Response); + webidl.brandCheck(this, _Response); const urlList = this[kState].urlList; const url = urlList[urlList.length - 1] ?? null; if (url === null) { @@ -6832,36 +4690,42 @@ var require_response = __commonJS({ } return URLSerializer(url, true); } + // Returns whether response was obtained through a redirect. get redirected() { - webidl.brandCheck(this, Response); + webidl.brandCheck(this, _Response); return this[kState].urlList.length > 1; } + // Returns response’s status. get status() { - webidl.brandCheck(this, Response); + webidl.brandCheck(this, _Response); return this[kState].status; } + // Returns whether response’s status is an ok status. get ok() { - webidl.brandCheck(this, Response); + webidl.brandCheck(this, _Response); return this[kState].status >= 200 && this[kState].status <= 299; } + // Returns response’s status message. get statusText() { - webidl.brandCheck(this, Response); + webidl.brandCheck(this, _Response); return this[kState].statusText; } + // Returns response’s headers as Headers. get headers() { - webidl.brandCheck(this, Response); + webidl.brandCheck(this, _Response); return this[kHeaders]; } get body() { - webidl.brandCheck(this, Response); + webidl.brandCheck(this, _Response); return this[kState].body ? this[kState].body.stream : null; } get bodyUsed() { - webidl.brandCheck(this, Response); + webidl.brandCheck(this, _Response); return !!this[kState].body && util.isDisturbed(this[kState].body.stream); } + // Returns a clone of response. clone() { - webidl.brandCheck(this, Response); + webidl.brandCheck(this, _Response); if (this.bodyUsed || this.body && this.body.locked) { throw webidl.errors.exception({ header: "Response.clone", @@ -6869,7 +4733,7 @@ var require_response = __commonJS({ }); } const clonedResponse = cloneResponse(this[kState]); - const clonedResponseObject = new Response(); + const clonedResponseObject = new _Response(); clonedResponseObject[kState] = clonedResponse; clonedResponseObject[kRealm] = this[kRealm]; clonedResponseObject[kHeaders][kHeadersList] = clonedResponse.headersList; @@ -6902,7 +4766,10 @@ var require_response = __commonJS({ }); function cloneResponse(response) { if (response.internalResponse) { - return filterResponse(cloneResponse(response.internalResponse), response.type); + return filterResponse( + cloneResponse(response.internalResponse), + response.type + ); } const newResponse = makeResponse({ ...response, body: null }); if (response.body != null) { @@ -7017,9 +4884,15 @@ var require_response = __commonJS({ } } } - webidl.converters.ReadableStream = webidl.interfaceConverter(ReadableStream); - webidl.converters.FormData = webidl.interfaceConverter(FormData); - webidl.converters.URLSearchParams = webidl.interfaceConverter(URLSearchParams); + webidl.converters.ReadableStream = webidl.interfaceConverter( + ReadableStream + ); + webidl.converters.FormData = webidl.interfaceConverter( + FormData + ); + webidl.converters.URLSearchParams = webidl.interfaceConverter( + URLSearchParams + ); webidl.converters.XMLHttpRequestBodyInit = function(V) { if (typeof V === "string") { return webidl.converters.USVString(V); @@ -7092,14 +4965,22 @@ var require_dispatcher_weakref = __commonJS({ this.finalizer = finalizer; } register(dispatcher, key) { - dispatcher.on("disconnect", () => { - if (dispatcher[kConnected] === 0 && dispatcher[kSize] === 0) { - this.finalizer(key); - } - }); + if (dispatcher.on) { + dispatcher.on("disconnect", () => { + if (dispatcher[kConnected] === 0 && dispatcher[kSize] === 0) { + this.finalizer(key); + } + }); + } } }; module2.exports = function() { + if (process.env.NODE_V8_COVERAGE) { + return { + WeakRef: CompatWeakRef, + FinalizationRegistry: CompatFinalizer + }; + } return { WeakRef: global.WeakRef || CompatWeakRef, FinalizationRegistry: global.FinalizationRegistry || CompatFinalizer @@ -7146,7 +5027,8 @@ var require_request = __commonJS({ var requestFinalizer = new FinalizationRegistry(({ signal, abort }) => { signal.removeEventListener("abort", abort); }); - var Request = class { + var Request = class _Request { + // https://fetch.spec.whatwg.org/#dom-request constructor(input, init = {}) { if (input === kInit) { return; @@ -7175,12 +5057,14 @@ var require_request = __commonJS({ throw new TypeError("Failed to parse URL from " + input, { cause: err }); } if (parsedURL.username || parsedURL.password) { - throw new TypeError("Request cannot be constructed from a URL that includes credentials: " + input); + throw new TypeError( + "Request cannot be constructed from a URL that includes credentials: " + input + ); } request = makeRequest({ urlList: [parsedURL] }); fallbackMode = "cors"; } else { - assert(input instanceof Request); + assert(input instanceof _Request); request = input[kState]; signal = input[kSignal]; } @@ -7196,23 +5080,46 @@ var require_request = __commonJS({ window = "no-window"; } request = makeRequest({ + // URL request’s URL. + // undici implementation note: this is set as the first item in request's urlList in makeRequest + // method request’s method. method: request.method, + // header list A copy of request’s header list. + // undici implementation note: headersList is cloned in makeRequest headersList: request.headersList, + // unsafe-request flag Set. unsafeRequest: request.unsafeRequest, + // client This’s relevant settings object. client: this[kRealm].settingsObject, + // window window. window, + // priority request’s priority. priority: request.priority, + // origin request’s origin. The propagation of the origin is only significant for navigation requests + // being handled by a service worker. In this scenario a request can have an origin that is different + // from the current client. origin: request.origin, + // referrer request’s referrer. referrer: request.referrer, + // referrer policy request’s referrer policy. referrerPolicy: request.referrerPolicy, + // mode request’s mode. mode: request.mode, + // credentials mode request’s credentials mode. credentials: request.credentials, + // cache mode request’s cache mode. cache: request.cache, + // redirect mode request’s redirect mode. redirect: request.redirect, + // integrity metadata request’s integrity metadata. integrity: request.integrity, + // keepalive request’s keepalive. keepalive: request.keepalive, + // reload-navigation flag request’s reload-navigation flag. reloadNavigation: request.reloadNavigation, + // history-navigation flag request’s history-navigation flag. historyNavigation: request.historyNavigation, + // URL list A clone of request’s URL list. urlList: [...request.urlList] }); if (Object.keys(init).length > 0) { @@ -7270,7 +5177,9 @@ var require_request = __commonJS({ request.cache = init.cache; } if (request.cache === "only-if-cached" && request.mode !== "same-origin") { - throw new TypeError("'only-if-cached' can be set only with 'same-origin' mode"); + throw new TypeError( + "'only-if-cached' can be set only with 'same-origin' mode" + ); } if (init.redirect !== void 0) { request.redirect = init.redirect; @@ -7301,7 +5210,9 @@ var require_request = __commonJS({ this[kSignal][kRealm] = this[kRealm]; if (signal != null) { if (!signal || typeof signal.aborted !== "boolean" || typeof signal.addEventListener !== "function") { - throw new TypeError("Failed to construct 'Request': member signal is not of type AbortSignal."); + throw new TypeError( + "Failed to construct 'Request': member signal is not of type AbortSignal." + ); } if (signal.aborted) { ac.abort(signal.reason); @@ -7332,7 +5243,9 @@ var require_request = __commonJS({ this[kHeaders][kRealm] = this[kRealm]; if (mode === "no-cors") { if (!corsSafeListedMethods.includes(request.method)) { - throw new TypeError(`'${request.method} is unsupported in no-cors mode.`); + throw new TypeError( + `'${request.method} is unsupported in no-cors mode.` + ); } this[kHeaders][kGuard] = "request-no-cors"; } @@ -7350,13 +5263,16 @@ var require_request = __commonJS({ fillHeaders(this[kHeaders], headers); } } - const inputBody = input instanceof Request ? input[kState].body : null; + const inputBody = input instanceof _Request ? input[kState].body : null; if ((init.body != null || inputBody != null) && (request.method === "GET" || request.method === "HEAD")) { throw new TypeError("Request with GET/HEAD method cannot have body."); } let initBody = null; if (init.body != null) { - const [extractedBody, contentType] = extractBody(init.body, request.keepalive); + const [extractedBody, contentType] = extractBody( + init.body, + request.keepalive + ); initBody = extractedBody; if (contentType && !this[kHeaders][kHeadersList].contains("content-type")) { this[kHeaders].append("content-type", contentType); @@ -7368,14 +5284,18 @@ var require_request = __commonJS({ throw new TypeError("RequestInit: duplex option is required when sending a body."); } if (request.mode !== "same-origin" && request.mode !== "cors") { - throw new TypeError('If request is made from ReadableStream, mode should be "same-origin" or "cors"'); + throw new TypeError( + 'If request is made from ReadableStream, mode should be "same-origin" or "cors"' + ); } request.useCORSPreflightFlag = true; } let finalBody = inputOrInitBody; if (initBody == null && inputBody != null) { if (util.isDisturbed(inputBody.stream) || inputBody.stream.locked) { - throw new TypeError("Cannot construct a Request with a Request object that has already been used."); + throw new TypeError( + "Cannot construct a Request with a Request object that has already been used." + ); } if (!TransformStream) { TransformStream = require("stream/web").TransformStream; @@ -7390,24 +5310,36 @@ var require_request = __commonJS({ } this[kState].body = finalBody; } + // Returns request’s HTTP method, which is "GET" by default. get method() { - webidl.brandCheck(this, Request); + webidl.brandCheck(this, _Request); return this[kState].method; } + // Returns the URL of request as a string. get url() { - webidl.brandCheck(this, Request); + webidl.brandCheck(this, _Request); return URLSerializer(this[kState].url); } + // Returns a Headers object consisting of the headers associated with request. + // Note that headers added in the network layer by the user agent will not + // be accounted for in this object, e.g., the "Host" header. get headers() { - webidl.brandCheck(this, Request); + webidl.brandCheck(this, _Request); return this[kHeaders]; } + // Returns the kind of resource requested by request, e.g., "document" + // or "script". get destination() { - webidl.brandCheck(this, Request); + webidl.brandCheck(this, _Request); return this[kState].destination; } + // Returns the referrer of request. Its value can be a same-origin URL if + // explicitly set in init, the empty string to indicate no referrer, and + // "about:client" when defaulting to the global’s default. This is used + // during fetching to determine the value of the `Referer` header of the + // request being made. get referrer() { - webidl.brandCheck(this, Request); + webidl.brandCheck(this, _Request); if (this[kState].referrer === "no-referrer") { return ""; } @@ -7416,64 +5348,93 @@ var require_request = __commonJS({ } return this[kState].referrer.toString(); } + // Returns the referrer policy associated with request. + // This is used during fetching to compute the value of the request’s + // referrer. get referrerPolicy() { - webidl.brandCheck(this, Request); + webidl.brandCheck(this, _Request); return this[kState].referrerPolicy; } + // Returns the mode associated with request, which is a string indicating + // whether the request will use CORS, or will be restricted to same-origin + // URLs. get mode() { - webidl.brandCheck(this, Request); + webidl.brandCheck(this, _Request); return this[kState].mode; } + // Returns the credentials mode associated with request, + // which is a string indicating whether credentials will be sent with the + // request always, never, or only when sent to a same-origin URL. get credentials() { return this[kState].credentials; } + // Returns the cache mode associated with request, + // which is a string indicating how the request will + // interact with the browser’s cache when fetching. get cache() { - webidl.brandCheck(this, Request); + webidl.brandCheck(this, _Request); return this[kState].cache; } + // Returns the redirect mode associated with request, + // which is a string indicating how redirects for the + // request will be handled during fetching. A request + // will follow redirects by default. get redirect() { - webidl.brandCheck(this, Request); + webidl.brandCheck(this, _Request); return this[kState].redirect; } + // Returns request’s subresource integrity metadata, which is a + // cryptographic hash of the resource being fetched. Its value + // consists of multiple hashes separated by whitespace. [SRI] get integrity() { - webidl.brandCheck(this, Request); + webidl.brandCheck(this, _Request); return this[kState].integrity; } + // Returns a boolean indicating whether or not request can outlive the + // global in which it was created. get keepalive() { - webidl.brandCheck(this, Request); + webidl.brandCheck(this, _Request); return this[kState].keepalive; } + // Returns a boolean indicating whether or not request is for a reload + // navigation. get isReloadNavigation() { - webidl.brandCheck(this, Request); + webidl.brandCheck(this, _Request); return this[kState].reloadNavigation; } + // Returns a boolean indicating whether or not request is for a history + // navigation (a.k.a. back-foward navigation). get isHistoryNavigation() { - webidl.brandCheck(this, Request); + webidl.brandCheck(this, _Request); return this[kState].historyNavigation; } + // Returns the signal associated with request, which is an AbortSignal + // object indicating whether or not request has been aborted, and its + // abort event handler. get signal() { - webidl.brandCheck(this, Request); + webidl.brandCheck(this, _Request); return this[kSignal]; } get body() { - webidl.brandCheck(this, Request); + webidl.brandCheck(this, _Request); return this[kState].body ? this[kState].body.stream : null; } get bodyUsed() { - webidl.brandCheck(this, Request); + webidl.brandCheck(this, _Request); return !!this[kState].body && util.isDisturbed(this[kState].body.stream); } get duplex() { - webidl.brandCheck(this, Request); + webidl.brandCheck(this, _Request); return "half"; } + // Returns a clone of request. clone() { - webidl.brandCheck(this, Request); + webidl.brandCheck(this, _Request); if (this.bodyUsed || this.body?.locked) { throw new TypeError("unusable"); } const clonedRequest = cloneRequest(this[kState]); - const clonedRequestObject = new Request(kInit); + const clonedRequestObject = new _Request(kInit); clonedRequestObject[kState] = clonedRequest; clonedRequestObject[kRealm] = this[kRealm]; clonedRequestObject[kHeaders] = new Headers(); @@ -7484,9 +5445,12 @@ var require_request = __commonJS({ if (this.signal.aborted) { ac.abort(this.signal.reason); } else { - util.addAbortListener(this.signal, () => { - ac.abort(this.signal.reason); - }); + util.addAbortListener( + this.signal, + () => { + ac.abort(this.signal.reason); + } + ); } clonedRequestObject[kSignal] = ac.signal; return clonedRequestObject; @@ -7569,7 +5533,9 @@ var require_request = __commonJS({ configurable: true } }); - webidl.converters.Request = webidl.interfaceConverter(Request); + webidl.converters.Request = webidl.interfaceConverter( + Request + ); webidl.converters.RequestInfo = function(V) { if (typeof V === "string") { return webidl.converters.USVString(V); @@ -7579,7 +5545,9 @@ var require_request = __commonJS({ } return webidl.converters.USVString(V); }; - webidl.converters.AbortSignal = webidl.interfaceConverter(AbortSignal); + webidl.converters.AbortSignal = webidl.interfaceConverter( + AbortSignal + ); webidl.converters.RequestInit = webidl.dictionaryConverter([ { key: "method", @@ -7591,7 +5559,9 @@ var require_request = __commonJS({ }, { key: "body", - converter: webidl.nullableConverter(webidl.converters.BodyInit) + converter: webidl.nullableConverter( + webidl.converters.BodyInit + ) }, { key: "referrer", @@ -7600,26 +5570,31 @@ var require_request = __commonJS({ { key: "referrerPolicy", converter: webidl.converters.DOMString, + // https://w3c.github.io/webappsec-referrer-policy/#referrer-policy allowedValues: referrerPolicy }, { key: "mode", converter: webidl.converters.DOMString, + // https://fetch.spec.whatwg.org/#concept-request-mode allowedValues: requestMode }, { key: "credentials", converter: webidl.converters.DOMString, + // https://fetch.spec.whatwg.org/#requestcredentials allowedValues: requestCredentials }, { key: "cache", converter: webidl.converters.DOMString, + // https://fetch.spec.whatwg.org/#requestcache allowedValues: requestCache }, { key: "redirect", converter: webidl.converters.DOMString, + // https://fetch.spec.whatwg.org/#requestredirect allowedValues: requestRedirect }, { @@ -7632,7 +5607,12 @@ var require_request = __commonJS({ }, { key: "signal", - converter: webidl.nullableConverter((signal) => webidl.converters.AbortSignal(signal, { strict: false })) + converter: webidl.nullableConverter( + (signal) => webidl.converters.AbortSignal( + signal, + { strict: false } + ) + ) }, { key: "window", @@ -7756,7 +5736,10 @@ var require_dispatcher_base = __commonJS({ if (callback === void 0) { return new Promise((resolve, reject) => { this.destroy(err, (err2, data) => { - return err2 ? reject(err2) : resolve(data); + return err2 ? ( + /* istanbul ignore next: should never error */ + reject(err2) + ) : resolve(data); }); }); } @@ -8185,7 +6168,7 @@ var require_request2 = __commonJS({ channels.trailers = { hasSubscribers: false }; channels.error = { hasSubscribers: false }; } - var Request = class { + var Request = class _Request { constructor(origin, { path, method, @@ -8360,17 +6343,18 @@ var require_request2 = __commonJS({ this.aborted = true; return this[kHandler].onError(error); } + // TODO: adjust to support H2 addHeader(key, value) { processHeader(this, key, value); return this; } static [kHTTP1BuildRequest](origin, opts, handler) { - return new Request(origin, opts, handler); + return new _Request(origin, opts, handler); } static [kHTTP2BuildRequest](origin, opts, handler) { const headers = opts.headers; opts = { ...opts, headers: null }; - const request = new Request(origin, opts, handler); + const request = new _Request(origin, opts, handler); request.headers = {}; if (Array.isArray(headers)) { if (headers.length % 2 !== 0) { @@ -8434,7 +6418,10 @@ var require_request2 = __commonJS({ } } else if (request.contentType === null && key.length === 12 && key.toLowerCase() === "content-type") { request.contentType = val; - request.headers += processHeaderValue(key, val); + if (skipAppend) + request.headers[key] = processHeaderValue(key, val, skipAppend); + else + request.headers += processHeaderValue(key, val); } else if (key.length === 17 && key.toLowerCase() === "transfer-encoding") { throw new InvalidArgumentError("invalid transfer-encoding header"); } else if (key.length === 10 && key.toLowerCase() === "connection") { @@ -8486,7 +6473,7 @@ var require_connect = __commonJS({ var { InvalidArgumentError, ConnectTimeoutError } = require_errors(); var tls; var SessionCache; - if (global.FinalizationRegistry) { + if (global.FinalizationRegistry && !process.env.NODE_V8_COVERAGE) { SessionCache = class WeakSessionCache { constructor(maxCachedSessions) { this._maxCachedSessions = maxCachedSessions; @@ -8554,12 +6541,15 @@ var require_connect = __commonJS({ assert(sessionKey); socket = tls.connect({ highWaterMark: 16384, + // TLS in node can't have bigger HWM anyway... ...options, servername, session, localAddress, + // TODO(HTTP/2): Add support for h2c ALPNProtocols: allowH2 ? ["http/1.1", "h2"] : ["http/1.1"], socket: httpSocket, + // upgrade socket connection port: port || 443, host: hostname }); @@ -8570,6 +6560,7 @@ var require_connect = __commonJS({ assert(!httpSocket, "httpSocket can only be sent on TLS update"); socket = net.connect({ highWaterMark: 64 * 1024, + // Same as nodejs fs streams. ...options, localAddress, port: port || 80, @@ -8629,7 +6620,7 @@ var require_connect = __commonJS({ }); // lib/llhttp/utils.js -var require_utils2 = __commonJS({ +var require_utils = __commonJS({ "lib/llhttp/utils.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); @@ -8654,7 +6645,7 @@ var require_constants2 = __commonJS({ "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.SPECIAL_HEADERS = exports2.HEADER_STATE = exports2.MINOR = exports2.MAJOR = exports2.CONNECTION_TOKEN_CHARS = exports2.HEADER_CHARS = exports2.TOKEN = exports2.STRICT_TOKEN = exports2.HEX = exports2.URL_CHAR = exports2.STRICT_URL_CHAR = exports2.USERINFO_CHARS = exports2.MARK = exports2.ALPHANUM = exports2.NUM = exports2.HEX_MAP = exports2.NUM_MAP = exports2.ALPHA = exports2.FINISH = exports2.H_METHOD_MAP = exports2.METHOD_MAP = exports2.METHODS_RTSP = exports2.METHODS_ICE = exports2.METHODS_HTTP = exports2.METHODS = exports2.LENIENT_FLAGS = exports2.FLAGS = exports2.TYPE = exports2.ERROR = void 0; - var utils_1 = require_utils2(); + var utils_1 = require_utils(); var ERROR; (function(ERROR2) { ERROR2[ERROR2["OK"] = 0] = "OK"; @@ -8791,6 +6782,7 @@ var require_constants2 = __commonJS({ METHODS.LINK, METHODS.UNLINK, METHODS.PRI, + // TODO(indutny): should we allow it with HTTP? METHODS.SOURCE ]; exports2.METHODS_ICE = [ @@ -8809,6 +6801,7 @@ var require_constants2 = __commonJS({ METHODS.REDIRECT, METHODS.RECORD, METHODS.FLUSH, + // For AirPlay METHODS.GET, METHODS.POST ]; @@ -9149,6 +7142,7 @@ var require_client = __commonJS({ "use strict"; var assert = require("assert"); var net = require("net"); + var http = require("http"); var { pipeline } = require("stream"); var util = require_util(); var timers = require_timers(); @@ -9213,6 +7207,7 @@ var require_client = __commonJS({ kLocalAddress, kMaxResponseSize, kHTTPConnVersion, + // HTTP2 kHost, kHTTP2Session, kHTTP2SessionState, @@ -9231,6 +7226,7 @@ var require_client = __commonJS({ HTTP2_HEADER_AUTHORITY, HTTP2_HEADER_METHOD, HTTP2_HEADER_PATH, + HTTP2_HEADER_SCHEME, HTTP2_HEADER_CONTENT_LENGTH, HTTP2_HEADER_EXPECT, HTTP2_HEADER_STATUS @@ -9253,6 +7249,11 @@ var require_client = __commonJS({ channels.connected = { hasSubscribers: false }; } var Client = class extends DispatcherBase { + /** + * + * @param {string|URL} url + * @param {import('../types/client').Client.Options} options + */ constructor(url, { interceptors, maxHeaderSize, @@ -9279,6 +7280,7 @@ var require_client = __commonJS({ maxResponseSize, autoSelectFamily, autoSelectFamilyAttemptTimeout, + // h2 allowH2, maxConcurrentStreams } = {}) { @@ -9362,7 +7364,7 @@ var require_client = __commonJS({ this[kConnector] = connect2; this[kSocket] = null; this[kPipelining] = pipelining != null ? pipelining : 1; - this[kMaxHeadersSize] = maxHeaderSize || 16384; + this[kMaxHeadersSize] = maxHeaderSize || http.maxHeaderSize; this[kKeepAliveDefaultTimeout] = keepAliveTimeout == null ? 4e3 : keepAliveTimeout; this[kKeepAliveMaxTimeout] = keepAliveMaxTimeout == null ? 6e5 : keepAliveMaxTimeout; this[kKeepAliveTimeoutThreshold] = keepAliveTimeoutThreshold == null ? 1e3 : keepAliveTimeoutThreshold; @@ -9383,8 +7385,11 @@ var require_client = __commonJS({ this[kHTTPConnVersion] = "h1"; this[kHTTP2Session] = null; this[kHTTP2SessionState] = !allowH2 ? null : { + // streams: null, // Fixed queue of streams - For future support of `push` openStreams: 0, + // Keep track of them to decide wether or not unref the session maxConcurrentStreams: maxConcurrentStreams != null ? maxConcurrentStreams : 100 + // Max peerConcurrentStreams for a Node h2 server }; this[kHost] = `${this[kUrl].hostname}${this[kUrl].port ? `:${this[kUrl].port}` : ""}`; this[kQueue] = []; @@ -9414,6 +7419,7 @@ var require_client = __commonJS({ const socket = this[kSocket]; return socket && (socket[kReset] || socket[kWriting] || socket[kBlocking]) || this[kSize] >= (this[kPipelining] || 1) || this[kPending] > 0; } + /* istanbul ignore: only used for test */ [kConnect](cb) { connect(this); this.once("connect", cb); @@ -9506,7 +7512,12 @@ var require_client = __commonJS({ } client[kPendingIdx] = client[kRunningIdx]; assert(client[kRunning] === 0); - client.emit("disconnect", client[kUrl], [client], err); + client.emit( + "disconnect", + client[kUrl], + [client], + err + ); resume(client); } var constants = require_constants2(); @@ -9522,6 +7533,7 @@ var require_client = __commonJS({ } return await WebAssembly.instantiate(mod, { env: { + /* eslint-disable camelcase */ wasm_on_url: (p, at, len) => { return 0; }, @@ -9557,6 +7569,7 @@ var require_client = __commonJS({ assert.strictEqual(currentParser.ptr, p); return currentParser.onMessageComplete() || 0; } + /* eslint-enable camelcase */ } }); } @@ -9793,7 +7806,8 @@ var require_client = __commonJS({ } assert.strictEqual(this.timeoutType, TIMEOUT_HEADERS); this.statusCode = statusCode; - this.shouldKeepAlive = shouldKeepAlive || request.method === "HEAD" && !socket[kReset] && this.connection.toLowerCase() === "keep-alive"; + this.shouldKeepAlive = shouldKeepAlive || // Override llhttp value which does not allow keepAlive for HEAD. + request.method === "HEAD" && !socket[kReset] && this.connection.toLowerCase() === "keep-alive"; if (this.statusCode >= 200) { const bodyTimeout = request.bodyTimeout != null ? request.bodyTimeout : client[kBodyTimeout]; this.setTimeout(bodyTimeout, TIMEOUT_BODY); @@ -9818,7 +7832,10 @@ var require_client = __commonJS({ if (this.shouldKeepAlive && client[kPipelining]) { const keepAliveTimeout = this.keepAlive ? util.parseKeepAliveTimeout(this.keepAlive) : null; if (keepAliveTimeout != null) { - const timeout = Math.min(keepAliveTimeout - client[kKeepAliveTimeoutThreshold], client[kKeepAliveMaxTimeout]); + const timeout = Math.min( + keepAliveTimeout - client[kKeepAliveTimeoutThreshold], + client[kKeepAliveMaxTimeout] + ); if (timeout <= 0) { socket[kReset] = true; } else { @@ -10240,9 +8257,13 @@ var require_client = __commonJS({ return; } if (util.isStream(request.body) && util.bodyLength(request.body) === 0) { - request.body.on("data", function() { - assert(false); - }).on("error", function(err) { + request.body.on( + "data", + /* istanbul ignore next */ + function() { + assert(false); + } + ).on("error", function(err) { errorRequest(client, request, err); }).on("end", function() { util.destroy(this); @@ -10402,7 +8423,7 @@ upgrade: ${upgrade}\r let stream; const h2State = client[kHTTP2SessionState]; headers[HTTP2_HEADER_AUTHORITY] = host || client[kHost]; - headers[HTTP2_HEADER_PATH] = path; + headers[HTTP2_HEADER_METHOD] = method; if (method === "CONNECT") { session.ref(); stream = session.request(headers, { endStream: false, signal }); @@ -10421,9 +8442,9 @@ upgrade: ${upgrade}\r session.unref(); }); return true; - } else { - headers[HTTP2_HEADER_METHOD] = method; } + headers[HTTP2_HEADER_PATH] = path; + headers[HTTP2_HEADER_SCHEME] = "https"; const expectsPayload = method === "PUT" || method === "POST" || method === "PATCH"; if (body && typeof body.read === "function") { body.read(0); @@ -10500,6 +8521,7 @@ upgrade: ${upgrade}\r stream.cork(); stream.write(body); stream.uncork(); + stream.end(); request.onBodySent(body); request.onRequestSent(); } else if (util.isBlobLike(body)) { @@ -10559,14 +8581,18 @@ upgrade: ${upgrade}\r let onPipeData = function(chunk) { request.onBodySent(chunk); }; - const pipe = pipeline(body, h2stream, (err) => { - if (err) { - util.destroy(body, err); - util.destroy(h2stream, err); - } else { - request.onRequestSent(); + const pipe = pipeline( + body, + h2stream, + (err) => { + if (err) { + util.destroy(body, err); + util.destroy(h2stream, err); + } else { + request.onRequestSent(); + } } - }); + ); pipe.on("data", onPipeData); pipe.once("end", () => { pipe.removeListener("data", onPipeData); @@ -10682,13 +8708,17 @@ upgrade: ${upgrade}\r if (socket[kError]) { throw socket[kError]; } - if (!h2stream.write(chunk)) { + const res = h2stream.write(chunk); + request.onBodySent(chunk); + if (!res) { await waitForDrain(); } } } catch (err) { h2stream.destroy(err); } finally { + request.onRequestSent(); + h2stream.end(); h2stream.off("close", onDrain).off("drain", onDrain); } return; @@ -10955,12 +8985,15 @@ var require_agent = __commonJS({ this[kMaxRedirections] = maxRedirections; this[kFactory] = factory; this[kClients] = /* @__PURE__ */ new Map(); - this[kFinalizer] = new FinalizationRegistry((key) => { - const ref = this[kClients].get(key); - if (ref !== void 0 && ref.deref() === void 0) { - this[kClients].delete(key); + this[kFinalizer] = new FinalizationRegistry( + /* istanbul ignore next: gc is undeterministic */ + (key) => { + const ref = this[kClients].get(key); + if (ref !== void 0 && ref.deref() === void 0) { + this[kClients].delete(key); + } } - }); + ); const agent = this; this[kOnDrain] = (origin, targets) => { agent.emit("drain", origin, [agent, ...targets]); @@ -11060,7 +9093,7 @@ var require_global2 = __commonJS({ // lib/fetch/index.js var require_fetch = __commonJS({ "lib/fetch/index.js"(exports2, module2) { - "use strict"; + var esbuildDetection = 1; var { Response, makeNetworkError, @@ -11140,6 +9173,7 @@ var require_fetch = __commonJS({ this.connection?.destroy(reason); this.emit("terminated", reason); } + // https://fetch.spec.whatwg.org/#fetch-controller-abort abort(error) { if (this.state !== "ongoing") { return; @@ -11176,12 +9210,15 @@ var require_fetch = __commonJS({ const relevantRealm = null; let locallyAborted = false; let controller = null; - addAbortListener(requestObject.signal, () => { - locallyAborted = true; - assert(controller != null); - controller.abort(requestObject.signal.reason); - abortFetch(p, request, responseObject, requestObject.signal.reason); - }); + addAbortListener( + requestObject.signal, + () => { + locallyAborted = true; + assert(controller != null); + controller.abort(requestObject.signal.reason); + abortFetch(p, request, responseObject, requestObject.signal.reason); + } + ); const handleFetchDone = (response) => finalizeAndReportTiming(response, "fetch"); const processResponse = (response) => { if (locallyAborted) { @@ -11192,7 +9229,9 @@ var require_fetch = __commonJS({ return; } if (response.type === "error") { - p.reject(Object.assign(new TypeError("fetch failed"), { cause: response.error })); + p.reject( + Object.assign(new TypeError("fetch failed"), { cause: response.error }) + ); return; } responseObject = new Response(); @@ -11208,6 +9247,7 @@ var require_fetch = __commonJS({ processResponseEndOfBody: handleFetchDone, processResponse, dispatcher: init.dispatcher ?? getGlobalDispatcher() + // undici }); return p.promise; } @@ -11235,7 +9275,13 @@ var require_fetch = __commonJS({ } timingInfo.endTime = coarsenedSharedCurrentTime(); response.timingInfo = timingInfo; - markResourceTiming(timingInfo, originalURL, initiatorType, globalThis, cacheState); + markResourceTiming( + timingInfo, + originalURL, + initiatorType, + globalThis, + cacheState + ); } function markResourceTiming(timingInfo, originalURL, initiatorType, globalThis2, cacheState) { if (nodeMajor > 18 || nodeMajor === 18 && nodeMinor >= 2) { @@ -11277,6 +9323,7 @@ var require_fetch = __commonJS({ processResponseConsumeBody, useParallelQueue = false, dispatcher + // undici }) { let taskDestination = null; let crossOriginIsolatedCapability = false; @@ -11309,7 +9356,9 @@ var require_fetch = __commonJS({ } if (request.policyContainer === "client") { if (request.client != null) { - request.policyContainer = clonePolicyContainer(request.client.policyContainer); + request.policyContainer = clonePolicyContainer( + request.client.policyContainer + ); } else { request.policyContainer = makePolicyContainer(); } @@ -11349,7 +9398,13 @@ var require_fetch = __commonJS({ if (response === null) { response = await (async () => { const currentURL = requestCurrentURL(request); - if (sameOrigin(currentURL, request.url) && request.responseTainting === "basic" || currentURL.protocol === "data:" || (request.mode === "navigate" || request.mode === "websocket")) { + if ( + // - request’s current URL’s origin is same origin with request’s origin, + // and request’s response tainting is "basic" + sameOrigin(currentURL, request.url) && request.responseTainting === "basic" || // request’s current URL’s scheme is "data" + currentURL.protocol === "data:" || // - request’s mode is "navigate" or "websocket" + (request.mode === "navigate" || request.mode === "websocket") + ) { request.responseTainting = "basic"; return await schemeFetch(fetchParams); } @@ -11358,7 +9413,9 @@ var require_fetch = __commonJS({ } if (request.mode === "no-cors") { if (request.redirect !== "follow") { - return makeNetworkError('redirect mode cannot be "follow" for "no-cors" request'); + return makeNetworkError( + 'redirect mode cannot be "follow" for "no-cors" request' + ); } request.responseTainting = "opaque"; return await schemeFetch(fetchParams); @@ -11555,7 +9612,12 @@ var require_fetch = __commonJS({ request.timingAllowFailed = true; } } - if ((request.responseTainting === "opaque" || response.type === "opaque") && crossOriginResourcePolicyCheck(request.origin, request.client, request.destination, actualResponse) === "blocked") { + if ((request.responseTainting === "opaque" || response.type === "opaque") && crossOriginResourcePolicyCheck( + request.origin, + request.client, + request.destination, + actualResponse + ) === "blocked") { return makeNetworkError("blocked"); } if (redirectStatus.includes(actualResponse.status)) { @@ -11580,7 +9642,10 @@ var require_fetch = __commonJS({ const actualResponse = response.internalResponse ? response.internalResponse : response; let locationURL; try { - locationURL = responseLocationURL(actualResponse, requestCurrentURL(request).hash); + locationURL = responseLocationURL( + actualResponse, + requestCurrentURL(request).hash + ); if (locationURL == null) { return response; } @@ -11598,7 +9663,9 @@ var require_fetch = __commonJS({ return makeNetworkError('cross origin not allowed for request mode "cors"'); } if (request.responseTainting === "cors" && (locationURL.username || locationURL.password)) { - return makeNetworkError('URL cannot contain credentials for request mode "cors"'); + return makeNetworkError( + 'URL cannot contain credentials for request mode "cors"' + ); } if (actualResponse.status !== 303 && request.body != null && request.body.source == null) { return makeNetworkError(); @@ -11612,6 +9679,8 @@ var require_fetch = __commonJS({ } if (!sameOrigin(requestCurrentURL(request), locationURL)) { request.headersList.delete("authorization"); + request.headersList.delete("cookie"); + request.headersList.delete("host"); } if (request.body != null) { assert(request.body.source != null); @@ -11661,7 +9730,7 @@ var require_fetch = __commonJS({ appendRequestOriginHeader(httpRequest); appendFetchMetadata(httpRequest); if (!httpRequest.headersList.contains("user-agent")) { - httpRequest.headersList.append("user-agent", "undici"); + httpRequest.headersList.append("user-agent", typeof esbuildDetection === "undefined" ? "undici" : "node"); } if (httpRequest.cache === "default" && (httpRequest.headersList.contains("if-modified-since") || httpRequest.headersList.contains("if-none-match") || httpRequest.headersList.contains("if-unmodified-since") || httpRequest.headersList.contains("if-match") || httpRequest.headersList.contains("if-range"))) { httpRequest.cache = "no-store"; @@ -11687,6 +9756,7 @@ var require_fetch = __commonJS({ httpRequest.headersList.append("accept-encoding", "gzip, deflate"); } } + httpRequest.headersList.delete("host"); if (includeCredentials) { } if (httpCache == null) { @@ -11698,7 +9768,11 @@ var require_fetch = __commonJS({ if (httpRequest.mode === "only-if-cached") { return makeNetworkError("only if cached"); } - const forwardResponse = await httpNetworkFetch(httpFetchParams, includeCredentials, isNewConnectionFetch); + const forwardResponse = await httpNetworkFetch( + httpFetchParams, + includeCredentials, + isNewConnectionFetch + ); if (!safeMethods.includes(httpRequest.method) && forwardResponse.status >= 200 && forwardResponse.status <= 399) { } if (revalidatingFlag && forwardResponse.status === 304) { @@ -11721,12 +9795,21 @@ var require_fetch = __commonJS({ } return makeNetworkError("proxy authentication required"); } - if (response.status === 421 && !isNewConnectionFetch && (request.body == null || request.body.source != null)) { + if ( + // response’s status is 421 + response.status === 421 && // isNewConnectionFetch is false + !isNewConnectionFetch && // request’s body is null, or request’s body is non-null and request’s body’s source is non-null + (request.body == null || request.body.source != null) + ) { if (isCancelled(fetchParams)) { return makeAppropriateNetworkError(fetchParams); } fetchParams.controller.connection.destroy(); - response = await httpNetworkOrCacheFetch(fetchParams, isAuthenticationFetch, true); + response = await httpNetworkOrCacheFetch( + fetchParams, + isAuthenticationFetch, + true + ); } if (isAuthenticationFetch) { } @@ -11820,22 +9903,25 @@ var require_fetch = __commonJS({ if (!ReadableStream) { ReadableStream = require("stream/web").ReadableStream; } - const stream = new ReadableStream({ - async start(controller) { - fetchParams.controller.controller = controller; - }, - async pull(controller) { - await pullAlgorithm(controller); + const stream = new ReadableStream( + { + async start(controller) { + fetchParams.controller.controller = controller; + }, + async pull(controller) { + await pullAlgorithm(controller); + }, + async cancel(reason) { + await cancelAlgorithm(reason); + } }, - async cancel(reason) { - await cancelAlgorithm(reason); - } - }, { - highWaterMark: 0, - size() { - return 1; + { + highWaterMark: 0, + size() { + return 1; + } } - }); + ); response.body = { stream }; fetchParams.controller.on("terminated", onAborted); fetchParams.controller.resume = async () => { @@ -11880,7 +9966,9 @@ var require_fetch = __commonJS({ if (isAborted(fetchParams)) { response.aborted = true; if (isReadable(stream)) { - fetchParams.controller.controller.error(fetchParams.controller.serializedAbortReason); + fetchParams.controller.controller.error( + fetchParams.controller.serializedAbortReason + ); } } else { if (isReadable(stream)) { @@ -11895,128 +9983,135 @@ var require_fetch = __commonJS({ async function dispatch({ body }) { const url = requestCurrentURL(request); const agent = fetchParams.controller.dispatcher; - return new Promise((resolve, reject) => agent.dispatch({ - path: url.pathname + url.search, - origin: url.origin, - method: request.method, - body: fetchParams.controller.dispatcher.isMockActive ? request.body && request.body.source : body, - headers: request.headersList.entries, - maxRedirections: 0, - upgrade: request.mode === "websocket" ? "websocket" : void 0 - }, { - body: null, - abort: null, - onConnect(abort) { - const { connection } = fetchParams.controller; - if (connection.destroyed) { - abort(new DOMException("The operation was aborted.", "AbortError")); - } else { - fetchParams.controller.on("terminated", abort); - this.abort = connection.abort = abort; - } + return new Promise((resolve, reject) => agent.dispatch( + { + path: url.pathname + url.search, + origin: url.origin, + method: request.method, + body: fetchParams.controller.dispatcher.isMockActive ? request.body && request.body.source : body, + headers: request.headersList.entries, + maxRedirections: 0, + upgrade: request.mode === "websocket" ? "websocket" : void 0 }, - onHeaders(status, headersList, resume, statusText) { - if (status < 200) { - return; - } - let codings = []; - let location = ""; - const headers = new Headers(); - if (Array.isArray(headersList)) { - for (let n = 0; n < headersList.length; n += 2) { - const key = headersList[n + 0].toString("latin1"); - const val = headersList[n + 1].toString("latin1"); - if (key.toLowerCase() === "content-encoding") { - codings = val.toLowerCase().split(",").map((x) => x.trim()); - } else if (key.toLowerCase() === "location") { - location = val; - } - headers.append(key, val); + { + body: null, + abort: null, + onConnect(abort) { + const { connection } = fetchParams.controller; + if (connection.destroyed) { + abort(new DOMException("The operation was aborted.", "AbortError")); + } else { + fetchParams.controller.on("terminated", abort); + this.abort = connection.abort = abort; } - } else { - const keys = Object.keys(headersList); - for (const key of keys) { - const val = headersList[key]; - if (key.toLowerCase() === "content-encoding") { - codings = val.toLowerCase().split(",").map((x) => x.trim()).reverse(); - } else if (key.toLowerCase() === "location") { - location = val; + }, + onHeaders(status, headersList, resume, statusText) { + if (status < 200) { + return; + } + let codings = []; + let location = ""; + const headers = new Headers(); + if (Array.isArray(headersList)) { + for (let n = 0; n < headersList.length; n += 2) { + const key = headersList[n + 0].toString("latin1"); + const val = headersList[n + 1].toString("latin1"); + if (key.toLowerCase() === "content-encoding") { + codings = val.toLowerCase().split(",").map((x) => x.trim()); + } else if (key.toLowerCase() === "location") { + location = val; + } + headers.append(key, val); + } + } else { + const keys = Object.keys(headersList); + for (const key of keys) { + const val = headersList[key]; + if (key.toLowerCase() === "content-encoding") { + codings = val.toLowerCase().split(",").map((x) => x.trim()).reverse(); + } else if (key.toLowerCase() === "location") { + location = val; + } + headers.append(key, val); } - headers.append(key, val); } - } - this.body = new Readable({ read: resume }); - const decoders = []; - const willFollow = request.redirect === "follow" && location && redirectStatus.includes(status); - if (request.method !== "HEAD" && request.method !== "CONNECT" && !nullBodyStatus.includes(status) && !willFollow) { - for (const coding of codings) { - if (coding === "x-gzip" || coding === "gzip") { - decoders.push(zlib.createGunzip({ - flush: zlib.constants.Z_SYNC_FLUSH, - finishFlush: zlib.constants.Z_SYNC_FLUSH - })); - } else if (coding === "deflate") { - decoders.push(zlib.createInflate()); - } else if (coding === "br") { - decoders.push(zlib.createBrotliDecompress()); - } else { - decoders.length = 0; - break; + this.body = new Readable({ read: resume }); + const decoders = []; + const willFollow = request.redirect === "follow" && location && redirectStatus.includes(status); + if (request.method !== "HEAD" && request.method !== "CONNECT" && !nullBodyStatus.includes(status) && !willFollow) { + for (const coding of codings) { + if (coding === "x-gzip" || coding === "gzip") { + decoders.push(zlib.createGunzip({ + // Be less strict when decoding compressed responses, since sometimes + // servers send slightly invalid responses that are still accepted + // by common browsers. + // Always using Z_SYNC_FLUSH is what cURL does. + flush: zlib.constants.Z_SYNC_FLUSH, + finishFlush: zlib.constants.Z_SYNC_FLUSH + })); + } else if (coding === "deflate") { + decoders.push(zlib.createInflate()); + } else if (coding === "br") { + decoders.push(zlib.createBrotliDecompress()); + } else { + decoders.length = 0; + break; + } } } + resolve({ + status, + statusText, + headersList: headers[kHeadersList], + body: decoders.length ? pipeline(this.body, ...decoders, () => { + }) : this.body.on("error", () => { + }) + }); + return true; + }, + onData(chunk) { + if (fetchParams.controller.dump) { + return; + } + const bytes = chunk; + timingInfo.encodedBodySize += bytes.byteLength; + return this.body.push(bytes); + }, + onComplete() { + if (this.abort) { + fetchParams.controller.off("terminated", this.abort); + } + fetchParams.controller.ended = true; + this.body.push(null); + }, + onError(error) { + if (this.abort) { + fetchParams.controller.off("terminated", this.abort); + } + this.body?.destroy(error); + fetchParams.controller.terminate(error); + reject(error); + }, + onUpgrade(status, headersList, socket) { + if (status !== 101) { + return; + } + const headers = new Headers(); + for (let n = 0; n < headersList.length; n += 2) { + const key = headersList[n + 0].toString("latin1"); + const val = headersList[n + 1].toString("latin1"); + headers.append(key, val); + } + resolve({ + status, + statusText: STATUS_CODES[status], + headersList: headers[kHeadersList], + socket + }); + return true; } - resolve({ - status, - statusText, - headersList: headers[kHeadersList], - body: decoders.length ? pipeline(this.body, ...decoders, () => { - }) : this.body.on("error", () => { - }) - }); - return true; - }, - onData(chunk) { - if (fetchParams.controller.dump) { - return; - } - const bytes = chunk; - timingInfo.encodedBodySize += bytes.byteLength; - return this.body.push(bytes); - }, - onComplete() { - if (this.abort) { - fetchParams.controller.off("terminated", this.abort); - } - fetchParams.controller.ended = true; - this.body.push(null); - }, - onError(error) { - if (this.abort) { - fetchParams.controller.off("terminated", this.abort); - } - this.body?.destroy(error); - fetchParams.controller.terminate(error); - reject(error); - }, - onUpgrade(status, headersList, socket) { - if (status !== 101) { - return; - } - const headers = new Headers(); - for (let n = 0; n < headersList.length; n += 2) { - const key = headersList[n + 0].toString("latin1"); - const val = headersList[n + 1].toString("latin1"); - headers.append(key, val); - } - resolve({ - status, - statusText: STATUS_CODES[status], - headersList: headers[kHeadersList], - socket - }); - return true; } - })); + )); } } module2.exports = { @@ -12096,7 +10191,7 @@ var require_events = __commonJS({ var { webidl } = require_webidl(); var { kEnumerableProperty } = require_util(); var { MessagePort } = require("worker_threads"); - var MessageEvent = class extends Event { + var MessageEvent = class _MessageEvent extends Event { #eventInit; constructor(type, eventInitDict = {}) { webidl.argumentLengthCheck(arguments, 1, { header: "MessageEvent constructor" }); @@ -12106,32 +10201,32 @@ var require_events = __commonJS({ this.#eventInit = eventInitDict; } get data() { - webidl.brandCheck(this, MessageEvent); + webidl.brandCheck(this, _MessageEvent); return this.#eventInit.data; } get origin() { - webidl.brandCheck(this, MessageEvent); + webidl.brandCheck(this, _MessageEvent); return this.#eventInit.origin; } get lastEventId() { - webidl.brandCheck(this, MessageEvent); + webidl.brandCheck(this, _MessageEvent); return this.#eventInit.lastEventId; } get source() { - webidl.brandCheck(this, MessageEvent); + webidl.brandCheck(this, _MessageEvent); return this.#eventInit.source; } get ports() { - webidl.brandCheck(this, MessageEvent); + webidl.brandCheck(this, _MessageEvent); if (!Object.isFrozen(this.#eventInit.ports)) { Object.freeze(this.#eventInit.ports); } return this.#eventInit.ports; } initMessageEvent(type, bubbles = false, cancelable = false, data = null, origin = "", lastEventId = "", source = null, ports = []) { - webidl.brandCheck(this, MessageEvent); + webidl.brandCheck(this, _MessageEvent); webidl.argumentLengthCheck(arguments, 1, { header: "MessageEvent.initMessageEvent" }); - return new MessageEvent(type, { + return new _MessageEvent(type, { bubbles, cancelable, data, @@ -12142,7 +10237,7 @@ var require_events = __commonJS({ }); } }; - var CloseEvent = class extends Event { + var CloseEvent = class _CloseEvent extends Event { #eventInit; constructor(type, eventInitDict = {}) { webidl.argumentLengthCheck(arguments, 1, { header: "CloseEvent constructor" }); @@ -12152,19 +10247,19 @@ var require_events = __commonJS({ this.#eventInit = eventInitDict; } get wasClean() { - webidl.brandCheck(this, CloseEvent); + webidl.brandCheck(this, _CloseEvent); return this.#eventInit.wasClean; } get code() { - webidl.brandCheck(this, CloseEvent); + webidl.brandCheck(this, _CloseEvent); return this.#eventInit.code; } get reason() { - webidl.brandCheck(this, CloseEvent); + webidl.brandCheck(this, _CloseEvent); return this.#eventInit.reason; } }; - var ErrorEvent = class extends Event { + var ErrorEvent = class _ErrorEvent extends Event { #eventInit; constructor(type, eventInitDict) { webidl.argumentLengthCheck(arguments, 1, { header: "ErrorEvent constructor" }); @@ -12174,23 +10269,23 @@ var require_events = __commonJS({ this.#eventInit = eventInitDict; } get message() { - webidl.brandCheck(this, ErrorEvent); + webidl.brandCheck(this, _ErrorEvent); return this.#eventInit.message; } get filename() { - webidl.brandCheck(this, ErrorEvent); + webidl.brandCheck(this, _ErrorEvent); return this.#eventInit.filename; } get lineno() { - webidl.brandCheck(this, ErrorEvent); + webidl.brandCheck(this, _ErrorEvent); return this.#eventInit.lineno; } get colno() { - webidl.brandCheck(this, ErrorEvent); + webidl.brandCheck(this, _ErrorEvent); return this.#eventInit.colno; } get error() { - webidl.brandCheck(this, ErrorEvent); + webidl.brandCheck(this, _ErrorEvent); return this.#eventInit.error; } }; @@ -12227,7 +10322,9 @@ var require_events = __commonJS({ error: kEnumerableProperty }); webidl.converters.MessagePort = webidl.interfaceConverter(MessagePort); - webidl.converters["sequence"] = webidl.sequenceConverter(webidl.converters.MessagePort); + webidl.converters["sequence"] = webidl.sequenceConverter( + webidl.converters.MessagePort + ); var eventInit = [ { key: "bubbles", @@ -12264,6 +10361,8 @@ var require_events = __commonJS({ }, { key: "source", + // Node doesn't implement WindowProxy or ServiceWorker, so the only + // valid value for source is a MessagePort. converter: webidl.nullableConverter(webidl.converters.MessagePort), defaultValue: null }, @@ -12378,7 +10477,8 @@ var require_util3 = __commonJS({ } for (const char of protocol) { const code = char.charCodeAt(0); - if (code < 33 || code > 126 || char === "(" || char === ")" || char === "<" || char === ">" || char === "@" || char === "," || char === ";" || char === ":" || char === "\\" || char === '"' || char === "/" || char === "[" || char === "]" || char === "?" || char === "=" || char === "{" || char === "}" || code === 32 || code === 9) { + if (code < 33 || code > 126 || char === "(" || char === ")" || char === "<" || char === ">" || char === "@" || char === "," || char === ";" || char === ":" || char === "\\" || char === '"' || char === "/" || char === "[" || char === "]" || char === "?" || char === "=" || char === "{" || char === "}" || code === 32 || // SP + code === 9) { return false; } } @@ -12386,7 +10486,9 @@ var require_util3 = __commonJS({ } function isValidStatusCode(code) { if (code >= 1e3 && code < 1015) { - return code !== 1004 && code !== 1005 && code !== 1006; + return code !== 1004 && // reserved + code !== 1005 && // "MUST NOT be set as a status code" + code !== 1006; } return code >= 3e3 && code <= 4999; } @@ -12574,6 +10676,9 @@ var require_frame = __commonJS({ } catch { } var WebsocketFrameSend = class { + /** + * @param {Buffer|undefined} data + */ constructor(data) { this.frameData = data; this.maskKey = crypto.randomBytes(4); @@ -12640,11 +10745,20 @@ var require_receiver = __commonJS({ super(); this.ws = ws; } + /** + * @param {Buffer} chunk + * @param {() => void} callback + */ _write(chunk, _, callback) { this.#buffers.push(chunk); this.#byteOffset += chunk.length; this.run(callback); } + /** + * Runs whenever a new chunk is received. + * Callback is called whenever there are no more chunks buffering, + * or not enough bytes are buffered to parse. + */ run(callback) { while (true) { if (this.#state === parserStates.INFO) { @@ -12686,11 +10800,14 @@ var require_receiver = __commonJS({ const body2 = Buffer.allocUnsafe(2); body2.writeUInt16BE(this.#info.closeInfo.code, 0); const closeFrame = new WebsocketFrameSend(body2); - this.ws[kResponse].socket.write(closeFrame.createFrame(opcodes.CLOSE), (err) => { - if (!err) { - this.ws[kSentClose] = true; + this.ws[kResponse].socket.write( + closeFrame.createFrame(opcodes.CLOSE), + (err) => { + if (!err) { + this.ws[kSentClose] = true; + } } - }); + ); } this.ws[kReadyState] = states.CLOSING; this.ws[kReceivedClose] = true; @@ -12771,6 +10888,11 @@ var require_receiver = __commonJS({ } } } + /** + * Take n bytes from the buffered Buffers + * @param {number} n + * @returns {Buffer|null} + */ consume(n) { if (n > this.#byteOffset) { return null; @@ -12862,7 +10984,7 @@ var require_websocket = __commonJS({ var { getGlobalDispatcher } = require_global2(); var { types } = require("util"); var experimentalWarned = false; - var WebSocket = class extends EventTarget { + var WebSocket = class _WebSocket extends EventTarget { #events = { open: null, error: null, @@ -12872,6 +10994,10 @@ var require_websocket = __commonJS({ #bufferedAmount = 0; #protocol = ""; #extensions = ""; + /** + * @param {string} url + * @param {string|string[]} protocols + */ constructor(url, protocols = []) { super(); webidl.argumentLengthCheck(arguments, 1, { header: "WebSocket constructor" }); @@ -12897,7 +11023,10 @@ var require_websocket = __commonJS({ urlRecord.protocol = "wss:"; } if (urlRecord.protocol !== "ws:" && urlRecord.protocol !== "wss:") { - throw new DOMException(`Expected a ws: or wss: protocol, got ${urlRecord.protocol}`, "SyntaxError"); + throw new DOMException( + `Expected a ws: or wss: protocol, got ${urlRecord.protocol}`, + "SyntaxError" + ); } if (urlRecord.hash || urlRecord.href.endsWith("#")) { throw new DOMException("Got fragment", "SyntaxError"); @@ -12912,12 +11041,23 @@ var require_websocket = __commonJS({ throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError"); } this[kWebSocketURL] = new URL(urlRecord.href); - this[kController] = establishWebSocketConnection(urlRecord, protocols, this, (response) => this.#onConnectionEstablished(response), options); - this[kReadyState] = WebSocket.CONNECTING; + this[kController] = establishWebSocketConnection( + urlRecord, + protocols, + this, + (response) => this.#onConnectionEstablished(response), + options + ); + this[kReadyState] = _WebSocket.CONNECTING; this[kBinaryType] = "blob"; } + /** + * @see https://websockets.spec.whatwg.org/#dom-websocket-close + * @param {number|undefined} code + * @param {string|undefined} reason + */ close(code = void 0, reason = void 0) { - webidl.brandCheck(this, WebSocket); + webidl.brandCheck(this, _WebSocket); if (code !== void 0) { code = webidl.converters["unsigned short"](code, { clamp: true }); } @@ -12933,13 +11073,16 @@ var require_websocket = __commonJS({ if (reason !== void 0) { reasonByteLength = Buffer.byteLength(reason); if (reasonByteLength > 123) { - throw new DOMException(`Reason must be less than 123 bytes; received ${reasonByteLength}`, "SyntaxError"); + throw new DOMException( + `Reason must be less than 123 bytes; received ${reasonByteLength}`, + "SyntaxError" + ); } } - if (this[kReadyState] === WebSocket.CLOSING || this[kReadyState] === WebSocket.CLOSED) { + if (this[kReadyState] === _WebSocket.CLOSING || this[kReadyState] === _WebSocket.CLOSED) { } else if (!isEstablished(this)) { failWebsocketConnection(this, "Connection was closed before it was established."); - this[kReadyState] = WebSocket.CLOSING; + this[kReadyState] = _WebSocket.CLOSING; } else if (!isClosing(this)) { const frame = new WebsocketFrameSend(); if (code !== void 0 && reason === void 0) { @@ -12960,14 +11103,18 @@ var require_websocket = __commonJS({ }); this[kReadyState] = states.CLOSING; } else { - this[kReadyState] = WebSocket.CLOSING; + this[kReadyState] = _WebSocket.CLOSING; } } + /** + * @see https://websockets.spec.whatwg.org/#dom-websocket-send + * @param {NodeJS.TypedArray|ArrayBuffer|Blob|string} data + */ send(data) { - webidl.brandCheck(this, WebSocket); + webidl.brandCheck(this, _WebSocket); webidl.argumentLengthCheck(arguments, 1, { header: "WebSocket.send" }); data = webidl.converters.WebSocketSendData(data); - if (this[kReadyState] === WebSocket.CONNECTING) { + if (this[kReadyState] === _WebSocket.CONNECTING) { throw new DOMException("Sent before connected.", "InvalidStateError"); } if (!isEstablished(this) || isClosing(this)) { @@ -13012,31 +11159,31 @@ var require_websocket = __commonJS({ } } get readyState() { - webidl.brandCheck(this, WebSocket); + webidl.brandCheck(this, _WebSocket); return this[kReadyState]; } get bufferedAmount() { - webidl.brandCheck(this, WebSocket); + webidl.brandCheck(this, _WebSocket); return this.#bufferedAmount; } get url() { - webidl.brandCheck(this, WebSocket); + webidl.brandCheck(this, _WebSocket); return URLSerializer(this[kWebSocketURL]); } get extensions() { - webidl.brandCheck(this, WebSocket); + webidl.brandCheck(this, _WebSocket); return this.#extensions; } get protocol() { - webidl.brandCheck(this, WebSocket); + webidl.brandCheck(this, _WebSocket); return this.#protocol; } get onopen() { - webidl.brandCheck(this, WebSocket); + webidl.brandCheck(this, _WebSocket); return this.#events.open; } set onopen(fn) { - webidl.brandCheck(this, WebSocket); + webidl.brandCheck(this, _WebSocket); if (this.#events.open) { this.removeEventListener("open", this.#events.open); } @@ -13048,11 +11195,11 @@ var require_websocket = __commonJS({ } } get onerror() { - webidl.brandCheck(this, WebSocket); + webidl.brandCheck(this, _WebSocket); return this.#events.error; } set onerror(fn) { - webidl.brandCheck(this, WebSocket); + webidl.brandCheck(this, _WebSocket); if (this.#events.error) { this.removeEventListener("error", this.#events.error); } @@ -13064,11 +11211,11 @@ var require_websocket = __commonJS({ } } get onclose() { - webidl.brandCheck(this, WebSocket); + webidl.brandCheck(this, _WebSocket); return this.#events.close; } set onclose(fn) { - webidl.brandCheck(this, WebSocket); + webidl.brandCheck(this, _WebSocket); if (this.#events.close) { this.removeEventListener("close", this.#events.close); } @@ -13080,11 +11227,11 @@ var require_websocket = __commonJS({ } } get onmessage() { - webidl.brandCheck(this, WebSocket); + webidl.brandCheck(this, _WebSocket); return this.#events.message; } set onmessage(fn) { - webidl.brandCheck(this, WebSocket); + webidl.brandCheck(this, _WebSocket); if (this.#events.message) { this.removeEventListener("message", this.#events.message); } @@ -13096,17 +11243,20 @@ var require_websocket = __commonJS({ } } get binaryType() { - webidl.brandCheck(this, WebSocket); + webidl.brandCheck(this, _WebSocket); return this[kBinaryType]; } set binaryType(type) { - webidl.brandCheck(this, WebSocket); + webidl.brandCheck(this, _WebSocket); if (type !== "blob" && type !== "arraybuffer") { this[kBinaryType] = "blob"; } else { this[kBinaryType] = type; } } + /** + * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol + */ #onConnectionEstablished(response) { this[kResponse] = response; const parser = new ByteParser(this); @@ -13161,7 +11311,9 @@ var require_websocket = __commonJS({ CLOSING: staticPropertyDescriptors, CLOSED: staticPropertyDescriptors }); - webidl.converters["sequence"] = webidl.sequenceConverter(webidl.converters.DOMString); + webidl.converters["sequence"] = webidl.sequenceConverter( + webidl.converters.DOMString + ); webidl.converters["DOMString or sequence"] = function(V) { if (webidl.util.Type(V) === "Object" && Symbol.iterator in V) { return webidl.converters["sequence"](V); @@ -13226,5 +11378,11 @@ module.exports.Headers = require_headers().Headers; module.exports.Response = require_response().Response; module.exports.Request = require_request().Request; module.exports.WebSocket = require_websocket().WebSocket; -/*! formdata-polyfill. MIT License. Jimmy Wärting */ -/*! ws. MIT License. Einar Otto Stangvik */ +/*! Bundled license information: + +undici/lib/fetch/body.js: + (*! formdata-polyfill. MIT License. Jimmy Wärting *) + +undici/lib/websocket/frame.js: + (*! ws. MIT License. Einar Otto Stangvik *) +*/ diff --git a/doc/contributing/maintaining/maintaining-dependencies.md b/doc/contributing/maintaining/maintaining-dependencies.md index 6f84a92ebb9385..c980c6ce526f53 100644 --- a/doc/contributing/maintaining/maintaining-dependencies.md +++ b/doc/contributing/maintaining/maintaining-dependencies.md @@ -28,7 +28,7 @@ This a list of all the dependencies: * [openssl 3.0.8][] * [postject 1.0.0-alpha.6][] * [simdutf 3.2.17][] -* [undici 5.25.2][] +* [undici 5.26.3][] * [uvwasi 0.0.16][] * [V8 11.3.244.8][] * [zlib 1.2.13.1-motley-f5fd0ad][] @@ -291,7 +291,7 @@ The [postject](https://github.com/nodejs/postject) dependency is used for the The [simdutf](https://github.com/simdutf/simdutf) dependency is a C++ library for fast UTF-8 decoding and encoding. -### undici 5.25.2 +### undici 5.26.3 The [undici](https://github.com/nodejs/undici) dependency is an HTTP/1.1 client, written from scratch for Node.js.. @@ -345,7 +345,7 @@ performance improvements not currently available in standard zlib. [openssl 3.0.8]: #openssl-308 [postject 1.0.0-alpha.6]: #postject-100-alpha6 [simdutf 3.2.17]: #simdutf-3217 -[undici 5.25.2]: #undici-5252 +[undici 5.26.3]: #undici-5263 [update-openssl-action]: ../../../.github/workflows/update-openssl.yml [uvwasi 0.0.16]: #uvwasi-0016 [v8 11.3.244.8]: #v8-1132448 diff --git a/src/undici_version.h b/src/undici_version.h index d47c6d538b7355..31a28ae20d3510 100644 --- a/src/undici_version.h +++ b/src/undici_version.h @@ -2,5 +2,5 @@ // Refer to tools/update-undici.sh #ifndef SRC_UNDICI_VERSION_H_ #define SRC_UNDICI_VERSION_H_ -#define UNDICI_VERSION "5.25.2" +#define UNDICI_VERSION "5.26.3" #endif // SRC_UNDICI_VERSION_H_ diff --git a/tools/dep_updaters/update-undici.sh b/tools/dep_updaters/update-undici.sh index a869daf025df24..962557f7a0d185 100755 --- a/tools/dep_updaters/update-undici.sh +++ b/tools/dep_updaters/update-undici.sh @@ -34,7 +34,10 @@ rm -f deps/undici/undici.js "$NODE" "$NPM" install --global-style --no-bin-links --ignore-scripts "undici@$NEW_VERSION" cd node_modules/undici + "$NODE" "$NPM" install --no-bin-link --ignore-scripts "$NODE" "$NPM" run build:node + "$NODE" "$NPM" prune --production + rm node_modules/.package-lock.json ) # update version information in src/undici_version.h