diff --git a/dist/index.js b/dist/index.js index bc6693d4..701a31ef 100644 --- a/dist/index.js +++ b/dist/index.js @@ -933,7 +933,9 @@ var require_symbols = __commonJS({ kHTTP2BuildRequest: Symbol("http2 build request"), kHTTP1BuildRequest: Symbol("http1 build request"), kHTTP2CopyHeaders: Symbol("http2 copy headers"), - kHTTPConnVersion: Symbol("http connection version") + kHTTPConnVersion: Symbol("http connection version"), + kRetryHandlerDefaultRetry: Symbol("retry agent default retry"), + kConstruct: Symbol("constructable") }; } }); @@ -1116,6 +1118,18 @@ var require_errors = __commonJS({ this.code = "UND_ERR_RES_EXCEEDED_MAX_SIZE"; } }; + var RequestRetryError = class _RequestRetryError extends UndiciError { + constructor(message, code, { headers, data }) { + super(message); + Error.captureStackTrace(this, _RequestRetryError); + this.name = "RequestRetryError"; + this.message = message || "Request retry error"; + this.code = "UND_ERR_REQ_RETRY"; + this.statusCode = code; + this.data = data; + this.headers = headers; + } + }; module.exports = { HTTPParserError, UndiciError, @@ -1135,7 +1149,8 @@ var require_errors = __commonJS({ NotSupportedError, ResponseContentLengthMismatchError, BalancedPoolMissingUpstreamError, - ResponseExceededMaxSizeError + ResponseExceededMaxSizeError, + RequestRetryError }; } }); @@ -1226,12 +1241,12 @@ var require_util = __commonJS({ if (host[0] === "[") { const idx2 = host.indexOf("]"); assert(idx2 !== -1); - return host.substr(1, idx2 - 1); + return host.substring(1, idx2); } const idx = host.indexOf(":"); if (idx === -1) return host; - return host.substr(0, idx); + return host.substring(0, idx); } function getServerName(host) { if (!host) { @@ -1274,7 +1289,7 @@ var require_util = __commonJS({ return isDestroyed(stream2) && state && !state.endEmitted; } function destroy(stream2, err) { - if (!isStream(stream2) || isDestroyed(stream2)) { + if (stream2 == null || !isStream(stream2) || isDestroyed(stream2)) { return; } if (typeof stream2.destroy === "function") { @@ -1304,7 +1319,7 @@ var require_util = __commonJS({ let val = obj[key]; if (!val) { if (Array.isArray(headers[i + 1])) { - obj[key] = headers[i + 1]; + obj[key] = headers[i + 1].map((x) => x.toString("utf8")); } else { obj[key] = headers[i + 1].toString("utf8"); } @@ -1454,16 +1469,7 @@ var require_util = __commonJS({ } } } - var events; function addAbortListener(signal, listener) { - if (typeof Symbol.dispose === "symbol") { - if (!events) { - events = __require("events"); - } - if (typeof events.addAbortListener === "function" && "aborted" in signal) { - return events.addAbortListener(signal, listener); - } - } if ("addEventListener" in signal) { signal.addEventListener("abort", listener, { once: true }); return () => signal.removeEventListener("abort", listener); @@ -1480,6 +1486,16 @@ var require_util = __commonJS({ } return `${val}`; } + function parseRangeHeader(range) { + if (range == null || range === "") + return { start: 0, end: null, size: null }; + const m = range ? range.match(/^bytes (\d+)-(\d+)\/(\d+)?$/) : null; + return m ? { + start: parseInt(m[1]), + end: m[2] ? parseInt(m[2]) : null, + size: m[3] ? parseInt(m[3]) : null + } : null; + } var kEnumerableProperty = /* @__PURE__ */ Object.create(null); kEnumerableProperty.enumerable = true; module.exports = { @@ -1512,9 +1528,11 @@ var require_util = __commonJS({ buildURL, throwIfAborted, addAbortListener, + parseRangeHeader, nodeMajor, nodeMinor, - nodeHasAutoSelectFamily: nodeMajor > 18 || nodeMajor === 18 && nodeMinor >= 13 + nodeHasAutoSelectFamily: nodeMajor > 18 || nodeMajor === 18 && nodeMinor >= 13, + safeHTTPMethods: ["GET", "HEAD", "OPTIONS", "TRACE"] }; } }); @@ -3031,8 +3049,10 @@ var require_constants = __commonJS({ "use strict"; var { MessageChannel, receiveMessageOnPort } = __require("worker_threads"); var corsSafeListedMethods = ["GET", "HEAD", "POST"]; + var corsSafeListedMethodsSet = new Set(corsSafeListedMethods); var nullBodyStatus = [101, 204, 205, 304]; var redirectStatus = [301, 302, 303, 307, 308]; + var redirectStatusSet = new Set(redirectStatus); var badPorts = [ "1", "7", @@ -3115,6 +3135,7 @@ var require_constants = __commonJS({ "6697", "10080" ]; + var badPortsSet = new Set(badPorts); var referrerPolicy = [ "", "no-referrer", @@ -3126,8 +3147,10 @@ var require_constants = __commonJS({ "strict-origin-when-cross-origin", "unsafe-url" ]; + var referrerPolicySet = new Set(referrerPolicy); var requestRedirect = ["follow", "manual", "error"]; var safeMethods = ["GET", "HEAD", "OPTIONS", "TRACE"]; + var safeMethodsSet = new Set(safeMethods); var requestMode = ["navigate", "same-origin", "no-cors", "cors"]; var requestCredentials = ["omit", "same-origin", "include"]; var requestCache = [ @@ -3153,6 +3176,7 @@ var require_constants = __commonJS({ "half" ]; var forbiddenMethods = ["CONNECT", "TRACE", "TRACK"]; + var forbiddenMethodsSet = new Set(forbiddenMethods); var subresource = [ "audio", "audioworklet", @@ -3167,6 +3191,7 @@ var require_constants = __commonJS({ "xslt", "" ]; + var subresourceSet = new Set(subresource); var DOMException2 = globalThis.DOMException ?? (() => { try { atob("~"); @@ -3205,7 +3230,14 @@ var require_constants = __commonJS({ nullBodyStatus, safeMethods, badPorts, - requestDuplex + requestDuplex, + subresourceSet, + badPortsSet, + redirectStatusSet, + corsSafeListedMethodsSet, + safeMethodsSet, + forbiddenMethodsSet, + referrerPolicySet }; } }); @@ -3250,7 +3282,7 @@ var require_global = __commonJS({ var require_util2 = __commonJS({ "node_modules/undici/lib/fetch/util.js"(exports, module) { "use strict"; - var { redirectStatus, badPorts, referrerPolicy: referrerPolicyTokens } = require_constants(); + var { redirectStatusSet, referrerPolicySet: referrerPolicyTokens, badPortsSet } = require_constants(); var { getGlobalOrigin } = require_global(); var { performance: performance2 } = __require("perf_hooks"); var { isBlobLike, toUSVString, ReadableStreamFrom } = require_util(); @@ -3267,7 +3299,7 @@ var require_util2 = __commonJS({ return length === 0 ? null : urlList[length - 1].toString(); } function responseLocationURL(response, requestFragment) { - if (!redirectStatus.includes(response.status)) { + if (!redirectStatusSet.has(response.status)) { return null; } let location = response.headersList.get("location"); @@ -3284,7 +3316,7 @@ var require_util2 = __commonJS({ } function requestBadPort(request) { const url = requestCurrentURL(request); - if (urlIsHttpHttpsScheme(url) && badPorts.includes(url.port)) { + if (urlIsHttpHttpsScheme(url) && badPortsSet.has(url.port)) { return "blocked"; } return "allowed"; @@ -3303,25 +3335,42 @@ var require_util2 = __commonJS({ } return true; } - function isTokenChar(c) { - return !(c >= 127 || c <= 32 || c === "(" || c === ")" || c === "<" || c === ">" || c === "@" || c === "," || c === ";" || c === ":" || c === "\\" || c === '"' || c === "/" || c === "[" || c === "]" || c === "?" || c === "=" || c === "{" || c === "}"); + function isTokenCharCode(c) { + switch (c) { + case 34: + case 40: + case 41: + case 44: + case 47: + case 58: + case 59: + case 60: + case 61: + case 62: + case 63: + case 64: + case 91: + case 92: + case 93: + case 123: + case 125: + return false; + default: + return c >= 33 && c <= 126; + } } function isValidHTTPToken(characters) { - if (!characters || typeof characters !== "string") { + if (characters.length === 0) { return false; } for (let i = 0; i < characters.length; ++i) { - const c = characters.charCodeAt(i); - if (c > 127 || !isTokenChar(c)) { + if (!isTokenCharCode(characters.charCodeAt(i))) { return false; } } return true; } function isValidHeaderName(potentialValue) { - if (potentialValue.length === 0) { - return false; - } return isValidHTTPToken(potentialValue); } function isValidHeaderValue(potentialValue) { @@ -3340,7 +3389,7 @@ var require_util2 = __commonJS({ if (policyHeader.length > 0) { for (let i = policyHeader.length; i !== 0; i--) { const token = policyHeader[i - 1].trim(); - if (referrerPolicyTokens.includes(token)) { + if (referrerPolicyTokens.has(token)) { policy = token; break; } @@ -3590,8 +3639,23 @@ var require_util2 = __commonJS({ function isCancelled(fetchParams) { return fetchParams.controller.state === "aborted" || fetchParams.controller.state === "terminated"; } + var normalizeMethodRecord = { + delete: "DELETE", + DELETE: "DELETE", + get: "GET", + GET: "GET", + head: "HEAD", + HEAD: "HEAD", + options: "OPTIONS", + OPTIONS: "OPTIONS", + post: "POST", + POST: "POST", + put: "PUT", + PUT: "PUT" + }; + Object.setPrototypeOf(normalizeMethodRecord, null); function normalizeMethod(method) { - return /^(DELETE|GET|HEAD|OPTIONS|POST|PUT)$/i.test(method) ? method.toUpperCase() : method; + return normalizeMethodRecord[method.toLowerCase()] ?? method; } function serializeJavascriptValueToJSONString(value) { const result = JSON.stringify(value); @@ -3771,7 +3835,8 @@ var require_util2 = __commonJS({ urlIsLocal, urlHasHttpsScheme, urlIsHttpHttpsScheme, - readAllBytes + readAllBytes, + normalizeMethodRecord }; } }); @@ -4053,10 +4118,9 @@ var require_webidl = __commonJS({ webidl.converters.ByteString = function(V) { const x = webidl.converters.DOMString(V); for (let index = 0; index < x.length; index++) { - const charCode = x.charCodeAt(index); - if (charCode > 255) { + if (x.charCodeAt(index) > 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.` + `Cannot convert argument to a ByteString because the character at index ${index} has a value of ${x.charCodeAt(index)} which is greater than 255.` ); } } @@ -4209,15 +4273,12 @@ var require_dataURL = __commonJS({ return { mimeType: mimeTypeRecord, body }; } function URLSerializer(url, excludeFragment = false) { - const href = url.href; if (!excludeFragment) { - return href; + return url.href; } - const hash = href.lastIndexOf("#"); - if (hash === -1) { - return href; - } - return href.slice(0, hash); + const href = url.href; + const hashLength = url.hash.length; + return hashLength === 0 ? href : href.substring(0, href.length - hashLength); } function collectASequenceOfCodePoints(condition, input, position) { let result = ""; @@ -4464,6 +4525,7 @@ var require_file = __commonJS({ var { webidl } = require_webidl(); var { parseMIMEType, serializeAMimeType } = require_dataURL(); var { kEnumerableProperty } = require_util(); + var encoder = new TextEncoder(); var File = class _File extends Blob2 { constructor(fileBits, fileName, options = {}) { webidl.argumentLengthCheck(arguments, 2, { header: "File constructor" }); @@ -4609,7 +4671,7 @@ var require_file = __commonJS({ if (options.endings === "native") { s = convertLineEndingsNative(s); } - bytes.push(new TextEncoder().encode(s)); + bytes.push(encoder.encode(s)); } else if (types.isAnyArrayBuffer(element) || types.isTypedArray(element)) { if (!element.buffer) { bytes.push(new Uint8Array(element)); @@ -4821,6 +4883,8 @@ var require_body = __commonJS({ var { parseMIMEType, serializeAMimeType } = require_dataURL(); var ReadableStream = globalThis.ReadableStream; var File = NativeFile ?? UndiciFile; + var textEncoder = new TextEncoder(); + var textDecoder = new TextDecoder(); function extractBody(object, keepalive = false) { if (!ReadableStream) { ReadableStream = __require("stream/web").ReadableStream; @@ -4834,7 +4898,7 @@ var require_body = __commonJS({ stream = new ReadableStream({ async pull(controller) { controller.enqueue( - typeof source === "string" ? new TextEncoder().encode(source) : source + typeof source === "string" ? textEncoder.encode(source) : source ); queueMicrotask(() => readableStreamClose(controller)); }, @@ -4864,21 +4928,20 @@ var require_body = __commonJS({ Content-Disposition: form-data`; const escape = (str) => str.replace(/\n/g, "%0A").replace(/\r/g, "%0D").replace(/"/g, "%22"); const normalizeLinefeeds = (value) => value.replace(/\r?\n|\r/g, "\r\n"); - const enc = new TextEncoder(); const blobParts = []; const rn = new Uint8Array([13, 10]); length = 0; let hasUnknownSizeValue = false; for (const [name, value] of object) { if (typeof value === "string") { - const chunk2 = enc.encode(prefix + `; name="${escape(normalizeLinefeeds(name))}"\r + const chunk2 = textEncoder.encode(prefix + `; name="${escape(normalizeLinefeeds(name))}"\r \r ${normalizeLinefeeds(value)}\r `); blobParts.push(chunk2); length += chunk2.byteLength; } else { - const chunk2 = enc.encode(`${prefix}; name="${escape(normalizeLinefeeds(name))}"` + (value.name ? `; filename="${escape(value.name)}"` : "") + `\r + const chunk2 = textEncoder.encode(`${prefix}; name="${escape(normalizeLinefeeds(name))}"` + (value.name ? `; filename="${escape(value.name)}"` : "") + `\r Content-Type: ${value.type || "application/octet-stream"}\r \r `); @@ -4890,7 +4953,7 @@ Content-Type: ${value.type || "application/octet-stream"}\r } } } - const chunk = enc.encode(`--${boundary}--`); + const chunk = textEncoder.encode(`--${boundary}--`); blobParts.push(chunk); length += chunk.byteLength; if (hasUnknownSizeValue) { @@ -5080,14 +5143,14 @@ Content-Type: ${value.type || "application/octet-stream"}\r let entries; try { let text = ""; - const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); + const streamingDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); for await (const chunk of consumeBody(this[kState].body)) { if (!isUint8Array(chunk)) { throw new TypeError("Expected Uint8Array chunk"); } - text += textDecoder.decode(chunk, { stream: true }); + text += streamingDecoder.decode(chunk, { stream: true }); } - text += textDecoder.decode(); + text += streamingDecoder.decode(); entries = new URLSearchParams(text); } catch (err) { throw Object.assign(new TypeError(), { cause: err }); @@ -5144,7 +5207,7 @@ Content-Type: ${value.type || "application/octet-stream"}\r if (buffer[0] === 239 && buffer[1] === 187 && buffer[2] === 191) { buffer = buffer.subarray(3); } - const output = new TextDecoder().decode(buffer); + const output = textDecoder.decode(buffer); return output; } function parseJSONFromBytes(bytes) { @@ -5245,10 +5308,26 @@ var require_request = __commonJS({ this.bodyTimeout = bodyTimeout; this.throwOnError = throwOnError === true; this.method = method; + this.abort = null; if (body == null) { this.body = null; } else if (util2.isStream(body)) { this.body = body; + const rState = this.body._readableState; + if (!rState || !rState.autoDestroy) { + this.endHandler = function autoDestroy() { + util2.destroy(this); + }; + this.body.on("end", this.endHandler); + } + this.errorHandler = (err) => { + if (this.abort) { + this.abort(err); + } else { + this.error = err; + } + }; + this.body.on("error", this.errorHandler); } else if (util2.isBuffer(body)) { this.body = body.byteLength ? body : null; } else if (ArrayBuffer.isView(body)) { @@ -5321,9 +5400,9 @@ var require_request = __commonJS({ onBodySent(chunk) { if (this[kHandler].onBodySent) { try { - this[kHandler].onBodySent(chunk); + return this[kHandler].onBodySent(chunk); } catch (err) { - this.onError(err); + this.abort(err); } } } @@ -5331,11 +5410,23 @@ var require_request = __commonJS({ if (channels.bodySent.hasSubscribers) { channels.bodySent.publish({ request: this }); } + if (this[kHandler].onRequestSent) { + try { + return this[kHandler].onRequestSent(); + } catch (err) { + this.abort(err); + } + } } onConnect(abort) { assert(!this.aborted); assert(!this.completed); - return this[kHandler].onConnect(abort); + if (this.error) { + abort(this.error); + } else { + this.abort = abort; + return this[kHandler].onConnect(abort); + } } onHeaders(statusCode, headers, resume, statusText) { assert(!this.aborted); @@ -5343,12 +5434,21 @@ var require_request = __commonJS({ if (channels.headers.hasSubscribers) { channels.headers.publish({ request: this, response: { statusCode, headers, statusText } }); } - return this[kHandler].onHeaders(statusCode, headers, resume, statusText); + try { + return this[kHandler].onHeaders(statusCode, headers, resume, statusText); + } catch (err) { + this.abort(err); + } } onData(chunk) { assert(!this.aborted); assert(!this.completed); - return this[kHandler].onData(chunk); + try { + return this[kHandler].onData(chunk); + } catch (err) { + this.abort(err); + return false; + } } onUpgrade(statusCode, headers, socket) { assert(!this.aborted); @@ -5356,14 +5456,20 @@ var require_request = __commonJS({ return this[kHandler].onUpgrade(statusCode, headers, socket); } onComplete(trailers) { + this.onFinally(); assert(!this.aborted); this.completed = true; if (channels.trailers.hasSubscribers) { channels.trailers.publish({ request: this, trailers }); } - return this[kHandler].onComplete(trailers); + try { + return this[kHandler].onComplete(trailers); + } catch (err) { + this.onError(err); + } } onError(error2) { + this.onFinally(); if (channels.error.hasSubscribers) { channels.error.publish({ request: this, error: error2 }); } @@ -5373,6 +5479,16 @@ var require_request = __commonJS({ this.aborted = true; return this[kHandler].onError(error2); } + onFinally() { + if (this.errorHandler) { + this.body.off("error", this.errorHandler); + this.errorHandler = null; + } + if (this.endHandler) { + this.body.off("end", this.endHandler); + this.endHandler = null; + } + } // TODO: adjust to support H2 addHeader(key, value) { processHeader(this, key, value); @@ -7060,11 +7176,8 @@ var require_client = __commonJS({ } else { socket[kReset] = true; } - let pause; - try { - pause = request.onHeaders(statusCode, headers, this.resume, statusText) === false; - } catch (err) { - util2.destroy(socket, err); + const pause = request.onHeaders(statusCode, headers, this.resume, statusText) === false; + if (request.aborted) { return -1; } if (request.method === "HEAD") { @@ -7098,13 +7211,8 @@ var require_client = __commonJS({ return -1; } this.bytesRead += buf.length; - try { - if (request.onData(buf) === false) { - return constants.ERROR.PAUSED; - } - } catch (err) { - util2.destroy(socket, err); - return -1; + if (request.onData(buf) === false) { + return constants.ERROR.PAUSED; } } onMessageComplete() { @@ -7134,11 +7242,7 @@ var require_client = __commonJS({ util2.destroy(socket, new ResponseContentLengthMismatchError()); return -1; } - try { - request.onComplete(headers); - } catch (err) { - errorRequest(client, request, err); - } + request.onComplete(headers); client[kQueue][client[kRunningIdx]++] = null; if (socket[kWriting]) { assert.strictEqual(client[kRunning], 0); @@ -7175,7 +7279,9 @@ var require_client = __commonJS({ } function onSocketReadable() { const { [kParser]: parser } = this; - parser.readMore(); + if (parser) { + parser.readMore(); + } } function onSocketError(err) { const { [kClient]: client, [kParser]: parser } = this; @@ -7245,7 +7351,7 @@ var require_client = __commonJS({ if (hostname[0] === "[") { const idx = hostname.indexOf("]"); assert(idx !== -1); - const ip = hostname.substr(1, idx - 1); + const ip = hostname.substring(1, idx); assert(net.isIP(ip)); hostname = ip; } @@ -7469,21 +7575,7 @@ var require_client = __commonJS({ if (client[kRunning] > 0 && (request.upgrade || request.method === "CONNECT")) { return; } - if (util2.isStream(request.body) && util2.bodyLength(request.body) === 0) { - request.body.on( - "data", - /* istanbul ignore next */ - function() { - assert(false); - } - ).on("error", function(err) { - errorRequest(client, request, err); - }).on("end", function() { - util2.destroy(this); - }); - request.body = null; - } - if (client[kRunning] > 0 && (util2.isStream(request.body) || util2.isAsyncIterable(request.body))) { + if (client[kRunning] > 0 && util2.bodyLength(request.body) !== 0 && (util2.isStream(request.body) || util2.isAsyncIterable(request.body))) { return; } if (!request.aborted && write(client, request)) { @@ -7493,6 +7585,9 @@ var require_client = __commonJS({ } } } + function shouldSendContentLength(method) { + return method !== "GET" && method !== "HEAD" && method !== "OPTIONS" && method !== "TRACE" && method !== "CONNECT"; + } function write(client, request) { if (client[kHTTPConnVersion] === "h2") { writeH2(client, client[kHTTP2Session], request); @@ -7503,14 +7598,15 @@ var require_client = __commonJS({ if (body && typeof body.read === "function") { body.read(0); } - let contentLength = util2.bodyLength(body); + const bodyLength = util2.bodyLength(body); + let contentLength = bodyLength; if (contentLength === null) { contentLength = request.contentLength; } if (contentLength === 0 && !expectsPayload) { contentLength = null; } - if (request.contentLength !== null && request.contentLength !== contentLength) { + if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength !== null && request.contentLength !== contentLength) { if (client[kStrictContentLength]) { errorRequest(client, request, new RequestContentLengthMismatchError()); return false; @@ -7570,7 +7666,7 @@ upgrade: ${upgrade}\r if (channels.sendHeaders.hasSubscribers) { channels.sendHeaders.publish({ request, headers: header, socket }); } - if (!body) { + if (!body || bodyLength === 0) { if (contentLength === 0) { socket.write(`${header}content-length: 0\r \r @@ -7669,7 +7765,7 @@ upgrade: ${upgrade}\r if (contentLength === 0 || !expectsPayload) { contentLength = null; } - if (request.contentLength != null && request.contentLength !== contentLength) { + if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength != null && request.contentLength !== contentLength) { if (client[kStrictContentLength]) { errorRequest(client, request, new RequestContentLengthMismatchError()); return false; @@ -7695,7 +7791,8 @@ upgrade: ${upgrade}\r } ++h2State.openStreams; stream.once("response", (headers2) => { - if (request.onHeaders(Number(headers2[HTTP2_HEADER_STATUS]), headers2, stream.resume.bind(stream), "") === false) { + const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers2; + if (request.onHeaders(Number(statusCode), realHeaders, stream.resume.bind(stream), "") === false) { stream.pause(); } }); @@ -7703,13 +7800,15 @@ upgrade: ${upgrade}\r request.onComplete([]); }); stream.on("data", (chunk) => { - if (request.onData(chunk) === false) + if (request.onData(chunk) === false) { stream.pause(); + } }); stream.once("close", () => { h2State.openStreams -= 1; - if (h2State.openStreams === 0) + if (h2State.openStreams === 0) { session.unref(); + } }); stream.once("error", function(err) { if (client[kHTTP2Session] && !client[kHTTP2Session].destroyed && !this.closed && !this.destroyed) { @@ -7836,7 +7935,11 @@ upgrade: ${upgrade}\r } }; const onAbort = function() { - onFinished(new RequestAbortedError()); + if (finished) { + return; + } + const err = new RequestAbortedError(); + queueMicrotask(() => onFinished(err)); }; const onFinished = function(err) { if (finished) { @@ -8370,7 +8473,7 @@ var require_pool = __commonJS({ maxCachedSessions, allowH2, socketPath, - timeout: connectTimeout == null ? 1e4 : connectTimeout, + timeout: connectTimeout, ...util2.nodeHasAutoSelectFamily && autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : void 0, ...connect }); @@ -8709,6 +8812,8 @@ var require_readable = __commonJS({ var kBody = Symbol("kBody"); var kAbort = Symbol("abort"); var kContentType = Symbol("kContentType"); + var noop = () => { + }; module.exports = class BodyReadable extends Readable { constructor({ resume, @@ -8810,37 +8915,40 @@ var require_readable = __commonJS({ } return this[kBody]; } - async dump(opts) { + dump(opts) { let limit = opts && Number.isFinite(opts.limit) ? opts.limit : 262144; const signal = opts && opts.signal; - const abortFn = () => { - this.destroy(); - }; - let signalListenerCleanup; if (signal) { - if (typeof signal !== "object" || !("aborted" in signal)) { - throw new InvalidArgumentError("signal must be an AbortSignal"); - } - util2.throwIfAborted(signal); - signalListenerCleanup = util2.addAbortListener(signal, abortFn); - } - try { - for await (const chunk of this) { - util2.throwIfAborted(signal); - limit -= Buffer.byteLength(chunk); - if (limit < 0) { - return; + try { + if (typeof signal !== "object" || !("aborted" in signal)) { + throw new InvalidArgumentError("signal must be an AbortSignal"); } - } - } catch { - util2.throwIfAborted(signal); - } finally { - if (typeof signalListenerCleanup === "function") { - signalListenerCleanup(); - } else if (signalListenerCleanup) { - signalListenerCleanup[Symbol.dispose](); + util2.throwIfAborted(signal); + } catch (err) { + return Promise.reject(err); } } + if (this.closed) { + return Promise.resolve(null); + } + return new Promise((resolve, reject) => { + const signalListenerCleanup = signal ? util2.addAbortListener(signal, () => { + this.destroy(); + }) : noop; + this.on("close", function() { + signalListenerCleanup(); + if (signal && signal.aborted) { + reject(signal.reason || Object.assign(new Error("The operation was aborted"), { name: "AbortError" })); + } else { + resolve(null); + } + }).on("error", noop).on("data", function(chunk) { + limit -= chunk.length; + if (limit <= 0) { + this.destroy(); + } + }).resume(); + }); } }; function isLocked(self) { @@ -8906,7 +9014,7 @@ var require_readable = __commonJS({ dst.set(buf, pos); pos += buf.byteLength; } - resolve(dst); + resolve(dst.buffer); } else if (type === "blob") { if (!Blob2) { Blob2 = __require("buffer").Blob; @@ -9183,6 +9291,7 @@ var require_api_request = __commonJS({ } } module.exports = request; + module.exports.RequestHandler = RequestHandler; } }); @@ -9276,6 +9385,9 @@ var require_api_stream = __commonJS({ { callback, body: res, contentType, statusCode, statusMessage, headers } ); } else { + if (factory === null) { + return; + } res = this.runInAsyncScope(factory, null, { statusCode, headers, @@ -9305,11 +9417,14 @@ var require_api_stream = __commonJS({ } onData(chunk) { const { res } = this; - return res.write(chunk); + return res ? res.write(chunk) : true; } onComplete(trailers) { const { res } = this; removeSignal(this); + if (!res) { + return; + } this.trailers = util2.parseHeaders(trailers); res.end(); } @@ -10599,15 +10714,17 @@ var require_proxy_agent = __commonJS({ this[kRequestTls] = opts.requestTls; this[kProxyTls] = opts.proxyTls; this[kProxyHeaders] = opts.headers || {}; + const resolvedUrl = new URL3(opts.uri); + const { origin, port, host, username, password } = resolvedUrl; if (opts.auth && opts.token) { throw new InvalidArgumentError("opts.auth cannot be used in combination with opts.token"); } else if (opts.auth) { this[kProxyHeaders]["proxy-authorization"] = `Basic ${opts.auth}`; } else if (opts.token) { this[kProxyHeaders]["proxy-authorization"] = opts.token; + } else if (username && password) { + this[kProxyHeaders]["proxy-authorization"] = `Basic ${Buffer.from(`${decodeURIComponent(username)}:${decodeURIComponent(password)}`).toString("base64")}`; } - const resolvedUrl = new URL3(opts.uri); - const { origin, port, host } = resolvedUrl; const connect = buildConnector({ ...opts.proxyTls }); this[kConnectEndpoint] = buildConnector({ ...opts.requestTls }); this[kClient] = clientFactory(resolvedUrl, { connect }); @@ -10632,7 +10749,7 @@ var require_proxy_agent = __commonJS({ if (statusCode !== 200) { socket.on("error", () => { }).destroy(); - callback(new RequestAbortedError("Proxy response !== 200 when HTTP Tunneling")); + callback(new RequestAbortedError(`Proxy response (${statusCode}) !== 200 when HTTP Tunneling`)); } if (opts2.protocol !== "https:") { callback(null, socket); @@ -10695,6 +10812,274 @@ var require_proxy_agent = __commonJS({ } }); +// node_modules/undici/lib/handler/RetryHandler.js +var require_RetryHandler = __commonJS({ + "node_modules/undici/lib/handler/RetryHandler.js"(exports, module) { + var assert = __require("assert"); + var { kRetryHandlerDefaultRetry } = require_symbols(); + var { RequestRetryError } = require_errors(); + var { isDisturbed, parseHeaders, parseRangeHeader } = require_util(); + function calculateRetryAfterHeader(retryAfter) { + const current = Date.now(); + const diff = new Date(retryAfter).getTime() - current; + return diff; + } + var RetryHandler = class _RetryHandler { + constructor(opts, handlers) { + const { retryOptions, ...dispatchOpts } = opts; + const { + // Retry scoped + retry: retryFn, + maxRetries, + maxTimeout, + minTimeout, + timeoutFactor, + // Response scoped + methods, + errorCodes, + retryAfter, + statusCodes + } = retryOptions ?? {}; + this.dispatch = handlers.dispatch; + this.handler = handlers.handler; + this.opts = dispatchOpts; + this.abort = null; + this.aborted = false; + this.retryOpts = { + retry: retryFn ?? _RetryHandler[kRetryHandlerDefaultRetry], + retryAfter: retryAfter ?? true, + maxTimeout: maxTimeout ?? 30 * 1e3, + // 30s, + timeout: minTimeout ?? 500, + // .5s + timeoutFactor: timeoutFactor ?? 2, + maxRetries: maxRetries ?? 5, + // What errors we should retry + methods: methods ?? ["GET", "HEAD", "OPTIONS", "PUT", "DELETE", "TRACE"], + // Indicates which errors to retry + statusCodes: statusCodes ?? [500, 502, 503, 504, 429], + // List of errors to retry + errorCodes: errorCodes ?? [ + "ECONNRESET", + "ECONNREFUSED", + "ENOTFOUND", + "ENETDOWN", + "ENETUNREACH", + "EHOSTDOWN", + "EHOSTUNREACH", + "EPIPE" + ] + }; + this.retryCount = 0; + this.start = 0; + this.end = null; + this.etag = null; + this.resume = null; + this.handler.onConnect((reason) => { + this.aborted = true; + if (this.abort) { + this.abort(reason); + } else { + this.reason = reason; + } + }); + } + onRequestSent() { + if (this.handler.onRequestSent) { + this.handler.onRequestSent(); + } + } + onUpgrade(statusCode, headers, socket) { + if (this.handler.onUpgrade) { + this.handler.onUpgrade(statusCode, headers, socket); + } + } + onConnect(abort) { + if (this.aborted) { + abort(this.reason); + } else { + this.abort = abort; + } + } + onBodySent(chunk) { + if (this.handler.onBodySent) + return this.handler.onBodySent(chunk); + } + static [kRetryHandlerDefaultRetry](err, { state, opts }, cb) { + const { statusCode, code, headers } = err; + const { method, retryOptions } = opts; + const { + maxRetries, + timeout, + maxTimeout, + timeoutFactor, + statusCodes, + errorCodes, + methods + } = retryOptions; + let { counter, currentTimeout } = state; + currentTimeout = currentTimeout != null && currentTimeout > 0 ? currentTimeout : timeout; + if (code && code !== "UND_ERR_REQ_RETRY" && code !== "UND_ERR_SOCKET" && !errorCodes.includes(code)) { + cb(err); + return; + } + if (Array.isArray(methods) && !methods.includes(method)) { + cb(err); + return; + } + if (statusCode != null && Array.isArray(statusCodes) && !statusCodes.includes(statusCode)) { + cb(err); + return; + } + if (counter > maxRetries) { + cb(err); + return; + } + let retryAfterHeader = headers != null && headers["retry-after"]; + if (retryAfterHeader) { + retryAfterHeader = Number(retryAfterHeader); + retryAfterHeader = isNaN(retryAfterHeader) ? calculateRetryAfterHeader(retryAfterHeader) : retryAfterHeader * 1e3; + } + const retryTimeout = retryAfterHeader > 0 ? Math.min(retryAfterHeader, maxTimeout) : Math.min(currentTimeout * timeoutFactor ** counter, maxTimeout); + state.currentTimeout = retryTimeout; + setTimeout(() => cb(null), retryTimeout); + } + onHeaders(statusCode, rawHeaders, resume, statusMessage) { + const headers = parseHeaders(rawHeaders); + this.retryCount += 1; + if (statusCode >= 300) { + this.abort( + new RequestRetryError("Request failed", statusCode, { + headers, + count: this.retryCount + }) + ); + return false; + } + if (this.resume != null) { + this.resume = null; + if (statusCode !== 206) { + return true; + } + const contentRange = parseRangeHeader(headers["content-range"]); + if (!contentRange) { + this.abort( + new RequestRetryError("Content-Range mismatch", statusCode, { + headers, + count: this.retryCount + }) + ); + return false; + } + if (this.etag != null && this.etag !== headers.etag) { + this.abort( + new RequestRetryError("ETag mismatch", statusCode, { + headers, + count: this.retryCount + }) + ); + return false; + } + const { start, size, end = size } = contentRange; + assert(this.start === start, "content-range mismatch"); + assert(this.end == null || this.end === end, "content-range mismatch"); + this.resume = resume; + return true; + } + if (this.end == null) { + if (statusCode === 206) { + const range = parseRangeHeader(headers["content-range"]); + if (range == null) { + return this.handler.onHeaders( + statusCode, + rawHeaders, + resume, + statusMessage + ); + } + const { start, size, end = size } = range; + assert( + start != null && Number.isFinite(start) && this.start !== start, + "content-range mismatch" + ); + assert(Number.isFinite(start)); + assert( + end != null && Number.isFinite(end) && this.end !== end, + "invalid content-length" + ); + this.start = start; + this.end = end; + } + if (this.end == null) { + const contentLength = headers["content-length"]; + this.end = contentLength != null ? Number(contentLength) : null; + } + assert(Number.isFinite(this.start)); + assert( + this.end == null || Number.isFinite(this.end), + "invalid content-length" + ); + this.resume = resume; + this.etag = headers.etag != null ? headers.etag : null; + return this.handler.onHeaders( + statusCode, + rawHeaders, + resume, + statusMessage + ); + } + const err = new RequestRetryError("Request failed", statusCode, { + headers, + count: this.retryCount + }); + this.abort(err); + return false; + } + onData(chunk) { + this.start += chunk.length; + return this.handler.onData(chunk); + } + onComplete(rawTrailers) { + this.retryCount = 0; + return this.handler.onComplete(rawTrailers); + } + onError(err) { + if (this.aborted || isDisturbed(this.opts.body)) { + return this.handler.onError(err); + } + this.retryOpts.retry( + err, + { + state: { counter: this.retryCount++, currentTimeout: this.retryAfter }, + opts: { retryOptions: this.retryOpts, ...this.opts } + }, + onRetry.bind(this) + ); + function onRetry(err2) { + if (err2 != null || this.aborted || isDisturbed(this.opts.body)) { + return this.handler.onError(err2); + } + if (this.start !== 0) { + this.opts = { + ...this.opts, + headers: { + ...this.opts.headers, + range: `bytes=${this.start}-${this.end ?? ""}` + } + }; + } + try { + this.dispatch(this.opts, this); + } catch (err3) { + this.handler.onError(err3); + } + } + } + }; + module.exports = RetryHandler; + } +}); + // node_modules/undici/lib/global.js var require_global2 = __commonJS({ "node_modules/undici/lib/global.js"(exports, module) { @@ -10763,7 +11148,7 @@ var require_DecoratorHandler = __commonJS({ var require_headers = __commonJS({ "node_modules/undici/lib/fetch/headers.js"(exports, module) { "use strict"; - var { kHeadersList } = require_symbols(); + var { kHeadersList, kConstruct } = require_symbols(); var { kGuard } = require_symbols2(); var { kEnumerableProperty } = require_util(); var { @@ -10775,26 +11160,34 @@ var require_headers = __commonJS({ var assert = __require("assert"); var kHeadersMap = Symbol("headers map"); var kHeadersSortedMap = Symbol("headers map sorted"); + function isHTTPWhiteSpaceCharCode(code) { + return code === 10 || code === 13 || code === 9 || code === 32; + } function headerValueNormalize(potentialValue) { - let i = potentialValue.length; - while (/[\r\n\t ]/.test(potentialValue.charAt(--i))) - ; - return potentialValue.slice(0, i + 1).replace(/^[\r\n\t ]+/, ""); + let i = 0; + let j = potentialValue.length; + while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(j - 1))) + --j; + while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(i))) + ++i; + return i === 0 && j === potentialValue.length ? potentialValue : potentialValue.substring(i, j); } function fill(headers, object) { if (Array.isArray(object)) { - for (const header of object) { + for (let i = 0; i < object.length; ++i) { + const header = object[i]; if (header.length !== 2) { throw webidl.errors.exception({ header: "Headers constructor", message: `expected name/value pair to be length 2, found ${header.length}.` }); } - headers.append(header[0], header[1]); + appendHeader(headers, header[0], header[1]); } } else if (typeof object === "object" && object !== null) { - for (const [key, value] of Object.entries(object)) { - headers.append(key, value); + const keys = Object.keys(object); + for (let i = 0; i < keys.length; ++i) { + appendHeader(headers, keys[i], object[keys[i]]); } } else { throw webidl.errors.conversionFailed({ @@ -10804,6 +11197,27 @@ var require_headers = __commonJS({ }); } } + function appendHeader(headers, name, value) { + value = headerValueNormalize(value); + if (!isValidHeaderName(name)) { + throw webidl.errors.invalidArgument({ + prefix: "Headers.append", + value: name, + type: "header name" + }); + } else if (!isValidHeaderValue(value)) { + throw webidl.errors.invalidArgument({ + prefix: "Headers.append", + value, + type: "header value" + }); + } + if (headers[kGuard] === "immutable") { + throw new TypeError("immutable"); + } else if (headers[kGuard] === "request-no-cors") { + } + return headers[kHeadersList].append(name, value); + } var HeadersList = class _HeadersList { /** @type {[string, string][]|null} */ cookies = null; @@ -10811,7 +11225,7 @@ var require_headers = __commonJS({ if (init instanceof _HeadersList) { this[kHeadersMap] = new Map(init[kHeadersMap]); this[kHeadersSortedMap] = init[kHeadersSortedMap]; - this.cookies = init.cookies; + this.cookies = init.cookies === null ? null : [...init.cookies]; } else { this[kHeadersMap] = new Map(init); this[kHeadersSortedMap] = null; @@ -10853,7 +11267,7 @@ var require_headers = __commonJS({ if (lowercaseName === "set-cookie") { this.cookies = [value]; } - return this[kHeadersMap].set(lowercaseName, { name, value }); + this[kHeadersMap].set(lowercaseName, { name, value }); } // https://fetch.spec.whatwg.org/#concept-header-list-delete delete(name) { @@ -10862,14 +11276,12 @@ var require_headers = __commonJS({ if (name === "set-cookie") { this.cookies = null; } - return this[kHeadersMap].delete(name); + this[kHeadersMap].delete(name); } // https://fetch.spec.whatwg.org/#concept-header-list-get get(name) { - if (!this.contains(name)) { - return null; - } - return this[kHeadersMap].get(name.toLowerCase())?.value ?? null; + const value = this[kHeadersMap].get(name.toLowerCase()); + return value === void 0 ? null : value.value; } *[Symbol.iterator]() { for (const [name, { value }] of this[kHeadersMap]) { @@ -10888,6 +11300,9 @@ var require_headers = __commonJS({ }; var Headers = class _Headers { constructor(init = void 0) { + if (init === kConstruct) { + return; + } this[kHeadersList] = new HeadersList(); this[kGuard] = "none"; if (init !== void 0) { @@ -10901,25 +11316,7 @@ var require_headers = __commonJS({ webidl.argumentLengthCheck(arguments, 2, { header: "Headers.append" }); name = webidl.converters.ByteString(name); value = webidl.converters.ByteString(value); - value = headerValueNormalize(value); - if (!isValidHeaderName(name)) { - throw webidl.errors.invalidArgument({ - prefix: "Headers.append", - value: name, - type: "header name" - }); - } else if (!isValidHeaderValue(value)) { - throw webidl.errors.invalidArgument({ - prefix: "Headers.append", - value, - type: "header value" - }); - } - if (this[kGuard] === "immutable") { - throw new TypeError("immutable"); - } else if (this[kGuard] === "request-no-cors") { - } - return this[kHeadersList].append(name, value); + return appendHeader(this, name, value); } // https://fetch.spec.whatwg.org/#dom-headers-delete delete(name) { @@ -10940,7 +11337,7 @@ var require_headers = __commonJS({ if (!this[kHeadersList].contains(name)) { return; } - return this[kHeadersList].delete(name); + this[kHeadersList].delete(name); } // https://fetch.spec.whatwg.org/#dom-headers-get get(name) { @@ -10994,7 +11391,7 @@ var require_headers = __commonJS({ throw new TypeError("immutable"); } else if (this[kGuard] === "request-no-cors") { } - return this[kHeadersList].set(name, value); + this[kHeadersList].set(name, value); } // https://fetch.spec.whatwg.org/#dom-headers-getsetcookie getSetCookie() { @@ -11013,10 +11410,11 @@ var require_headers = __commonJS({ const headers = []; const names = [...this[kHeadersList]].sort((a, b) => a[0] < b[0] ? -1 : 1); const cookies = this[kHeadersList].cookies; - for (const [name, value] of names) { + for (let i = 0; i < names.length; ++i) { + const [name, value] = names[i]; if (name === "set-cookie") { - for (const value2 of cookies) { - headers.push([name, value2]); + for (let j = 0; j < cookies.length; ++j) { + headers.push([name, cookies[j]]); } } else { assert(value !== null); @@ -11028,6 +11426,14 @@ var require_headers = __commonJS({ } keys() { webidl.brandCheck(this, _Headers); + if (this[kGuard] === "immutable") { + const value = this[kHeadersSortedMap]; + return makeIterator( + () => value, + "Headers", + "key" + ); + } return makeIterator( () => [...this[kHeadersSortedMap].values()], "Headers", @@ -11036,6 +11442,14 @@ var require_headers = __commonJS({ } values() { webidl.brandCheck(this, _Headers); + if (this[kGuard] === "immutable") { + const value = this[kHeadersSortedMap]; + return makeIterator( + () => value, + "Headers", + "value" + ); + } return makeIterator( () => [...this[kHeadersSortedMap].values()], "Headers", @@ -11044,6 +11458,14 @@ var require_headers = __commonJS({ } entries() { webidl.brandCheck(this, _Headers); + if (this[kGuard] === "immutable") { + const value = this[kHeadersSortedMap]; + return makeIterator( + () => value, + "Headers", + "key+value" + ); + } return makeIterator( () => [...this[kHeadersSortedMap].values()], "Headers", @@ -11128,7 +11550,7 @@ var require_response = __commonJS({ isomorphicEncode } = require_util2(); var { - redirectStatus, + redirectStatusSet, nullBodyStatus, DOMException: DOMException2 } = require_constants(); @@ -11137,10 +11559,11 @@ var require_response = __commonJS({ var { FormData } = require_formdata(); var { getGlobalOrigin } = require_global(); var { URLSerializer } = require_dataURL(); - var { kHeadersList } = require_symbols(); + var { kHeadersList, kConstruct } = require_symbols(); var assert = __require("assert"); var { types } = __require("util"); var ReadableStream = globalThis.ReadableStream || __require("stream/web").ReadableStream; + var textEncoder = new TextEncoder("utf-8"); var Response = class _Response { // Creates network error Response. static error() { @@ -11159,7 +11582,7 @@ var require_response = __commonJS({ if (init !== null) { init = webidl.converters.ResponseInit(init); } - const bytes = new TextEncoder("utf-8").encode( + const bytes = textEncoder.encode( serializeJavascriptValueToJSONString(data) ); const body = extractBody(bytes); @@ -11185,7 +11608,7 @@ var require_response = __commonJS({ cause: err }); } - if (!redirectStatus.includes(status)) { + if (!redirectStatusSet.has(status)) { throw new RangeError("Invalid status code " + status); } const responseObject = new _Response(); @@ -11205,7 +11628,7 @@ var require_response = __commonJS({ init = webidl.converters.ResponseInit(init); this[kRealm] = { settingsObject: {} }; this[kState] = makeResponse({}); - this[kHeaders] = new Headers(); + this[kHeaders] = new Headers(kConstruct); this[kHeaders][kGuard] = "response"; this[kHeaders][kHeadersList] = this[kState].headersList; this[kHeaders][kRealm] = this[kRealm]; @@ -11441,7 +11864,7 @@ var require_response = __commonJS({ if (isBlobLike(V)) { return webidl.converters.Blob(V, { strict: false }); } - if (types.isAnyArrayBuffer(V) || types.isTypedArray(V) || types.isDataView(V)) { + if (types.isArrayBuffer(V) || types.isTypedArray(V) || types.isDataView(V)) { return webidl.converters.BufferSource(V); } if (util2.isFormDataLike(V)) { @@ -11500,11 +11923,12 @@ var require_request2 = __commonJS({ isValidHTTPToken, sameOrigin, normalizeMethod, - makePolicyContainer + makePolicyContainer, + normalizeMethodRecord } = require_util2(); var { - forbiddenMethods, - corsSafeListedMethods, + forbiddenMethodsSet, + corsSafeListedMethodsSet, referrerPolicy, requestRedirect, requestMode, @@ -11517,11 +11941,10 @@ var require_request2 = __commonJS({ var { webidl } = require_webidl(); var { getGlobalOrigin } = require_global(); var { URLSerializer } = require_dataURL(); - var { kHeadersList } = require_symbols(); + var { kHeadersList, kConstruct } = require_symbols(); var assert = __require("assert"); var { getMaxListeners, setMaxListeners, getEventListeners, defaultMaxListeners } = __require("events"); var TransformStream = globalThis.TransformStream; - var kInit = Symbol("init"); var kAbortController = Symbol("abortController"); var requestFinalizer = new FinalizationRegistry(({ signal, abort }) => { signal.removeEventListener("abort", abort); @@ -11529,7 +11952,7 @@ var require_request2 = __commonJS({ var Request = class _Request { // https://fetch.spec.whatwg.org/#dom-request constructor(input, init = {}) { - if (input === kInit) { + if (input === kConstruct) { return; } webidl.argumentLengthCheck(arguments, 1, { header: "Request constructor" }); @@ -11621,7 +12044,8 @@ var require_request2 = __commonJS({ // URL list A clone of request’s URL list. urlList: [...request.urlList] }); - if (Object.keys(init).length > 0) { + const initHasKey = Object.keys(init).length !== 0; + if (initHasKey) { if (request.mode === "navigate") { request.mode = "same-origin"; } @@ -11683,7 +12107,7 @@ var require_request2 = __commonJS({ if (init.redirect !== void 0) { request.redirect = init.redirect; } - if (init.integrity !== void 0 && init.integrity != null) { + if (init.integrity != null) { request.integrity = String(init.integrity); } if (init.keepalive !== void 0) { @@ -11691,13 +12115,13 @@ var require_request2 = __commonJS({ } if (init.method !== void 0) { let method = init.method; - if (!isValidHTTPToken(init.method)) { - throw TypeError(`'${init.method}' is not a valid HTTP method.`); + if (!isValidHTTPToken(method)) { + throw new TypeError(`'${method}' is not a valid HTTP method.`); } - if (forbiddenMethods.indexOf(method.toUpperCase()) !== -1) { - throw TypeError(`'${init.method}' HTTP method is unsupported.`); + if (forbiddenMethodsSet.has(method.toUpperCase())) { + throw new TypeError(`'${method}' HTTP method is unsupported.`); } - method = normalizeMethod(init.method); + method = normalizeMethodRecord[method] ?? normalizeMethod(method); request.method = method; } if (init.signal !== void 0) { @@ -11736,28 +12160,27 @@ var require_request2 = __commonJS({ requestFinalizer.register(ac, { signal, abort }); } } - this[kHeaders] = new Headers(); + this[kHeaders] = new Headers(kConstruct); this[kHeaders][kHeadersList] = request.headersList; this[kHeaders][kGuard] = "request"; this[kHeaders][kRealm] = this[kRealm]; if (mode === "no-cors") { - if (!corsSafeListedMethods.includes(request.method)) { + if (!corsSafeListedMethodsSet.has(request.method)) { throw new TypeError( `'${request.method} is unsupported in no-cors mode.` ); } this[kHeaders][kGuard] = "request-no-cors"; } - if (Object.keys(init).length !== 0) { - let headers = new Headers(this[kHeaders]); - if (init.headers !== void 0) { - headers = init.headers; - } - this[kHeaders][kHeadersList].clear(); - if (headers.constructor.name === "Headers") { + if (initHasKey) { + const headersList = this[kHeaders][kHeadersList]; + const headers = init.headers !== void 0 ? init.headers : new HeadersList(headersList); + headersList.clear(); + if (headers instanceof HeadersList) { for (const [key, val] of headers) { - this[kHeaders].append(key, val); + headersList.append(key, val); } + headersList.cookies = headers.cookies; } else { fillHeaders(this[kHeaders], headers); } @@ -11933,10 +12356,10 @@ var require_request2 = __commonJS({ throw new TypeError("unusable"); } const clonedRequest = cloneRequest(this[kState]); - const clonedRequestObject = new _Request(kInit); + const clonedRequestObject = new _Request(kConstruct); clonedRequestObject[kState] = clonedRequest; clonedRequestObject[kRealm] = this[kRealm]; - clonedRequestObject[kHeaders] = new Headers(); + clonedRequestObject[kHeaders] = new Headers(kConstruct); clonedRequestObject[kHeaders][kHeadersList] = clonedRequest.headersList; clonedRequestObject[kHeaders][kGuard] = this[kHeaders][kGuard]; clonedRequestObject[kHeaders][kRealm] = this[kHeaders][kRealm]; @@ -12175,11 +12598,11 @@ var require_fetch = __commonJS({ var assert = __require("assert"); var { safelyExtractBody } = require_body(); var { - redirectStatus, + redirectStatusSet, nullBodyStatus, - safeMethods, + safeMethodsSet, requestBodyHeader, - subresource, + subresourceSet, DOMException: DOMException2 } = require_constants(); var { kHeadersList } = require_symbols(); @@ -12191,6 +12614,7 @@ var require_fetch = __commonJS({ var { getGlobalDispatcher } = require_global2(); var { webidl } = require_webidl(); var { STATUS_CODES } = __require("http"); + var GET_OR_HEAD = ["GET", "HEAD"]; var resolveObjectURL; var ReadableStream = globalThis.ReadableStream; var Fetch = class extends EE { @@ -12224,7 +12648,7 @@ var require_fetch = __commonJS({ this.emit("terminated", error2); } }; - async function fetch(input, init = {}) { + function fetch(input, init = {}) { webidl.argumentLengthCheck(arguments, 1, { header: "globalThis.fetch" }); const p = createDeferredPromise(); let requestObject; @@ -12259,17 +12683,17 @@ var require_fetch = __commonJS({ const handleFetchDone = (response) => finalizeAndReportTiming(response, "fetch"); const processResponse = (response) => { if (locallyAborted) { - return; + return Promise.resolve(); } if (response.aborted) { abortFetch(p, request, responseObject, controller.serializedAbortReason); - return; + return Promise.resolve(); } if (response.type === "error") { p.reject( Object.assign(new TypeError("fetch failed"), { cause: response.error }) ); - return; + return Promise.resolve(); } responseObject = new Response(); responseObject[kState] = response; @@ -12304,7 +12728,7 @@ var require_fetch = __commonJS({ if (timingInfo === null) { return; } - if (!timingInfo.timingAllowPassed) { + if (!response.timingAllowPassed) { timingInfo = createOpaqueTimingInfo({ startTime: timingInfo.startTime }); @@ -12409,7 +12833,7 @@ var require_fetch = __commonJS({ } if (request.priority === null) { } - if (subresource.includes(request.destination)) { + if (subresourceSet.has(request.destination)) { } mainFetch(fetchParams).catch((err) => { fetchParams.controller.terminate(err); @@ -12513,15 +12937,15 @@ var require_fetch = __commonJS({ fetchFinale(fetchParams, response); } } - async function schemeFetch(fetchParams) { + function schemeFetch(fetchParams) { if (isCancelled(fetchParams) && fetchParams.request.redirectCount === 0) { - return makeAppropriateNetworkError(fetchParams); + return Promise.resolve(makeAppropriateNetworkError(fetchParams)); } const { request } = fetchParams; const { protocol: scheme } = requestCurrentURL(request); switch (scheme) { case "about:": { - return makeNetworkError("about scheme is not supported"); + return Promise.resolve(makeNetworkError("about scheme is not supported")); } case "blob:": { if (!resolveObjectURL) { @@ -12529,11 +12953,11 @@ var require_fetch = __commonJS({ } const blobURLEntry = requestCurrentURL(request); if (blobURLEntry.search.length !== 0) { - return makeNetworkError("NetworkError when attempting to fetch resource."); + return Promise.resolve(makeNetworkError("NetworkError when attempting to fetch resource.")); } const blobURLEntryObject = resolveObjectURL(blobURLEntry.toString()); if (request.method !== "GET" || !isBlobLike(blobURLEntryObject)) { - return makeNetworkError("invalid method"); + return Promise.resolve(makeNetworkError("invalid method")); } const bodyWithType = safelyExtractBody(blobURLEntryObject); const body = bodyWithType[0]; @@ -12547,32 +12971,32 @@ var require_fetch = __commonJS({ ] }); response.body = body; - return response; + return Promise.resolve(response); } case "data:": { const currentURL = requestCurrentURL(request); const dataURLStruct = dataURLProcessor(currentURL); if (dataURLStruct === "failure") { - return makeNetworkError("failed to fetch the data URL"); + return Promise.resolve(makeNetworkError("failed to fetch the data URL")); } const mimeType = serializeAMimeType(dataURLStruct.mimeType); - return makeResponse({ + return Promise.resolve(makeResponse({ statusText: "OK", headersList: [ ["content-type", { name: "Content-Type", value: mimeType }] ], body: safelyExtractBody(dataURLStruct.body)[0] - }); + })); } case "file:": { - return makeNetworkError("not implemented... yet..."); + return Promise.resolve(makeNetworkError("not implemented... yet...")); } case "http:": case "https:": { - return await httpFetch(fetchParams).catch((err) => makeNetworkError(err)); + return httpFetch(fetchParams).catch((err) => makeNetworkError(err)); } default: { - return makeNetworkError("unknown scheme"); + return Promise.resolve(makeNetworkError("unknown scheme")); } } } @@ -12582,7 +13006,7 @@ var require_fetch = __commonJS({ queueMicrotask(() => fetchParams.processResponseDone(response)); } } - async function fetchFinale(fetchParams, response) { + function fetchFinale(fetchParams, response) { if (response.type === "error") { response.urlList = [fetchParams.request.urlList[0]]; response.timingInfo = createOpaqueTimingInfo({ @@ -12626,8 +13050,9 @@ var require_fetch = __commonJS({ if (response.body == null) { queueMicrotask(() => processBody(null)); } else { - await fullyReadBody(response.body, processBody, processBodyError); + return fullyReadBody(response.body, processBody, processBodyError); } + return Promise.resolve(); } } async function httpFetch(fetchParams) { @@ -12657,7 +13082,7 @@ var require_fetch = __commonJS({ ) === "blocked") { return makeNetworkError("blocked"); } - if (redirectStatus.includes(actualResponse.status)) { + if (redirectStatusSet.has(actualResponse.status)) { if (request.redirect !== "manual") { fetchParams.controller.connection.destroy(); } @@ -12674,7 +13099,7 @@ var require_fetch = __commonJS({ response.timingInfo = timingInfo; return response; } - async function httpRedirectFetch(fetchParams, response) { + function httpRedirectFetch(fetchParams, response) { const request = fetchParams.request; const actualResponse = response.internalResponse ? response.internalResponse : response; let locationURL; @@ -12687,27 +13112,27 @@ var require_fetch = __commonJS({ return response; } } catch (err) { - return makeNetworkError(err); + return Promise.resolve(makeNetworkError(err)); } if (!urlIsHttpHttpsScheme(locationURL)) { - return makeNetworkError("URL scheme must be a HTTP(S) scheme"); + return Promise.resolve(makeNetworkError("URL scheme must be a HTTP(S) scheme")); } if (request.redirectCount === 20) { - return makeNetworkError("redirect count exceeded"); + return Promise.resolve(makeNetworkError("redirect count exceeded")); } request.redirectCount += 1; if (request.mode === "cors" && (locationURL.username || locationURL.password) && !sameOrigin(request, locationURL)) { - return makeNetworkError('cross origin not allowed for request mode "cors"'); + return Promise.resolve(makeNetworkError('cross origin not allowed for request mode "cors"')); } if (request.responseTainting === "cors" && (locationURL.username || locationURL.password)) { - return makeNetworkError( + return Promise.resolve(makeNetworkError( 'URL cannot contain credentials for request mode "cors"' - ); + )); } if (actualResponse.status !== 303 && request.body != null && request.body.source == null) { - return makeNetworkError(); + return Promise.resolve(makeNetworkError()); } - if ([301, 302].includes(actualResponse.status) && request.method === "POST" || actualResponse.status === 303 && !["GET", "HEAD"].includes(request.method)) { + if ([301, 302].includes(actualResponse.status) && request.method === "POST" || actualResponse.status === 303 && !GET_OR_HEAD.includes(request.method)) { request.method = "GET"; request.body = null; for (const headerName of requestBodyHeader) { @@ -12716,6 +13141,7 @@ var require_fetch = __commonJS({ } if (!sameOrigin(requestCurrentURL(request), locationURL)) { request.headersList.delete("authorization"); + request.headersList.delete("proxy-authorization", true); request.headersList.delete("cookie"); request.headersList.delete("host"); } @@ -12810,7 +13236,7 @@ var require_fetch = __commonJS({ includeCredentials, isNewConnectionFetch ); - if (!safeMethods.includes(httpRequest.method) && forwardResponse.status >= 200 && forwardResponse.status <= 399) { + if (!safeMethodsSet.has(httpRequest.method) && forwardResponse.status >= 200 && forwardResponse.status <= 399) { } if (revalidatingFlag && forwardResponse.status === 304) { } @@ -13025,7 +13451,7 @@ var require_fetch = __commonJS({ path: url.pathname + url.search, origin: url.origin, method: request.method, - body: fetchParams.controller.dispatcher.isMockActive ? request.body && request.body.source : body, + body: fetchParams.controller.dispatcher.isMockActive ? request.body && (request.body.source || request.body.stream) : body, headers: request.headersList.entries, maxRedirections: 0, upgrade: request.mode === "websocket" ? "websocket" : void 0 @@ -13058,7 +13484,7 @@ var require_fetch = __commonJS({ } else if (key.toLowerCase() === "location") { location = val; } - headers.append(key, val); + headers[kHeadersList].append(key, val); } } else { const keys = Object.keys(headersList); @@ -13069,12 +13495,12 @@ var require_fetch = __commonJS({ } else if (key.toLowerCase() === "location") { location = val; } - headers.append(key, val); + headers[kHeadersList].append(key, val); } } this.body = new Readable({ read: resume }); const decoders = []; - const willFollow = request.redirect === "follow" && location && redirectStatus.includes(status); + const willFollow = request.redirect === "follow" && location && redirectStatusSet.has(status); if (request.method !== "HEAD" && request.method !== "CONNECT" && !nullBodyStatus.includes(status) && !willFollow) { for (const coding of codings) { if (coding === "x-gzip" || coding === "gzip") { @@ -13137,7 +13563,7 @@ var require_fetch = __commonJS({ 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); + headers[kHeadersList].append(key, val); } resolve({ status, @@ -13979,7 +14405,7 @@ var require_symbols4 = __commonJS({ "node_modules/undici/lib/cache/symbols.js"(exports, module) { "use strict"; module.exports = { - kConstruct: Symbol("constructable") + kConstruct: require_symbols().kConstruct }; } }); @@ -16356,6 +16782,7 @@ var require_undici = __commonJS({ var MockPool = require_mock_pool(); var mockErrors = require_mock_errors(); var ProxyAgent = require_proxy_agent(); + var RetryHandler = require_RetryHandler(); var { getGlobalDispatcher, setGlobalDispatcher } = require_global2(); var DecoratorHandler = require_DecoratorHandler(); var RedirectHandler = require_RedirectHandler(); @@ -16374,6 +16801,7 @@ var require_undici = __commonJS({ module.exports.BalancedPool = BalancedPool; module.exports.Agent = Agent; module.exports.ProxyAgent = ProxyAgent; + module.exports.RetryHandler = RetryHandler; module.exports.DecoratorHandler = DecoratorHandler; module.exports.RedirectHandler = RedirectHandler; module.exports.createRedirectInterceptor = createRedirectInterceptor; diff --git a/package-lock.json b/package-lock.json index f86b10d3..c7133cac 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1179,9 +1179,9 @@ } }, "node_modules/undici": { - "version": "5.26.3", - "resolved": "https://registry.npmjs.org/undici/-/undici-5.26.3.tgz", - "integrity": "sha512-H7n2zmKEWgOllKkIUkLvFmsJQj062lSm3uA4EYApG8gLuiOM0/go9bIoC3HVaSnfg4xunowDE2i9p8drkXuvDw==", + "version": "5.28.3", + "resolved": "https://registry.npmjs.org/undici/-/undici-5.28.3.tgz", + "integrity": "sha512-3ItfzbrhDlINjaP0duwnNsKpDQk3acHI3gVJ1z4fmwMK31k5G9OVIAMLSIaP6w4FaGkaAkN6zaQO9LUvZ1t7VA==", "dependencies": { "@fastify/busboy": "^2.0.0" }, @@ -1860,9 +1860,9 @@ "dev": true }, "undici": { - "version": "5.26.3", - "resolved": "https://registry.npmjs.org/undici/-/undici-5.26.3.tgz", - "integrity": "sha512-H7n2zmKEWgOllKkIUkLvFmsJQj062lSm3uA4EYApG8gLuiOM0/go9bIoC3HVaSnfg4xunowDE2i9p8drkXuvDw==", + "version": "5.28.3", + "resolved": "https://registry.npmjs.org/undici/-/undici-5.28.3.tgz", + "integrity": "sha512-3ItfzbrhDlINjaP0duwnNsKpDQk3acHI3gVJ1z4fmwMK31k5G9OVIAMLSIaP6w4FaGkaAkN6zaQO9LUvZ1t7VA==", "requires": { "@fastify/busboy": "^2.0.0" }