oricore 1.4.1 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -96,12 +96,16 @@ var require_symbols = __commonJS({
96
96
  kListeners: /* @__PURE__ */ Symbol("listeners"),
97
97
  kHTTPContext: /* @__PURE__ */ Symbol("http context"),
98
98
  kMaxConcurrentStreams: /* @__PURE__ */ Symbol("max concurrent streams"),
99
+ kHTTP2InitialWindowSize: /* @__PURE__ */ Symbol("http2 initial window size"),
100
+ kHTTP2ConnectionWindowSize: /* @__PURE__ */ Symbol("http2 connection window size"),
99
101
  kEnableConnectProtocol: /* @__PURE__ */ Symbol("http2session connect protocol"),
100
102
  kRemoteSettings: /* @__PURE__ */ Symbol("http2session remote settings"),
101
103
  kHTTP2Stream: /* @__PURE__ */ Symbol("http2session client stream"),
104
+ kPingInterval: /* @__PURE__ */ Symbol("ping interval"),
102
105
  kNoProxyAgent: /* @__PURE__ */ Symbol("no proxy agent"),
103
106
  kHttpProxyAgent: /* @__PURE__ */ Symbol("http proxy agent"),
104
- kHttpsProxyAgent: /* @__PURE__ */ Symbol("https proxy agent")
107
+ kHttpsProxyAgent: /* @__PURE__ */ Symbol("https proxy agent"),
108
+ kSocks5ProxyAgent: /* @__PURE__ */ Symbol("socks5 proxy agent")
105
109
  };
106
110
  }
107
111
  });
@@ -691,6 +695,29 @@ var require_errors = __commonJS({
691
695
  return true;
692
696
  }
693
697
  };
698
+ var Socks5ProxyError = class extends UndiciError {
699
+ constructor(message, code) {
700
+ super(message);
701
+ this.name = "Socks5ProxyError";
702
+ this.message = message || "SOCKS5 proxy error";
703
+ this.code = code || "UND_ERR_SOCKS5";
704
+ }
705
+ };
706
+ var kMessageSizeExceededError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_WS_MESSAGE_SIZE_EXCEEDED");
707
+ var MessageSizeExceededError = class extends UndiciError {
708
+ constructor(message) {
709
+ super(message);
710
+ this.name = "MessageSizeExceededError";
711
+ this.message = message || "Max decompressed message size exceeded";
712
+ this.code = "UND_ERR_WS_MESSAGE_SIZE_EXCEEDED";
713
+ }
714
+ static [Symbol.hasInstance](instance) {
715
+ return instance && instance[kMessageSizeExceededError] === true;
716
+ }
717
+ get [kMessageSizeExceededError]() {
718
+ return true;
719
+ }
720
+ };
694
721
  module.exports = {
695
722
  AbortError,
696
723
  HTTPParserError,
@@ -714,7 +741,9 @@ var require_errors = __commonJS({
714
741
  RequestRetryError,
715
742
  ResponseError,
716
743
  SecureProxyConnectionError,
717
- MaxOriginsReachedError
744
+ MaxOriginsReachedError,
745
+ Socks5ProxyError,
746
+ MessageSizeExceededError
718
747
  };
719
748
  }
720
749
  });
@@ -1034,6 +1063,8 @@ var require_util = __commonJS({
1034
1063
  return body;
1035
1064
  } else if (body && typeof body.pipeTo === "function") {
1036
1065
  return new BodyAsyncIterable(body);
1066
+ } else if (body && isFormDataLike(body)) {
1067
+ return body;
1037
1068
  } else if (body && typeof body !== "string" && !ArrayBuffer.isView(body) && isIterable(body)) {
1038
1069
  return new BodyAsyncIterable(body);
1039
1070
  } else {
@@ -1158,6 +1189,11 @@ var require_util = __commonJS({
1158
1189
  function isIterable(obj) {
1159
1190
  return !!(obj != null && (typeof obj[Symbol.iterator] === "function" || typeof obj[Symbol.asyncIterator] === "function"));
1160
1191
  }
1192
+ function hasSafeIterator(obj) {
1193
+ const prototype = Object.getPrototypeOf(obj);
1194
+ const ownIterator = Object.prototype.hasOwnProperty.call(obj, Symbol.iterator);
1195
+ return ownIterator || prototype != null && prototype !== Object.prototype && typeof obj[Symbol.iterator] === "function";
1196
+ }
1161
1197
  function bodyLength(body) {
1162
1198
  if (body == null) {
1163
1199
  return 0;
@@ -1208,51 +1244,46 @@ var require_util = __commonJS({
1208
1244
  for (let i = 0; i < headers.length; i += 2) {
1209
1245
  const key = headerNameToString(headers[i]);
1210
1246
  let val = obj[key];
1211
- if (val) {
1212
- if (typeof val === "string") {
1213
- val = [val];
1214
- obj[key] = val;
1215
- }
1216
- val.push(headers[i + 1].toString("utf8"));
1217
- } else {
1218
- const headersValue = headers[i + 1];
1219
- if (typeof headersValue === "string") {
1220
- obj[key] = headersValue;
1247
+ if (val !== void 0) {
1248
+ if (!Object.hasOwn(obj, key)) {
1249
+ const headersValue = typeof headers[i + 1] === "string" ? headers[i + 1] : Array.isArray(headers[i + 1]) ? headers[i + 1].map((x) => x.toString("latin1")) : headers[i + 1].toString("latin1");
1250
+ if (key === "__proto__") {
1251
+ Object.defineProperty(obj, key, {
1252
+ value: headersValue,
1253
+ enumerable: true,
1254
+ configurable: true,
1255
+ writable: true
1256
+ });
1257
+ } else {
1258
+ obj[key] = headersValue;
1259
+ }
1221
1260
  } else {
1222
- obj[key] = Array.isArray(headersValue) ? headersValue.map((x) => x.toString("utf8")) : headersValue.toString("utf8");
1261
+ if (typeof val === "string") {
1262
+ val = [val];
1263
+ obj[key] = val;
1264
+ }
1265
+ val.push(headers[i + 1].toString("latin1"));
1223
1266
  }
1267
+ } else {
1268
+ const headersValue = typeof headers[i + 1] === "string" ? headers[i + 1] : Array.isArray(headers[i + 1]) ? headers[i + 1].map((x) => x.toString("latin1")) : headers[i + 1].toString("latin1");
1269
+ obj[key] = headersValue;
1224
1270
  }
1225
1271
  }
1226
- if ("content-length" in obj && "content-disposition" in obj) {
1227
- obj["content-disposition"] = Buffer.from(obj["content-disposition"]).toString("latin1");
1228
- }
1229
1272
  return obj;
1230
1273
  }
1231
1274
  function parseRawHeaders(headers) {
1232
1275
  const headersLength = headers.length;
1233
1276
  const ret = new Array(headersLength);
1234
- let hasContentLength = false;
1235
- let contentDispositionIdx = -1;
1236
1277
  let key;
1237
1278
  let val;
1238
- let kLen = 0;
1239
1279
  for (let n = 0; n < headersLength; n += 2) {
1240
1280
  key = headers[n];
1241
1281
  val = headers[n + 1];
1242
1282
  typeof key !== "string" && (key = key.toString());
1243
- typeof val !== "string" && (val = val.toString("utf8"));
1244
- kLen = key.length;
1245
- if (kLen === 14 && key[7] === "-" && (key === "content-length" || key.toLowerCase() === "content-length")) {
1246
- hasContentLength = true;
1247
- } else if (kLen === 19 && key[7] === "-" && (key === "content-disposition" || key.toLowerCase() === "content-disposition")) {
1248
- contentDispositionIdx = n + 1;
1249
- }
1283
+ typeof val !== "string" && (val = val.toString("latin1"));
1250
1284
  ret[n] = key;
1251
1285
  ret[n + 1] = val;
1252
1286
  }
1253
- if (hasContentLength && contentDispositionIdx !== -1) {
1254
- ret[contentDispositionIdx] = Buffer.from(ret[contentDispositionIdx]).toString("latin1");
1255
- }
1256
1287
  return ret;
1257
1288
  }
1258
1289
  function encodeRawHeaders(headers) {
@@ -1767,6 +1798,7 @@ var require_util = __commonJS({
1767
1798
  getServerName,
1768
1799
  isStream,
1769
1800
  isIterable,
1801
+ hasSafeIterator,
1770
1802
  isAsyncIterable,
1771
1803
  isDestroyed,
1772
1804
  headerNameToString,
@@ -2005,10 +2037,12 @@ var require_diagnostics = __commonJS({
2005
2037
  diagnosticsChannel.subscribe(
2006
2038
  "undici:websocket:open",
2007
2039
  (evt) => {
2008
- const {
2009
- address: { address, port }
2010
- } = evt;
2011
- debugLog("connection opened %s%s", address, port ? `:${port}` : "");
2040
+ if (evt.address != null) {
2041
+ const { address, port } = evt.address;
2042
+ debugLog("connection opened %s%s", address, port ? `:${port}` : "");
2043
+ } else {
2044
+ debugLog("connection opened");
2045
+ }
2012
2046
  }
2013
2047
  );
2014
2048
  diagnosticsChannel.subscribe(
@@ -2073,6 +2107,7 @@ var require_request = __commonJS({
2073
2107
  isBuffer,
2074
2108
  isFormDataLike,
2075
2109
  isIterable,
2110
+ hasSafeIterator,
2076
2111
  isBlobLike,
2077
2112
  serializePathWithQuery,
2078
2113
  assertRequestHandler,
@@ -2100,7 +2135,8 @@ var require_request = __commonJS({
2100
2135
  expectContinue,
2101
2136
  servername,
2102
2137
  throwOnError,
2103
- maxRedirections
2138
+ maxRedirections,
2139
+ typeOfService
2104
2140
  }, handler) {
2105
2141
  if (typeof path !== "string") {
2106
2142
  throw new InvalidArgumentError("path must be a string");
@@ -2117,6 +2153,9 @@ var require_request = __commonJS({
2117
2153
  if (upgrade && typeof upgrade !== "string") {
2118
2154
  throw new InvalidArgumentError("upgrade must be a string");
2119
2155
  }
2156
+ if (upgrade && !isValidHeaderValue(upgrade)) {
2157
+ throw new InvalidArgumentError("invalid upgrade header");
2158
+ }
2120
2159
  if (headersTimeout != null && (!Number.isFinite(headersTimeout) || headersTimeout < 0)) {
2121
2160
  throw new InvalidArgumentError("invalid headersTimeout");
2122
2161
  }
@@ -2135,9 +2174,13 @@ var require_request = __commonJS({
2135
2174
  if (maxRedirections != null && maxRedirections !== 0) {
2136
2175
  throw new InvalidArgumentError("maxRedirections is not supported, use the redirect interceptor");
2137
2176
  }
2177
+ if (typeOfService != null && (!Number.isInteger(typeOfService) || typeOfService < 0 || typeOfService > 255)) {
2178
+ throw new InvalidArgumentError("typeOfService must be an integer between 0 and 255");
2179
+ }
2138
2180
  this.headersTimeout = headersTimeout;
2139
2181
  this.bodyTimeout = bodyTimeout;
2140
2182
  this.method = method;
2183
+ this.typeOfService = typeOfService ?? 0;
2141
2184
  this.abort = null;
2142
2185
  if (body == null) {
2143
2186
  this.body = null;
@@ -2193,7 +2236,7 @@ var require_request = __commonJS({
2193
2236
  processHeader(this, headers[i], headers[i + 1]);
2194
2237
  }
2195
2238
  } else if (headers && typeof headers === "object") {
2196
- if (headers[Symbol.iterator]) {
2239
+ if (hasSafeIterator(headers)) {
2197
2240
  for (const header of headers) {
2198
2241
  if (!Array.isArray(header) || header.length !== 2) {
2199
2242
  throw new InvalidArgumentError("headers must be in key-value pair format");
@@ -2362,12 +2405,18 @@ var require_request = __commonJS({
2362
2405
  } else {
2363
2406
  val = `${val}`;
2364
2407
  }
2365
- if (request.host === null && headerName === "host") {
2408
+ if (headerName === "host") {
2409
+ if (request.host !== null) {
2410
+ throw new InvalidArgumentError("duplicate host header");
2411
+ }
2366
2412
  if (typeof val !== "string") {
2367
2413
  throw new InvalidArgumentError("invalid host header");
2368
2414
  }
2369
2415
  request.host = val;
2370
- } else if (request.contentLength === null && headerName === "content-length") {
2416
+ } else if (headerName === "content-length") {
2417
+ if (request.contentLength !== null) {
2418
+ throw new InvalidArgumentError("duplicate content-length header");
2419
+ }
2371
2420
  request.contentLength = parseInt(val, 10);
2372
2421
  if (!Number.isFinite(request.contentLength)) {
2373
2422
  throw new InvalidArgumentError("invalid content-length header");
@@ -2378,12 +2427,18 @@ var require_request = __commonJS({
2378
2427
  } else if (headerName === "transfer-encoding" || headerName === "keep-alive" || headerName === "upgrade") {
2379
2428
  throw new InvalidArgumentError(`invalid ${headerName} header`);
2380
2429
  } else if (headerName === "connection") {
2381
- const value = typeof val === "string" ? val.toLowerCase() : null;
2382
- if (value !== "close" && value !== "keep-alive") {
2430
+ const value = typeof val === "string" ? val : null;
2431
+ if (value === null) {
2383
2432
  throw new InvalidArgumentError("invalid connection header");
2384
2433
  }
2385
- if (value === "close") {
2386
- request.reset = true;
2434
+ for (const token of value.toLowerCase().split(",")) {
2435
+ const trimmed = token.trim();
2436
+ if (!isValidHTTPToken(trimmed)) {
2437
+ throw new InvalidArgumentError("invalid connection header");
2438
+ }
2439
+ if (trimmed === "close") {
2440
+ request.reset = true;
2441
+ }
2387
2442
  }
2388
2443
  } else if (headerName === "expect") {
2389
2444
  throw new NotSupportedError("expect header not supported");
@@ -2412,6 +2467,9 @@ var require_wrap_handler = __commonJS({
2412
2467
  onConnect(abort, context) {
2413
2468
  return this.#handler.onConnect?.(abort, context);
2414
2469
  }
2470
+ onResponseStarted() {
2471
+ return this.#handler.onResponseStarted?.();
2472
+ }
2415
2473
  onHeaders(statusCode, rawHeaders, resume, statusMessage) {
2416
2474
  return this.#handler.onHeaders?.(statusCode, rawHeaders, resume, statusMessage);
2417
2475
  }
@@ -2437,14 +2495,14 @@ var require_wrap_handler = __commonJS({
2437
2495
  onRequestUpgrade(controller, statusCode, headers, socket) {
2438
2496
  const rawHeaders = [];
2439
2497
  for (const [key, val] of Object.entries(headers)) {
2440
- rawHeaders.push(Buffer.from(key), Array.isArray(val) ? val.map((v) => Buffer.from(v)) : Buffer.from(val));
2498
+ rawHeaders.push(Buffer.from(key, "latin1"), toRawHeaderValue(val));
2441
2499
  }
2442
2500
  this.#handler.onUpgrade?.(statusCode, rawHeaders, socket);
2443
2501
  }
2444
2502
  onResponseStart(controller, statusCode, headers, statusMessage) {
2445
2503
  const rawHeaders = [];
2446
2504
  for (const [key, val] of Object.entries(headers)) {
2447
- rawHeaders.push(Buffer.from(key), Array.isArray(val) ? val.map((v) => Buffer.from(v)) : Buffer.from(val));
2505
+ rawHeaders.push(Buffer.from(key, "latin1"), toRawHeaderValue(val));
2448
2506
  }
2449
2507
  if (this.#handler.onHeaders?.(statusCode, rawHeaders, () => controller.resume(), statusMessage) === false) {
2450
2508
  controller.pause();
@@ -2458,7 +2516,7 @@ var require_wrap_handler = __commonJS({
2458
2516
  onResponseEnd(controller, trailers) {
2459
2517
  const rawTrailers = [];
2460
2518
  for (const [key, val] of Object.entries(trailers)) {
2461
- rawTrailers.push(Buffer.from(key), Array.isArray(val) ? val.map((v) => Buffer.from(v)) : Buffer.from(val));
2519
+ rawTrailers.push(Buffer.from(key, "latin1"), toRawHeaderValue(val));
2462
2520
  }
2463
2521
  this.#handler.onComplete?.(rawTrailers);
2464
2522
  }
@@ -2469,6 +2527,9 @@ var require_wrap_handler = __commonJS({
2469
2527
  this.#handler.onError?.(err);
2470
2528
  }
2471
2529
  };
2530
+ function toRawHeaderValue(value) {
2531
+ return Array.isArray(value) ? value.map((item) => Buffer.from(item, "latin1")) : Buffer.from(value, "latin1");
2532
+ }
2472
2533
  }
2473
2534
  });
2474
2535
 
@@ -2569,6 +2630,9 @@ var require_unwrap_handler = __commonJS({
2569
2630
  this.#controller = new UnwrapController(abort);
2570
2631
  this.#handler.onRequestStart?.(this.#controller, context);
2571
2632
  }
2633
+ onResponseStarted() {
2634
+ return this.#handler.onResponseStarted?.();
2635
+ }
2572
2636
  onUpgrade(statusCode, rawHeaders, socket) {
2573
2637
  this.#handler.onRequestUpgrade?.(this.#controller, statusCode, parseHeaders(rawHeaders), socket);
2574
2638
  }
@@ -4288,6 +4352,7 @@ var require_runtime_features = __commonJS({
4288
4352
  var require_webidl = __commonJS({
4289
4353
  "node_modules/undici/lib/web/webidl/index.js"(exports, module) {
4290
4354
  "use strict";
4355
+ var assert = __require("assert");
4291
4356
  var { types, inspect } = __require("util");
4292
4357
  var { runtimeFeatures } = require_runtime_features();
4293
4358
  var UNDEFINED = 1;
@@ -4574,6 +4639,7 @@ var require_webidl = __commonJS({
4574
4639
  };
4575
4640
  };
4576
4641
  webidl.dictionaryConverter = function(converters) {
4642
+ converters.sort((a, b) => (a.key > b.key) - (a.key < b.key));
4577
4643
  return (dictionary, prefix, argument) => {
4578
4644
  const dict = {};
4579
4645
  if (dictionary != null && webidl.util.Type(dictionary) !== OBJECT) {
@@ -4632,6 +4698,27 @@ var require_webidl = __commonJS({
4632
4698
  webidl.is.BufferSource = function(V) {
4633
4699
  return types.isArrayBuffer(V) || ArrayBuffer.isView(V) && types.isArrayBuffer(V.buffer);
4634
4700
  };
4701
+ webidl.util.getCopyOfBytesHeldByBufferSource = function(bufferSource) {
4702
+ const jsBufferSource = bufferSource;
4703
+ let jsArrayBuffer = jsBufferSource;
4704
+ let offset = 0;
4705
+ let length = 0;
4706
+ if (types.isTypedArray(jsBufferSource) || types.isDataView(jsBufferSource)) {
4707
+ jsArrayBuffer = jsBufferSource.buffer;
4708
+ offset = jsBufferSource.byteOffset;
4709
+ length = jsBufferSource.byteLength;
4710
+ } else {
4711
+ assert(types.isAnyArrayBuffer(jsBufferSource));
4712
+ length = jsBufferSource.byteLength;
4713
+ }
4714
+ if (jsArrayBuffer.detached) {
4715
+ return new Uint8Array(0);
4716
+ }
4717
+ const bytes = new Uint8Array(length);
4718
+ const view = new Uint8Array(jsArrayBuffer, offset, length);
4719
+ bytes.set(view);
4720
+ return bytes;
4721
+ };
4635
4722
  webidl.converters.DOMString = function(V, prefix, argument, flags) {
4636
4723
  if (V === null && webidl.util.HasFlag(flags, webidl.attributes.LegacyNullToEmptyString)) {
4637
4724
  return "";
@@ -5556,6 +5643,15 @@ var require_util2 = __commonJS({
5556
5643
  }
5557
5644
  return gettingDecodingSplitting(value);
5558
5645
  }
5646
+ function hasAuthenticationEntry(request) {
5647
+ return false;
5648
+ }
5649
+ function includesCredentials(url) {
5650
+ return !!(url.username || url.password);
5651
+ }
5652
+ function isTraversableNavigable(navigable) {
5653
+ return true;
5654
+ }
5559
5655
  var EnvironmentSettingsObjectBase = class {
5560
5656
  get baseUrl() {
5561
5657
  return getGlobalOrigin();
@@ -5613,7 +5709,10 @@ var require_util2 = __commonJS({
5613
5709
  extractMimeType,
5614
5710
  getDecodeSplit,
5615
5711
  environmentSettingsObject,
5616
- isOriginIPPotentiallyTrustworthy
5712
+ isOriginIPPotentiallyTrustworthy,
5713
+ hasAuthenticationEntry,
5714
+ includesCredentials,
5715
+ isTraversableNavigable
5617
5716
  };
5618
5717
  }
5619
5718
  });
@@ -5790,9 +5889,9 @@ var require_formdata_parser = __commonJS({
5790
5889
  var { webidl } = require_webidl();
5791
5890
  var assert = __require("assert");
5792
5891
  var { isomorphicDecode } = require_infra();
5793
- var { utf8DecodeBytes } = require_encoding();
5794
5892
  var dd = Buffer.from("--");
5795
5893
  var decoder = new TextDecoder();
5894
+ var decoderIgnoreBOM = new TextDecoder("utf-8", { ignoreBOM: true });
5796
5895
  function isAsciiString(chars) {
5797
5896
  for (let i = 0; i < chars.length; ++i) {
5798
5897
  if ((chars.charCodeAt(i) & ~127) !== 0) {
@@ -5869,7 +5968,7 @@ var require_formdata_parser = __commonJS({
5869
5968
  }
5870
5969
  value = new File([body], filename, { type: contentType });
5871
5970
  } else {
5872
- value = utf8DecodeBytes(Buffer.from(body));
5971
+ value = decoderIgnoreBOM.decode(Buffer.from(body));
5873
5972
  }
5874
5973
  assert(webidl.is.USVString(name));
5875
5974
  assert(typeof value === "string" && webidl.is.USVString(value) || webidl.is.File(value));
@@ -6138,7 +6237,7 @@ var require_body = __commonJS({
6138
6237
  var { webidl } = require_webidl();
6139
6238
  var assert = __require("assert");
6140
6239
  var { isErrored, isDisturbed } = __require("stream");
6141
- var { isArrayBuffer } = __require("util/types");
6240
+ var { isUint8Array } = __require("util/types");
6142
6241
  var { serializeAMimeType } = require_data_url();
6143
6242
  var { multipartFormDataParser } = require_formdata_parser();
6144
6243
  var { createDeferredPromise } = require_promise();
@@ -6157,20 +6256,19 @@ var require_body = __commonJS({
6157
6256
  });
6158
6257
  function extractBody(object, keepalive = false) {
6159
6258
  let stream = null;
6259
+ let controller = null;
6160
6260
  if (webidl.is.ReadableStream(object)) {
6161
6261
  stream = object;
6162
6262
  } else if (webidl.is.Blob(object)) {
6163
6263
  stream = object.stream();
6164
6264
  } else {
6165
6265
  stream = new ReadableStream({
6166
- pull(controller) {
6167
- const buffer = typeof source === "string" ? textEncoder.encode(source) : source;
6168
- if (buffer.byteLength) {
6169
- controller.enqueue(buffer);
6170
- }
6171
- queueMicrotask(() => readableStreamClose(controller));
6266
+ pull() {
6172
6267
  },
6173
- start() {
6268
+ start(c) {
6269
+ controller = c;
6270
+ },
6271
+ cancel() {
6174
6272
  },
6175
6273
  type: "bytes"
6176
6274
  });
@@ -6187,7 +6285,7 @@ var require_body = __commonJS({
6187
6285
  source = object.toString();
6188
6286
  type = "application/x-www-form-urlencoded;charset=UTF-8";
6189
6287
  } else if (webidl.is.BufferSource(object)) {
6190
- source = isArrayBuffer(object) ? new Uint8Array(object.slice()) : new Uint8Array(object.buffer.slice(object.byteOffset, object.byteOffset + object.byteLength));
6288
+ source = webidl.util.getCopyOfBytesHeldByBufferSource(object);
6191
6289
  } else if (webidl.is.FormData(object)) {
6192
6290
  const boundary = `----formdata-undici-0${`${random(1e11)}`.padStart(11, "0")}`;
6193
6291
  const prefix = `--${boundary}\r
@@ -6254,38 +6352,29 @@ Content-Type: ${value.type || "application/octet-stream"}\r
6254
6352
  }
6255
6353
  stream = webidl.is.ReadableStream(object) ? object : ReadableStreamFrom(object);
6256
6354
  }
6257
- if (typeof source === "string" || util.isBuffer(source)) {
6258
- length = Buffer.byteLength(source);
6355
+ if (typeof source === "string" || isUint8Array(source)) {
6356
+ action = () => {
6357
+ length = typeof source === "string" ? Buffer.byteLength(source) : source.length;
6358
+ return source;
6359
+ };
6259
6360
  }
6260
6361
  if (action != null) {
6261
- let iterator;
6262
- stream = new ReadableStream({
6263
- start() {
6264
- iterator = action(object)[Symbol.asyncIterator]();
6265
- },
6266
- pull(controller) {
6267
- return iterator.next().then(({ value, done }) => {
6268
- if (done) {
6269
- queueMicrotask(() => {
6270
- controller.close();
6271
- controller.byobRequest?.respond(0);
6272
- });
6273
- } else {
6274
- if (!isErrored(stream)) {
6275
- const buffer = new Uint8Array(value);
6276
- if (buffer.byteLength) {
6277
- controller.enqueue(buffer);
6278
- }
6279
- }
6362
+ ;
6363
+ (async () => {
6364
+ const result = action();
6365
+ const iterator = result?.[Symbol.asyncIterator]?.();
6366
+ if (iterator) {
6367
+ for await (const bytes of iterator) {
6368
+ if (isErrored(stream)) break;
6369
+ if (bytes.length) {
6370
+ controller.enqueue(new Uint8Array(bytes));
6280
6371
  }
6281
- return controller.desiredSize > 0;
6282
- });
6283
- },
6284
- cancel(reason) {
6285
- return iterator.return();
6286
- },
6287
- type: "bytes"
6288
- });
6372
+ }
6373
+ } else if (result?.length && !isErrored(stream)) {
6374
+ controller.enqueue(typeof result === "string" ? textEncoder.encode(result) : new Uint8Array(result));
6375
+ }
6376
+ queueMicrotask(() => readableStreamClose(controller));
6377
+ })();
6289
6378
  }
6290
6379
  const body = { stream, source, length };
6291
6380
  return [body, type];
@@ -6373,13 +6462,10 @@ Content-Type: ${value.type || "application/octet-stream"}\r
6373
6462
  } catch (e) {
6374
6463
  return Promise.reject(e);
6375
6464
  }
6376
- const state = getInternalState(object);
6377
- if (bodyUnusable(state)) {
6465
+ object = getInternalState(object);
6466
+ if (bodyUnusable(object)) {
6378
6467
  return Promise.reject(new TypeError("Body is unusable: Body has already been read"));
6379
6468
  }
6380
- if (state.aborted) {
6381
- return Promise.reject(new DOMException("The operation was aborted.", "AbortError"));
6382
- }
6383
6469
  const promise = createDeferredPromise();
6384
6470
  const errorSteps = promise.reject;
6385
6471
  const successSteps = (data) => {
@@ -6389,11 +6475,11 @@ Content-Type: ${value.type || "application/octet-stream"}\r
6389
6475
  errorSteps(e);
6390
6476
  }
6391
6477
  };
6392
- if (state.body == null) {
6478
+ if (object.body == null) {
6393
6479
  successSteps(Buffer.allocUnsafe(0));
6394
6480
  return promise.promise;
6395
6481
  }
6396
- fullyReadBody(state.body, successSteps, errorSteps);
6482
+ fullyReadBody(object.body, successSteps, errorSteps);
6397
6483
  return promise.promise;
6398
6484
  }
6399
6485
  function bodyUnusable(object) {
@@ -6995,8 +7081,12 @@ var require_client_h1 = __commonJS({
6995
7081
  return 0;
6996
7082
  }
6997
7083
  };
6998
- function onParserTimeout(parser) {
6999
- const { socket, timeoutType, client, paused } = parser.deref();
7084
+ function onParserTimeout(parserWeakRef) {
7085
+ const parser = parserWeakRef.deref();
7086
+ if (!parser) {
7087
+ return;
7088
+ }
7089
+ const { socket, timeoutType, client, paused } = parser;
7000
7090
  if (timeoutType === TIMEOUT_HEADERS) {
7001
7091
  if (!socket[kWriting] || socket.writableNeedDrain || client[kRunning] > 1) {
7002
7092
  assert(!paused, "cannot be paused while waiting for headers");
@@ -7232,6 +7322,9 @@ var require_client_h1 = __commonJS({
7232
7322
  if (blocking) {
7233
7323
  socket[kBlocking] = true;
7234
7324
  }
7325
+ if (socket.setTypeOfService) {
7326
+ socket.setTypeOfService(request.typeOfService);
7327
+ }
7235
7328
  let header = `${method} ${path} HTTP/1.1\r
7236
7329
  `;
7237
7330
  if (typeof host === "string") {
@@ -7606,7 +7699,10 @@ var require_client_h2 = __commonJS({
7606
7699
  kStrictContentLength,
7607
7700
  kOnError,
7608
7701
  kMaxConcurrentStreams,
7702
+ kPingInterval,
7609
7703
  kHTTP2Session,
7704
+ kHTTP2InitialWindowSize,
7705
+ kHTTP2ConnectionWindowSize,
7610
7706
  kResume,
7611
7707
  kSize,
7612
7708
  kHTTPContext,
@@ -7614,7 +7710,8 @@ var require_client_h2 = __commonJS({
7614
7710
  kBodyTimeout,
7615
7711
  kEnableConnectProtocol,
7616
7712
  kRemoteSettings,
7617
- kHTTP2Stream
7713
+ kHTTP2Stream,
7714
+ kHTTP2SessionState
7618
7715
  } = require_symbols();
7619
7716
  var { channels } = require_diagnostics();
7620
7717
  var kOpenStreams = /* @__PURE__ */ Symbol("open streams");
@@ -7654,20 +7751,31 @@ var require_client_h2 = __commonJS({
7654
7751
  }
7655
7752
  function connectH2(client, socket) {
7656
7753
  client[kSocket] = socket;
7754
+ const http2InitialWindowSize = client[kHTTP2InitialWindowSize];
7755
+ const http2ConnectionWindowSize = client[kHTTP2ConnectionWindowSize];
7657
7756
  const session = http2.connect(client[kUrl], {
7658
7757
  createConnection: () => socket,
7659
7758
  peerMaxConcurrentStreams: client[kMaxConcurrentStreams],
7660
7759
  settings: {
7661
7760
  // TODO(metcoder95): add support for PUSH
7662
- enablePush: false
7761
+ enablePush: false,
7762
+ ...http2InitialWindowSize != null ? { initialWindowSize: http2InitialWindowSize } : null
7663
7763
  }
7664
7764
  });
7765
+ client[kSocket] = socket;
7665
7766
  session[kOpenStreams] = 0;
7666
7767
  session[kClient] = client;
7667
7768
  session[kSocket] = socket;
7668
- session[kHTTP2Session] = null;
7769
+ session[kHTTP2SessionState] = {
7770
+ ping: {
7771
+ interval: client[kPingInterval] === 0 ? null : setInterval(onHttp2SendPing, client[kPingInterval], session).unref()
7772
+ }
7773
+ };
7669
7774
  session[kEnableConnectProtocol] = false;
7670
7775
  session[kRemoteSettings] = false;
7776
+ if (http2ConnectionWindowSize) {
7777
+ util.addListener(session, "connect", applyConnectionWindowSize.bind(session, http2ConnectionWindowSize));
7778
+ }
7671
7779
  util.addListener(session, "error", onHttp2SessionError);
7672
7780
  util.addListener(session, "frameError", onHttp2FrameError);
7673
7781
  util.addListener(session, "end", onHttp2SessionEnd);
@@ -7745,6 +7853,14 @@ var require_client_h2 = __commonJS({
7745
7853
  }
7746
7854
  }
7747
7855
  }
7856
+ function applyConnectionWindowSize(connectionWindowSize) {
7857
+ try {
7858
+ if (typeof this.setLocalWindowSize === "function") {
7859
+ this.setLocalWindowSize(connectionWindowSize);
7860
+ }
7861
+ } catch {
7862
+ }
7863
+ }
7748
7864
  function onHttp2RemoteSettings(settings) {
7749
7865
  this[kClient][kMaxConcurrentStreams] = settings.maxConcurrentStreams ?? this[kClient][kMaxConcurrentStreams];
7750
7866
  if (this[kRemoteSettings] === true && this[kEnableConnectProtocol] === true && settings.enableConnectProtocol === false) {
@@ -7757,6 +7873,26 @@ var require_client_h2 = __commonJS({
7757
7873
  this[kRemoteSettings] = true;
7758
7874
  this[kClient][kResume]();
7759
7875
  }
7876
+ function onHttp2SendPing(session) {
7877
+ const state = session[kHTTP2SessionState];
7878
+ if ((session.closed || session.destroyed) && state.ping.interval != null) {
7879
+ clearInterval(state.ping.interval);
7880
+ state.ping.interval = null;
7881
+ return;
7882
+ }
7883
+ session.ping(onPing.bind(session));
7884
+ function onPing(err, duration) {
7885
+ const client = this[kClient];
7886
+ const socket = this[kClient];
7887
+ if (err != null) {
7888
+ const error = new InformationalError(`HTTP/2: "PING" errored - type ${err.message}`);
7889
+ socket[kError] = error;
7890
+ client[kOnError](error);
7891
+ } else {
7892
+ client.emit("ping", duration);
7893
+ }
7894
+ }
7895
+ }
7760
7896
  function onHttp2SessionError(err) {
7761
7897
  assert(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID");
7762
7898
  this[kSocket][kError] = err;
@@ -7794,11 +7930,15 @@ var require_client_h2 = __commonJS({
7794
7930
  client[kResume]();
7795
7931
  }
7796
7932
  function onHttp2SessionClose() {
7797
- const { [kClient]: client } = this;
7933
+ const { [kClient]: client, [kHTTP2SessionState]: state } = this;
7798
7934
  const { [kSocket]: socket } = client;
7799
7935
  const err = this[kSocket][kError] || this[kError] || new SocketError("closed", util.getSocketInfo(socket));
7800
7936
  client[kSocket] = null;
7801
7937
  client[kHTTPContext] = null;
7938
+ if (state.ping.interval != null) {
7939
+ clearInterval(state.ping.interval);
7940
+ state.ping.interval = null;
7941
+ }
7802
7942
  if (client.destroyed) {
7803
7943
  assert(client[kPending] === 0);
7804
7944
  const requests = client[kQueue].splice(client[kRunningIdx]);
@@ -8003,9 +8143,11 @@ var require_client_h2 = __commonJS({
8003
8143
  }
8004
8144
  ++session[kOpenStreams];
8005
8145
  stream.setTimeout(requestTimeout);
8146
+ let responseReceived = false;
8006
8147
  stream.once("response", (headers2) => {
8007
8148
  const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers2;
8008
8149
  request.onResponseStarted();
8150
+ responseReceived = true;
8009
8151
  if (request.aborted) {
8010
8152
  stream.removeAllListeners("data");
8011
8153
  return;
@@ -8013,26 +8155,25 @@ var require_client_h2 = __commonJS({
8013
8155
  if (request.onHeaders(Number(statusCode), parseH2Headers(realHeaders), stream.resume.bind(stream), "") === false) {
8014
8156
  stream.pause();
8015
8157
  }
8158
+ stream.on("data", (chunk) => {
8159
+ if (request.aborted || request.completed) {
8160
+ return;
8161
+ }
8162
+ if (request.onData(chunk) === false) {
8163
+ stream.pause();
8164
+ }
8165
+ });
8016
8166
  });
8017
- stream.on("data", (chunk) => {
8018
- if (request.onData(chunk) === false) {
8019
- stream.pause();
8020
- }
8021
- });
8022
- stream.once("end", (err) => {
8167
+ stream.once("end", () => {
8023
8168
  stream.removeAllListeners("data");
8024
- if (stream.state?.state == null || stream.state.state < 6) {
8169
+ if (responseReceived) {
8025
8170
  if (!request.aborted && !request.completed) {
8026
8171
  request.onComplete({});
8027
8172
  }
8028
8173
  client[kQueue][client[kRunningIdx]++] = null;
8029
8174
  client[kResume]();
8030
8175
  } else {
8031
- --session[kOpenStreams];
8032
- if (session[kOpenStreams] === 0) {
8033
- session.unref();
8034
- }
8035
- abort(err ?? new InformationalError("HTTP/2: stream half-closed (remote)"));
8176
+ abort(new InformationalError("HTTP/2: stream half-closed (remote)"));
8036
8177
  client[kQueue][client[kRunningIdx]++] = null;
8037
8178
  client[kPendingIdx] = client[kRunningIdx];
8038
8179
  client[kResume]();
@@ -8069,6 +8210,7 @@ var require_client_h2 = __commonJS({
8069
8210
  if (request.aborted || request.completed) {
8070
8211
  return;
8071
8212
  }
8213
+ stream.removeAllListeners("data");
8072
8214
  request.onComplete(trailers);
8073
8215
  });
8074
8216
  return true;
@@ -8312,7 +8454,10 @@ var require_client = __commonJS({
8312
8454
  kOnError,
8313
8455
  kHTTPContext,
8314
8456
  kMaxConcurrentStreams,
8315
- kResume
8457
+ kHTTP2InitialWindowSize,
8458
+ kHTTP2ConnectionWindowSize,
8459
+ kResume,
8460
+ kPingInterval
8316
8461
  } = require_symbols();
8317
8462
  var connectH1 = require_client_h1();
8318
8463
  var connectH2 = require_client_h2();
@@ -8358,7 +8503,10 @@ var require_client = __commonJS({
8358
8503
  // h2
8359
8504
  maxConcurrentStreams,
8360
8505
  allowH2,
8361
- useH2c
8506
+ useH2c,
8507
+ initialWindowSize,
8508
+ connectionWindowSize,
8509
+ pingInterval
8362
8510
  } = {}) {
8363
8511
  if (keepAlive !== void 0) {
8364
8512
  throw new InvalidArgumentError("unsupported keepAlive, use pipelining=0 instead");
@@ -8427,6 +8575,15 @@ var require_client = __commonJS({
8427
8575
  if (useH2c != null && typeof useH2c !== "boolean") {
8428
8576
  throw new InvalidArgumentError("useH2c must be a valid boolean value");
8429
8577
  }
8578
+ if (initialWindowSize != null && (!Number.isInteger(initialWindowSize) || initialWindowSize < 1)) {
8579
+ throw new InvalidArgumentError("initialWindowSize must be a positive integer, greater than 0");
8580
+ }
8581
+ if (connectionWindowSize != null && (!Number.isInteger(connectionWindowSize) || connectionWindowSize < 1)) {
8582
+ throw new InvalidArgumentError("connectionWindowSize must be a positive integer, greater than 0");
8583
+ }
8584
+ if (pingInterval != null && (typeof pingInterval !== "number" || !Number.isInteger(pingInterval) || pingInterval < 0)) {
8585
+ throw new InvalidArgumentError("pingInterval must be a positive integer, greater or equal to 0");
8586
+ }
8430
8587
  super();
8431
8588
  if (typeof connect2 !== "function") {
8432
8589
  connect2 = buildConnector({
@@ -8439,6 +8596,9 @@ var require_client = __commonJS({
8439
8596
  ...typeof autoSelectFamily === "boolean" ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : void 0,
8440
8597
  ...connect2
8441
8598
  });
8599
+ } else if (socketPath != null) {
8600
+ const customConnect = connect2;
8601
+ connect2 = (opts, callback) => customConnect({ ...opts, socketPath }, callback);
8442
8602
  }
8443
8603
  this[kUrl] = util.parseOrigin(url);
8444
8604
  this[kConnector] = connect2;
@@ -8460,8 +8620,11 @@ var require_client = __commonJS({
8460
8620
  this[kMaxRequests] = maxRequestsPerClient;
8461
8621
  this[kClosedResolve] = null;
8462
8622
  this[kMaxResponseSize] = maxResponseSize > -1 ? maxResponseSize : -1;
8463
- this[kMaxConcurrentStreams] = maxConcurrentStreams != null ? maxConcurrentStreams : 100;
8464
8623
  this[kHTTPContext] = null;
8624
+ this[kMaxConcurrentStreams] = maxConcurrentStreams != null ? maxConcurrentStreams : 100;
8625
+ this[kHTTP2InitialWindowSize] = initialWindowSize != null ? initialWindowSize : 262144;
8626
+ this[kHTTP2ConnectionWindowSize] = connectionWindowSize != null ? connectionWindowSize : 524288;
8627
+ this[kPingInterval] = pingInterval != null ? pingInterval : 6e4;
8465
8628
  this[kQueue] = [];
8466
8629
  this[kRunningIdx] = 0;
8467
8630
  this[kPendingIdx] = 0;
@@ -8584,56 +8747,61 @@ var require_client = __commonJS({
8584
8747
  connector: client[kConnector]
8585
8748
  });
8586
8749
  }
8587
- client[kConnector]({
8588
- host,
8589
- hostname,
8590
- protocol,
8591
- port,
8592
- servername: client[kServerName],
8593
- localAddress: client[kLocalAddress]
8594
- }, (err, socket) => {
8595
- if (err) {
8596
- handleConnectError(client, err, { host, hostname, protocol, port });
8597
- client[kResume]();
8598
- return;
8599
- }
8600
- if (client.destroyed) {
8601
- util.destroy(socket.on("error", noop), new ClientDestroyedError());
8602
- client[kResume]();
8603
- return;
8604
- }
8605
- assert(socket);
8606
- try {
8607
- client[kHTTPContext] = socket.alpnProtocol === "h2" ? connectH2(client, socket) : connectH1(client, socket);
8608
- } catch (err2) {
8609
- socket.destroy().on("error", noop);
8610
- handleConnectError(client, err2, { host, hostname, protocol, port });
8750
+ try {
8751
+ client[kConnector]({
8752
+ host,
8753
+ hostname,
8754
+ protocol,
8755
+ port,
8756
+ servername: client[kServerName],
8757
+ localAddress: client[kLocalAddress]
8758
+ }, (err, socket) => {
8759
+ if (err) {
8760
+ handleConnectError(client, err, { host, hostname, protocol, port });
8761
+ client[kResume]();
8762
+ return;
8763
+ }
8764
+ if (client.destroyed) {
8765
+ util.destroy(socket.on("error", noop), new ClientDestroyedError());
8766
+ client[kResume]();
8767
+ return;
8768
+ }
8769
+ assert(socket);
8770
+ try {
8771
+ client[kHTTPContext] = socket.alpnProtocol === "h2" ? connectH2(client, socket) : connectH1(client, socket);
8772
+ } catch (err2) {
8773
+ socket.destroy().on("error", noop);
8774
+ handleConnectError(client, err2, { host, hostname, protocol, port });
8775
+ client[kResume]();
8776
+ return;
8777
+ }
8778
+ client[kConnecting] = false;
8779
+ socket[kCounter] = 0;
8780
+ socket[kMaxRequests] = client[kMaxRequests];
8781
+ socket[kClient] = client;
8782
+ socket[kError] = null;
8783
+ if (channels.connected.hasSubscribers) {
8784
+ channels.connected.publish({
8785
+ connectParams: {
8786
+ host,
8787
+ hostname,
8788
+ protocol,
8789
+ port,
8790
+ version: client[kHTTPContext]?.version,
8791
+ servername: client[kServerName],
8792
+ localAddress: client[kLocalAddress]
8793
+ },
8794
+ connector: client[kConnector],
8795
+ socket
8796
+ });
8797
+ }
8798
+ client.emit("connect", client[kUrl], [client]);
8611
8799
  client[kResume]();
8612
- return;
8613
- }
8614
- client[kConnecting] = false;
8615
- socket[kCounter] = 0;
8616
- socket[kMaxRequests] = client[kMaxRequests];
8617
- socket[kClient] = client;
8618
- socket[kError] = null;
8619
- if (channels.connected.hasSubscribers) {
8620
- channels.connected.publish({
8621
- connectParams: {
8622
- host,
8623
- hostname,
8624
- protocol,
8625
- port,
8626
- version: client[kHTTPContext]?.version,
8627
- servername: client[kServerName],
8628
- localAddress: client[kLocalAddress]
8629
- },
8630
- connector: client[kConnector],
8631
- socket
8632
- });
8633
- }
8634
- client.emit("connect", client[kUrl], [client]);
8800
+ });
8801
+ } catch (err) {
8802
+ handleConnectError(client, err, { host, hostname, protocol, port });
8635
8803
  client[kResume]();
8636
- });
8804
+ }
8637
8805
  }
8638
8806
  function handleConnectError(client, err, { host, hostname, protocol, port }) {
8639
8807
  if (client.destroyed) {
@@ -8715,6 +8883,9 @@ var require_client = __commonJS({
8715
8883
  return;
8716
8884
  }
8717
8885
  const request = client[kQueue][client[kPendingIdx]];
8886
+ if (request === null) {
8887
+ return;
8888
+ }
8718
8889
  if (client[kUrl].protocol === "https:" && client[kServerName] !== request.servername) {
8719
8890
  if (client[kRunning] > 0) {
8720
8891
  return;
@@ -8861,9 +9032,12 @@ var require_pool_base = __commonJS({
8861
9032
  this.emit("drain", origin, [this, ...targets]);
8862
9033
  }
8863
9034
  if (this[kClosedResolve] && queue.isEmpty()) {
8864
- const closeAll = new Array(this[kClients].length);
9035
+ const closeAll = [];
8865
9036
  for (let i = 0; i < this[kClients].length; i++) {
8866
- closeAll[i] = this[kClients][i].close();
9037
+ const client2 = this[kClients][i];
9038
+ if (!client2.destroyed) {
9039
+ closeAll.push(client2.close());
9040
+ }
8867
9041
  }
8868
9042
  return Promise.all(closeAll).then(this[kClosedResolve]);
8869
9043
  }
@@ -8920,9 +9094,12 @@ var require_pool_base = __commonJS({
8920
9094
  }
8921
9095
  [kClose]() {
8922
9096
  if (this[kQueue].isEmpty()) {
8923
- const closeAll = new Array(this[kClients].length);
9097
+ const closeAll = [];
8924
9098
  for (let i = 0; i < this[kClients].length; i++) {
8925
- closeAll[i] = this[kClients][i].close();
9099
+ const client = this[kClients][i];
9100
+ if (!client.destroyed) {
9101
+ closeAll.push(client.close());
9102
+ }
8926
9103
  }
8927
9104
  return Promise.all(closeAll);
8928
9105
  } else {
@@ -9053,7 +9230,7 @@ var require_pool = __commonJS({
9053
9230
  super();
9054
9231
  this[kConnections] = connections || null;
9055
9232
  this[kUrl] = util.parseOrigin(origin);
9056
- this[kOptions] = { ...util.deepClone(options), connect, allowH2, clientTtl };
9233
+ this[kOptions] = { ...util.deepClone(options), connect, allowH2, clientTtl, socketPath };
9057
9234
  this[kOptions].interceptors = options.interceptors ? { ...options.interceptors } : void 0;
9058
9235
  this[kFactory] = factory;
9059
9236
  this.on("connect", (origin2, targets) => {
@@ -9110,7 +9287,7 @@ var require_balanced_pool = __commonJS({
9110
9287
  } = require_pool_base();
9111
9288
  var Pool = require_pool();
9112
9289
  var { kUrl } = require_symbols();
9113
- var { parseOrigin } = require_util();
9290
+ var util = require_util();
9114
9291
  var kFactory = /* @__PURE__ */ Symbol("factory");
9115
9292
  var kOptions = /* @__PURE__ */ Symbol("options");
9116
9293
  var kGreatestCommonDivisor = /* @__PURE__ */ Symbol("kGreatestCommonDivisor");
@@ -9137,7 +9314,8 @@ var require_balanced_pool = __commonJS({
9137
9314
  throw new InvalidArgumentError("factory must be a function.");
9138
9315
  }
9139
9316
  super();
9140
- this[kOptions] = opts;
9317
+ this[kOptions] = { ...util.deepClone(opts) };
9318
+ this[kOptions].interceptors = opts.interceptors ? { ...opts.interceptors } : void 0;
9141
9319
  this[kIndex] = -1;
9142
9320
  this[kCurrentWeight] = 0;
9143
9321
  this[kMaxWeightPerServer] = this[kOptions].maxWeightPerServer || 100;
@@ -9152,11 +9330,11 @@ var require_balanced_pool = __commonJS({
9152
9330
  this._updateBalancedPoolStats();
9153
9331
  }
9154
9332
  addUpstream(upstream) {
9155
- const upstreamOrigin = parseOrigin(upstream).origin;
9333
+ const upstreamOrigin = util.parseOrigin(upstream).origin;
9156
9334
  if (this[kClients].find((pool2) => pool2[kUrl].origin === upstreamOrigin && pool2.closed !== true && pool2.destroyed !== true)) {
9157
9335
  return this;
9158
9336
  }
9159
- const pool = this[kFactory](upstreamOrigin, Object.assign({}, this[kOptions]));
9337
+ const pool = this[kFactory](upstreamOrigin, this[kOptions]);
9160
9338
  this[kAddClient](pool);
9161
9339
  pool.on("connect", () => {
9162
9340
  pool[kWeight] = Math.min(this[kMaxWeightPerServer], pool[kWeight] + this[kErrorPenalty]);
@@ -9186,7 +9364,7 @@ var require_balanced_pool = __commonJS({
9186
9364
  this[kGreatestCommonDivisor] = result;
9187
9365
  }
9188
9366
  removeUpstream(upstream) {
9189
- const upstreamOrigin = parseOrigin(upstream).origin;
9367
+ const upstreamOrigin = util.parseOrigin(upstream).origin;
9190
9368
  const pool = this[kClients].find((pool2) => pool2[kUrl].origin === upstreamOrigin && pool2.closed !== true && pool2.destroyed !== true);
9191
9369
  if (pool) {
9192
9370
  this[kRemoveClient](pool);
@@ -9194,7 +9372,7 @@ var require_balanced_pool = __commonJS({
9194
9372
  return this;
9195
9373
  }
9196
9374
  getUpstream(upstream) {
9197
- const upstreamOrigin = parseOrigin(upstream).origin;
9375
+ const upstreamOrigin = util.parseOrigin(upstream).origin;
9198
9376
  return this[kClients].find((pool) => pool[kUrl].origin === upstreamOrigin && pool.closed !== true && pool.destroyed !== true);
9199
9377
  }
9200
9378
  get upstreams() {
@@ -9303,7 +9481,7 @@ var require_round_robin_pool = __commonJS({
9303
9481
  super();
9304
9482
  this[kConnections] = connections || null;
9305
9483
  this[kUrl] = util.parseOrigin(origin);
9306
- this[kOptions] = { ...util.deepClone(options), connect, allowH2, clientTtl };
9484
+ this[kOptions] = { ...util.deepClone(options), connect, allowH2, clientTtl, socketPath };
9307
9485
  this[kOptions].interceptors = options.interceptors ? { ...options.interceptors } : void 0;
9308
9486
  this[kFactory] = factory;
9309
9487
  this[kIndex] = -1;
@@ -9434,7 +9612,9 @@ var require_agent = __commonJS({
9434
9612
  if (connected) result2.count -= 1;
9435
9613
  if (result2.count <= 0) {
9436
9614
  this[kClients].delete(key);
9437
- result2.dispatcher.close();
9615
+ if (!result2.dispatcher.destroyed) {
9616
+ result2.dispatcher.close();
9617
+ }
9438
9618
  }
9439
9619
  this[kOrigins].delete(key);
9440
9620
  }
@@ -9487,82 +9667,744 @@ var require_agent = __commonJS({
9487
9667
  }
9488
9668
  });
9489
9669
 
9490
- // node_modules/undici/lib/dispatcher/proxy-agent.js
9491
- var require_proxy_agent = __commonJS({
9492
- "node_modules/undici/lib/dispatcher/proxy-agent.js"(exports, module) {
9670
+ // node_modules/undici/lib/core/socks5-utils.js
9671
+ var require_socks5_utils = __commonJS({
9672
+ "node_modules/undici/lib/core/socks5-utils.js"(exports, module) {
9493
9673
  "use strict";
9494
- var { kProxy, kClose, kDestroy, kDispatch } = require_symbols();
9495
- var Agent = require_agent();
9496
- var Pool = require_pool();
9497
- var DispatcherBase = require_dispatcher_base();
9498
- var { InvalidArgumentError, RequestAbortedError, SecureProxyConnectionError } = require_errors();
9499
- var buildConnector = require_connect();
9500
- var Client = require_client();
9501
- var { channels } = require_diagnostics();
9502
- var kAgent = /* @__PURE__ */ Symbol("proxy agent");
9503
- var kClient = /* @__PURE__ */ Symbol("proxy client");
9504
- var kProxyHeaders = /* @__PURE__ */ Symbol("proxy headers");
9505
- var kRequestTls = /* @__PURE__ */ Symbol("request tls settings");
9506
- var kProxyTls = /* @__PURE__ */ Symbol("proxy tls settings");
9507
- var kConnectEndpoint = /* @__PURE__ */ Symbol("connect endpoint function");
9508
- var kTunnelProxy = /* @__PURE__ */ Symbol("tunnel proxy");
9509
- function defaultProtocolPort(protocol) {
9510
- return protocol === "https:" ? 443 : 80;
9511
- }
9512
- function defaultFactory(origin, opts) {
9513
- return new Pool(origin, opts);
9514
- }
9515
- var noop = () => {
9516
- };
9517
- function defaultAgentFactory(origin, opts) {
9518
- if (opts.connections === 1) {
9519
- return new Client(origin, opts);
9674
+ var { Buffer: Buffer2 } = __require("buffer");
9675
+ var net = __require("net");
9676
+ var { InvalidArgumentError } = require_errors();
9677
+ function parseAddress(address) {
9678
+ if (net.isIPv4(address)) {
9679
+ const parts = address.split(".").map(Number);
9680
+ return {
9681
+ type: 1,
9682
+ // IPv4
9683
+ buffer: Buffer2.from(parts)
9684
+ };
9520
9685
  }
9521
- return new Pool(origin, opts);
9686
+ if (net.isIPv6(address)) {
9687
+ return {
9688
+ type: 4,
9689
+ // IPv6
9690
+ buffer: parseIPv6(address)
9691
+ };
9692
+ }
9693
+ const domainBuffer = Buffer2.from(address, "utf8");
9694
+ if (domainBuffer.length > 255) {
9695
+ throw new InvalidArgumentError("Domain name too long (max 255 bytes)");
9696
+ }
9697
+ return {
9698
+ type: 3,
9699
+ // Domain
9700
+ buffer: Buffer2.concat([Buffer2.from([domainBuffer.length]), domainBuffer])
9701
+ };
9522
9702
  }
9523
- var Http1ProxyWrapper = class extends DispatcherBase {
9524
- #client;
9525
- constructor(proxyUrl, { headers = {}, connect, factory }) {
9526
- if (!proxyUrl) {
9527
- throw new InvalidArgumentError("Proxy URL is mandatory");
9703
+ function parseIPv6(address) {
9704
+ const buffer = Buffer2.alloc(16);
9705
+ const parts = address.split(":");
9706
+ let partIndex = 0;
9707
+ let bufferIndex = 0;
9708
+ const doubleColonIndex = address.indexOf("::");
9709
+ if (doubleColonIndex !== -1) {
9710
+ const nonEmptyParts = parts.filter((p) => p.length > 0).length;
9711
+ const skipParts = 8 - nonEmptyParts;
9712
+ for (let i = 0; i < parts.length; i++) {
9713
+ if (parts[i] === "" && i === doubleColonIndex / 3) {
9714
+ bufferIndex += skipParts * 2;
9715
+ } else if (parts[i] !== "") {
9716
+ const value = parseInt(parts[i], 16);
9717
+ buffer.writeUInt16BE(value, bufferIndex);
9718
+ bufferIndex += 2;
9719
+ }
9528
9720
  }
9529
- super();
9530
- this[kProxyHeaders] = headers;
9531
- if (factory) {
9532
- this.#client = factory(proxyUrl, { connect });
9533
- } else {
9534
- this.#client = new Client(proxyUrl, { connect });
9721
+ } else {
9722
+ for (const part of parts) {
9723
+ if (part === "") continue;
9724
+ const value = parseInt(part, 16);
9725
+ buffer.writeUInt16BE(value, partIndex * 2);
9726
+ partIndex++;
9535
9727
  }
9536
9728
  }
9537
- [kDispatch](opts, handler) {
9538
- const onHeaders = handler.onHeaders;
9539
- handler.onHeaders = function(statusCode, data, resume) {
9540
- if (statusCode === 407) {
9541
- if (typeof handler.onError === "function") {
9542
- handler.onError(new InvalidArgumentError("Proxy Authentication Required (407)"));
9543
- }
9544
- return;
9729
+ return buffer;
9730
+ }
9731
+ function buildAddressBuffer(type, addressBuffer, port) {
9732
+ const portBuffer = Buffer2.allocUnsafe(2);
9733
+ portBuffer.writeUInt16BE(port, 0);
9734
+ return Buffer2.concat([
9735
+ Buffer2.from([type]),
9736
+ addressBuffer,
9737
+ portBuffer
9738
+ ]);
9739
+ }
9740
+ function parseResponseAddress(buffer, offset = 0) {
9741
+ if (buffer.length < offset + 1) {
9742
+ throw new InvalidArgumentError("Buffer too small to contain address type");
9743
+ }
9744
+ const addressType = buffer[offset];
9745
+ let address;
9746
+ let currentOffset = offset + 1;
9747
+ switch (addressType) {
9748
+ case 1: {
9749
+ if (buffer.length < currentOffset + 6) {
9750
+ throw new InvalidArgumentError("Buffer too small for IPv4 address");
9751
+ }
9752
+ address = Array.from(buffer.subarray(currentOffset, currentOffset + 4)).join(".");
9753
+ currentOffset += 4;
9754
+ break;
9755
+ }
9756
+ case 3: {
9757
+ if (buffer.length < currentOffset + 1) {
9758
+ throw new InvalidArgumentError("Buffer too small for domain length");
9545
9759
  }
9546
- if (onHeaders) onHeaders.call(this, statusCode, data, resume);
9547
- };
9548
- const {
9549
- origin,
9550
- path = "/",
9551
- headers = {}
9552
- } = opts;
9553
- opts.path = origin + path;
9554
- if (!("host" in headers) && !("Host" in headers)) {
9555
- const { host } = new URL(origin);
9556
- headers.host = host;
9760
+ const domainLength = buffer[currentOffset];
9761
+ currentOffset += 1;
9762
+ if (buffer.length < currentOffset + domainLength + 2) {
9763
+ throw new InvalidArgumentError("Buffer too small for domain address");
9764
+ }
9765
+ address = buffer.subarray(currentOffset, currentOffset + domainLength).toString("utf8");
9766
+ currentOffset += domainLength;
9767
+ break;
9557
9768
  }
9558
- opts.headers = { ...this[kProxyHeaders], ...headers };
9559
- return this.#client[kDispatch](opts, handler);
9560
- }
9561
- [kClose]() {
9562
- return this.#client.close();
9769
+ case 4: {
9770
+ if (buffer.length < currentOffset + 18) {
9771
+ throw new InvalidArgumentError("Buffer too small for IPv6 address");
9772
+ }
9773
+ const parts = [];
9774
+ for (let i = 0; i < 8; i++) {
9775
+ const value = buffer.readUInt16BE(currentOffset + i * 2);
9776
+ parts.push(value.toString(16));
9777
+ }
9778
+ address = parts.join(":");
9779
+ currentOffset += 16;
9780
+ break;
9781
+ }
9782
+ default:
9783
+ throw new InvalidArgumentError(`Invalid address type: ${addressType}`);
9563
9784
  }
9564
- [kDestroy](err) {
9565
- return this.#client.destroy(err);
9785
+ if (buffer.length < currentOffset + 2) {
9786
+ throw new InvalidArgumentError("Buffer too small for port");
9787
+ }
9788
+ const port = buffer.readUInt16BE(currentOffset);
9789
+ currentOffset += 2;
9790
+ return {
9791
+ address,
9792
+ port,
9793
+ bytesRead: currentOffset - offset
9794
+ };
9795
+ }
9796
+ function createReplyError(replyCode) {
9797
+ const messages = {
9798
+ 1: "General SOCKS server failure",
9799
+ 2: "Connection not allowed by ruleset",
9800
+ 3: "Network unreachable",
9801
+ 4: "Host unreachable",
9802
+ 5: "Connection refused",
9803
+ 6: "TTL expired",
9804
+ 7: "Command not supported",
9805
+ 8: "Address type not supported"
9806
+ };
9807
+ const message = messages[replyCode] || `Unknown SOCKS5 error code: ${replyCode}`;
9808
+ const error = new Error(message);
9809
+ error.code = `SOCKS5_${replyCode}`;
9810
+ return error;
9811
+ }
9812
+ module.exports = {
9813
+ parseAddress,
9814
+ parseIPv6,
9815
+ buildAddressBuffer,
9816
+ parseResponseAddress,
9817
+ createReplyError
9818
+ };
9819
+ }
9820
+ });
9821
+
9822
+ // node_modules/undici/lib/core/socks5-client.js
9823
+ var require_socks5_client = __commonJS({
9824
+ "node_modules/undici/lib/core/socks5-client.js"(exports, module) {
9825
+ "use strict";
9826
+ var { EventEmitter } = __require("events");
9827
+ var { Buffer: Buffer2 } = __require("buffer");
9828
+ var { InvalidArgumentError, Socks5ProxyError } = require_errors();
9829
+ var { debuglog } = __require("util");
9830
+ var { parseAddress } = require_socks5_utils();
9831
+ var debug = debuglog("undici:socks5");
9832
+ var SOCKS_VERSION = 5;
9833
+ var AUTH_METHODS = {
9834
+ NO_AUTH: 0,
9835
+ GSSAPI: 1,
9836
+ USERNAME_PASSWORD: 2,
9837
+ NO_ACCEPTABLE: 255
9838
+ };
9839
+ var COMMANDS = {
9840
+ CONNECT: 1,
9841
+ BIND: 2,
9842
+ UDP_ASSOCIATE: 3
9843
+ };
9844
+ var ADDRESS_TYPES = {
9845
+ IPV4: 1,
9846
+ DOMAIN: 3,
9847
+ IPV6: 4
9848
+ };
9849
+ var REPLY_CODES = {
9850
+ SUCCEEDED: 0,
9851
+ GENERAL_FAILURE: 1,
9852
+ CONNECTION_NOT_ALLOWED: 2,
9853
+ NETWORK_UNREACHABLE: 3,
9854
+ HOST_UNREACHABLE: 4,
9855
+ CONNECTION_REFUSED: 5,
9856
+ TTL_EXPIRED: 6,
9857
+ COMMAND_NOT_SUPPORTED: 7,
9858
+ ADDRESS_TYPE_NOT_SUPPORTED: 8
9859
+ };
9860
+ var STATES = {
9861
+ INITIAL: "initial",
9862
+ HANDSHAKING: "handshaking",
9863
+ AUTHENTICATING: "authenticating",
9864
+ CONNECTING: "connecting",
9865
+ CONNECTED: "connected",
9866
+ ERROR: "error",
9867
+ CLOSED: "closed"
9868
+ };
9869
+ var Socks5Client = class extends EventEmitter {
9870
+ constructor(socket, options = {}) {
9871
+ super();
9872
+ if (!socket) {
9873
+ throw new InvalidArgumentError("socket is required");
9874
+ }
9875
+ this.socket = socket;
9876
+ this.options = options;
9877
+ this.state = STATES.INITIAL;
9878
+ this.buffer = Buffer2.alloc(0);
9879
+ this.authMethods = [];
9880
+ if (options.username && options.password) {
9881
+ this.authMethods.push(AUTH_METHODS.USERNAME_PASSWORD);
9882
+ }
9883
+ this.authMethods.push(AUTH_METHODS.NO_AUTH);
9884
+ this.socket.on("data", this.onData.bind(this));
9885
+ this.socket.on("error", this.onError.bind(this));
9886
+ this.socket.on("close", this.onClose.bind(this));
9887
+ }
9888
+ /**
9889
+ * Handle incoming data from the socket
9890
+ */
9891
+ onData(data) {
9892
+ debug("received data", data.length, "bytes in state", this.state);
9893
+ this.buffer = Buffer2.concat([this.buffer, data]);
9894
+ try {
9895
+ switch (this.state) {
9896
+ case STATES.HANDSHAKING:
9897
+ this.handleHandshakeResponse();
9898
+ break;
9899
+ case STATES.AUTHENTICATING:
9900
+ this.handleAuthResponse();
9901
+ break;
9902
+ case STATES.CONNECTING:
9903
+ this.handleConnectResponse();
9904
+ break;
9905
+ }
9906
+ } catch (err) {
9907
+ this.onError(err);
9908
+ }
9909
+ }
9910
+ /**
9911
+ * Handle socket errors
9912
+ */
9913
+ onError(err) {
9914
+ debug("socket error", err);
9915
+ this.state = STATES.ERROR;
9916
+ this.emit("error", err);
9917
+ this.destroy();
9918
+ }
9919
+ /**
9920
+ * Handle socket close
9921
+ */
9922
+ onClose() {
9923
+ debug("socket closed");
9924
+ this.state = STATES.CLOSED;
9925
+ this.emit("close");
9926
+ }
9927
+ /**
9928
+ * Destroy the client and underlying socket
9929
+ */
9930
+ destroy() {
9931
+ if (this.socket && !this.socket.destroyed) {
9932
+ this.socket.destroy();
9933
+ }
9934
+ }
9935
+ /**
9936
+ * Start the SOCKS5 handshake
9937
+ */
9938
+ handshake() {
9939
+ if (this.state !== STATES.INITIAL) {
9940
+ throw new InvalidArgumentError("Handshake already started");
9941
+ }
9942
+ debug("starting handshake with", this.authMethods.length, "auth methods");
9943
+ this.state = STATES.HANDSHAKING;
9944
+ const request = Buffer2.alloc(2 + this.authMethods.length);
9945
+ request[0] = SOCKS_VERSION;
9946
+ request[1] = this.authMethods.length;
9947
+ this.authMethods.forEach((method, i) => {
9948
+ request[2 + i] = method;
9949
+ });
9950
+ this.socket.write(request);
9951
+ }
9952
+ /**
9953
+ * Handle handshake response from server
9954
+ */
9955
+ handleHandshakeResponse() {
9956
+ if (this.buffer.length < 2) {
9957
+ return;
9958
+ }
9959
+ const version = this.buffer[0];
9960
+ const method = this.buffer[1];
9961
+ if (version !== SOCKS_VERSION) {
9962
+ throw new Socks5ProxyError(`Invalid SOCKS version: ${version}`, "UND_ERR_SOCKS5_VERSION");
9963
+ }
9964
+ if (method === AUTH_METHODS.NO_ACCEPTABLE) {
9965
+ throw new Socks5ProxyError("No acceptable authentication method", "UND_ERR_SOCKS5_AUTH_REJECTED");
9966
+ }
9967
+ this.buffer = this.buffer.subarray(2);
9968
+ debug("server selected auth method", method);
9969
+ if (method === AUTH_METHODS.NO_AUTH) {
9970
+ this.emit("authenticated");
9971
+ } else if (method === AUTH_METHODS.USERNAME_PASSWORD) {
9972
+ this.state = STATES.AUTHENTICATING;
9973
+ this.sendAuthRequest();
9974
+ } else {
9975
+ throw new Socks5ProxyError(`Unsupported authentication method: ${method}`, "UND_ERR_SOCKS5_AUTH_METHOD");
9976
+ }
9977
+ }
9978
+ /**
9979
+ * Send username/password authentication request
9980
+ */
9981
+ sendAuthRequest() {
9982
+ const { username, password } = this.options;
9983
+ if (!username || !password) {
9984
+ throw new InvalidArgumentError("Username and password required for authentication");
9985
+ }
9986
+ debug("sending username/password auth");
9987
+ const usernameBuffer = Buffer2.from(username);
9988
+ const passwordBuffer = Buffer2.from(password);
9989
+ if (usernameBuffer.length > 255 || passwordBuffer.length > 255) {
9990
+ throw new InvalidArgumentError("Username or password too long");
9991
+ }
9992
+ const request = Buffer2.alloc(3 + usernameBuffer.length + passwordBuffer.length);
9993
+ request[0] = 1;
9994
+ request[1] = usernameBuffer.length;
9995
+ usernameBuffer.copy(request, 2);
9996
+ request[2 + usernameBuffer.length] = passwordBuffer.length;
9997
+ passwordBuffer.copy(request, 3 + usernameBuffer.length);
9998
+ this.socket.write(request);
9999
+ }
10000
+ /**
10001
+ * Handle authentication response
10002
+ */
10003
+ handleAuthResponse() {
10004
+ if (this.buffer.length < 2) {
10005
+ return;
10006
+ }
10007
+ const version = this.buffer[0];
10008
+ const status = this.buffer[1];
10009
+ if (version !== 1) {
10010
+ throw new Socks5ProxyError(`Invalid auth sub-negotiation version: ${version}`, "UND_ERR_SOCKS5_AUTH_VERSION");
10011
+ }
10012
+ if (status !== 0) {
10013
+ throw new Socks5ProxyError("Authentication failed", "UND_ERR_SOCKS5_AUTH_FAILED");
10014
+ }
10015
+ this.buffer = this.buffer.subarray(2);
10016
+ debug("authentication successful");
10017
+ this.emit("authenticated");
10018
+ }
10019
+ /**
10020
+ * Send CONNECT command
10021
+ * @param {string} address - Target address (IP or domain)
10022
+ * @param {number} port - Target port
10023
+ */
10024
+ connect(address, port) {
10025
+ if (this.state === STATES.CONNECTED) {
10026
+ throw new InvalidArgumentError("Already connected");
10027
+ }
10028
+ debug("connecting to", address, port);
10029
+ this.state = STATES.CONNECTING;
10030
+ const request = this.buildConnectRequest(COMMANDS.CONNECT, address, port);
10031
+ this.socket.write(request);
10032
+ }
10033
+ /**
10034
+ * Build a SOCKS5 request
10035
+ */
10036
+ buildConnectRequest(command, address, port) {
10037
+ const { type: addressType, buffer: addressBuffer } = parseAddress(address);
10038
+ const request = Buffer2.alloc(4 + addressBuffer.length + 2);
10039
+ request[0] = SOCKS_VERSION;
10040
+ request[1] = command;
10041
+ request[2] = 0;
10042
+ request[3] = addressType;
10043
+ addressBuffer.copy(request, 4);
10044
+ request.writeUInt16BE(port, 4 + addressBuffer.length);
10045
+ return request;
10046
+ }
10047
+ /**
10048
+ * Handle CONNECT response
10049
+ */
10050
+ handleConnectResponse() {
10051
+ if (this.buffer.length < 4) {
10052
+ return;
10053
+ }
10054
+ const version = this.buffer[0];
10055
+ const reply = this.buffer[1];
10056
+ const addressType = this.buffer[3];
10057
+ if (version !== SOCKS_VERSION) {
10058
+ throw new Socks5ProxyError(`Invalid SOCKS version in reply: ${version}`, "UND_ERR_SOCKS5_REPLY_VERSION");
10059
+ }
10060
+ let responseLength = 4;
10061
+ if (addressType === ADDRESS_TYPES.IPV4) {
10062
+ responseLength += 4 + 2;
10063
+ } else if (addressType === ADDRESS_TYPES.DOMAIN) {
10064
+ if (this.buffer.length < 5) {
10065
+ return;
10066
+ }
10067
+ responseLength += 1 + this.buffer[4] + 2;
10068
+ } else if (addressType === ADDRESS_TYPES.IPV6) {
10069
+ responseLength += 16 + 2;
10070
+ } else {
10071
+ throw new Socks5ProxyError(`Invalid address type in reply: ${addressType}`, "UND_ERR_SOCKS5_ADDR_TYPE");
10072
+ }
10073
+ if (this.buffer.length < responseLength) {
10074
+ return;
10075
+ }
10076
+ if (reply !== REPLY_CODES.SUCCEEDED) {
10077
+ const errorMessage = this.getReplyErrorMessage(reply);
10078
+ throw new Socks5ProxyError(`SOCKS5 connection failed: ${errorMessage}`, `UND_ERR_SOCKS5_REPLY_${reply}`);
10079
+ }
10080
+ let boundAddress;
10081
+ let offset = 4;
10082
+ if (addressType === ADDRESS_TYPES.IPV4) {
10083
+ boundAddress = Array.from(this.buffer.subarray(offset, offset + 4)).join(".");
10084
+ offset += 4;
10085
+ } else if (addressType === ADDRESS_TYPES.DOMAIN) {
10086
+ const domainLength = this.buffer[offset];
10087
+ offset += 1;
10088
+ boundAddress = this.buffer.subarray(offset, offset + domainLength).toString();
10089
+ offset += domainLength;
10090
+ } else if (addressType === ADDRESS_TYPES.IPV6) {
10091
+ const parts = [];
10092
+ for (let i = 0; i < 8; i++) {
10093
+ const value = this.buffer.readUInt16BE(offset + i * 2);
10094
+ parts.push(value.toString(16));
10095
+ }
10096
+ boundAddress = parts.join(":");
10097
+ offset += 16;
10098
+ }
10099
+ const boundPort = this.buffer.readUInt16BE(offset);
10100
+ this.buffer = this.buffer.subarray(responseLength);
10101
+ this.state = STATES.CONNECTED;
10102
+ debug("connected, bound address:", boundAddress, "port:", boundPort);
10103
+ this.emit("connected", { address: boundAddress, port: boundPort });
10104
+ }
10105
+ /**
10106
+ * Get human-readable error message for reply code
10107
+ */
10108
+ getReplyErrorMessage(reply) {
10109
+ switch (reply) {
10110
+ case REPLY_CODES.GENERAL_FAILURE:
10111
+ return "General SOCKS server failure";
10112
+ case REPLY_CODES.CONNECTION_NOT_ALLOWED:
10113
+ return "Connection not allowed by ruleset";
10114
+ case REPLY_CODES.NETWORK_UNREACHABLE:
10115
+ return "Network unreachable";
10116
+ case REPLY_CODES.HOST_UNREACHABLE:
10117
+ return "Host unreachable";
10118
+ case REPLY_CODES.CONNECTION_REFUSED:
10119
+ return "Connection refused";
10120
+ case REPLY_CODES.TTL_EXPIRED:
10121
+ return "TTL expired";
10122
+ case REPLY_CODES.COMMAND_NOT_SUPPORTED:
10123
+ return "Command not supported";
10124
+ case REPLY_CODES.ADDRESS_TYPE_NOT_SUPPORTED:
10125
+ return "Address type not supported";
10126
+ default:
10127
+ return `Unknown error code: ${reply}`;
10128
+ }
10129
+ }
10130
+ };
10131
+ module.exports = {
10132
+ Socks5Client,
10133
+ AUTH_METHODS,
10134
+ COMMANDS,
10135
+ ADDRESS_TYPES,
10136
+ REPLY_CODES,
10137
+ STATES
10138
+ };
10139
+ }
10140
+ });
10141
+
10142
+ // node_modules/undici/lib/dispatcher/socks5-proxy-agent.js
10143
+ var require_socks5_proxy_agent = __commonJS({
10144
+ "node_modules/undici/lib/dispatcher/socks5-proxy-agent.js"(exports, module) {
10145
+ "use strict";
10146
+ var net = __require("net");
10147
+ var { URL: URL2 } = __require("url");
10148
+ var tls;
10149
+ var DispatcherBase = require_dispatcher_base();
10150
+ var { InvalidArgumentError } = require_errors();
10151
+ var { Socks5Client } = require_socks5_client();
10152
+ var { kDispatch, kClose, kDestroy } = require_symbols();
10153
+ var Pool = require_pool();
10154
+ var buildConnector = require_connect();
10155
+ var { debuglog } = __require("util");
10156
+ var debug = debuglog("undici:socks5-proxy");
10157
+ var kProxyUrl = /* @__PURE__ */ Symbol("proxy url");
10158
+ var kProxyHeaders = /* @__PURE__ */ Symbol("proxy headers");
10159
+ var kProxyAuth = /* @__PURE__ */ Symbol("proxy auth");
10160
+ var kPool = /* @__PURE__ */ Symbol("pool");
10161
+ var kConnector = /* @__PURE__ */ Symbol("connector");
10162
+ var experimentalWarningEmitted = false;
10163
+ var Socks5ProxyAgent = class extends DispatcherBase {
10164
+ constructor(proxyUrl, options = {}) {
10165
+ super();
10166
+ if (!experimentalWarningEmitted) {
10167
+ process.emitWarning(
10168
+ "SOCKS5 proxy support is experimental and subject to change",
10169
+ "ExperimentalWarning"
10170
+ );
10171
+ experimentalWarningEmitted = true;
10172
+ }
10173
+ if (!proxyUrl) {
10174
+ throw new InvalidArgumentError("Proxy URL is mandatory");
10175
+ }
10176
+ const url = typeof proxyUrl === "string" ? new URL2(proxyUrl) : proxyUrl;
10177
+ if (url.protocol !== "socks5:" && url.protocol !== "socks:") {
10178
+ throw new InvalidArgumentError("Proxy URL must use socks5:// or socks:// protocol");
10179
+ }
10180
+ this[kProxyUrl] = url;
10181
+ this[kProxyHeaders] = options.headers || {};
10182
+ this[kProxyAuth] = {
10183
+ username: options.username || (url.username ? decodeURIComponent(url.username) : null),
10184
+ password: options.password || (url.password ? decodeURIComponent(url.password) : null)
10185
+ };
10186
+ this[kConnector] = options.connect || buildConnector({
10187
+ ...options.proxyTls,
10188
+ servername: options.proxyTls?.servername || url.hostname
10189
+ });
10190
+ this[kPool] = null;
10191
+ }
10192
+ /**
10193
+ * Create a SOCKS5 connection to the proxy
10194
+ */
10195
+ async createSocks5Connection(targetHost, targetPort) {
10196
+ const proxyHost = this[kProxyUrl].hostname;
10197
+ const proxyPort = parseInt(this[kProxyUrl].port) || 1080;
10198
+ debug("creating SOCKS5 connection to", proxyHost, proxyPort);
10199
+ const socket = await new Promise((resolve, reject) => {
10200
+ const onConnect = () => {
10201
+ socket2.removeListener("error", onError);
10202
+ resolve(socket2);
10203
+ };
10204
+ const onError = (err) => {
10205
+ socket2.removeListener("connect", onConnect);
10206
+ reject(err);
10207
+ };
10208
+ const socket2 = net.connect({
10209
+ host: proxyHost,
10210
+ port: proxyPort
10211
+ });
10212
+ socket2.once("connect", onConnect);
10213
+ socket2.once("error", onError);
10214
+ });
10215
+ const socks5Client = new Socks5Client(socket, this[kProxyAuth]);
10216
+ socks5Client.on("error", (err) => {
10217
+ debug("SOCKS5 error:", err);
10218
+ socket.destroy();
10219
+ });
10220
+ await socks5Client.handshake();
10221
+ await new Promise((resolve, reject) => {
10222
+ const timeout = setTimeout(() => {
10223
+ reject(new Error("SOCKS5 authentication timeout"));
10224
+ }, 5e3);
10225
+ const onAuthenticated = () => {
10226
+ clearTimeout(timeout);
10227
+ socks5Client.removeListener("error", onError);
10228
+ resolve();
10229
+ };
10230
+ const onError = (err) => {
10231
+ clearTimeout(timeout);
10232
+ socks5Client.removeListener("authenticated", onAuthenticated);
10233
+ reject(err);
10234
+ };
10235
+ if (socks5Client.state === "authenticated") {
10236
+ clearTimeout(timeout);
10237
+ resolve();
10238
+ } else {
10239
+ socks5Client.once("authenticated", onAuthenticated);
10240
+ socks5Client.once("error", onError);
10241
+ }
10242
+ });
10243
+ await socks5Client.connect(targetHost, targetPort);
10244
+ await new Promise((resolve, reject) => {
10245
+ const timeout = setTimeout(() => {
10246
+ reject(new Error("SOCKS5 connection timeout"));
10247
+ }, 5e3);
10248
+ const onConnected = (info) => {
10249
+ debug("SOCKS5 tunnel established to", targetHost, targetPort, "via", info);
10250
+ clearTimeout(timeout);
10251
+ socks5Client.removeListener("error", onError);
10252
+ resolve();
10253
+ };
10254
+ const onError = (err) => {
10255
+ clearTimeout(timeout);
10256
+ socks5Client.removeListener("connected", onConnected);
10257
+ reject(err);
10258
+ };
10259
+ socks5Client.once("connected", onConnected);
10260
+ socks5Client.once("error", onError);
10261
+ });
10262
+ return socket;
10263
+ }
10264
+ /**
10265
+ * Dispatch a request through the SOCKS5 proxy
10266
+ */
10267
+ async [kDispatch](opts, handler) {
10268
+ const { origin } = opts;
10269
+ debug("dispatching request to", origin, "via SOCKS5");
10270
+ try {
10271
+ if (!this[kPool] || this[kPool].destroyed || this[kPool].closed) {
10272
+ this[kPool] = new Pool(origin, {
10273
+ pipelining: opts.pipelining,
10274
+ connections: opts.connections,
10275
+ connect: async (connectOpts, callback) => {
10276
+ try {
10277
+ const url = new URL2(origin);
10278
+ const targetHost = url.hostname;
10279
+ const targetPort = parseInt(url.port) || (url.protocol === "https:" ? 443 : 80);
10280
+ debug("establishing SOCKS5 connection to", targetHost, targetPort);
10281
+ const socket = await this.createSocks5Connection(targetHost, targetPort);
10282
+ let finalSocket = socket;
10283
+ if (url.protocol === "https:") {
10284
+ if (!tls) {
10285
+ tls = __require("tls");
10286
+ }
10287
+ debug("upgrading to TLS");
10288
+ finalSocket = tls.connect({
10289
+ socket,
10290
+ servername: targetHost,
10291
+ ...connectOpts.tls || {}
10292
+ });
10293
+ await new Promise((resolve, reject) => {
10294
+ finalSocket.once("secureConnect", resolve);
10295
+ finalSocket.once("error", reject);
10296
+ });
10297
+ }
10298
+ callback(null, finalSocket);
10299
+ } catch (err) {
10300
+ debug("SOCKS5 connection error:", err);
10301
+ callback(err);
10302
+ }
10303
+ }
10304
+ });
10305
+ }
10306
+ return this[kPool][kDispatch](opts, handler);
10307
+ } catch (err) {
10308
+ debug("dispatch error:", err);
10309
+ if (typeof handler.onError === "function") {
10310
+ handler.onError(err);
10311
+ } else {
10312
+ throw err;
10313
+ }
10314
+ }
10315
+ }
10316
+ async [kClose]() {
10317
+ if (this[kPool]) {
10318
+ await this[kPool].close();
10319
+ }
10320
+ }
10321
+ async [kDestroy](err) {
10322
+ if (this[kPool]) {
10323
+ await this[kPool].destroy(err);
10324
+ }
10325
+ }
10326
+ };
10327
+ module.exports = Socks5ProxyAgent;
10328
+ }
10329
+ });
10330
+
10331
+ // node_modules/undici/lib/dispatcher/proxy-agent.js
10332
+ var require_proxy_agent = __commonJS({
10333
+ "node_modules/undici/lib/dispatcher/proxy-agent.js"(exports, module) {
10334
+ "use strict";
10335
+ var { kProxy, kClose, kDestroy, kDispatch } = require_symbols();
10336
+ var Agent = require_agent();
10337
+ var Pool = require_pool();
10338
+ var DispatcherBase = require_dispatcher_base();
10339
+ var { InvalidArgumentError, RequestAbortedError, SecureProxyConnectionError } = require_errors();
10340
+ var buildConnector = require_connect();
10341
+ var Client = require_client();
10342
+ var { channels } = require_diagnostics();
10343
+ var Socks5ProxyAgent = require_socks5_proxy_agent();
10344
+ var kAgent = /* @__PURE__ */ Symbol("proxy agent");
10345
+ var kClient = /* @__PURE__ */ Symbol("proxy client");
10346
+ var kProxyHeaders = /* @__PURE__ */ Symbol("proxy headers");
10347
+ var kRequestTls = /* @__PURE__ */ Symbol("request tls settings");
10348
+ var kProxyTls = /* @__PURE__ */ Symbol("proxy tls settings");
10349
+ var kConnectEndpoint = /* @__PURE__ */ Symbol("connect endpoint function");
10350
+ var kTunnelProxy = /* @__PURE__ */ Symbol("tunnel proxy");
10351
+ function defaultProtocolPort(protocol) {
10352
+ return protocol === "https:" ? 443 : 80;
10353
+ }
10354
+ function defaultFactory(origin, opts) {
10355
+ return new Pool(origin, opts);
10356
+ }
10357
+ var noop = () => {
10358
+ };
10359
+ function defaultAgentFactory(origin, opts) {
10360
+ if (opts.connections === 1) {
10361
+ return new Client(origin, opts);
10362
+ }
10363
+ return new Pool(origin, opts);
10364
+ }
10365
+ var Http1ProxyWrapper = class extends DispatcherBase {
10366
+ #client;
10367
+ constructor(proxyUrl, { headers = {}, connect, factory }) {
10368
+ if (!proxyUrl) {
10369
+ throw new InvalidArgumentError("Proxy URL is mandatory");
10370
+ }
10371
+ super();
10372
+ this[kProxyHeaders] = headers;
10373
+ if (factory) {
10374
+ this.#client = factory(proxyUrl, { connect });
10375
+ } else {
10376
+ this.#client = new Client(proxyUrl, { connect });
10377
+ }
10378
+ }
10379
+ [kDispatch](opts, handler) {
10380
+ const onHeaders = handler.onHeaders;
10381
+ handler.onHeaders = function(statusCode, data, resume) {
10382
+ if (statusCode === 407) {
10383
+ if (typeof handler.onError === "function") {
10384
+ handler.onError(new InvalidArgumentError("Proxy Authentication Required (407)"));
10385
+ }
10386
+ return;
10387
+ }
10388
+ if (onHeaders) onHeaders.call(this, statusCode, data, resume);
10389
+ };
10390
+ const {
10391
+ origin,
10392
+ path = "/",
10393
+ headers = {}
10394
+ } = opts;
10395
+ opts.path = origin + path;
10396
+ if (!("host" in headers) && !("Host" in headers)) {
10397
+ const { host } = new URL(origin);
10398
+ headers.host = host;
10399
+ }
10400
+ opts.headers = { ...this[kProxyHeaders], ...headers };
10401
+ return this.#client[kDispatch](opts, handler);
10402
+ }
10403
+ [kClose]() {
10404
+ return this.#client.close();
10405
+ }
10406
+ [kDestroy](err) {
10407
+ return this.#client.destroy(err);
9566
10408
  }
9567
10409
  };
9568
10410
  var ProxyAgent = class extends DispatcherBase {
@@ -9597,6 +10439,16 @@ var require_proxy_agent = __commonJS({
9597
10439
  const agentFactory = opts.factory || defaultAgentFactory;
9598
10440
  const factory = (origin2, options) => {
9599
10441
  const { protocol: protocol2 } = new URL(origin2);
10442
+ if (this[kProxy].protocol === "socks5:" || this[kProxy].protocol === "socks:") {
10443
+ return new Socks5ProxyAgent(this[kProxy].uri, {
10444
+ headers: this[kProxyHeaders],
10445
+ connect,
10446
+ factory: agentFactory,
10447
+ username: opts.username || username,
10448
+ password: opts.password || password,
10449
+ proxyTls: opts.proxyTls
10450
+ });
10451
+ }
9600
10452
  if (!this[kTunnelProxy] && protocol2 === "http:" && this[kProxy].protocol === "http:") {
9601
10453
  return new Http1ProxyWrapper(this[kProxy].uri, {
9602
10454
  headers: this[kProxyHeaders],
@@ -9606,11 +10458,19 @@ var require_proxy_agent = __commonJS({
9606
10458
  }
9607
10459
  return agentFactory(origin2, options);
9608
10460
  };
9609
- this[kClient] = clientFactory(url, { connect });
10461
+ if (protocol === "socks5:" || protocol === "socks:") {
10462
+ this[kClient] = null;
10463
+ } else {
10464
+ this[kClient] = clientFactory(url, { connect });
10465
+ }
9610
10466
  this[kAgent] = new Agent({
9611
10467
  ...opts,
9612
10468
  factory,
9613
10469
  connect: async (opts2, callback) => {
10470
+ if (!this[kClient]) {
10471
+ callback(new InvalidArgumentError("Cannot establish tunnel connection without a proxy client"));
10472
+ return;
10473
+ }
9614
10474
  let requestedPath = opts2.host;
9615
10475
  if (!opts2.port) {
9616
10476
  requestedPath += `:${defaultProtocolPort(opts2.protocol)}`;
@@ -9690,16 +10550,18 @@ var require_proxy_agent = __commonJS({
9690
10550
  }
9691
10551
  }
9692
10552
  [kClose]() {
9693
- return Promise.all([
9694
- this[kAgent].close(),
9695
- this[kClient].close()
9696
- ]);
10553
+ const promises = [this[kAgent].close()];
10554
+ if (this[kClient]) {
10555
+ promises.push(this[kClient].close());
10556
+ }
10557
+ return Promise.all(promises);
9697
10558
  }
9698
10559
  [kDestroy]() {
9699
- return Promise.all([
9700
- this[kAgent].destroy(),
9701
- this[kClient].destroy()
9702
- ]);
10560
+ const promises = [this[kAgent].destroy()];
10561
+ if (this[kClient]) {
10562
+ promises.push(this[kClient].destroy());
10563
+ }
10564
+ return Promise.all(promises);
9703
10565
  }
9704
10566
  };
9705
10567
  function buildHeaders(headers) {
@@ -9803,14 +10665,11 @@ var require_env_http_proxy_agent = __commonJS({
9803
10665
  if (entry.port && entry.port !== port) {
9804
10666
  continue;
9805
10667
  }
9806
- if (!/^[.*]/.test(entry.hostname)) {
9807
- if (hostname === entry.hostname) {
9808
- return false;
9809
- }
9810
- } else {
9811
- if (hostname.endsWith(entry.hostname.replace(/^\*/, ""))) {
9812
- return false;
9813
- }
10668
+ if (hostname === entry.hostname) {
10669
+ return false;
10670
+ }
10671
+ if (hostname.slice(-(entry.hostname.length + 1)) === `.${entry.hostname}`) {
10672
+ return false;
9814
10673
  }
9815
10674
  }
9816
10675
  return true;
@@ -9826,7 +10685,8 @@ var require_env_http_proxy_agent = __commonJS({
9826
10685
  }
9827
10686
  const parsed = entry.match(/^(.+):(\d+)$/);
9828
10687
  noProxyEntries.push({
9829
- hostname: (parsed ? parsed[1] : entry).toLowerCase(),
10688
+ // strip leading dot or asterisk with dot
10689
+ hostname: (parsed ? parsed[1] : entry).replace(/^\*?\./, "").toLowerCase(),
9830
10690
  port: parsed ? Number.parseInt(parsed[2], 10) : 0
9831
10691
  });
9832
10692
  }
@@ -10740,6 +11600,7 @@ var require_api_request = __commonJS({
10740
11600
  try {
10741
11601
  this.runInAsyncScope(callback, null, null, {
10742
11602
  statusCode,
11603
+ statusText: statusMessage,
10743
11604
  headers,
10744
11605
  trailers: this.trailers,
10745
11606
  opaque,
@@ -11481,7 +12342,8 @@ var require_mock_symbols = __commonJS({
11481
12342
  kMockAgentAddCallHistoryLog: /* @__PURE__ */ Symbol("mock agent add call history log"),
11482
12343
  kMockAgentIsCallHistoryEnabled: /* @__PURE__ */ Symbol("mock agent is call history enabled"),
11483
12344
  kMockAgentAcceptsNonStandardSearchParameters: /* @__PURE__ */ Symbol("mock agent accepts non standard search parameters"),
11484
- kMockCallHistoryAddLog: /* @__PURE__ */ Symbol("mock call history add log")
12345
+ kMockCallHistoryAddLog: /* @__PURE__ */ Symbol("mock call history add log"),
12346
+ kTotalDispatchCount: /* @__PURE__ */ Symbol("total dispatch count")
11485
12347
  };
11486
12348
  }
11487
12349
  });
@@ -11496,7 +12358,8 @@ var require_mock_utils = __commonJS({
11496
12358
  kMockAgent,
11497
12359
  kOriginalDispatch,
11498
12360
  kOrigin,
11499
- kGetNetConnect
12361
+ kGetNetConnect,
12362
+ kTotalDispatchCount
11500
12363
  } = require_mock_symbols();
11501
12364
  var { serializePathWithQuery } = require_util();
11502
12365
  var { STATUS_CODES } = __require("http");
@@ -11656,6 +12519,7 @@ var require_mock_utils = __commonJS({
11656
12519
  const replyData = typeof data === "function" ? { callback: data } : { ...data };
11657
12520
  const newMockDispatch = { ...baseData, ...key, pending: true, data: { error: null, ...replyData } };
11658
12521
  mockDispatches.push(newMockDispatch);
12522
+ mockDispatches[kTotalDispatchCount] = (mockDispatches[kTotalDispatchCount] || 0) + 1;
11659
12523
  return newMockDispatch;
11660
12524
  }
11661
12525
  function deleteMockDispatch(mockDispatches, key) {
@@ -11731,23 +12595,43 @@ var require_mock_utils = __commonJS({
11731
12595
  handler.onError(error);
11732
12596
  return true;
11733
12597
  }
12598
+ let aborted = false;
12599
+ let timer = null;
12600
+ function abort(err) {
12601
+ if (aborted) {
12602
+ return;
12603
+ }
12604
+ aborted = true;
12605
+ if (timer !== null) {
12606
+ clearTimeout(timer);
12607
+ timer = null;
12608
+ }
12609
+ handler.onError(err);
12610
+ }
12611
+ handler.onConnect?.(abort, null);
11734
12612
  if (typeof delay === "number" && delay > 0) {
11735
- setTimeout(() => {
12613
+ timer = setTimeout(() => {
12614
+ timer = null;
11736
12615
  handleReply(this[kDispatches]);
11737
12616
  }, delay);
11738
12617
  } else {
11739
12618
  handleReply(this[kDispatches]);
11740
12619
  }
11741
12620
  function handleReply(mockDispatches, _data = data) {
12621
+ if (aborted) {
12622
+ return;
12623
+ }
11742
12624
  const optsHeaders = Array.isArray(opts.headers) ? buildHeadersFromArray(opts.headers) : opts.headers;
11743
12625
  const body = typeof _data === "function" ? _data({ ...opts, headers: optsHeaders }) : _data;
11744
12626
  if (isPromise(body)) {
11745
12627
  return body.then((newData) => handleReply(mockDispatches, newData));
11746
12628
  }
12629
+ if (aborted) {
12630
+ return;
12631
+ }
11747
12632
  const responseData = getResponseData(body);
11748
12633
  const responseHeaders = generateKeyValues(headers);
11749
12634
  const responseTrailers = generateKeyValues(trailers);
11750
- handler.onConnect?.((err) => handler.onError(err), null);
11751
12635
  handler.onHeaders?.(statusCode, responseHeaders, resume, getStatusText(statusCode));
11752
12636
  handler.onData?.(Buffer.from(responseData));
11753
12637
  handler.onComplete?.(responseTrailers);
@@ -11768,13 +12652,16 @@ var require_mock_utils = __commonJS({
11768
12652
  } catch (error) {
11769
12653
  if (error.code === "UND_MOCK_ERR_MOCK_NOT_MATCHED") {
11770
12654
  const netConnect = agent[kGetNetConnect]();
12655
+ const totalInterceptsCount = this[kDispatches][kTotalDispatchCount] || this[kDispatches].length;
12656
+ const pendingInterceptsCount = this[kDispatches].filter(({ consumed }) => !consumed).length;
12657
+ const interceptsMessage = `, ${pendingInterceptsCount} interceptor(s) remaining out of ${totalInterceptsCount} defined`;
11771
12658
  if (netConnect === false) {
11772
- throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect disabled)`);
12659
+ throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect disabled)${interceptsMessage}`);
11773
12660
  }
11774
12661
  if (checkNetConnect(netConnect, origin)) {
11775
12662
  originalDispatch.call(this, opts, handler);
11776
12663
  } else {
11777
- throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect is not enabled for this origin)`);
12664
+ throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect is not enabled for this origin)${interceptsMessage}`);
11778
12665
  }
11779
12666
  } else {
11780
12667
  throw error;
@@ -11794,6 +12681,15 @@ var require_mock_utils = __commonJS({
11794
12681
  }
11795
12682
  return false;
11796
12683
  }
12684
+ function normalizeOrigin(origin) {
12685
+ if (typeof origin !== "string" && !(origin instanceof URL)) {
12686
+ return origin;
12687
+ }
12688
+ if (origin instanceof URL) {
12689
+ return origin.origin;
12690
+ }
12691
+ return origin.toLowerCase();
12692
+ }
11797
12693
  function buildAndValidateMockOptions(opts) {
11798
12694
  const { agent, ...mockOptions } = opts;
11799
12695
  if ("enableCallHistory" in mockOptions && typeof mockOptions.enableCallHistory !== "boolean") {
@@ -11823,7 +12719,8 @@ var require_mock_utils = __commonJS({
11823
12719
  buildAndValidateMockOptions,
11824
12720
  getHeaderByName,
11825
12721
  buildHeadersFromArray,
11826
- normalizeSearchParams
12722
+ normalizeSearchParams,
12723
+ normalizeOrigin
11827
12724
  };
11828
12725
  }
11829
12726
  });
@@ -12381,7 +13278,7 @@ var require_mock_agent = __commonJS({
12381
13278
  } = require_mock_symbols();
12382
13279
  var MockClient = require_mock_client();
12383
13280
  var MockPool = require_mock_pool();
12384
- var { matchValue, normalizeSearchParams, buildAndValidateMockOptions } = require_mock_utils();
13281
+ var { matchValue, normalizeSearchParams, buildAndValidateMockOptions, normalizeOrigin } = require_mock_utils();
12385
13282
  var { InvalidArgumentError, UndiciError } = require_errors();
12386
13283
  var Dispatcher = require_dispatcher();
12387
13284
  var PendingInterceptorsFormatter = require_pending_interceptors_formatter();
@@ -12407,7 +13304,8 @@ var require_mock_agent = __commonJS({
12407
13304
  }
12408
13305
  }
12409
13306
  get(origin) {
12410
- const originKey = this[kIgnoreTrailingSlash] ? origin.replace(/\/$/, "") : origin;
13307
+ const normalizedOrigin = normalizeOrigin(origin);
13308
+ const originKey = this[kIgnoreTrailingSlash] ? normalizedOrigin.replace(/\/$/, "") : normalizedOrigin;
12411
13309
  let dispatcher = this[kMockAgentGet](originKey);
12412
13310
  if (!dispatcher) {
12413
13311
  dispatcher = this[kFactory](originKey);
@@ -12416,6 +13314,7 @@ var require_mock_agent = __commonJS({
12416
13314
  return dispatcher;
12417
13315
  }
12418
13316
  dispatch(opts, handler) {
13317
+ opts.origin = normalizeOrigin(opts.origin);
12419
13318
  this.get(opts.origin);
12420
13319
  this[kMockAgentAddCallHistoryLog](opts);
12421
13320
  const acceptNonStandardSearchParameters = this[kMockAgentAcceptsNonStandardSearchParameters];
@@ -13534,7 +14433,7 @@ var require_redirect_handler = __commonJS({
13534
14433
  }
13535
14434
  }
13536
14435
  } else if (headers && typeof headers === "object") {
13537
- const entries = typeof headers[Symbol.iterator] === "function" ? headers : Object.entries(headers);
14436
+ const entries = util.hasSafeIterator(headers) ? headers : Object.entries(headers);
13538
14437
  for (const [key, value] of entries) {
13539
14438
  if (!shouldRemoveHeader(key, removeContent, unknownOrigin)) {
13540
14439
  ret.push(key, value);
@@ -13772,6 +14671,85 @@ var require_dns = __commonJS({
13772
14671
  var DecoratorHandler = require_decorator_handler();
13773
14672
  var { InvalidArgumentError, InformationalError } = require_errors();
13774
14673
  var maxInt = Math.pow(2, 31) - 1;
14674
+ function hasSafeIterator(headers) {
14675
+ const prototype = Object.getPrototypeOf(headers);
14676
+ const ownIterator = Object.prototype.hasOwnProperty.call(headers, Symbol.iterator);
14677
+ return ownIterator || prototype != null && prototype !== Object.prototype && typeof headers[Symbol.iterator] === "function";
14678
+ }
14679
+ function isHostHeader(key) {
14680
+ return typeof key === "string" && key.toLowerCase() === "host";
14681
+ }
14682
+ function normalizeHeaders(headers) {
14683
+ if (headers == null) {
14684
+ return null;
14685
+ }
14686
+ if (Array.isArray(headers)) {
14687
+ if (headers.length === 0 || !Array.isArray(headers[0])) {
14688
+ return headers;
14689
+ }
14690
+ const normalized = [];
14691
+ for (const header of headers) {
14692
+ if (Array.isArray(header) && header.length === 2) {
14693
+ normalized.push(header[0], header[1]);
14694
+ } else {
14695
+ normalized.push(header);
14696
+ }
14697
+ }
14698
+ return normalized;
14699
+ }
14700
+ if (typeof headers === "object" && hasSafeIterator(headers)) {
14701
+ const normalized = [];
14702
+ for (const header of headers) {
14703
+ if (Array.isArray(header) && header.length === 2) {
14704
+ normalized.push(header[0], header[1]);
14705
+ } else {
14706
+ normalized.push(header);
14707
+ }
14708
+ }
14709
+ return normalized;
14710
+ }
14711
+ return headers;
14712
+ }
14713
+ function hasHostHeader(headers) {
14714
+ if (headers == null) {
14715
+ return false;
14716
+ }
14717
+ if (Array.isArray(headers)) {
14718
+ if (headers.length === 0) {
14719
+ return false;
14720
+ }
14721
+ for (let i = 0; i < headers.length; i += 2) {
14722
+ if (isHostHeader(headers[i])) {
14723
+ return true;
14724
+ }
14725
+ }
14726
+ return false;
14727
+ }
14728
+ if (typeof headers === "object") {
14729
+ for (const key in headers) {
14730
+ if (isHostHeader(key)) {
14731
+ return true;
14732
+ }
14733
+ }
14734
+ }
14735
+ return false;
14736
+ }
14737
+ function withHostHeader(host, headers) {
14738
+ const normalizedHeaders = normalizeHeaders(headers);
14739
+ if (hasHostHeader(normalizedHeaders)) {
14740
+ return normalizedHeaders;
14741
+ }
14742
+ if (Array.isArray(normalizedHeaders)) {
14743
+ return ["host", host, ...normalizedHeaders];
14744
+ }
14745
+ if (normalizedHeaders && typeof normalizedHeaders === "object") {
14746
+ return {
14747
+ host,
14748
+ ...normalizedHeaders
14749
+ };
14750
+ }
14751
+ return { host };
14752
+ }
13775
14753
  var DNSStorage = class {
13776
14754
  #maxItems = 0;
13777
14755
  #records = /* @__PURE__ */ new Map();
@@ -14030,7 +15008,8 @@ var require_dns = __commonJS({
14030
15008
  }
14031
15009
  const dispatchOpts = {
14032
15010
  ...this.#opts,
14033
- origin: `${this.#origin.protocol}//${ip.family === 6 ? `[${ip.address}]` : ip.address}${port}`
15011
+ origin: `${this.#origin.protocol}//${ip.family === 6 ? `[${ip.address}]` : ip.address}${port}`,
15012
+ headers: withHostHeader(this.#origin.host, this.#opts.headers)
14034
15013
  };
14035
15014
  this.#dispatch(dispatchOpts, this);
14036
15015
  return;
@@ -14105,10 +15084,7 @@ var require_dns = __commonJS({
14105
15084
  servername: origin.hostname,
14106
15085
  // For SNI on TLS
14107
15086
  origin: newOrigin.origin,
14108
- headers: {
14109
- host: origin.host,
14110
- ...origDispatchOpts.headers
14111
- }
15087
+ headers: withHostHeader(origin.host, origDispatchOpts.headers)
14112
15088
  };
14113
15089
  dispatch(
14114
15090
  dispatchOpts,
@@ -14131,7 +15107,8 @@ var require_cache = __commonJS({
14131
15107
  "use strict";
14132
15108
  var {
14133
15109
  safeHTTPMethods,
14134
- pathHasQueryOrFragment
15110
+ pathHasQueryOrFragment,
15111
+ hasSafeIterator
14135
15112
  } = require_util();
14136
15113
  var { serializePathWithQuery } = require_util();
14137
15114
  function makeCacheKey(opts) {
@@ -14153,22 +15130,23 @@ var require_cache = __commonJS({
14153
15130
  let headers;
14154
15131
  if (opts.headers == null) {
14155
15132
  headers = {};
14156
- } else if (typeof opts.headers[Symbol.iterator] === "function") {
15133
+ } else if (typeof opts.headers === "object") {
14157
15134
  headers = {};
14158
- for (const x of opts.headers) {
14159
- if (!Array.isArray(x)) {
14160
- throw new Error("opts.headers is not a valid header map");
15135
+ if (hasSafeIterator(opts.headers)) {
15136
+ for (const x of opts.headers) {
15137
+ if (!Array.isArray(x)) {
15138
+ throw new Error("opts.headers is not a valid header map");
15139
+ }
15140
+ const [key, val] = x;
15141
+ if (typeof key !== "string" || typeof val !== "string") {
15142
+ throw new Error("opts.headers is not a valid header map");
15143
+ }
15144
+ headers[key.toLowerCase()] = val;
14161
15145
  }
14162
- const [key, val] = x;
14163
- if (typeof key !== "string" || typeof val !== "string") {
14164
- throw new Error("opts.headers is not a valid header map");
15146
+ } else {
15147
+ for (const key of Object.keys(opts.headers)) {
15148
+ headers[key.toLowerCase()] = opts.headers[key];
14165
15149
  }
14166
- headers[key.toLowerCase()] = val;
14167
- }
14168
- } else if (typeof opts.headers === "object") {
14169
- headers = {};
14170
- for (const key of Object.keys(opts.headers)) {
14171
- headers[key.toLowerCase()] = opts.headers[key];
14172
15150
  }
14173
15151
  } else {
14174
15152
  throw new Error("opts.headers is not an object");
@@ -14992,7 +15970,7 @@ var require_cache_handler = __commonJS({
14992
15970
  return downstreamOnHeaders();
14993
15971
  }
14994
15972
  const cacheControlDirectives = cacheControlHeader ? parseCacheControlHeader(cacheControlHeader) : {};
14995
- if (!canCacheResponse(this.#cacheType, statusCode, resHeaders, cacheControlDirectives)) {
15973
+ if (!canCacheResponse(this.#cacheType, statusCode, resHeaders, cacheControlDirectives, this.#cacheKey.headers)) {
14996
15974
  return downstreamOnHeaders();
14997
15975
  }
14998
15976
  const now = Date.now();
@@ -15028,42 +16006,69 @@ var require_cache_handler = __commonJS({
15028
16006
  cachedAt: resAge ? now - resAge : now,
15029
16007
  staleAt: absoluteStaleAt,
15030
16008
  deleteAt
15031
- };
15032
- if (statusCode === 304) {
15033
- const cachedValue = this.#store.get(this.#cacheKey);
15034
- if (!cachedValue) {
15035
- return downstreamOnHeaders();
15036
- }
15037
- value.statusCode = cachedValue.statusCode;
15038
- value.statusMessage = cachedValue.statusMessage;
15039
- value.etag = cachedValue.etag;
15040
- value.headers = { ...cachedValue.headers, ...strippedHeaders };
15041
- downstreamOnHeaders();
15042
- this.#writeStream = this.#store.createWriteStream(this.#cacheKey, value);
15043
- if (!this.#writeStream || !cachedValue?.body) {
15044
- return;
15045
- }
15046
- const bodyIterator = cachedValue.body.values();
15047
- const streamCachedBody = () => {
15048
- for (const chunk of bodyIterator) {
15049
- const full = this.#writeStream.write(chunk) === false;
15050
- this.#handler.onResponseData?.(controller, chunk);
15051
- if (full) {
15052
- break;
15053
- }
16009
+ };
16010
+ if (statusCode === 304) {
16011
+ const handle304 = (cachedValue) => {
16012
+ if (!cachedValue) {
16013
+ return downstreamOnHeaders();
15054
16014
  }
15055
- };
15056
- this.#writeStream.on("error", function() {
15057
- handler.#writeStream = void 0;
15058
- handler.#store.delete(handler.#cacheKey);
15059
- }).on("drain", () => {
15060
- streamCachedBody();
15061
- }).on("close", function() {
15062
- if (handler.#writeStream === this) {
15063
- handler.#writeStream = void 0;
16015
+ value.statusCode = cachedValue.statusCode;
16016
+ value.statusMessage = cachedValue.statusMessage;
16017
+ value.etag = cachedValue.etag;
16018
+ value.headers = { ...cachedValue.headers, ...strippedHeaders };
16019
+ downstreamOnHeaders();
16020
+ this.#writeStream = this.#store.createWriteStream(this.#cacheKey, value);
16021
+ if (!this.#writeStream || !cachedValue?.body) {
16022
+ return;
15064
16023
  }
15065
- });
15066
- streamCachedBody();
16024
+ if (typeof cachedValue.body.values === "function") {
16025
+ const bodyIterator = cachedValue.body.values();
16026
+ const streamCachedBody = () => {
16027
+ for (const chunk of bodyIterator) {
16028
+ const full = this.#writeStream.write(chunk) === false;
16029
+ this.#handler.onResponseData?.(controller, chunk);
16030
+ if (full) {
16031
+ break;
16032
+ }
16033
+ }
16034
+ };
16035
+ this.#writeStream.on("error", function() {
16036
+ handler.#writeStream = void 0;
16037
+ handler.#store.delete(handler.#cacheKey);
16038
+ }).on("drain", () => {
16039
+ streamCachedBody();
16040
+ }).on("close", function() {
16041
+ if (handler.#writeStream === this) {
16042
+ handler.#writeStream = void 0;
16043
+ }
16044
+ });
16045
+ streamCachedBody();
16046
+ } else if (typeof cachedValue.body.on === "function") {
16047
+ cachedValue.body.on("data", (chunk) => {
16048
+ this.#writeStream.write(chunk);
16049
+ this.#handler.onResponseData?.(controller, chunk);
16050
+ }).on("end", () => {
16051
+ this.#writeStream.end();
16052
+ }).on("error", () => {
16053
+ this.#writeStream = void 0;
16054
+ this.#store.delete(this.#cacheKey);
16055
+ });
16056
+ this.#writeStream.on("error", function() {
16057
+ handler.#writeStream = void 0;
16058
+ handler.#store.delete(handler.#cacheKey);
16059
+ }).on("close", function() {
16060
+ if (handler.#writeStream === this) {
16061
+ handler.#writeStream = void 0;
16062
+ }
16063
+ });
16064
+ }
16065
+ };
16066
+ const result = this.#store.get(this.#cacheKey);
16067
+ if (result && typeof result.then === "function") {
16068
+ result.then(handle304);
16069
+ } else {
16070
+ handle304(result);
16071
+ }
15067
16072
  } else {
15068
16073
  if (typeof resHeaders.etag === "string" && isEtagUsable(resHeaders.etag)) {
15069
16074
  value.etag = resHeaders.etag;
@@ -15100,7 +16105,7 @@ var require_cache_handler = __commonJS({
15100
16105
  this.#handler.onResponseError?.(controller, err);
15101
16106
  }
15102
16107
  };
15103
- function canCacheResponse(cacheType, statusCode, resHeaders, cacheControlDirectives) {
16108
+ function canCacheResponse(cacheType, statusCode, resHeaders, cacheControlDirectives, reqHeaders) {
15104
16109
  if (statusCode < 200 || NOT_UNDERSTOOD_STATUS_CODES.includes(statusCode)) {
15105
16110
  return false;
15106
16111
  }
@@ -15117,8 +16122,11 @@ var require_cache_handler = __commonJS({
15117
16122
  if (resHeaders.vary?.includes("*")) {
15118
16123
  return false;
15119
16124
  }
15120
- if (resHeaders.authorization) {
15121
- if (!cacheControlDirectives.public || typeof resHeaders.authorization !== "string") {
16125
+ if (reqHeaders?.authorization) {
16126
+ if (!cacheControlDirectives.public && !cacheControlDirectives["s-maxage"] && !cacheControlDirectives["must-revalidate"]) {
16127
+ return false;
16128
+ }
16129
+ if (typeof reqHeaders.authorization !== "string") {
15122
16130
  return false;
15123
16131
  }
15124
16132
  if (Array.isArray(cacheControlDirectives["no-cache"]) && cacheControlDirectives["no-cache"].includes("authorization")) {
@@ -15187,9 +16195,13 @@ var require_cache_handler = __commonJS({
15187
16195
  if (cacheControlDirectives["stale-if-error"]) {
15188
16196
  staleIfError = staleAt + cacheControlDirectives["stale-if-error"] * 1e3;
15189
16197
  }
15190
- if (staleWhileRevalidate === -Infinity && staleIfError === -Infinity) {
16198
+ if (cacheControlDirectives.immutable && staleWhileRevalidate === -Infinity && staleIfError === -Infinity) {
15191
16199
  immutable = now + 31536e6;
15192
16200
  }
16201
+ if (staleWhileRevalidate === -Infinity && staleIfError === -Infinity && immutable === -Infinity) {
16202
+ const freshnessLifetime = staleAt - now;
16203
+ return staleAt + freshnessLifetime;
16204
+ }
15193
16205
  return Math.max(staleAt, staleWhileRevalidate, staleIfError, immutable);
15194
16206
  }
15195
16207
  function stripNecessaryHeaders(resHeaders, cacheControlDirectives) {
@@ -15510,6 +16522,18 @@ var require_cache2 = __commonJS({
15510
16522
  var CacheRevalidationHandler = require_cache_revalidation_handler();
15511
16523
  var { assertCacheStore, assertCacheMethods, makeCacheKey, normalizeHeaders, parseCacheControlHeader } = require_cache();
15512
16524
  var { AbortError } = require_errors();
16525
+ function assertCacheOrigins(origins, name) {
16526
+ if (origins === void 0) return;
16527
+ if (!Array.isArray(origins)) {
16528
+ throw new TypeError(`expected ${name} to be an array or undefined, got ${typeof origins}`);
16529
+ }
16530
+ for (let i = 0; i < origins.length; i++) {
16531
+ const origin = origins[i];
16532
+ if (typeof origin !== "string" && !(origin instanceof RegExp)) {
16533
+ throw new TypeError(`expected ${name}[${i}] to be a string or RegExp, got ${typeof origin}`);
16534
+ }
16535
+ }
16536
+ }
15513
16537
  var nop = () => {
15514
16538
  };
15515
16539
  function needsRevalidation(result, cacheControlDirectives, { headers = {} }) {
@@ -15654,7 +16678,7 @@ var require_cache2 = __commonJS({
15654
16678
  if (!revalidate && withinStaleWhileRevalidateWindow(result)) {
15655
16679
  sendCachedValue(handler, opts, result, age, null, true);
15656
16680
  queueMicrotask(() => {
15657
- let headers2 = {
16681
+ const headers2 = {
15658
16682
  ...opts.headers,
15659
16683
  "if-modified-since": new Date(result.cachedAt).toUTCString()
15660
16684
  };
@@ -15662,10 +16686,11 @@ var require_cache2 = __commonJS({
15662
16686
  headers2["if-none-match"] = result.etag;
15663
16687
  }
15664
16688
  if (result.vary) {
15665
- headers2 = {
15666
- ...headers2,
15667
- ...result.vary
15668
- };
16689
+ for (const key in result.vary) {
16690
+ if (result.vary[key] != null) {
16691
+ headers2[key] = result.vary[key];
16692
+ }
16693
+ }
15669
16694
  }
15670
16695
  dispatch(
15671
16696
  {
@@ -15696,7 +16721,7 @@ var require_cache2 = __commonJS({
15696
16721
  if (staleIfErrorExpiry) {
15697
16722
  withinStaleIfErrorThreshold = now < result.staleAt + staleIfErrorExpiry * 1e3;
15698
16723
  }
15699
- let headers = {
16724
+ const headers = {
15700
16725
  ...opts.headers,
15701
16726
  "if-modified-since": new Date(result.cachedAt).toUTCString()
15702
16727
  };
@@ -15704,10 +16729,11 @@ var require_cache2 = __commonJS({
15704
16729
  headers["if-none-match"] = result.etag;
15705
16730
  }
15706
16731
  if (result.vary) {
15707
- headers = {
15708
- ...headers,
15709
- ...result.vary
15710
- };
16732
+ for (const key in result.vary) {
16733
+ if (result.vary[key] != null) {
16734
+ headers[key] = result.vary[key];
16735
+ }
16736
+ }
15711
16737
  }
15712
16738
  return dispatch(
15713
16739
  {
@@ -15737,13 +16763,15 @@ var require_cache2 = __commonJS({
15737
16763
  store = new MemoryCacheStore(),
15738
16764
  methods = ["GET"],
15739
16765
  cacheByDefault = void 0,
15740
- type = "shared"
16766
+ type = "shared",
16767
+ origins = void 0
15741
16768
  } = opts;
15742
16769
  if (typeof opts !== "object" || opts === null) {
15743
16770
  throw new TypeError(`expected type of opts to be an Object, got ${opts === null ? "null" : typeof opts}`);
15744
16771
  }
15745
16772
  assertCacheStore(store, "opts.store");
15746
16773
  assertCacheMethods(methods, "opts.methods");
16774
+ assertCacheOrigins(origins, "opts.origins");
15747
16775
  if (typeof cacheByDefault !== "undefined" && typeof cacheByDefault !== "number") {
15748
16776
  throw new TypeError(`expected opts.cacheByDefault to be number or undefined, got ${typeof cacheByDefault}`);
15749
16777
  }
@@ -15762,6 +16790,25 @@ var require_cache2 = __commonJS({
15762
16790
  if (!opts2.origin || safeMethodsToNotCache.includes(opts2.method)) {
15763
16791
  return dispatch(opts2, handler);
15764
16792
  }
16793
+ if (origins !== void 0) {
16794
+ const requestOrigin = opts2.origin.toString().toLowerCase();
16795
+ let isAllowed = false;
16796
+ for (let i = 0; i < origins.length; i++) {
16797
+ const allowed = origins[i];
16798
+ if (typeof allowed === "string") {
16799
+ if (allowed.toLowerCase() === requestOrigin) {
16800
+ isAllowed = true;
16801
+ break;
16802
+ }
16803
+ } else if (allowed.test(requestOrigin)) {
16804
+ isAllowed = true;
16805
+ break;
16806
+ }
16807
+ }
16808
+ if (!isAllowed) {
16809
+ return dispatch(opts2, handler);
16810
+ }
16811
+ }
15765
16812
  opts2 = {
15766
16813
  ...opts2,
15767
16814
  headers: normalizeHeaders(opts2)
@@ -15827,8 +16874,6 @@ var require_decompress = __commonJS({
15827
16874
  var DecompressHandler = class extends DecoratorHandler {
15828
16875
  /** @type {Transform[]} */
15829
16876
  #decompressors = [];
15830
- /** @type {NodeJS.WritableStream&NodeJS.ReadableStream|null} */
15831
- #pipelineStream;
15832
16877
  /** @type {Readonly<number[]>} */
15833
16878
  #skipStatusCodes;
15834
16879
  /** @type {boolean} */
@@ -15915,7 +16960,7 @@ var require_decompress = __commonJS({
15915
16960
  #setupMultipleDecompressors(controller) {
15916
16961
  const lastDecompressor = this.#decompressors[this.#decompressors.length - 1];
15917
16962
  this.#setupDecompressorEvents(lastDecompressor, controller);
15918
- this.#pipelineStream = pipeline(this.#decompressors, (err) => {
16963
+ pipeline(this.#decompressors, (err) => {
15919
16964
  if (err) {
15920
16965
  super.onResponseError(controller, err);
15921
16966
  return;
@@ -15929,7 +16974,6 @@ var require_decompress = __commonJS({
15929
16974
  */
15930
16975
  #cleanupDecompressors() {
15931
16976
  this.#decompressors.length = 0;
15932
- this.#pipelineStream = null;
15933
16977
  }
15934
16978
  /**
15935
16979
  * @param {Controller} controller
@@ -15955,7 +16999,7 @@ var require_decompress = __commonJS({
15955
16999
  } else {
15956
17000
  this.#setupMultipleDecompressors(controller);
15957
17001
  }
15958
- super.onResponseStart(controller, statusCode, newHeaders, statusMessage);
17002
+ return super.onResponseStart(controller, statusCode, newHeaders, statusMessage);
15959
17003
  }
15960
17004
  /**
15961
17005
  * @param {Controller} controller
@@ -16020,19 +17064,21 @@ var require_decompress = __commonJS({
16020
17064
  var require_deduplication_handler = __commonJS({
16021
17065
  "node_modules/undici/lib/handler/deduplication-handler.js"(exports, module) {
16022
17066
  "use strict";
17067
+ var { RequestAbortedError } = require_errors();
17068
+ var DEFAULT_MAX_BUFFER_SIZE = 5 * 1024 * 1024;
16023
17069
  var DeduplicationHandler = class {
16024
17070
  /**
16025
17071
  * @type {DispatchHandler}
16026
17072
  */
16027
17073
  #primaryHandler;
16028
17074
  /**
16029
- * @type {DispatchHandler[]}
17075
+ * @type {WaitingHandler[]}
16030
17076
  */
16031
17077
  #waitingHandlers = [];
16032
17078
  /**
16033
- * @type {Buffer[]}
17079
+ * @type {number}
16034
17080
  */
16035
- #chunks = [];
17081
+ #maxBufferSize = DEFAULT_MAX_BUFFER_SIZE;
16036
17082
  /**
16037
17083
  * @type {number}
16038
17084
  */
@@ -16049,6 +17095,18 @@ var require_deduplication_handler = __commonJS({
16049
17095
  * @type {boolean}
16050
17096
  */
16051
17097
  #aborted = false;
17098
+ /**
17099
+ * @type {boolean}
17100
+ */
17101
+ #responseStarted = false;
17102
+ /**
17103
+ * @type {boolean}
17104
+ */
17105
+ #responseDataStarted = false;
17106
+ /**
17107
+ * @type {boolean}
17108
+ */
17109
+ #completed = false;
16052
17110
  /**
16053
17111
  * @type {import('../../types/dispatcher.d.ts').default.DispatchController | null}
16054
17112
  */
@@ -16060,20 +17118,51 @@ var require_deduplication_handler = __commonJS({
16060
17118
  /**
16061
17119
  * @param {DispatchHandler} primaryHandler The primary handler
16062
17120
  * @param {() => void} onComplete Callback when request completes
17121
+ * @param {number} [maxBufferSize] Maximum paused buffer size per waiting handler
16063
17122
  */
16064
- constructor(primaryHandler, onComplete) {
17123
+ constructor(primaryHandler, onComplete, maxBufferSize = DEFAULT_MAX_BUFFER_SIZE) {
16065
17124
  this.#primaryHandler = primaryHandler;
16066
17125
  this.#onComplete = onComplete;
17126
+ this.#maxBufferSize = maxBufferSize;
16067
17127
  }
16068
17128
  /**
16069
- * Add a waiting handler that will receive the buffered response
17129
+ * Add a waiting handler that will receive response events.
17130
+ * Returns false if deduplication can no longer safely attach this handler.
17131
+ *
16070
17132
  * @param {DispatchHandler} handler
17133
+ * @returns {boolean}
16071
17134
  */
16072
17135
  addWaitingHandler(handler) {
16073
- this.#waitingHandlers.push(handler);
17136
+ if (this.#completed || this.#responseDataStarted) {
17137
+ return false;
17138
+ }
17139
+ const waitingHandler = this.#createWaitingHandler(handler);
17140
+ const waitingController = waitingHandler.controller;
17141
+ try {
17142
+ handler.onRequestStart?.(waitingController, null);
17143
+ if (waitingController.aborted) {
17144
+ waitingHandler.done = true;
17145
+ return true;
17146
+ }
17147
+ if (this.#responseStarted) {
17148
+ handler.onResponseStart?.(
17149
+ waitingController,
17150
+ this.#statusCode,
17151
+ this.#headers,
17152
+ this.#statusMessage
17153
+ );
17154
+ }
17155
+ } catch {
17156
+ waitingHandler.done = true;
17157
+ return true;
17158
+ }
17159
+ if (!waitingController.aborted) {
17160
+ this.#waitingHandlers.push(waitingHandler);
17161
+ }
17162
+ return true;
16074
17163
  }
16075
17164
  /**
16076
- * @param {() => void} abort
17165
+ * @param {import('../../types/dispatcher.d.ts').default.DispatchController} controller
16077
17166
  * @param {any} context
16078
17167
  */
16079
17168
  onRequestStart(controller, context) {
@@ -16096,26 +17185,95 @@ var require_deduplication_handler = __commonJS({
16096
17185
  * @param {string} statusMessage
16097
17186
  */
16098
17187
  onResponseStart(controller, statusCode, headers, statusMessage) {
17188
+ this.#responseStarted = true;
16099
17189
  this.#statusCode = statusCode;
16100
17190
  this.#headers = headers;
16101
17191
  this.#statusMessage = statusMessage;
16102
17192
  this.#primaryHandler.onResponseStart?.(controller, statusCode, headers, statusMessage);
17193
+ for (const waitingHandler of this.#waitingHandlers) {
17194
+ const { handler, controller: waitingController } = waitingHandler;
17195
+ if (waitingHandler.done || waitingController.aborted) {
17196
+ waitingHandler.done = true;
17197
+ continue;
17198
+ }
17199
+ try {
17200
+ handler.onResponseStart?.(
17201
+ waitingController,
17202
+ statusCode,
17203
+ headers,
17204
+ statusMessage
17205
+ );
17206
+ } catch {
17207
+ }
17208
+ if (waitingController.aborted) {
17209
+ waitingHandler.done = true;
17210
+ }
17211
+ }
17212
+ this.#pruneDoneWaitingHandlers();
16103
17213
  }
16104
17214
  /**
16105
17215
  * @param {import('../../types/dispatcher.d.ts').default.DispatchController} controller
16106
17216
  * @param {Buffer} chunk
16107
17217
  */
16108
17218
  onResponseData(controller, chunk) {
16109
- this.#chunks.push(Buffer.from(chunk));
17219
+ if (this.#aborted || this.#completed) {
17220
+ return;
17221
+ }
17222
+ this.#responseDataStarted = true;
16110
17223
  this.#primaryHandler.onResponseData?.(controller, chunk);
17224
+ for (const waitingHandler of this.#waitingHandlers) {
17225
+ const { handler, controller: waitingController } = waitingHandler;
17226
+ if (waitingHandler.done || waitingController.aborted) {
17227
+ waitingHandler.done = true;
17228
+ continue;
17229
+ }
17230
+ if (waitingController.paused) {
17231
+ this.#bufferWaitingChunk(waitingHandler, chunk);
17232
+ continue;
17233
+ }
17234
+ try {
17235
+ handler.onResponseData?.(waitingController, chunk);
17236
+ } catch {
17237
+ }
17238
+ if (waitingController.aborted) {
17239
+ waitingHandler.done = true;
17240
+ waitingHandler.bufferedChunks = [];
17241
+ waitingHandler.bufferedBytes = 0;
17242
+ }
17243
+ }
17244
+ this.#pruneDoneWaitingHandlers();
16111
17245
  }
16112
17246
  /**
16113
17247
  * @param {import('../../types/dispatcher.d.ts').default.DispatchController} controller
16114
17248
  * @param {object} trailers
16115
17249
  */
16116
17250
  onResponseEnd(controller, trailers) {
17251
+ if (this.#aborted || this.#completed) {
17252
+ return;
17253
+ }
17254
+ this.#completed = true;
16117
17255
  this.#primaryHandler.onResponseEnd?.(controller, trailers);
16118
- this.#notifyWaitingHandlers();
17256
+ for (const waitingHandler of this.#waitingHandlers) {
17257
+ if (waitingHandler.done || waitingHandler.controller.aborted) {
17258
+ waitingHandler.done = true;
17259
+ continue;
17260
+ }
17261
+ this.#flushWaitingHandler(waitingHandler);
17262
+ if (waitingHandler.done || waitingHandler.controller.aborted) {
17263
+ waitingHandler.done = true;
17264
+ continue;
17265
+ }
17266
+ if (waitingHandler.controller.paused && waitingHandler.bufferedChunks.length > 0) {
17267
+ waitingHandler.pendingTrailers = trailers;
17268
+ continue;
17269
+ }
17270
+ try {
17271
+ waitingHandler.handler.onResponseEnd?.(waitingHandler.controller, trailers);
17272
+ } catch {
17273
+ }
17274
+ waitingHandler.done = true;
17275
+ }
17276
+ this.#pruneDoneWaitingHandlers();
16119
17277
  this.#onComplete?.();
16120
17278
  }
16121
17279
  /**
@@ -16123,89 +17281,138 @@ var require_deduplication_handler = __commonJS({
16123
17281
  * @param {Error} err
16124
17282
  */
16125
17283
  onResponseError(controller, err) {
17284
+ if (this.#completed) {
17285
+ return;
17286
+ }
16126
17287
  this.#aborted = true;
17288
+ this.#completed = true;
16127
17289
  this.#primaryHandler.onResponseError?.(controller, err);
16128
- this.#notifyWaitingHandlersError(err);
17290
+ for (const waitingHandler of this.#waitingHandlers) {
17291
+ this.#errorWaitingHandler(waitingHandler, err);
17292
+ }
17293
+ this.#waitingHandlers = [];
16129
17294
  this.#onComplete?.();
16130
17295
  }
16131
17296
  /**
16132
- * Notify all waiting handlers with the buffered response
17297
+ * @param {DispatchHandler} handler
17298
+ * @returns {WaitingHandler}
16133
17299
  */
16134
- #notifyWaitingHandlers() {
16135
- const body = Buffer.concat(this.#chunks);
16136
- for (const handler of this.#waitingHandlers) {
16137
- const waitingController = {
16138
- resume() {
16139
- },
16140
- pause() {
16141
- },
16142
- get paused() {
16143
- return false;
16144
- },
16145
- get aborted() {
16146
- return false;
16147
- },
16148
- get reason() {
16149
- return null;
16150
- },
16151
- abort() {
16152
- }
16153
- };
16154
- try {
16155
- handler.onRequestStart?.(waitingController, null);
16156
- if (waitingController.aborted) {
16157
- continue;
17300
+ #createWaitingHandler(handler) {
17301
+ const waitingHandler = {
17302
+ handler,
17303
+ controller: null,
17304
+ bufferedChunks: [],
17305
+ bufferedBytes: 0,
17306
+ pendingTrailers: null,
17307
+ done: false
17308
+ };
17309
+ const state = {
17310
+ aborted: false,
17311
+ paused: false,
17312
+ reason: null
17313
+ };
17314
+ waitingHandler.controller = {
17315
+ resume: () => {
17316
+ if (state.aborted) {
17317
+ return;
16158
17318
  }
16159
- handler.onResponseStart?.(
16160
- waitingController,
16161
- this.#statusCode,
16162
- this.#headers,
16163
- this.#statusMessage
16164
- );
16165
- if (waitingController.aborted) {
16166
- continue;
17319
+ state.paused = false;
17320
+ this.#flushWaitingHandler(waitingHandler);
17321
+ if (this.#completed && waitingHandler.pendingTrailers && waitingHandler.bufferedChunks.length === 0 && !state.paused && !state.aborted) {
17322
+ try {
17323
+ waitingHandler.handler.onResponseEnd?.(waitingHandler.controller, waitingHandler.pendingTrailers);
17324
+ } catch {
17325
+ }
17326
+ waitingHandler.pendingTrailers = null;
17327
+ waitingHandler.done = true;
16167
17328
  }
16168
- if (body.length > 0) {
16169
- handler.onResponseData?.(waitingController, body);
17329
+ this.#pruneDoneWaitingHandlers();
17330
+ },
17331
+ pause: () => {
17332
+ if (!state.aborted) {
17333
+ state.paused = true;
16170
17334
  }
16171
- handler.onResponseEnd?.(waitingController, {});
16172
- } catch {
17335
+ },
17336
+ get paused() {
17337
+ return state.paused;
17338
+ },
17339
+ get aborted() {
17340
+ return state.aborted;
17341
+ },
17342
+ get reason() {
17343
+ return state.reason;
17344
+ },
17345
+ abort: (reason) => {
17346
+ state.aborted = true;
17347
+ state.reason = reason ?? null;
17348
+ waitingHandler.done = true;
17349
+ waitingHandler.pendingTrailers = null;
17350
+ waitingHandler.bufferedChunks = [];
17351
+ waitingHandler.bufferedBytes = 0;
16173
17352
  }
17353
+ };
17354
+ return waitingHandler;
17355
+ }
17356
+ /**
17357
+ * @param {WaitingHandler} waitingHandler
17358
+ * @param {Buffer} chunk
17359
+ */
17360
+ #bufferWaitingChunk(waitingHandler, chunk) {
17361
+ if (waitingHandler.done || waitingHandler.controller.aborted) {
17362
+ waitingHandler.done = true;
17363
+ waitingHandler.bufferedChunks = [];
17364
+ waitingHandler.bufferedBytes = 0;
17365
+ return;
17366
+ }
17367
+ const bufferedChunk = Buffer.from(chunk);
17368
+ waitingHandler.bufferedChunks.push(bufferedChunk);
17369
+ waitingHandler.bufferedBytes += bufferedChunk.length;
17370
+ if (waitingHandler.bufferedBytes > this.#maxBufferSize) {
17371
+ const err = new RequestAbortedError(`Deduplicated waiting handler exceeded maxBufferSize (${this.#maxBufferSize} bytes) while paused`);
17372
+ this.#errorWaitingHandler(waitingHandler, err);
16174
17373
  }
16175
- this.#waitingHandlers = [];
16176
- this.#chunks = [];
16177
17374
  }
16178
17375
  /**
16179
- * Notify all waiting handlers of an error
16180
- * @param {Error} err
17376
+ * @param {WaitingHandler} waitingHandler
16181
17377
  */
16182
- #notifyWaitingHandlersError(err) {
16183
- for (const handler of this.#waitingHandlers) {
16184
- const waitingController = {
16185
- resume() {
16186
- },
16187
- pause() {
16188
- },
16189
- get paused() {
16190
- return false;
16191
- },
16192
- get aborted() {
16193
- return true;
16194
- },
16195
- get reason() {
16196
- return err;
16197
- },
16198
- abort() {
16199
- }
16200
- };
17378
+ #flushWaitingHandler(waitingHandler) {
17379
+ const { handler, controller } = waitingHandler;
17380
+ while (!waitingHandler.done && !controller.aborted && !controller.paused && waitingHandler.bufferedChunks.length > 0) {
17381
+ const bufferedChunk = waitingHandler.bufferedChunks.shift();
17382
+ waitingHandler.bufferedBytes -= bufferedChunk.length;
16201
17383
  try {
16202
- handler.onRequestStart?.(waitingController, null);
16203
- handler.onResponseError?.(waitingController, err);
17384
+ handler.onResponseData?.(controller, bufferedChunk);
16204
17385
  } catch {
16205
17386
  }
17387
+ if (controller.aborted) {
17388
+ waitingHandler.done = true;
17389
+ waitingHandler.pendingTrailers = null;
17390
+ waitingHandler.bufferedChunks = [];
17391
+ waitingHandler.bufferedBytes = 0;
17392
+ break;
17393
+ }
16206
17394
  }
16207
- this.#waitingHandlers = [];
16208
- this.#chunks = [];
17395
+ }
17396
+ /**
17397
+ * @param {WaitingHandler} waitingHandler
17398
+ * @param {Error} err
17399
+ */
17400
+ #errorWaitingHandler(waitingHandler, err) {
17401
+ if (waitingHandler.done) {
17402
+ return;
17403
+ }
17404
+ waitingHandler.done = true;
17405
+ waitingHandler.pendingTrailers = null;
17406
+ waitingHandler.bufferedChunks = [];
17407
+ waitingHandler.bufferedBytes = 0;
17408
+ try {
17409
+ waitingHandler.controller.abort(err);
17410
+ waitingHandler.handler.onResponseError?.(waitingHandler.controller, err);
17411
+ } catch {
17412
+ }
17413
+ }
17414
+ #pruneDoneWaitingHandlers() {
17415
+ this.#waitingHandlers = this.#waitingHandlers.filter((waitingHandler) => waitingHandler.done === false);
16209
17416
  }
16210
17417
  };
16211
17418
  module.exports = DeduplicationHandler;
@@ -16225,7 +17432,8 @@ var require_deduplicate = __commonJS({
16225
17432
  const {
16226
17433
  methods = ["GET"],
16227
17434
  skipHeaderNames = [],
16228
- excludeHeaderNames = []
17435
+ excludeHeaderNames = [],
17436
+ maxBufferSize = 5 * 1024 * 1024
16229
17437
  } = opts;
16230
17438
  if (typeof opts !== "object" || opts === null) {
16231
17439
  throw new TypeError(`expected type of opts to be an Object, got ${opts === null ? "null" : typeof opts}`);
@@ -16244,13 +17452,15 @@ var require_deduplicate = __commonJS({
16244
17452
  if (!Array.isArray(excludeHeaderNames)) {
16245
17453
  throw new TypeError(`expected opts.excludeHeaderNames to be an array, got ${typeof excludeHeaderNames}`);
16246
17454
  }
17455
+ if (!Number.isFinite(maxBufferSize) || maxBufferSize <= 0) {
17456
+ throw new TypeError(`expected opts.maxBufferSize to be a positive finite number, got ${maxBufferSize}`);
17457
+ }
16247
17458
  const skipHeaderNamesSet = new Set(skipHeaderNames.map((name) => name.toLowerCase()));
16248
17459
  const excludeHeaderNamesSet = new Set(excludeHeaderNames.map((name) => name.toLowerCase()));
16249
- const safeMethodsToNotDeduplicate = util.safeHTTPMethods.filter((method) => methods.includes(method) === false);
16250
17460
  const pendingRequests = /* @__PURE__ */ new Map();
16251
17461
  return (dispatch) => {
16252
17462
  return (opts2, handler) => {
16253
- if (!opts2.origin || safeMethodsToNotDeduplicate.includes(opts2.method)) {
17463
+ if (!opts2.origin || methods.includes(opts2.method) === false) {
16254
17464
  return dispatch(opts2, handler);
16255
17465
  }
16256
17466
  opts2 = {
@@ -16268,8 +17478,10 @@ var require_deduplicate = __commonJS({
16268
17478
  const dedupeKey = makeDeduplicationKey(cacheKey, excludeHeaderNamesSet);
16269
17479
  const pendingHandler = pendingRequests.get(dedupeKey);
16270
17480
  if (pendingHandler) {
16271
- pendingHandler.addWaitingHandler(handler);
16272
- return true;
17481
+ if (pendingHandler.addWaitingHandler(handler)) {
17482
+ return true;
17483
+ }
17484
+ return dispatch(opts2, handler);
16273
17485
  }
16274
17486
  const deduplicationHandler = new DeduplicationHandler(
16275
17487
  handler,
@@ -16278,7 +17490,8 @@ var require_deduplicate = __commonJS({
16278
17490
  if (pendingRequestsChannel.hasSubscribers) {
16279
17491
  pendingRequestsChannel.publish({ size: pendingRequests.size, key: dedupeKey, type: "removed" });
16280
17492
  }
16281
- }
17493
+ },
17494
+ maxBufferSize
16282
17495
  );
16283
17496
  pendingRequests.set(dedupeKey, deduplicationHandler);
16284
17497
  if (pendingRequestsChannel.hasSubscribers) {
@@ -17259,7 +18472,7 @@ var require_response = __commonJS({
17259
18472
  });
17260
18473
  }
17261
18474
  const clonedResponse = cloneResponse(this.#state);
17262
- if (this.#state.body?.stream) {
18475
+ if (this.#state.urlList.length !== 0 && this.#state.body?.stream) {
17263
18476
  streamRegistry.register(this, new WeakRef(this.#state.body.stream));
17264
18477
  }
17265
18478
  return fromInnerResponse(clonedResponse, getHeadersGuard(this.#headers));
@@ -17470,7 +18683,7 @@ var require_response = __commonJS({
17470
18683
  setResponseHeaders(response, headers);
17471
18684
  setHeadersList(headers, innerResponse.headersList);
17472
18685
  setHeadersGuard(headers, guard);
17473
- if (innerResponse.body?.stream) {
18686
+ if (innerResponse.urlList.length !== 0 && innerResponse.body?.stream) {
17474
18687
  streamRegistry.register(response, new WeakRef(innerResponse.body.stream));
17475
18688
  }
17476
18689
  return response;
@@ -18129,6 +19342,8 @@ var require_request2 = __commonJS({
18129
19342
  preventNoCacheCacheControlHeaderModification: init.preventNoCacheCacheControlHeaderModification ?? false,
18130
19343
  done: init.done ?? false,
18131
19344
  timingAllowFailed: init.timingAllowFailed ?? false,
19345
+ useURLCredentials: init.useURLCredentials ?? void 0,
19346
+ traversableForUserPrompts: init.traversableForUserPrompts ?? "client",
18132
19347
  urlList: init.urlList,
18133
19348
  url: init.urlList[0],
18134
19349
  headersList: init.headersList ? new HeadersList(init.headersList) : new HeadersList()
@@ -18470,7 +19685,10 @@ var require_fetch = __commonJS({
18470
19685
  simpleRangeHeaderValue,
18471
19686
  buildContentRange,
18472
19687
  createInflate,
18473
- extractMimeType
19688
+ extractMimeType,
19689
+ hasAuthenticationEntry,
19690
+ includesCredentials,
19691
+ isTraversableNavigable
18474
19692
  } = require_util2();
18475
19693
  var assert = __require("assert");
18476
19694
  var { safelyExtractBody, extractBody } = require_body();
@@ -18541,7 +19759,7 @@ var require_fetch = __commonJS({
18541
19759
  }
18542
19760
  const request = getRequestState(requestObject);
18543
19761
  if (requestObject.signal.aborted) {
18544
- abortFetch(p, request, null, requestObject.signal.reason);
19762
+ abortFetch(p, request, null, requestObject.signal.reason, null);
18545
19763
  return p.promise;
18546
19764
  }
18547
19765
  const globalObject = request.client.globalObject;
@@ -18558,7 +19776,7 @@ var require_fetch = __commonJS({
18558
19776
  assert(controller != null);
18559
19777
  controller.abort(requestObject.signal.reason);
18560
19778
  const realResponse = responseObject?.deref();
18561
- abortFetch(p, request, realResponse, requestObject.signal.reason);
19779
+ abortFetch(p, request, realResponse, requestObject.signal.reason, controller.controller);
18562
19780
  }
18563
19781
  );
18564
19782
  const processResponse = (response) => {
@@ -18566,7 +19784,7 @@ var require_fetch = __commonJS({
18566
19784
  return;
18567
19785
  }
18568
19786
  if (response.aborted) {
18569
- abortFetch(p, request, responseObject, controller.serializedAbortReason);
19787
+ abortFetch(p, request, responseObject, controller.serializedAbortReason, controller.controller);
18570
19788
  return;
18571
19789
  }
18572
19790
  if (response.type === "error") {
@@ -18581,8 +19799,11 @@ var require_fetch = __commonJS({
18581
19799
  request,
18582
19800
  processResponseEndOfBody: handleFetchDone,
18583
19801
  processResponse,
18584
- dispatcher: getRequestDispatcher(requestObject)
19802
+ dispatcher: getRequestDispatcher(requestObject),
18585
19803
  // undici
19804
+ // Keep requestObject alive to prevent its AbortController from being GC'd
19805
+ // See https://github.com/nodejs/undici/issues/4627
19806
+ requestObject
18586
19807
  });
18587
19808
  return p.promise;
18588
19809
  }
@@ -18622,7 +19843,7 @@ var require_fetch = __commonJS({
18622
19843
  );
18623
19844
  }
18624
19845
  var markResourceTiming = performance.markResourceTiming;
18625
- function abortFetch(p, request, responseObject, error) {
19846
+ function abortFetch(p, request, responseObject, error, controller) {
18626
19847
  if (p) {
18627
19848
  p.reject(error);
18628
19849
  }
@@ -18639,12 +19860,7 @@ var require_fetch = __commonJS({
18639
19860
  }
18640
19861
  const response = getResponseState(responseObject);
18641
19862
  if (response.body?.stream != null && isReadable(response.body.stream)) {
18642
- response.body.stream.cancel(error).catch((err) => {
18643
- if (err.code === "ERR_INVALID_STATE") {
18644
- return;
18645
- }
18646
- throw err;
18647
- });
19863
+ controller.error(error);
18648
19864
  }
18649
19865
  }
18650
19866
  function fetching({
@@ -18655,8 +19871,10 @@ var require_fetch = __commonJS({
18655
19871
  processResponseEndOfBody,
18656
19872
  processResponseConsumeBody,
18657
19873
  useParallelQueue = false,
18658
- dispatcher = getGlobalDispatcher()
19874
+ dispatcher = getGlobalDispatcher(),
18659
19875
  // undici
19876
+ requestObject = null
19877
+ // Keep alive to prevent AbortController GC, see #4627
18660
19878
  }) {
18661
19879
  assert(dispatcher);
18662
19880
  let taskDestination = null;
@@ -18679,7 +19897,9 @@ var require_fetch = __commonJS({
18679
19897
  processResponseConsumeBody,
18680
19898
  processResponseEndOfBody,
18681
19899
  taskDestination,
18682
- crossOriginIsolatedCapability
19900
+ crossOriginIsolatedCapability,
19901
+ // Keep requestObject alive to prevent its AbortController from being GC'd
19902
+ requestObject
18683
19903
  };
18684
19904
  assert(!request.body || request.body.stream);
18685
19905
  if (request.window === "client") {
@@ -19128,6 +20348,17 @@ var require_fetch = __commonJS({
19128
20348
  }
19129
20349
  httpRequest.headersList.delete("host", true);
19130
20350
  if (includeCredentials) {
20351
+ if (!httpRequest.headersList.contains("authorization", true)) {
20352
+ let authorizationValue = null;
20353
+ if (hasAuthenticationEntry(httpRequest) && (httpRequest.useURLCredentials === void 0 || !includesCredentials(requestCurrentURL(httpRequest)))) {
20354
+ } else if (includesCredentials(requestCurrentURL(httpRequest)) && isAuthenticationFetch) {
20355
+ const { username, password } = requestCurrentURL(httpRequest);
20356
+ authorizationValue = `Basic ${Buffer.from(`${username}:${password}`).toString("base64")}`;
20357
+ }
20358
+ if (authorizationValue !== null) {
20359
+ httpRequest.headersList.append("Authorization", authorizationValue, false);
20360
+ }
20361
+ }
19131
20362
  }
19132
20363
  if (httpCache == null) {
19133
20364
  httpRequest.cache = "no-store";
@@ -19156,6 +20387,22 @@ var require_fetch = __commonJS({
19156
20387
  response.rangeRequested = true;
19157
20388
  }
19158
20389
  response.requestIncludesCredentials = includeCredentials;
20390
+ if (response.status === 401 && httpRequest.responseTainting !== "cors" && includeCredentials && isTraversableNavigable(request.traversableForUserPrompts)) {
20391
+ if (request.body != null) {
20392
+ if (request.body.source == null) {
20393
+ return makeNetworkError("expected non-null body source");
20394
+ }
20395
+ request.body = safelyExtractBody(request.body.source)[0];
20396
+ }
20397
+ if (request.useURLCredentials === void 0 || isAuthenticationFetch) {
20398
+ if (isCancelled(fetchParams)) {
20399
+ return makeAppropriateNetworkError(fetchParams);
20400
+ }
20401
+ return response;
20402
+ }
20403
+ fetchParams.controller.connection.destroy();
20404
+ response = await httpNetworkOrCacheFetch(fetchParams, true);
20405
+ }
19159
20406
  if (response.status === 407) {
19160
20407
  if (request.window === "no-window") {
19161
20408
  return makeNetworkError();
@@ -19350,9 +20597,11 @@ var require_fetch = __commonJS({
19350
20597
  function dispatch({ body }) {
19351
20598
  const url = requestCurrentURL(request);
19352
20599
  const agent = fetchParams.controller.dispatcher;
20600
+ const path = url.pathname + url.search;
20601
+ const hasTrailingQuestionMark = url.search.length === 0 && url.href[url.href.length - url.hash.length - 1] === "?";
19353
20602
  return new Promise((resolve, reject) => agent.dispatch(
19354
20603
  {
19355
- path: url.pathname + url.search,
20604
+ path: hasTrailingQuestionMark ? `${path}?` : path,
19356
20605
  origin: url.origin,
19357
20606
  method: request.method,
19358
20607
  body: agent.isMockActive ? request.body && (request.body.source || request.body.stream) : body,
@@ -19465,6 +20714,32 @@ var require_fetch = __commonJS({
19465
20714
  fetchParams.controller.terminate(error);
19466
20715
  reject(error);
19467
20716
  },
20717
+ onRequestUpgrade(_controller, status, headers, socket) {
20718
+ if (socket.session != null && status !== 200 || socket.session == null && status !== 101) {
20719
+ return false;
20720
+ }
20721
+ const headersList = new HeadersList();
20722
+ for (const [name, value] of Object.entries(headers)) {
20723
+ if (value == null) {
20724
+ continue;
20725
+ }
20726
+ const headerName = name.toLowerCase();
20727
+ if (Array.isArray(value)) {
20728
+ for (const entry of value) {
20729
+ headersList.append(headerName, String(entry), true);
20730
+ }
20731
+ } else {
20732
+ headersList.append(headerName, String(value), true);
20733
+ }
20734
+ }
20735
+ resolve({
20736
+ status,
20737
+ statusText: STATUS_CODES[status],
20738
+ headersList,
20739
+ socket
20740
+ });
20741
+ return true;
20742
+ },
19468
20743
  onUpgrade(status, rawHeaders, socket) {
19469
20744
  if (socket.session != null && status !== 200 || socket.session == null && status !== 101) {
19470
20745
  return false;
@@ -20013,8 +21288,8 @@ var require_cache3 = __commonJS({
20013
21288
  }
20014
21289
  const responseList = [];
20015
21290
  for (const response of responses) {
20016
- const responseObject = fromInnerResponse(response, "immutable");
20017
- responseList.push(responseObject.clone());
21291
+ const responseObject = fromInnerResponse(cloneResponse(response), "immutable");
21292
+ responseList.push(responseObject);
20018
21293
  if (responseList.length >= maxResponses) {
20019
21294
  break;
20020
21295
  }
@@ -21063,13 +22338,17 @@ var require_util5 = __commonJS({
21063
22338
  return extensionList;
21064
22339
  }
21065
22340
  function isValidClientWindowBits(value) {
22341
+ if (value.length === 0) {
22342
+ return false;
22343
+ }
21066
22344
  for (let i = 0; i < value.length; i++) {
21067
22345
  const byte = value.charCodeAt(i);
21068
22346
  if (byte < 48 || byte > 57) {
21069
22347
  return false;
21070
22348
  }
21071
22349
  }
21072
- return true;
22350
+ const num = Number.parseInt(value, 10);
22351
+ return num >= 8 && num <= 15;
21073
22352
  }
21074
22353
  function getURLRecord(url, baseURL) {
21075
22354
  let urlRecord;
@@ -21270,7 +22549,8 @@ var require_connection = __commonJS({
21270
22549
  mode: "websocket",
21271
22550
  credentials: "include",
21272
22551
  cache: "no-store",
21273
- redirect: "error"
22552
+ redirect: "error",
22553
+ useURLCredentials: true
21274
22554
  });
21275
22555
  if (options.headers) {
21276
22556
  const headersList = getHeadersList(new Headers(options.headers));
@@ -21405,18 +22685,31 @@ var require_permessage_deflate = __commonJS({
21405
22685
  "use strict";
21406
22686
  var { createInflateRaw, Z_DEFAULT_WINDOWBITS } = __require("zlib");
21407
22687
  var { isValidClientWindowBits } = require_util5();
22688
+ var { MessageSizeExceededError } = require_errors();
21408
22689
  var tail = Buffer.from([0, 0, 255, 255]);
21409
22690
  var kBuffer = /* @__PURE__ */ Symbol("kBuffer");
21410
22691
  var kLength = /* @__PURE__ */ Symbol("kLength");
22692
+ var kDefaultMaxDecompressedSize = 4 * 1024 * 1024;
21411
22693
  var PerMessageDeflate = class {
21412
22694
  /** @type {import('node:zlib').InflateRaw} */
21413
22695
  #inflate;
21414
22696
  #options = {};
22697
+ /** @type {boolean} */
22698
+ #aborted = false;
22699
+ /** @type {Function|null} */
22700
+ #currentCallback = null;
22701
+ /**
22702
+ * @param {Map<string, string>} extensions
22703
+ */
21415
22704
  constructor(extensions) {
21416
22705
  this.#options.serverNoContextTakeover = extensions.has("server_no_context_takeover");
21417
22706
  this.#options.serverMaxWindowBits = extensions.get("server_max_window_bits");
21418
22707
  }
21419
22708
  decompress(chunk, fin, callback) {
22709
+ if (this.#aborted) {
22710
+ callback(new MessageSizeExceededError());
22711
+ return;
22712
+ }
21420
22713
  if (!this.#inflate) {
21421
22714
  let windowBits = Z_DEFAULT_WINDOWBITS;
21422
22715
  if (this.#options.serverMaxWindowBits) {
@@ -21426,26 +22719,51 @@ var require_permessage_deflate = __commonJS({
21426
22719
  }
21427
22720
  windowBits = Number.parseInt(this.#options.serverMaxWindowBits);
21428
22721
  }
21429
- this.#inflate = createInflateRaw({ windowBits });
22722
+ try {
22723
+ this.#inflate = createInflateRaw({ windowBits });
22724
+ } catch (err) {
22725
+ callback(err);
22726
+ return;
22727
+ }
21430
22728
  this.#inflate[kBuffer] = [];
21431
22729
  this.#inflate[kLength] = 0;
21432
22730
  this.#inflate.on("data", (data) => {
21433
- this.#inflate[kBuffer].push(data);
22731
+ if (this.#aborted) {
22732
+ return;
22733
+ }
21434
22734
  this.#inflate[kLength] += data.length;
22735
+ if (this.#inflate[kLength] > kDefaultMaxDecompressedSize) {
22736
+ this.#aborted = true;
22737
+ this.#inflate.removeAllListeners();
22738
+ this.#inflate.destroy();
22739
+ this.#inflate = null;
22740
+ if (this.#currentCallback) {
22741
+ const cb = this.#currentCallback;
22742
+ this.#currentCallback = null;
22743
+ cb(new MessageSizeExceededError());
22744
+ }
22745
+ return;
22746
+ }
22747
+ this.#inflate[kBuffer].push(data);
21435
22748
  });
21436
22749
  this.#inflate.on("error", (err) => {
21437
22750
  this.#inflate = null;
21438
22751
  callback(err);
21439
22752
  });
21440
22753
  }
22754
+ this.#currentCallback = callback;
21441
22755
  this.#inflate.write(chunk);
21442
22756
  if (fin) {
21443
22757
  this.#inflate.write(tail);
21444
22758
  }
21445
22759
  this.#inflate.flush(() => {
22760
+ if (this.#aborted || !this.#inflate) {
22761
+ return;
22762
+ }
21446
22763
  const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]);
21447
22764
  this.#inflate[kBuffer].length = 0;
21448
22765
  this.#inflate[kLength] = 0;
22766
+ this.#currentCallback = null;
21449
22767
  callback(null, full);
21450
22768
  });
21451
22769
  }
@@ -21473,6 +22791,7 @@ var require_receiver = __commonJS({
21473
22791
  var { failWebsocketConnection } = require_connection();
21474
22792
  var { WebsocketFrameSend } = require_frame();
21475
22793
  var { PerMessageDeflate } = require_permessage_deflate();
22794
+ var { MessageSizeExceededError } = require_errors();
21476
22795
  var ByteParser = class extends Writable {
21477
22796
  #buffers = [];
21478
22797
  #fragmentsBytes = 0;
@@ -21485,6 +22804,10 @@ var require_receiver = __commonJS({
21485
22804
  #extensions;
21486
22805
  /** @type {import('./websocket').Handler} */
21487
22806
  #handler;
22807
+ /**
22808
+ * @param {import('./websocket').Handler} handler
22809
+ * @param {Map<string, string>|null} extensions
22810
+ */
21488
22811
  constructor(handler, extensions) {
21489
22812
  super();
21490
22813
  this.#handler = handler;
@@ -21588,12 +22911,12 @@ var require_receiver = __commonJS({
21588
22911
  }
21589
22912
  const buffer = this.consume(8);
21590
22913
  const upper = buffer.readUInt32BE(0);
21591
- if (upper > 2 ** 31 - 1) {
22914
+ const lower = buffer.readUInt32BE(4);
22915
+ if (upper !== 0 || lower > 2 ** 31 - 1) {
21592
22916
  failWebsocketConnection(this.#handler, 1009, "Received payload length > 2^31 bytes.");
21593
22917
  return;
21594
22918
  }
21595
- const lower = buffer.readUInt32BE(4);
21596
- this.#info.payloadLength = (upper << 8) + lower;
22919
+ this.#info.payloadLength = lower;
21597
22920
  this.#state = parserStates.READ_DATA;
21598
22921
  } else if (this.#state === parserStates.READ_DATA) {
21599
22922
  if (this.#byteOffset < this.#info.payloadLength) {
@@ -21613,7 +22936,8 @@ var require_receiver = __commonJS({
21613
22936
  } else {
21614
22937
  this.#extensions.get("permessage-deflate").decompress(body, this.#info.fin, (error, data) => {
21615
22938
  if (error) {
21616
- failWebsocketConnection(this.#handler, 1007, error.message);
22939
+ const code = error instanceof MessageSizeExceededError ? 1009 : 1007;
22940
+ failWebsocketConnection(this.#handler, code, error.message);
21617
22941
  return;
21618
22942
  }
21619
22943
  this.writeFragments(data);
@@ -21881,6 +23205,15 @@ var require_websocket = __commonJS({
21881
23205
  var { SendQueue } = require_sender();
21882
23206
  var { WebsocketFrameSend } = require_frame();
21883
23207
  var { channels } = require_diagnostics();
23208
+ function getSocketAddress(socket) {
23209
+ if (typeof socket?.address === "function") {
23210
+ return socket.address();
23211
+ }
23212
+ if (typeof socket?.session?.socket?.address === "function") {
23213
+ return socket.session.socket.address();
23214
+ }
23215
+ return null;
23216
+ }
21884
23217
  var WebSocket = class _WebSocket extends EventTarget {
21885
23218
  #events = {
21886
23219
  open: null,
@@ -22152,7 +23485,7 @@ var require_websocket = __commonJS({
22152
23485
  if (channels.open.hasSubscribers) {
22153
23486
  const headers = response.headersList.entries;
22154
23487
  channels.open.publish({
22155
- address: response.socket.address(),
23488
+ address: getSocketAddress(response.socket),
22156
23489
  protocol: this.#protocol,
22157
23490
  extensions: this.#extensions,
22158
23491
  websocket: this,
@@ -22639,7 +23972,7 @@ var require_websocketstream = __commonJS({
22639
23972
  if (!this.#handler.wasEverConnected) {
22640
23973
  this.#openedPromise.reject(new WebSocketError("Socket never opened"));
22641
23974
  }
22642
- const result = this.#parser.closingInfo;
23975
+ const result = this.#parser?.closingInfo;
22643
23976
  let code = result?.code ?? 1005;
22644
23977
  if (!this.#handler.closeState.has(sentCloseFrameState.SENT) && !this.#handler.closeState.has(sentCloseFrameState.RECEIVED)) {
22645
23978
  code = 1006;
@@ -22656,8 +23989,8 @@ var require_websocketstream = __commonJS({
22656
23989
  });
22657
23990
  } else {
22658
23991
  const error = createUnvalidatedWebSocketError("unclean close", code, reason);
22659
- this.#readableStreamController.error(error);
22660
- this.#writableStream.abort(error);
23992
+ this.#readableStreamController?.error(error);
23993
+ this.#writableStream?.abort(error);
22661
23994
  this.#closedPromise.reject(error);
22662
23995
  }
22663
23996
  }
@@ -23299,6 +24632,7 @@ var require_undici = __commonJS({
23299
24632
  var RoundRobinPool = require_round_robin_pool();
23300
24633
  var Agent = require_agent();
23301
24634
  var ProxyAgent = require_proxy_agent();
24635
+ var Socks5ProxyAgent = require_socks5_proxy_agent();
23302
24636
  var EnvHttpProxyAgent = require_env_http_proxy_agent();
23303
24637
  var RetryAgent = require_retry_agent();
23304
24638
  var H2CClient = require_h2c_client();
@@ -23325,6 +24659,7 @@ var require_undici = __commonJS({
23325
24659
  module.exports.RoundRobinPool = RoundRobinPool;
23326
24660
  module.exports.Agent = Agent;
23327
24661
  module.exports.ProxyAgent = ProxyAgent;
24662
+ module.exports.Socks5ProxyAgent = Socks5ProxyAgent;
23328
24663
  module.exports.EnvHttpProxyAgent = EnvHttpProxyAgent;
23329
24664
  module.exports.RetryAgent = RetryAgent;
23330
24665
  module.exports.H2CClient = H2CClient;
@@ -23394,10 +24729,31 @@ var require_undici = __commonJS({
23394
24729
  module.exports.setGlobalDispatcher = setGlobalDispatcher;
23395
24730
  module.exports.getGlobalDispatcher = getGlobalDispatcher;
23396
24731
  var fetchImpl = require_fetch().fetch;
24732
+ var currentFilename = typeof __filename !== "undefined" ? __filename : void 0;
24733
+ function appendFetchStackTrace(err, filename) {
24734
+ if (!err || typeof err !== "object") {
24735
+ return;
24736
+ }
24737
+ const stack = typeof err.stack === "string" ? err.stack : "";
24738
+ const normalizedFilename = filename.replace(/\\/g, "/");
24739
+ if (stack && (stack.includes(filename) || stack.includes(normalizedFilename))) {
24740
+ return;
24741
+ }
24742
+ const capture = {};
24743
+ Error.captureStackTrace(capture, appendFetchStackTrace);
24744
+ if (!capture.stack) {
24745
+ return;
24746
+ }
24747
+ const captureLines = capture.stack.split("\n").slice(1).join("\n");
24748
+ err.stack = stack ? `${stack}
24749
+ ${captureLines}` : capture.stack;
24750
+ }
23397
24751
  module.exports.fetch = function fetch(init, options = void 0) {
23398
24752
  return fetchImpl(init, options).catch((err) => {
23399
- if (err && typeof err === "object") {
23400
- Error.captureStackTrace(err);
24753
+ if (currentFilename) {
24754
+ appendFetchStackTrace(err, currentFilename);
24755
+ } else if (err && typeof err === "object") {
24756
+ Error.captureStackTrace(err, module.exports.fetch);
23401
24757
  }
23402
24758
  throw err;
23403
24759
  });
@@ -23472,4 +24828,4 @@ undici/lib/web/fetch/body.js:
23472
24828
  undici/lib/web/websocket/frame.js:
23473
24829
  (*! ws. MIT License. Einar Otto Stangvik <einaros@gmail.com> *)
23474
24830
  */
23475
- //# sourceMappingURL=chunk-SXDGT4YB.js.map
24831
+ //# sourceMappingURL=chunk-DO76AL42.js.map