@node9/proxy 2.8.3 → 2.8.4

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.
Files changed (4) hide show
  1. package/README.md +1 -0
  2. package/dist/cli.js +1572 -506
  3. package/dist/cli.mjs +1572 -506
  4. package/package.json +1 -1
package/dist/cli.mjs CHANGED
@@ -24179,6 +24179,18 @@ var require_request = __commonJS({
24179
24179
  var { channels } = require_diagnostics();
24180
24180
  var { headerNameLowerCasedRecord } = require_constants();
24181
24181
  var invalidPathRegex = /[^\u0021-\u00ff]/;
24182
+ function isValidContentLengthHeaderValue(val) {
24183
+ if (typeof val !== "string" || val.length === 0) {
24184
+ return false;
24185
+ }
24186
+ for (let i = 0; i < val.length; i++) {
24187
+ const charCode = val.charCodeAt(i);
24188
+ if (charCode < 48 || charCode > 57) {
24189
+ return false;
24190
+ }
24191
+ }
24192
+ return true;
24193
+ }
24182
24194
  var kHandler = /* @__PURE__ */ Symbol("handler");
24183
24195
  var Request = class {
24184
24196
  constructor(origin, {
@@ -24453,7 +24465,11 @@ var require_request = __commonJS({
24453
24465
  } else if (typeof val[i] === "object") {
24454
24466
  throw new InvalidArgumentError(`invalid ${key} header`);
24455
24467
  } else {
24456
- arr.push(`${val[i]}`);
24468
+ const str2 = `${val[i]}`;
24469
+ if (!isValidHeaderValue(str2)) {
24470
+ throw new InvalidArgumentError(`invalid ${key} header`);
24471
+ }
24472
+ arr.push(str2);
24457
24473
  }
24458
24474
  }
24459
24475
  val = arr;
@@ -24465,6 +24481,9 @@ var require_request = __commonJS({
24465
24481
  val = "";
24466
24482
  } else {
24467
24483
  val = `${val}`;
24484
+ if (!isValidHeaderValue(val)) {
24485
+ throw new InvalidArgumentError(`invalid ${key} header`);
24486
+ }
24468
24487
  }
24469
24488
  if (headerName === "host") {
24470
24489
  if (request2.host !== null) {
@@ -24478,10 +24497,10 @@ var require_request = __commonJS({
24478
24497
  if (request2.contentLength !== null) {
24479
24498
  throw new InvalidArgumentError("duplicate content-length header");
24480
24499
  }
24481
- request2.contentLength = parseInt(val, 10);
24482
- if (!Number.isFinite(request2.contentLength)) {
24500
+ if (!isValidContentLengthHeaderValue(val)) {
24483
24501
  throw new InvalidArgumentError("invalid content-length header");
24484
24502
  }
24503
+ request2.contentLength = parseInt(val, 10);
24485
24504
  } else if (request2.contentType === null && headerName === "content-type") {
24486
24505
  request2.contentType = val;
24487
24506
  request2.headers.push(key, val);
@@ -24649,6 +24668,8 @@ var require_unwrap_handler = __commonJS({
24649
24668
  #aborted = false;
24650
24669
  #abort;
24651
24670
  [kResume] = null;
24671
+ rawHeaders = null;
24672
+ rawTrailers = null;
24652
24673
  constructor(abort) {
24653
24674
  this.#abort = abort;
24654
24675
  }
@@ -24695,10 +24716,12 @@ var require_unwrap_handler = __commonJS({
24695
24716
  return this.#handler.onResponseStarted?.();
24696
24717
  }
24697
24718
  onUpgrade(statusCode, rawHeaders, socket) {
24719
+ this.#controller.rawHeaders = rawHeaders;
24698
24720
  this.#handler.onRequestUpgrade?.(this.#controller, statusCode, parseHeaders(rawHeaders), socket);
24699
24721
  }
24700
24722
  onHeaders(statusCode, rawHeaders, resume, statusMessage) {
24701
24723
  this.#controller[kResume] = resume;
24724
+ this.#controller.rawHeaders = rawHeaders;
24702
24725
  this.#handler.onResponseStart?.(this.#controller, statusCode, parseHeaders(rawHeaders), statusMessage);
24703
24726
  return !this.#controller.paused;
24704
24727
  }
@@ -24707,6 +24730,7 @@ var require_unwrap_handler = __commonJS({
24707
24730
  return !this.#controller.paused;
24708
24731
  }
24709
24732
  onComplete(rawTrailers) {
24733
+ this.#controller.rawTrailers = rawTrailers;
24710
24734
  this.#handler.onResponseEnd?.(this.#controller, parseHeaders(rawTrailers));
24711
24735
  }
24712
24736
  onError(err2) {
@@ -24733,6 +24757,7 @@ var require_dispatcher_base = __commonJS({
24733
24757
  var { kDestroy, kClose, kClosed, kDestroyed, kDispatch } = require_symbols();
24734
24758
  var kOnDestroyed = /* @__PURE__ */ Symbol("onDestroyed");
24735
24759
  var kOnClosed = /* @__PURE__ */ Symbol("onClosed");
24760
+ var kWebSocketOptions = /* @__PURE__ */ Symbol("webSocketOptions");
24736
24761
  var DispatcherBase = class extends Dispatcher {
24737
24762
  /** @type {boolean} */
24738
24763
  [kDestroyed] = false;
@@ -24742,6 +24767,23 @@ var require_dispatcher_base = __commonJS({
24742
24767
  [kClosed] = false;
24743
24768
  /** @type {Array<Function>|null} */
24744
24769
  [kOnClosed] = null;
24770
+ /**
24771
+ * @param {import('../../types/dispatcher').DispatcherOptions} [opts]
24772
+ */
24773
+ constructor(opts) {
24774
+ super();
24775
+ this[kWebSocketOptions] = opts?.webSocket ?? {};
24776
+ }
24777
+ /**
24778
+ * @returns {import('../../types/dispatcher').WebSocketOptions}
24779
+ */
24780
+ get webSocketOptions() {
24781
+ return {
24782
+ maxFragments: this[kWebSocketOptions].maxFragments ?? 131072,
24783
+ maxPayloadSize: this[kWebSocketOptions].maxPayloadSize ?? 128 * 1024 * 1024
24784
+ // 128 MB default
24785
+ };
24786
+ }
24745
24787
  /** @returns {boolean} */
24746
24788
  get destroyed() {
24747
24789
  return this[kDestroyed];
@@ -24884,6 +24926,20 @@ var require_connect = __commonJS({
24884
24926
  if (this._maxCachedSessions === 0) {
24885
24927
  return;
24886
24928
  }
24929
+ if (this._sessionCache.has(sessionKey)) {
24930
+ this._sessionCache.delete(sessionKey);
24931
+ } else if (this._sessionCache.size >= this._maxCachedSessions) {
24932
+ for (const [key, ref] of this._sessionCache) {
24933
+ if (ref.deref() === void 0) {
24934
+ this._sessionCache.delete(key);
24935
+ return;
24936
+ }
24937
+ }
24938
+ const oldest = this._sessionCache.keys().next();
24939
+ if (!oldest.done) {
24940
+ this._sessionCache.delete(oldest.value);
24941
+ }
24942
+ }
24887
24943
  this._sessionCache.set(sessionKey, new WeakRef(session));
24888
24944
  this._sessionRegistry.register(session, sessionKey);
24889
24945
  }
@@ -26551,7 +26607,7 @@ var require_webidl = __commonJS({
26551
26607
  lowerBound = 0;
26552
26608
  upperBound = Math.pow(2, bitLength) - 1;
26553
26609
  } else {
26554
- lowerBound = Math.pow(-2, bitLength) - 1;
26610
+ lowerBound = -Math.pow(2, bitLength - 1);
26555
26611
  upperBound = Math.pow(2, bitLength - 1) - 1;
26556
26612
  }
26557
26613
  let x = Number(V);
@@ -26588,7 +26644,7 @@ var require_webidl = __commonJS({
26588
26644
  }
26589
26645
  x = webidl.util.IntegerPart(x);
26590
26646
  x = x % Math.pow(2, bitLength);
26591
- if (signedness === "signed" && x >= Math.pow(2, bitLength) - 1) {
26647
+ if (signedness === "signed" && x >= Math.pow(2, bitLength - 1)) {
26592
26648
  return x - Math.pow(2, bitLength);
26593
26649
  }
26594
26650
  return x;
@@ -27711,7 +27767,7 @@ var require_util2 = __commonJS({
27711
27767
  return !!(url.username || url.password);
27712
27768
  }
27713
27769
  function isTraversableNavigable(navigable) {
27714
- return true;
27770
+ return navigable != null && navigable !== "client" && navigable !== "no-traversable";
27715
27771
  }
27716
27772
  var EnvironmentSettingsObjectBase = class {
27717
27773
  get baseUrl() {
@@ -28106,7 +28162,7 @@ var require_formdata_parser = __commonJS({
28106
28162
  );
28107
28163
  value = decoder.decode(tokenValue);
28108
28164
  }
28109
- return { name: attrNameStr, value };
28165
+ return { name: attrNameStr, value, extended: isExtended };
28110
28166
  }
28111
28167
  function parseMultipartFormDataHeaders(input, position) {
28112
28168
  let name = null;
@@ -28141,6 +28197,7 @@ var require_formdata_parser = __commonJS({
28141
28197
  switch (bufferToLowerCasedHeaderName(headerName)) {
28142
28198
  case "content-disposition": {
28143
28199
  name = filename = null;
28200
+ let filenameIsExtended = false;
28144
28201
  const dispositionType = collectASequenceOfBytes(
28145
28202
  (char) => isToken(char),
28146
28203
  input,
@@ -28149,7 +28206,7 @@ var require_formdata_parser = __commonJS({
28149
28206
  if (dispositionType.toString("ascii").toLowerCase() !== "form-data") {
28150
28207
  throw parsingError("expected form-data for content-disposition header");
28151
28208
  }
28152
- while (position.position < input.length && input[position.position] !== 13 && input[position.position + 1] !== 10) {
28209
+ while (position.position < input.length && (input[position.position] !== 13 || input[position.position + 1] !== 10)) {
28153
28210
  const attribute = parseContentDispositionAttribute(input, position);
28154
28211
  if (!attribute) {
28155
28212
  break;
@@ -28157,7 +28214,12 @@ var require_formdata_parser = __commonJS({
28157
28214
  if (attribute.name === "name") {
28158
28215
  name = attribute.value;
28159
28216
  } else if (attribute.name === "filename") {
28160
- filename = attribute.value;
28217
+ if (attribute.extended) {
28218
+ filename = attribute.value;
28219
+ filenameIsExtended = true;
28220
+ } else if (!filenameIsExtended) {
28221
+ filename = attribute.value;
28222
+ }
28161
28223
  }
28162
28224
  }
28163
28225
  if (name === null) {
@@ -28193,7 +28255,7 @@ var require_formdata_parser = __commonJS({
28193
28255
  );
28194
28256
  }
28195
28257
  }
28196
- if (input[position.position] !== 13 && input[position.position + 1] !== 10) {
28258
+ if (input[position.position] !== 13 || input[position.position + 1] !== 10) {
28197
28259
  throw parsingError("expected CRLF");
28198
28260
  } else {
28199
28261
  position.position += 2;
@@ -28578,6 +28640,7 @@ var require_client_h1 = __commonJS({
28578
28640
  RequestContentLengthMismatchError,
28579
28641
  ResponseContentLengthMismatchError,
28580
28642
  RequestAbortedError,
28643
+ InvalidArgumentError,
28581
28644
  HeadersTimeoutError,
28582
28645
  HeadersOverflowError,
28583
28646
  SocketError,
@@ -28624,15 +28687,18 @@ var require_client_h1 = __commonJS({
28624
28687
  var EMPTY_BUF = Buffer.alloc(0);
28625
28688
  var FastBuffer = Buffer[Symbol.species];
28626
28689
  var removeAllListeners = util.removeAllListeners;
28690
+ var kIdleSocketValidation = /* @__PURE__ */ Symbol("kIdleSocketValidation");
28691
+ var kIdleSocketValidationTimeout = /* @__PURE__ */ Symbol("kIdleSocketValidationTimeout");
28692
+ var kSocketUsed = /* @__PURE__ */ Symbol("kSocketUsed");
28627
28693
  var extractBody;
28628
28694
  function lazyllhttp() {
28629
28695
  const llhttpWasmData = process.env.JEST_WORKER_ID ? require_llhttp_wasm() : void 0;
28630
28696
  let mod;
28631
28697
  let useWasmSIMD = process.arch !== "ppc64";
28632
28698
  if (process.env.UNDICI_NO_WASM_SIMD === "1") {
28633
- useWasmSIMD = true;
28634
- } else if (process.env.UNDICI_NO_WASM_SIMD === "0") {
28635
28699
  useWasmSIMD = false;
28700
+ } else if (process.env.UNDICI_NO_WASM_SIMD === "0") {
28701
+ useWasmSIMD = true;
28636
28702
  }
28637
28703
  if (useWasmSIMD) {
28638
28704
  try {
@@ -28750,6 +28816,7 @@ var require_client_h1 = __commonJS({
28750
28816
  this.client = client;
28751
28817
  this.socket = socket;
28752
28818
  this.timeout = null;
28819
+ this.timeoutWeakRef = new WeakRef(this);
28753
28820
  this.timeoutValue = null;
28754
28821
  this.timeoutType = null;
28755
28822
  this.statusCode = 0;
@@ -28775,9 +28842,9 @@ var require_client_h1 = __commonJS({
28775
28842
  }
28776
28843
  if (delay) {
28777
28844
  if (type & USE_FAST_TIMER) {
28778
- this.timeout = timers.setFastTimeout(onParserTimeout, delay, new WeakRef(this));
28845
+ this.timeout = timers.setFastTimeout(onParserTimeout, delay, this.timeoutWeakRef);
28779
28846
  } else {
28780
- this.timeout = setTimeout(onParserTimeout, delay, new WeakRef(this));
28847
+ this.timeout = setTimeout(onParserTimeout, delay, this.timeoutWeakRef);
28781
28848
  this.timeout?.unref();
28782
28849
  }
28783
28850
  }
@@ -28849,19 +28916,47 @@ var require_client_h1 = __commonJS({
28849
28916
  this.paused = true;
28850
28917
  socket.unshift(data);
28851
28918
  } else {
28852
- const ptr = llhttp.llhttp_get_error_reason(this.ptr);
28853
- let message = "";
28854
- if (ptr) {
28855
- const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0);
28856
- message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")";
28857
- }
28858
- throw new HTTPParserError(message, constants.ERROR[ret], data);
28919
+ throw this.createError(ret, data);
28859
28920
  }
28860
28921
  }
28861
28922
  } catch (err2) {
28862
28923
  util.destroy(socket, err2);
28863
28924
  }
28864
28925
  }
28926
+ finish() {
28927
+ assert(currentParser === null);
28928
+ assert(this.ptr != null);
28929
+ assert(!this.paused);
28930
+ const { llhttp } = this;
28931
+ let ret;
28932
+ try {
28933
+ currentParser = this;
28934
+ ret = llhttp.llhttp_finish(this.ptr);
28935
+ } finally {
28936
+ currentParser = null;
28937
+ }
28938
+ if (ret === constants.ERROR.OK) {
28939
+ return null;
28940
+ }
28941
+ if (ret === constants.ERROR.PAUSED || ret === constants.ERROR.PAUSED_UPGRADE) {
28942
+ this.paused = true;
28943
+ return null;
28944
+ }
28945
+ return this.createError(ret, EMPTY_BUF);
28946
+ }
28947
+ createError(ret, data) {
28948
+ const { llhttp, contentLength, bytesRead } = this;
28949
+ if (contentLength && bytesRead !== parseInt(contentLength, 10)) {
28950
+ return new ResponseContentLengthMismatchError();
28951
+ }
28952
+ const ptr = llhttp.llhttp_get_error_reason(this.ptr);
28953
+ let message = "";
28954
+ if (ptr) {
28955
+ const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0);
28956
+ message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")";
28957
+ }
28958
+ return new HTTPParserError(message, constants.ERROR[ret], data);
28959
+ }
28865
28960
  destroy() {
28866
28961
  assert(currentParser === null);
28867
28962
  assert(this.ptr != null);
@@ -28889,6 +28984,10 @@ var require_client_h1 = __commonJS({
28889
28984
  if (socket.destroyed) {
28890
28985
  return -1;
28891
28986
  }
28987
+ if (client[kRunning] === 0) {
28988
+ util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket)));
28989
+ return -1;
28990
+ }
28892
28991
  const request2 = client[kQueue][client[kRunningIdx]];
28893
28992
  if (!request2) {
28894
28993
  return -1;
@@ -28991,6 +29090,10 @@ var require_client_h1 = __commonJS({
28991
29090
  if (socket.destroyed) {
28992
29091
  return -1;
28993
29092
  }
29093
+ if (client[kRunning] === 0) {
29094
+ util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket)));
29095
+ return -1;
29096
+ }
28994
29097
  const request2 = client[kQueue][client[kRunningIdx]];
28995
29098
  if (!request2) {
28996
29099
  return -1;
@@ -29124,6 +29227,7 @@ var require_client_h1 = __commonJS({
29124
29227
  }
29125
29228
  request2.onComplete(headers);
29126
29229
  client[kQueue][client[kRunningIdx]++] = null;
29230
+ socket[kSocketUsed] = client[kPending] === 0;
29127
29231
  if (socket[kWriting]) {
29128
29232
  assert(client[kRunning] === 0);
29129
29233
  util.destroy(socket, new InformationalError("reset"));
@@ -29177,6 +29281,9 @@ var require_client_h1 = __commonJS({
29177
29281
  socket[kWriting] = false;
29178
29282
  socket[kReset] = false;
29179
29283
  socket[kBlocking] = false;
29284
+ socket[kIdleSocketValidation] = 0;
29285
+ socket[kIdleSocketValidationTimeout] = null;
29286
+ socket[kSocketUsed] = false;
29180
29287
  socket[kParser] = new Parser(client, socket, llhttpInstance);
29181
29288
  util.addListener(socket, "error", onHttpSocketError);
29182
29289
  util.addListener(socket, "readable", onHttpSocketReadable);
@@ -29216,7 +29323,7 @@ var require_client_h1 = __commonJS({
29216
29323
  * @returns {boolean}
29217
29324
  */
29218
29325
  busy(request2) {
29219
- if (socket[kWriting] || socket[kReset] || socket[kBlocking]) {
29326
+ if (socket[kWriting] || socket[kReset] || socket[kBlocking] || socket[kIdleSocketValidation] === 1) {
29220
29327
  return true;
29221
29328
  }
29222
29329
  if (request2) {
@@ -29238,7 +29345,11 @@ var require_client_h1 = __commonJS({
29238
29345
  assert(err2.code !== "ERR_TLS_CERT_ALTNAME_INVALID");
29239
29346
  const parser = this[kParser];
29240
29347
  if (err2.code === "ECONNRESET" && parser.statusCode && !parser.shouldKeepAlive) {
29241
- parser.onMessageComplete();
29348
+ const parserErr = parser.finish();
29349
+ if (parserErr) {
29350
+ this[kError] = parserErr;
29351
+ this[kClient][kOnError](parserErr);
29352
+ }
29242
29353
  return;
29243
29354
  }
29244
29355
  this[kError] = err2;
@@ -29250,16 +29361,20 @@ var require_client_h1 = __commonJS({
29250
29361
  function onHttpSocketEnd() {
29251
29362
  const parser = this[kParser];
29252
29363
  if (parser.statusCode && !parser.shouldKeepAlive) {
29253
- parser.onMessageComplete();
29364
+ const parserErr = parser.finish();
29365
+ if (parserErr) {
29366
+ util.destroy(this, parserErr);
29367
+ }
29254
29368
  return;
29255
29369
  }
29256
29370
  util.destroy(this, new SocketError("other side closed", util.getSocketInfo(this)));
29257
29371
  }
29258
29372
  function onHttpSocketClose() {
29259
29373
  const parser = this[kParser];
29374
+ clearIdleSocketValidation(this);
29260
29375
  if (parser) {
29261
29376
  if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) {
29262
- parser.onMessageComplete();
29377
+ this[kError] = parser.finish() || this[kError];
29263
29378
  }
29264
29379
  this[kParser].destroy();
29265
29380
  this[kParser] = null;
@@ -29288,6 +29403,23 @@ var require_client_h1 = __commonJS({
29288
29403
  function onSocketClose() {
29289
29404
  this[kClosed] = true;
29290
29405
  }
29406
+ function clearIdleSocketValidation(socket) {
29407
+ if (socket[kIdleSocketValidationTimeout]) {
29408
+ clearImmediate(socket[kIdleSocketValidationTimeout]);
29409
+ socket[kIdleSocketValidationTimeout] = null;
29410
+ }
29411
+ socket[kIdleSocketValidation] = 0;
29412
+ }
29413
+ function scheduleIdleSocketValidation(client, socket) {
29414
+ socket[kIdleSocketValidation] = 1;
29415
+ socket[kIdleSocketValidationTimeout] = setImmediate(() => {
29416
+ socket[kIdleSocketValidationTimeout] = null;
29417
+ socket[kIdleSocketValidation] = 2;
29418
+ if (client[kSocket] === socket && !socket.destroyed) {
29419
+ client[kResume]();
29420
+ }
29421
+ });
29422
+ }
29291
29423
  function resumeH1(client) {
29292
29424
  const socket = client[kSocket];
29293
29425
  if (socket && !socket.destroyed) {
@@ -29300,6 +29432,29 @@ var require_client_h1 = __commonJS({
29300
29432
  socket.ref();
29301
29433
  socket[kNoRef] = false;
29302
29434
  }
29435
+ if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) {
29436
+ if (socket[kIdleSocketValidation] === 0) {
29437
+ scheduleIdleSocketValidation(client, socket);
29438
+ socket[kParser].readMore();
29439
+ if (socket.destroyed) {
29440
+ return;
29441
+ }
29442
+ return;
29443
+ }
29444
+ if (socket[kIdleSocketValidation] === 1) {
29445
+ socket[kParser].readMore();
29446
+ if (socket.destroyed) {
29447
+ return;
29448
+ }
29449
+ return;
29450
+ }
29451
+ }
29452
+ if (client[kRunning] === 0) {
29453
+ socket[kParser].readMore();
29454
+ if (socket.destroyed) {
29455
+ return;
29456
+ }
29457
+ }
29303
29458
  if (client[kSize] === 0) {
29304
29459
  if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) {
29305
29460
  socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE);
@@ -29330,8 +29485,16 @@ var require_client_h1 = __commonJS({
29330
29485
  }
29331
29486
  body = bodyStream.stream;
29332
29487
  contentLength = bodyStream.length;
29333
- } else if (util.isBlobLike(body) && request2.contentType == null && body.type) {
29334
- headers.push("content-type", body.type);
29488
+ } else if (util.isBlobLike(body) && request2.contentType == null) {
29489
+ const contentType = body.type;
29490
+ if (contentType) {
29491
+ const contentTypeValue = `${contentType}`;
29492
+ if (!util.isValidHeaderValue(contentTypeValue)) {
29493
+ util.errorRequest(client, request2, new InvalidArgumentError("invalid content-type header"));
29494
+ return false;
29495
+ }
29496
+ headers.push("content-type", contentTypeValue);
29497
+ }
29335
29498
  }
29336
29499
  if (body && typeof body.read === "function") {
29337
29500
  body.read(0);
@@ -29352,6 +29515,7 @@ var require_client_h1 = __commonJS({
29352
29515
  process.emitWarning(new RequestContentLengthMismatchError());
29353
29516
  }
29354
29517
  const socket = client[kSocket];
29518
+ clearIdleSocketValidation(socket);
29355
29519
  const abort = (err2) => {
29356
29520
  if (request2.aborted || request2.completed) {
29357
29521
  return;
@@ -29744,7 +29908,9 @@ var require_client_h2 = __commonJS({
29744
29908
  RequestAbortedError,
29745
29909
  SocketError,
29746
29910
  InformationalError,
29747
- InvalidArgumentError
29911
+ InvalidArgumentError,
29912
+ HeadersTimeoutError,
29913
+ BodyTimeoutError
29748
29914
  } = require_errors();
29749
29915
  var {
29750
29916
  kUrl,
@@ -29769,6 +29935,7 @@ var require_client_h2 = __commonJS({
29769
29935
  kHTTPContext,
29770
29936
  kClosed,
29771
29937
  kBodyTimeout,
29938
+ kHeadersTimeout,
29772
29939
  kEnableConnectProtocol,
29773
29940
  kRemoteSettings,
29774
29941
  kHTTP2Stream,
@@ -29905,7 +30072,7 @@ var require_client_h2 = __commonJS({
29905
30072
  function resumeH2(client) {
29906
30073
  const socket = client[kSocket];
29907
30074
  if (socket?.destroyed === false) {
29908
- if (client[kSize] === 0 || client[kMaxConcurrentStreams] === 0) {
30075
+ if (client[kSize] === 0) {
29909
30076
  socket.unref();
29910
30077
  client[kHTTP2Session].unref();
29911
30078
  } else {
@@ -29971,6 +30138,24 @@ var require_client_h2 = __commonJS({
29971
30138
  this.destroy(err2);
29972
30139
  util.destroy(this[kSocket], err2);
29973
30140
  }
30141
+ function completeRequest(client, request2, resetPendingIdx = false) {
30142
+ const queue = client[kQueue];
30143
+ const runningIdx = client[kRunningIdx];
30144
+ if (runningIdx < client[kPendingIdx] && queue[runningIdx] === request2) {
30145
+ queue[runningIdx] = null;
30146
+ client[kRunningIdx] = runningIdx + 1;
30147
+ return;
30148
+ }
30149
+ const index = queue.indexOf(request2, runningIdx);
30150
+ if (index === -1 || index >= client[kPendingIdx]) {
30151
+ return;
30152
+ }
30153
+ queue.splice(index, 1);
30154
+ client[kPendingIdx]--;
30155
+ if (resetPendingIdx && client[kPendingIdx] < client[kRunningIdx]) {
30156
+ client[kPendingIdx] = client[kRunningIdx];
30157
+ }
30158
+ }
29974
30159
  function onHttp2SessionGoAway(errorCode) {
29975
30160
  const err2 = this[kError] || new SocketError(`HTTP/2: "GOAWAY" frame received with code ${errorCode}`, util.getSocketInfo(this[kSocket]));
29976
30161
  const client = this[kClient];
@@ -29982,7 +30167,9 @@ var require_client_h2 = __commonJS({
29982
30167
  if (client[kRunningIdx] < client[kQueue].length) {
29983
30168
  const request2 = client[kQueue][client[kRunningIdx]];
29984
30169
  client[kQueue][client[kRunningIdx]++] = null;
29985
- util.errorRequest(client, request2, err2);
30170
+ if (request2 != null) {
30171
+ util.errorRequest(client, request2, err2);
30172
+ }
29986
30173
  client[kPendingIdx] = client[kRunningIdx];
29987
30174
  }
29988
30175
  assert(client[kRunning] === 0);
@@ -30005,7 +30192,9 @@ var require_client_h2 = __commonJS({
30005
30192
  const requests = client[kQueue].splice(client[kRunningIdx]);
30006
30193
  for (let i = 0; i < requests.length; i++) {
30007
30194
  const request2 = requests[i];
30008
- util.errorRequest(client, request2, err2);
30195
+ if (request2 != null) {
30196
+ util.errorRequest(client, request2, err2);
30197
+ }
30009
30198
  }
30010
30199
  }
30011
30200
  }
@@ -30037,7 +30226,8 @@ var require_client_h2 = __commonJS({
30037
30226
  return method !== "GET" && method !== "HEAD" && method !== "OPTIONS" && method !== "TRACE" && method !== "CONNECT";
30038
30227
  }
30039
30228
  function writeH2(client, request2) {
30040
- const requestTimeout = request2.bodyTimeout ?? client[kBodyTimeout];
30229
+ const headersTimeout = request2.headersTimeout ?? client[kHeadersTimeout];
30230
+ const bodyTimeout = request2.bodyTimeout ?? client[kBodyTimeout];
30041
30231
  const session = client[kHTTP2Session];
30042
30232
  const { method, path: path74, host, upgrade, expectContinue, signal, protocol, headers: reqHeaders } = request2;
30043
30233
  let { body } = request2;
@@ -30085,6 +30275,7 @@ var require_client_h2 = __commonJS({
30085
30275
  stream.removeAllListeners("data");
30086
30276
  stream.close();
30087
30277
  client[kOnError](err2);
30278
+ completeRequest(client, request2);
30088
30279
  client[kResume]();
30089
30280
  }
30090
30281
  util.destroy(body, err2);
@@ -30119,7 +30310,7 @@ var require_client_h2 = __commonJS({
30119
30310
  const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers2;
30120
30311
  request2.onUpgrade(statusCode, parseH2Headers(realHeaders), stream);
30121
30312
  ++session[kOpenStreams];
30122
- client[kQueue][client[kRunningIdx]++] = null;
30313
+ completeRequest(client, request2);
30123
30314
  });
30124
30315
  stream.on("error", () => {
30125
30316
  if (stream.rstCode === NGHTTP2_REFUSED_STREAM || stream.rstCode === NGHTTP2_CANCEL) {
@@ -30130,7 +30321,7 @@ var require_client_h2 = __commonJS({
30130
30321
  session[kOpenStreams] -= 1;
30131
30322
  if (session[kOpenStreams] === 0) session.unref();
30132
30323
  });
30133
- stream.setTimeout(requestTimeout);
30324
+ stream.setTimeout(headersTimeout);
30134
30325
  return true;
30135
30326
  }
30136
30327
  stream = session.request(headers, { endStream: false, signal });
@@ -30139,13 +30330,14 @@ var require_client_h2 = __commonJS({
30139
30330
  const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers2;
30140
30331
  request2.onUpgrade(statusCode, parseH2Headers(realHeaders), stream);
30141
30332
  ++session[kOpenStreams];
30142
- client[kQueue][client[kRunningIdx]++] = null;
30333
+ completeRequest(client, request2);
30143
30334
  });
30335
+ stream.on("error", abort);
30144
30336
  stream.once("close", () => {
30145
30337
  session[kOpenStreams] -= 1;
30146
30338
  if (session[kOpenStreams] === 0) session.unref();
30147
30339
  });
30148
- stream.setTimeout(requestTimeout);
30340
+ stream.setTimeout(headersTimeout);
30149
30341
  return true;
30150
30342
  }
30151
30343
  headers[HTTP2_HEADER_PATH] = path74;
@@ -30203,12 +30395,13 @@ var require_client_h2 = __commonJS({
30203
30395
  writeBodyH2();
30204
30396
  }
30205
30397
  ++session[kOpenStreams];
30206
- stream.setTimeout(requestTimeout);
30398
+ stream.setTimeout(headersTimeout);
30207
30399
  let responseReceived = false;
30208
30400
  stream.once("response", (headers2) => {
30209
30401
  const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers2;
30210
30402
  request2.onResponseStarted();
30211
30403
  responseReceived = true;
30404
+ stream.setTimeout(bodyTimeout);
30212
30405
  if (request2.aborted) {
30213
30406
  stream.removeAllListeners("data");
30214
30407
  return;
@@ -30231,12 +30424,11 @@ var require_client_h2 = __commonJS({
30231
30424
  if (!request2.aborted && !request2.completed) {
30232
30425
  request2.onComplete({});
30233
30426
  }
30234
- client[kQueue][client[kRunningIdx]++] = null;
30427
+ completeRequest(client, request2);
30235
30428
  client[kResume]();
30236
30429
  } else {
30237
30430
  abort(new InformationalError("HTTP/2: stream half-closed (remote)"));
30238
- client[kQueue][client[kRunningIdx]++] = null;
30239
- client[kPendingIdx] = client[kRunningIdx];
30431
+ completeRequest(client, request2, true);
30240
30432
  client[kResume]();
30241
30433
  }
30242
30434
  });
@@ -30246,6 +30438,9 @@ var require_client_h2 = __commonJS({
30246
30438
  if (session[kOpenStreams] === 0) {
30247
30439
  session.unref();
30248
30440
  }
30441
+ if (!request2.aborted && !request2.completed) {
30442
+ abort(new InformationalError("HTTP/2: stream closed before the response was complete"));
30443
+ }
30249
30444
  });
30250
30445
  stream.once("error", function(err2) {
30251
30446
  stream.removeAllListeners("data");
@@ -30259,7 +30454,7 @@ var require_client_h2 = __commonJS({
30259
30454
  stream.removeAllListeners("data");
30260
30455
  });
30261
30456
  stream.on("timeout", () => {
30262
- const err2 = new InformationalError(`HTTP/2: "stream timeout after ${requestTimeout}"`);
30457
+ const err2 = responseReceived ? new BodyTimeoutError(`HTTP/2: "body timeout after ${bodyTimeout}"`) : new HeadersTimeoutError(`HTTP/2: "headers timeout after ${headersTimeout}"`);
30263
30458
  stream.removeAllListeners("data");
30264
30459
  session[kOpenStreams] -= 1;
30265
30460
  if (session[kOpenStreams] === 0) {
@@ -30567,7 +30762,8 @@ var require_client = __commonJS({
30567
30762
  useH2c,
30568
30763
  initialWindowSize,
30569
30764
  connectionWindowSize,
30570
- pingInterval
30765
+ pingInterval,
30766
+ webSocket
30571
30767
  } = {}) {
30572
30768
  if (keepAlive !== void 0) {
30573
30769
  throw new InvalidArgumentError("unsupported keepAlive, use pipelining=0 instead");
@@ -30645,7 +30841,7 @@ var require_client = __commonJS({
30645
30841
  if (pingInterval != null && (typeof pingInterval !== "number" || !Number.isInteger(pingInterval) || pingInterval < 0)) {
30646
30842
  throw new InvalidArgumentError("pingInterval must be a positive integer, greater or equal to 0");
30647
30843
  }
30648
- super();
30844
+ super({ webSocket });
30649
30845
  if (typeof connect2 !== "function") {
30650
30846
  connect2 = buildConnector({
30651
30847
  ...tls,
@@ -30657,9 +30853,13 @@ var require_client = __commonJS({
30657
30853
  ...typeof autoSelectFamily === "boolean" ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : void 0,
30658
30854
  ...connect2
30659
30855
  });
30660
- } else if (socketPath != null) {
30856
+ } else {
30661
30857
  const customConnect = connect2;
30662
- connect2 = (opts, callback) => customConnect({ ...opts, socketPath }, callback);
30858
+ connect2 = (opts, callback) => customConnect({
30859
+ ...opts,
30860
+ ...socketPath != null ? { socketPath } : null,
30861
+ ...allowH2 != null ? { allowH2 } : null
30862
+ }, callback);
30663
30863
  }
30664
30864
  this[kUrl] = util.parseOrigin(url);
30665
30865
  this[kConnector] = connect2;
@@ -30752,7 +30952,9 @@ var require_client = __commonJS({
30752
30952
  const requests = this[kQueue].splice(this[kPendingIdx]);
30753
30953
  for (let i = 0; i < requests.length; i++) {
30754
30954
  const request2 = requests[i];
30755
- util.errorRequest(this, request2, err2);
30955
+ if (request2 != null) {
30956
+ util.errorRequest(this, request2, err2);
30957
+ }
30756
30958
  }
30757
30959
  const callback = () => {
30758
30960
  if (this[kClosedResolve]) {
@@ -30777,7 +30979,9 @@ var require_client = __commonJS({
30777
30979
  const requests = client[kQueue].splice(client[kRunningIdx]);
30778
30980
  for (let i = 0; i < requests.length; i++) {
30779
30981
  const request2 = requests[i];
30780
- util.errorRequest(client, request2, err2);
30982
+ if (request2 != null) {
30983
+ util.errorRequest(client, request2, err2);
30984
+ }
30781
30985
  }
30782
30986
  assert(client[kSize] === 0);
30783
30987
  }
@@ -31288,7 +31492,7 @@ var require_pool = __commonJS({
31288
31492
  ...connect
31289
31493
  });
31290
31494
  }
31291
- super();
31495
+ super(options);
31292
31496
  this[kConnections] = connections || null;
31293
31497
  this[kUrl] = util.parseOrigin(origin);
31294
31498
  this[kOptions] = { ...util.deepClone(options), connect, allowH2, clientTtl, socketPath };
@@ -31370,12 +31574,14 @@ var require_balanced_pool = __commonJS({
31370
31574
  return new Pool(origin, opts);
31371
31575
  }
31372
31576
  var BalancedPool = class extends PoolBase {
31373
- constructor(upstreams = [], { factory = defaultFactory, ...opts } = {}) {
31577
+ constructor(upstreams = [], { factory = defaultFactory, connect, tls, ...opts } = {}) {
31374
31578
  if (typeof factory !== "function") {
31375
31579
  throw new InvalidArgumentError("factory must be a function.");
31376
31580
  }
31377
- super();
31378
- this[kOptions] = { ...util.deepClone(opts) };
31581
+ super(opts);
31582
+ if (connect && typeof connect !== "function") connect = { ...connect };
31583
+ if (tls && typeof tls !== "function") tls = { ...tls };
31584
+ this[kOptions] = { ...util.deepClone(opts), connect, tls };
31379
31585
  this[kOptions].interceptors = opts.interceptors ? { ...opts.interceptors } : void 0;
31380
31586
  this[kIndex] = -1;
31381
31587
  this[kCurrentWeight] = 0;
@@ -31626,7 +31832,7 @@ var require_agent = __commonJS({
31626
31832
  if (typeof maxOrigins !== "number" || Number.isNaN(maxOrigins) || maxOrigins <= 0) {
31627
31833
  throw new InvalidArgumentError("maxOrigins must be a number greater than 0");
31628
31834
  }
31629
- super();
31835
+ super(options);
31630
31836
  if (connect && typeof connect !== "function") {
31631
31837
  connect = { ...connect };
31632
31838
  }
@@ -31763,28 +31969,37 @@ var require_socks5_utils = __commonJS({
31763
31969
  }
31764
31970
  function parseIPv6(address) {
31765
31971
  const buffer = Buffer2.alloc(16);
31766
- const parts = address.split(":");
31767
- let partIndex = 0;
31768
- let bufferIndex = 0;
31769
- const doubleColonIndex = address.indexOf("::");
31972
+ let normalizedAddress = address;
31973
+ if (address.includes(".")) {
31974
+ const lastColonIndex = address.lastIndexOf(":");
31975
+ const ipv4Part = address.slice(lastColonIndex + 1);
31976
+ if (net3.isIPv4(ipv4Part)) {
31977
+ const octets = ipv4Part.split(".").map(Number);
31978
+ const high = (octets[0] << 8 | octets[1]).toString(16);
31979
+ const low = (octets[2] << 8 | octets[3]).toString(16);
31980
+ normalizedAddress = `${address.slice(0, lastColonIndex)}:${high}:${low}`;
31981
+ }
31982
+ }
31983
+ const doubleColonIndex = normalizedAddress.indexOf("::");
31770
31984
  if (doubleColonIndex !== -1) {
31771
- const nonEmptyParts = parts.filter((p) => p.length > 0).length;
31772
- const skipParts = 8 - nonEmptyParts;
31773
- for (let i = 0; i < parts.length; i++) {
31774
- if (parts[i] === "" && i === doubleColonIndex / 3) {
31775
- bufferIndex += skipParts * 2;
31776
- } else if (parts[i] !== "") {
31777
- const value = parseInt(parts[i], 16);
31778
- buffer.writeUInt16BE(value, bufferIndex);
31779
- bufferIndex += 2;
31780
- }
31985
+ const before = normalizedAddress.slice(0, doubleColonIndex);
31986
+ const after = normalizedAddress.slice(doubleColonIndex + 2);
31987
+ const beforeParts = before === "" ? [] : before.split(":");
31988
+ const afterParts = after === "" ? [] : after.split(":");
31989
+ let bufferIndex = 0;
31990
+ for (const part of beforeParts) {
31991
+ buffer.writeUInt16BE(parseInt(part, 16), bufferIndex);
31992
+ bufferIndex += 2;
31993
+ }
31994
+ bufferIndex = 16 - afterParts.length * 2;
31995
+ for (const part of afterParts) {
31996
+ buffer.writeUInt16BE(parseInt(part, 16), bufferIndex);
31997
+ bufferIndex += 2;
31781
31998
  }
31782
31999
  } else {
31783
- for (const part of parts) {
31784
- if (part === "") continue;
31785
- const value = parseInt(part, 16);
31786
- buffer.writeUInt16BE(value, partIndex * 2);
31787
- partIndex++;
32000
+ const parts = normalizedAddress.split(":");
32001
+ for (let i = 0; i < parts.length; i++) {
32002
+ buffer.writeUInt16BE(parseInt(parts[i], 16), i * 2);
31788
32003
  }
31789
32004
  }
31790
32005
  return buffer;
@@ -31890,6 +32105,7 @@ var require_socks5_client = __commonJS({
31890
32105
  var { debuglog } = __require("util");
31891
32106
  var { parseAddress } = require_socks5_utils();
31892
32107
  var debug = debuglog("undici:socks5");
32108
+ var EMPTY_BUFFER = Buffer2.alloc(0);
31893
32109
  var SOCKS_VERSION = 5;
31894
32110
  var AUTH_METHODS = {
31895
32111
  NO_AUTH: 0,
@@ -31922,6 +32138,7 @@ var require_socks5_client = __commonJS({
31922
32138
  INITIAL: "initial",
31923
32139
  HANDSHAKING: "handshaking",
31924
32140
  AUTHENTICATING: "authenticating",
32141
+ AUTHENTICATED: "authenticated",
31925
32142
  CONNECTING: "connecting",
31926
32143
  CONNECTED: "connected",
31927
32144
  ERROR: "error",
@@ -31936,15 +32153,18 @@ var require_socks5_client = __commonJS({
31936
32153
  this.socket = socket;
31937
32154
  this.options = options;
31938
32155
  this.state = STATES.INITIAL;
31939
- this.buffer = Buffer2.alloc(0);
32156
+ this.buffer = EMPTY_BUFFER;
32157
+ this.onSocketData = this.onData.bind(this);
32158
+ this.onSocketError = this.onError.bind(this);
32159
+ this.onSocketClose = this.onClose.bind(this);
31940
32160
  this.authMethods = [];
31941
32161
  if (options.username && options.password) {
31942
32162
  this.authMethods.push(AUTH_METHODS.USERNAME_PASSWORD);
31943
32163
  }
31944
32164
  this.authMethods.push(AUTH_METHODS.NO_AUTH);
31945
- this.socket.on("data", this.onData.bind(this));
31946
- this.socket.on("error", this.onError.bind(this));
31947
- this.socket.on("close", this.onClose.bind(this));
32165
+ this.socket.on("data", this.onSocketData);
32166
+ this.socket.on("error", this.onSocketError);
32167
+ this.socket.on("close", this.onSocketClose);
31948
32168
  }
31949
32169
  /**
31950
32170
  * Handle incoming data from the socket
@@ -31993,6 +32213,10 @@ var require_socks5_client = __commonJS({
31993
32213
  this.socket.destroy();
31994
32214
  }
31995
32215
  }
32216
+ markAuthenticated() {
32217
+ this.state = STATES.AUTHENTICATED;
32218
+ this.emit("authenticated");
32219
+ }
31996
32220
  /**
31997
32221
  * Start the SOCKS5 handshake
31998
32222
  */
@@ -32028,7 +32252,7 @@ var require_socks5_client = __commonJS({
32028
32252
  this.buffer = this.buffer.subarray(2);
32029
32253
  debug("server selected auth method", method);
32030
32254
  if (method === AUTH_METHODS.NO_AUTH) {
32031
- this.emit("authenticated");
32255
+ this.markAuthenticated();
32032
32256
  } else if (method === AUTH_METHODS.USERNAME_PASSWORD) {
32033
32257
  this.state = STATES.AUTHENTICATING;
32034
32258
  this.sendAuthRequest();
@@ -32075,7 +32299,7 @@ var require_socks5_client = __commonJS({
32075
32299
  }
32076
32300
  this.buffer = this.buffer.subarray(2);
32077
32301
  debug("authentication successful");
32078
- this.emit("authenticated");
32302
+ this.markAuthenticated();
32079
32303
  }
32080
32304
  /**
32081
32305
  * Send CONNECT command
@@ -32083,8 +32307,11 @@ var require_socks5_client = __commonJS({
32083
32307
  * @param {number} port - Target port
32084
32308
  */
32085
32309
  connect(address, port) {
32086
- if (this.state === STATES.CONNECTED) {
32087
- throw new InvalidArgumentError("Already connected");
32310
+ if (this.state === STATES.CONNECTING || this.state === STATES.CONNECTED) {
32311
+ throw new InvalidArgumentError("Connection already in progress");
32312
+ }
32313
+ if (this.state !== STATES.AUTHENTICATED) {
32314
+ throw new InvalidArgumentError("Client must be authenticated before CONNECT");
32088
32315
  }
32089
32316
  debug("connecting to", address, port);
32090
32317
  this.state = STATES.CONNECTING;
@@ -32158,8 +32385,9 @@ var require_socks5_client = __commonJS({
32158
32385
  offset += 16;
32159
32386
  }
32160
32387
  const boundPort = this.buffer.readUInt16BE(offset);
32161
- this.buffer = this.buffer.subarray(responseLength);
32388
+ this.buffer = EMPTY_BUFFER;
32162
32389
  this.state = STATES.CONNECTED;
32390
+ this.socket.removeListener("data", this.onSocketData);
32163
32391
  debug("connected, bound address:", boundAddress, "port:", boundPort);
32164
32392
  this.emit("connected", { address: boundAddress, port: boundPort });
32165
32393
  }
@@ -32204,12 +32432,11 @@ var require_socks5_client = __commonJS({
32204
32432
  var require_socks5_proxy_agent = __commonJS({
32205
32433
  "node_modules/undici/lib/dispatcher/socks5-proxy-agent.js"(exports, module) {
32206
32434
  "use strict";
32207
- var net3 = __require("net");
32208
32435
  var { URL: URL6 } = __require("url");
32209
32436
  var tls;
32210
32437
  var DispatcherBase = require_dispatcher_base();
32211
32438
  var { InvalidArgumentError } = require_errors();
32212
- var { Socks5Client } = require_socks5_client();
32439
+ var { Socks5Client, STATES } = require_socks5_client();
32213
32440
  var { kDispatch, kClose, kDestroy } = require_symbols();
32214
32441
  var Pool = require_pool();
32215
32442
  var buildConnector = require_connect();
@@ -32218,8 +32445,10 @@ var require_socks5_proxy_agent = __commonJS({
32218
32445
  var kProxyUrl = /* @__PURE__ */ Symbol("proxy url");
32219
32446
  var kProxyHeaders = /* @__PURE__ */ Symbol("proxy headers");
32220
32447
  var kProxyAuth = /* @__PURE__ */ Symbol("proxy auth");
32221
- var kPool = /* @__PURE__ */ Symbol("pool");
32448
+ var kProxyProtocol = /* @__PURE__ */ Symbol("proxy protocol");
32449
+ var kPools = /* @__PURE__ */ Symbol("pools");
32222
32450
  var kConnector = /* @__PURE__ */ Symbol("connector");
32451
+ var kRequestTls = /* @__PURE__ */ Symbol("request tls settings");
32223
32452
  var experimentalWarningEmitted = false;
32224
32453
  var Socks5ProxyAgent = class extends DispatcherBase {
32225
32454
  constructor(proxyUrl, options = {}) {
@@ -32240,6 +32469,8 @@ var require_socks5_proxy_agent = __commonJS({
32240
32469
  }
32241
32470
  this[kProxyUrl] = url;
32242
32471
  this[kProxyHeaders] = options.headers || {};
32472
+ this[kProxyProtocol] = options.proxyTls ? "https:" : "http:";
32473
+ this[kRequestTls] = options.requestTls;
32243
32474
  this[kProxyAuth] = {
32244
32475
  username: options.username || (url.username ? decodeURIComponent(url.username) : null),
32245
32476
  password: options.password || (url.password ? decodeURIComponent(url.password) : null)
@@ -32248,7 +32479,7 @@ var require_socks5_proxy_agent = __commonJS({
32248
32479
  ...options.proxyTls,
32249
32480
  servername: options.proxyTls?.servername || url.hostname
32250
32481
  });
32251
- this[kPool] = null;
32482
+ this[kPools] = /* @__PURE__ */ new Map();
32252
32483
  }
32253
32484
  /**
32254
32485
  * Create a SOCKS5 connection to the proxy
@@ -32258,20 +32489,18 @@ var require_socks5_proxy_agent = __commonJS({
32258
32489
  const proxyPort = parseInt(this[kProxyUrl].port) || 1080;
32259
32490
  debug("creating SOCKS5 connection to", proxyHost, proxyPort);
32260
32491
  const socket = await new Promise((resolve2, reject) => {
32261
- const onConnect = () => {
32262
- socket2.removeListener("error", onError);
32263
- resolve2(socket2);
32264
- };
32265
- const onError = (err2) => {
32266
- socket2.removeListener("connect", onConnect);
32267
- reject(err2);
32268
- };
32269
- const socket2 = net3.connect({
32492
+ this[kConnector]({
32493
+ hostname: proxyHost,
32270
32494
  host: proxyHost,
32271
- port: proxyPort
32495
+ port: proxyPort,
32496
+ protocol: this[kProxyProtocol]
32497
+ }, (err2, socket2) => {
32498
+ if (err2) {
32499
+ reject(err2);
32500
+ } else {
32501
+ resolve2(socket2);
32502
+ }
32272
32503
  });
32273
- socket2.once("connect", onConnect);
32274
- socket2.once("error", onError);
32275
32504
  });
32276
32505
  const socks5Client = new Socks5Client(socket, this[kProxyAuth]);
32277
32506
  socks5Client.on("error", (err2) => {
@@ -32293,7 +32522,7 @@ var require_socks5_proxy_agent = __commonJS({
32293
32522
  socks5Client.removeListener("authenticated", onAuthenticated);
32294
32523
  reject(err2);
32295
32524
  };
32296
- if (socks5Client.state === "authenticated") {
32525
+ if (socks5Client.state === STATES.AUTHENTICATED) {
32297
32526
  clearTimeout(timeout);
32298
32527
  resolve2();
32299
32528
  } else {
@@ -32325,12 +32554,14 @@ var require_socks5_proxy_agent = __commonJS({
32325
32554
  /**
32326
32555
  * Dispatch a request through the SOCKS5 proxy
32327
32556
  */
32328
- async [kDispatch](opts, handler) {
32557
+ [kDispatch](opts, handler) {
32329
32558
  const { origin } = opts;
32330
32559
  debug("dispatching request to", origin, "via SOCKS5");
32331
32560
  try {
32332
- if (!this[kPool] || this[kPool].destroyed || this[kPool].closed) {
32333
- this[kPool] = new Pool(origin, {
32561
+ const originKey = String(origin);
32562
+ let pool = this[kPools].get(originKey);
32563
+ if (!pool || pool.destroyed || pool.closed) {
32564
+ pool = new Pool(origin, {
32334
32565
  pipelining: opts.pipelining,
32335
32566
  connections: opts.connections,
32336
32567
  connect: async (connectOpts, callback) => {
@@ -32347,9 +32578,9 @@ var require_socks5_proxy_agent = __commonJS({
32347
32578
  }
32348
32579
  debug("upgrading to TLS");
32349
32580
  finalSocket = tls.connect({
32581
+ ...this[kRequestTls],
32350
32582
  socket,
32351
- servername: targetHost,
32352
- ...connectOpts.tls || {}
32583
+ servername: this[kRequestTls]?.servername || targetHost
32353
32584
  });
32354
32585
  await new Promise((resolve2, reject) => {
32355
32586
  finalSocket.once("secureConnect", resolve2);
@@ -32363,26 +32594,37 @@ var require_socks5_proxy_agent = __commonJS({
32363
32594
  }
32364
32595
  }
32365
32596
  });
32597
+ this[kPools].set(originKey, pool);
32366
32598
  }
32367
- return this[kPool][kDispatch](opts, handler);
32599
+ return pool[kDispatch](opts, handler);
32368
32600
  } catch (err2) {
32369
32601
  debug("dispatch error:", err2);
32370
- if (typeof handler.onError === "function") {
32602
+ if (typeof handler.onResponseError === "function") {
32603
+ handler.onResponseError(null, err2);
32604
+ return false;
32605
+ } else if (typeof handler.onError === "function") {
32371
32606
  handler.onError(err2);
32607
+ return false;
32372
32608
  } else {
32373
32609
  throw err2;
32374
32610
  }
32375
32611
  }
32376
32612
  }
32377
32613
  async [kClose]() {
32378
- if (this[kPool]) {
32379
- await this[kPool].close();
32614
+ const closePromises = [];
32615
+ for (const pool of this[kPools].values()) {
32616
+ closePromises.push(pool.close());
32380
32617
  }
32618
+ this[kPools].clear();
32619
+ await Promise.all(closePromises);
32381
32620
  }
32382
32621
  async [kDestroy](err2) {
32383
- if (this[kPool]) {
32384
- await this[kPool].destroy(err2);
32622
+ const destroyPromises = [];
32623
+ for (const pool of this[kPools].values()) {
32624
+ destroyPromises.push(pool.destroy(err2));
32385
32625
  }
32626
+ this[kPools].clear();
32627
+ await Promise.all(destroyPromises);
32386
32628
  }
32387
32629
  };
32388
32630
  module.exports = Socks5ProxyAgent;
@@ -32507,7 +32749,8 @@ var require_proxy_agent = __commonJS({
32507
32749
  factory: agentFactory,
32508
32750
  username: opts.username || username,
32509
32751
  password: opts.password || password,
32510
- proxyTls: opts.proxyTls
32752
+ proxyTls: opts.proxyTls,
32753
+ requestTls: opts.requestTls
32511
32754
  });
32512
32755
  }
32513
32756
  if (!this[kTunnelProxy] && protocol2 === "http:" && this[kProxy].protocol === "http:") {
@@ -32785,6 +33028,23 @@ var require_retry_handler = __commonJS({
32785
33028
  const retryTime = new Date(retryAfter).getTime();
32786
33029
  return isNaN(retryTime) ? 0 : retryTime - Date.now();
32787
33030
  }
33031
+ function validatePartialResponseContentLength(headers, range, statusCode, retryCount) {
33032
+ const contentLength = headers["content-length"];
33033
+ if (contentLength == null) {
33034
+ return;
33035
+ }
33036
+ if (!Number.isFinite(range.start) || !Number.isFinite(range.end)) {
33037
+ return;
33038
+ }
33039
+ const length = Number(contentLength);
33040
+ const expectedLength = range.end - range.start + 1;
33041
+ if (!Number.isFinite(length) || length !== expectedLength) {
33042
+ throw new RequestRetryError("Content-Length mismatch", statusCode, {
33043
+ headers,
33044
+ data: { count: retryCount }
33045
+ });
33046
+ }
33047
+ }
32788
33048
  var RetryHandler = class _RetryHandler {
32789
33049
  constructor(opts, { dispatch, handler }) {
32790
33050
  const { retryOptions, ...dispatchOpts } = opts;
@@ -32843,8 +33103,13 @@ var require_retry_handler = __commonJS({
32843
33103
  onResponseStartWithRetry(controller, statusCode, headers, statusMessage, err2) {
32844
33104
  if (this.retryOpts.throwOnError) {
32845
33105
  if (this.retryOpts.statusCodes.includes(statusCode) === false) {
32846
- this.headersSent = true;
32847
- this.handler.onResponseStart?.(controller, statusCode, headers, statusMessage);
33106
+ if (this.headersSent) {
33107
+ this.handler.onResponseError?.(controller, err2);
33108
+ } else {
33109
+ this.headersSent = true;
33110
+ this.checkpointResponseEnd(headers);
33111
+ this.handler.onResponseStart?.(controller, statusCode, headers, statusMessage);
33112
+ }
32848
33113
  } else {
32849
33114
  this.error = err2;
32850
33115
  }
@@ -32852,13 +33117,19 @@ var require_retry_handler = __commonJS({
32852
33117
  }
32853
33118
  if (isDisturbed(this.opts.body)) {
32854
33119
  this.headersSent = true;
33120
+ this.checkpointResponseEnd(headers);
32855
33121
  this.handler.onResponseStart?.(controller, statusCode, headers, statusMessage);
32856
33122
  return;
32857
33123
  }
32858
33124
  function shouldRetry(passedErr) {
32859
33125
  if (passedErr) {
32860
- this.headersSent = true;
32861
- this.handler.onResponseStart?.(controller, statusCode, headers, statusMessage);
33126
+ if (this.headersSent) {
33127
+ this.handler.onResponseError?.(controller, passedErr);
33128
+ } else {
33129
+ this.headersSent = true;
33130
+ this.checkpointResponseEnd(headers);
33131
+ this.handler.onResponseStart?.(controller, statusCode, headers, statusMessage);
33132
+ }
32862
33133
  controller.resume();
32863
33134
  return;
32864
33135
  }
@@ -32875,6 +33146,17 @@ var require_retry_handler = __commonJS({
32875
33146
  shouldRetry.bind(this)
32876
33147
  );
32877
33148
  }
33149
+ checkpointResponseEnd(headers) {
33150
+ if (this.end == null && this.opts.method !== "HEAD") {
33151
+ const contentLength = headers["content-length"];
33152
+ this.end = contentLength != null ? Number(contentLength) - 1 : null;
33153
+ assert(
33154
+ this.end == null || Number.isFinite(this.end),
33155
+ "invalid content-length"
33156
+ );
33157
+ this.resume = this.end != null;
33158
+ }
33159
+ }
32878
33160
  onRequestStart(controller, context) {
32879
33161
  if (!this.headersSent) {
32880
33162
  this.handler.onRequestStart?.(controller, context);
@@ -32953,9 +33235,14 @@ var require_retry_handler = __commonJS({
32953
33235
  data: { count: this.retryCount }
32954
33236
  });
32955
33237
  }
33238
+ validatePartialResponseContentLength(headers, contentRange, statusCode, this.retryCount);
32956
33239
  const { start, size, end = size ? size - 1 : null } = contentRange;
32957
- assert(this.start === start, "content-range mismatch");
32958
- assert(this.end == null || this.end === end, "content-range mismatch");
33240
+ if (this.start !== start || this.end != null && this.end !== end) {
33241
+ throw new RequestRetryError("Content-Range mismatch", statusCode, {
33242
+ headers,
33243
+ data: { count: this.retryCount }
33244
+ });
33245
+ }
32959
33246
  return;
32960
33247
  }
32961
33248
  if (this.end == null) {
@@ -32971,6 +33258,7 @@ var require_retry_handler = __commonJS({
32971
33258
  );
32972
33259
  return;
32973
33260
  }
33261
+ validatePartialResponseContentLength(headers, range, statusCode, this.retryCount);
32974
33262
  const { start, size, end = size ? size - 1 : null } = range;
32975
33263
  assert(
32976
33264
  start != null && Number.isFinite(start),
@@ -33047,7 +33335,7 @@ var require_retry_handler = __commonJS({
33047
33335
  }
33048
33336
  }
33049
33337
  onResponseError(controller, err2) {
33050
- if (controller?.aborted || isDisturbed(this.opts.body)) {
33338
+ if (controller?.aborted || isDisturbed(this.opts.body) || this.headersSent && !this.resume) {
33051
33339
  this.handler.onResponseError?.(controller, err2);
33052
33340
  return;
33053
33341
  }
@@ -33128,7 +33416,7 @@ var require_h2c_client = __commonJS({
33128
33416
  "h2c-client: Only h2c protocol is supported"
33129
33417
  );
33130
33418
  }
33131
- const { connect, maxConcurrentStreams, pipelining, ...opts } = clientOpts ?? {};
33419
+ const { maxConcurrentStreams, pipelining, ...opts } = clientOpts ?? {};
33132
33420
  let defaultMaxConcurrentStreams = 100;
33133
33421
  let defaultPipelining = 100;
33134
33422
  if (maxConcurrentStreams != null && Number.isInteger(maxConcurrentStreams) && maxConcurrentStreams > 0) {
@@ -33578,7 +33866,7 @@ var require_api_request = __commonJS({
33578
33866
  if (typeof callback !== "function") {
33579
33867
  throw new InvalidArgumentError("invalid callback");
33580
33868
  }
33581
- if (highWaterMark && (typeof highWaterMark !== "number" || highWaterMark < 0)) {
33869
+ if (highWaterMark != null && (!Number.isFinite(highWaterMark) || highWaterMark < 0)) {
33582
33870
  throw new InvalidArgumentError("invalid highWaterMark");
33583
33871
  }
33584
33872
  if (signal && typeof signal.on !== "function" && typeof signal.addEventListener !== "function") {
@@ -35017,13 +35305,13 @@ var require_mock_call_history = __commonJS({
35017
35305
  "use strict";
35018
35306
  var { kMockCallHistoryAddLog } = require_mock_symbols();
35019
35307
  var { InvalidArgumentError } = require_errors();
35020
- function handleFilterCallsWithOptions(criteria, options, handler, store) {
35308
+ function handleFilterCallsWithOptions(criteria, options, handler, store, allLogs) {
35021
35309
  switch (options.operator) {
35022
35310
  case "OR":
35023
- store.push(...handler(criteria));
35311
+ store.push(...handler(criteria, allLogs));
35024
35312
  return store;
35025
35313
  case "AND":
35026
- return handler.call({ logs: store }, criteria);
35314
+ return handler(criteria, store);
35027
35315
  default:
35028
35316
  throw new InvalidArgumentError("options.operator must to be a case insensitive string equal to 'OR' or 'AND'");
35029
35317
  }
@@ -35042,14 +35330,14 @@ var require_mock_call_history = __commonJS({
35042
35330
  return finalOptions;
35043
35331
  }
35044
35332
  function makeFilterCalls(parameterName) {
35045
- return (parameterValue) => {
35333
+ return (parameterValue, logs) => {
35046
35334
  if (typeof parameterValue === "string" || parameterValue == null) {
35047
- return this.logs.filter((log) => {
35335
+ return logs.filter((log) => {
35048
35336
  return log[parameterName] === parameterValue;
35049
35337
  });
35050
35338
  }
35051
35339
  if (parameterValue instanceof RegExp) {
35052
- return this.logs.filter((log) => {
35340
+ return logs.filter((log) => {
35053
35341
  return parameterValue.test(log[parameterName]);
35054
35342
  });
35055
35343
  }
@@ -35154,30 +35442,30 @@ var require_mock_call_history = __commonJS({
35154
35442
  return this.logs;
35155
35443
  }
35156
35444
  const finalOptions = { operator: "OR", ...buildAndValidateFilterCallsOptions(options) };
35157
- let maybeDuplicatedLogsFiltered = [];
35445
+ let maybeDuplicatedLogsFiltered = finalOptions.operator === "AND" ? this.logs : [];
35158
35446
  if ("protocol" in criteria) {
35159
- maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.protocol, finalOptions, this.filterCallsByProtocol, maybeDuplicatedLogsFiltered);
35447
+ maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.protocol, finalOptions, this.filterCallsByProtocol, maybeDuplicatedLogsFiltered, this.logs);
35160
35448
  }
35161
35449
  if ("host" in criteria) {
35162
- maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.host, finalOptions, this.filterCallsByHost, maybeDuplicatedLogsFiltered);
35450
+ maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.host, finalOptions, this.filterCallsByHost, maybeDuplicatedLogsFiltered, this.logs);
35163
35451
  }
35164
35452
  if ("port" in criteria) {
35165
- maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.port, finalOptions, this.filterCallsByPort, maybeDuplicatedLogsFiltered);
35453
+ maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.port, finalOptions, this.filterCallsByPort, maybeDuplicatedLogsFiltered, this.logs);
35166
35454
  }
35167
35455
  if ("origin" in criteria) {
35168
- maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.origin, finalOptions, this.filterCallsByOrigin, maybeDuplicatedLogsFiltered);
35456
+ maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.origin, finalOptions, this.filterCallsByOrigin, maybeDuplicatedLogsFiltered, this.logs);
35169
35457
  }
35170
35458
  if ("path" in criteria) {
35171
- maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.path, finalOptions, this.filterCallsByPath, maybeDuplicatedLogsFiltered);
35459
+ maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.path, finalOptions, this.filterCallsByPath, maybeDuplicatedLogsFiltered, this.logs);
35172
35460
  }
35173
35461
  if ("hash" in criteria) {
35174
- maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.hash, finalOptions, this.filterCallsByHash, maybeDuplicatedLogsFiltered);
35462
+ maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.hash, finalOptions, this.filterCallsByHash, maybeDuplicatedLogsFiltered, this.logs);
35175
35463
  }
35176
35464
  if ("fullUrl" in criteria) {
35177
- maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.fullUrl, finalOptions, this.filterCallsByFullUrl, maybeDuplicatedLogsFiltered);
35465
+ maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.fullUrl, finalOptions, this.filterCallsByFullUrl, maybeDuplicatedLogsFiltered, this.logs);
35178
35466
  }
35179
35467
  if ("method" in criteria) {
35180
- maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.method, finalOptions, this.filterCallsByMethod, maybeDuplicatedLogsFiltered);
35468
+ maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.method, finalOptions, this.filterCallsByMethod, maybeDuplicatedLogsFiltered, this.logs);
35181
35469
  }
35182
35470
  const uniqLogsFiltered = [...new Set(maybeDuplicatedLogsFiltered)];
35183
35471
  return uniqLogsFiltered;
@@ -36250,7 +36538,8 @@ var require_snapshot_agent = __commonJS({
36250
36538
  var require_global2 = __commonJS({
36251
36539
  "node_modules/undici/lib/global.js"(exports, module) {
36252
36540
  "use strict";
36253
- var globalDispatcher = /* @__PURE__ */ Symbol.for("undici.globalDispatcher.1");
36541
+ var globalDispatcher = /* @__PURE__ */ Symbol.for("undici.globalDispatcher.2");
36542
+ var legacyGlobalDispatcher = /* @__PURE__ */ Symbol.for("undici.globalDispatcher.1");
36254
36543
  var { InvalidArgumentError } = require_errors();
36255
36544
  var Agent = require_agent();
36256
36545
  if (getGlobalDispatcher() === void 0) {
@@ -36266,9 +36555,15 @@ var require_global2 = __commonJS({
36266
36555
  enumerable: false,
36267
36556
  configurable: false
36268
36557
  });
36558
+ Object.defineProperty(globalThis, legacyGlobalDispatcher, {
36559
+ value: agent,
36560
+ writable: true,
36561
+ enumerable: false,
36562
+ configurable: false
36563
+ });
36269
36564
  }
36270
36565
  function getGlobalDispatcher() {
36271
- return globalThis[globalDispatcher];
36566
+ return globalThis[legacyGlobalDispatcher];
36272
36567
  }
36273
36568
  var installedExports = (
36274
36569
  /** @type {const} */
@@ -36647,7 +36942,6 @@ var require_dump = __commonJS({
36647
36942
  #maxSize = 1024 * 1024;
36648
36943
  #dumped = false;
36649
36944
  #size = 0;
36650
- #controller = null;
36651
36945
  aborted = false;
36652
36946
  reason = false;
36653
36947
  constructor({ maxSize, signal }, handler) {
@@ -36663,7 +36957,6 @@ var require_dump = __commonJS({
36663
36957
  }
36664
36958
  onRequestStart(controller, context) {
36665
36959
  controller.abort = this.#abort.bind(this);
36666
- this.#controller = controller;
36667
36960
  return super.onRequestStart(controller, context);
36668
36961
  }
36669
36962
  onResponseStart(controller, statusCode, headers, statusMessage) {
@@ -36679,33 +36972,26 @@ var require_dump = __commonJS({
36679
36972
  return super.onResponseStart(controller, statusCode, headers, statusMessage);
36680
36973
  }
36681
36974
  onResponseError(controller, err2) {
36682
- if (this.#dumped) {
36683
- return;
36684
- }
36685
- err2 = this.#controller?.reason ?? err2;
36686
- super.onResponseError(controller, err2);
36975
+ super.onResponseError(controller, this.aborted === true ? this.reason : err2);
36687
36976
  }
36688
36977
  onResponseData(controller, chunk2) {
36689
36978
  this.#size = this.#size + chunk2.length;
36690
- if (this.#size >= this.#maxSize) {
36979
+ if (this.#size > this.#maxSize) {
36980
+ throw new RequestAbortedError(
36981
+ `Response size (${this.#size}) larger than maxSize (${this.#maxSize})`
36982
+ );
36983
+ }
36984
+ if (this.#size === this.#maxSize) {
36691
36985
  this.#dumped = true;
36692
- if (this.aborted === true) {
36693
- super.onResponseError(controller, this.reason);
36694
- } else {
36695
- super.onResponseEnd(controller, {});
36696
- }
36697
36986
  }
36698
36987
  return true;
36699
36988
  }
36700
36989
  onResponseEnd(controller, trailers) {
36701
- if (this.#dumped) {
36702
- return;
36703
- }
36704
- if (this.#controller.aborted === true) {
36990
+ if (this.aborted === true) {
36705
36991
  super.onResponseError(controller, this.reason);
36706
36992
  return;
36707
36993
  }
36708
- super.onResponseEnd(controller, trailers);
36994
+ super.onResponseEnd(controller, this.#dumped ? {} : trailers);
36709
36995
  }
36710
36996
  };
36711
36997
  function createDumpInterceptor({ maxSize: defaultMaxSize } = {
@@ -37169,15 +37455,127 @@ var require_cache = __commonJS({
37169
37455
  var {
37170
37456
  safeHTTPMethods,
37171
37457
  pathHasQueryOrFragment,
37172
- hasSafeIterator
37458
+ hasSafeIterator,
37459
+ isValidHTTPToken
37173
37460
  } = require_util();
37174
37461
  var { serializePathWithQuery } = require_util();
37462
+ var MAX_DELTA_SECONDS = 2147483647;
37463
+ var RESTRICTIVE_DIRECTIVE_NAMES = ["no-store", "private", "no-cache"];
37464
+ var kInvalidCacheControlDirectives = /* @__PURE__ */ Symbol("invalid cache-control directives");
37465
+ function trimOWS(value) {
37466
+ return value.replace(/^[\t ]+|[\t ]+$/g, "");
37467
+ }
37468
+ function arrayIncludes(array, value) {
37469
+ for (let i = 0; i < array.length; i++) {
37470
+ if (array[i] === value) {
37471
+ return true;
37472
+ }
37473
+ }
37474
+ return false;
37475
+ }
37476
+ function trimOWSStart(value) {
37477
+ return value.replace(/^[\t ]+/, "");
37478
+ }
37479
+ function trimOWSEnd(value) {
37480
+ return value.replace(/[\t ]+$/, "");
37481
+ }
37482
+ function findUnescapedQuote(value, start) {
37483
+ let escaped = false;
37484
+ for (let i = start; i < value.length; i++) {
37485
+ if (escaped) {
37486
+ escaped = false;
37487
+ } else if (value[i] === "\\") {
37488
+ escaped = true;
37489
+ } else if (value[i] === '"') {
37490
+ return i;
37491
+ }
37492
+ }
37493
+ return -1;
37494
+ }
37495
+ function splitCacheControlHeaderValue(value) {
37496
+ const directives = [];
37497
+ let start = 0;
37498
+ let quoteStart = -1;
37499
+ let inQuote = false;
37500
+ let escaped = false;
37501
+ for (let i = 0; i < value.length; i++) {
37502
+ if (inQuote) {
37503
+ if (escaped) {
37504
+ escaped = false;
37505
+ } else if (value[i] === "\\") {
37506
+ escaped = true;
37507
+ } else if (value[i] === '"') {
37508
+ inQuote = false;
37509
+ quoteStart = -1;
37510
+ }
37511
+ } else if (value[i] === '"') {
37512
+ inQuote = true;
37513
+ quoteStart = i;
37514
+ } else if (value[i] === ",") {
37515
+ directives.push({ value: value.substring(start, i), fromMalformedQuote: false });
37516
+ start = i + 1;
37517
+ }
37518
+ }
37519
+ if (!inQuote) {
37520
+ directives.push({ value: value.substring(start), fromMalformedQuote: false });
37521
+ return directives;
37522
+ }
37523
+ const tail = value.substring(start);
37524
+ const quoteOffset = quoteStart - start;
37525
+ let tailStart = 0;
37526
+ for (let i = 0; i < tail.length; i++) {
37527
+ if (tail[i] === ",") {
37528
+ directives.push({
37529
+ value: tail.substring(tailStart, i),
37530
+ fromMalformedQuote: tailStart > quoteOffset
37531
+ });
37532
+ tailStart = i + 1;
37533
+ }
37534
+ }
37535
+ directives.push({
37536
+ value: tail.substring(tailStart),
37537
+ fromMalformedQuote: tailStart > quoteOffset
37538
+ });
37539
+ return directives;
37540
+ }
37541
+ function markInvalidCacheControlDirective(directives, key) {
37542
+ let invalidDirectives = directives[kInvalidCacheControlDirectives];
37543
+ if (invalidDirectives === void 0) {
37544
+ invalidDirectives = /* @__PURE__ */ new Set();
37545
+ Object.defineProperty(directives, kInvalidCacheControlDirectives, {
37546
+ value: invalidDirectives
37547
+ });
37548
+ }
37549
+ invalidDirectives.add(key);
37550
+ }
37551
+ function hasInvalidCacheControlDirective(directives, key) {
37552
+ return directives[kInvalidCacheControlDirectives]?.has(key) === true;
37553
+ }
37554
+ function getMalformedRestrictiveDirectiveName(key) {
37555
+ for (const directiveName of RESTRICTIVE_DIRECTIVE_NAMES) {
37556
+ if (key.startsWith(directiveName) && key.length > directiveName.length && !isValidHTTPToken(key[directiveName.length])) {
37557
+ return directiveName;
37558
+ }
37559
+ }
37560
+ let tokenOnlyKey = "";
37561
+ let hasInvalidTokenChar = false;
37562
+ for (let i = 0; i < key.length; i++) {
37563
+ if (isValidHTTPToken(key[i])) {
37564
+ tokenOnlyKey += key[i];
37565
+ } else {
37566
+ hasInvalidTokenChar = true;
37567
+ }
37568
+ }
37569
+ if (hasInvalidTokenChar && arrayIncludes(RESTRICTIVE_DIRECTIVE_NAMES, tokenOnlyKey)) {
37570
+ return tokenOnlyKey;
37571
+ }
37572
+ }
37175
37573
  function makeCacheKey(opts) {
37176
37574
  if (!opts.origin) {
37177
37575
  throw new Error("opts.origin is undefined");
37178
37576
  }
37179
37577
  let fullPath = opts.path || "/";
37180
- if (opts.query && !pathHasQueryOrFragment(opts.path)) {
37578
+ if (opts.query && !pathHasQueryOrFragment(fullPath)) {
37181
37579
  fullPath = serializePathWithQuery(fullPath, opts.query);
37182
37580
  }
37183
37581
  return {
@@ -37187,6 +37585,18 @@ var require_cache = __commonJS({
37187
37585
  headers: opts.headers
37188
37586
  };
37189
37587
  }
37588
+ function appendHeader(headers, key, val) {
37589
+ const headerName = key.toLowerCase();
37590
+ const current = headers[headerName];
37591
+ const values = Array.isArray(val) ? val : [val];
37592
+ if (current === void 0) {
37593
+ headers[headerName] = Array.isArray(val) ? val.slice() : val;
37594
+ } else if (Array.isArray(current)) {
37595
+ current.push(...values);
37596
+ } else {
37597
+ headers[headerName] = [current, ...values];
37598
+ }
37599
+ }
37190
37600
  function normalizeHeaders(opts) {
37191
37601
  let headers;
37192
37602
  if (opts.headers == null) {
@@ -37202,11 +37612,11 @@ var require_cache = __commonJS({
37202
37612
  if (typeof key !== "string" || typeof val !== "string") {
37203
37613
  throw new Error("opts.headers is not a valid header map");
37204
37614
  }
37205
- headers[key.toLowerCase()] = val;
37615
+ appendHeader(headers, key, val);
37206
37616
  }
37207
37617
  } else {
37208
37618
  for (const key of Object.keys(opts.headers)) {
37209
- headers[key.toLowerCase()] = opts.headers[key];
37619
+ appendHeader(headers, key, opts.headers[key]);
37210
37620
  }
37211
37621
  }
37212
37622
  } else {
@@ -37251,25 +37661,32 @@ var require_cache = __commonJS({
37251
37661
  }
37252
37662
  function parseCacheControlHeader(header) {
37253
37663
  const output = {};
37254
- let directives;
37255
- if (Array.isArray(header)) {
37256
- directives = [];
37257
- for (const directive of header) {
37258
- directives.push(...directive.split(","));
37259
- }
37260
- } else {
37261
- directives = header.split(",");
37262
- }
37664
+ const invalidNumericDirectives = /* @__PURE__ */ new Set();
37665
+ const invalidNoArgumentDirectives = /* @__PURE__ */ new Set();
37666
+ const directives = splitCacheControlHeaderValue(Array.isArray(header) ? header.join(",") : header);
37263
37667
  for (let i = 0; i < directives.length; i++) {
37264
- const directive = directives[i].toLowerCase();
37668
+ const directiveRecord = directives[i];
37669
+ const directive = directiveRecord.value.toLowerCase();
37670
+ const fromMalformedQuote = directiveRecord.fromMalformedQuote;
37265
37671
  const keyValueDelimiter = directive.indexOf("=");
37266
37672
  let key;
37267
37673
  let value;
37674
+ let keyHasTrailingWhitespace = false;
37675
+ let valueHasLeadingWhitespace = false;
37268
37676
  if (keyValueDelimiter !== -1) {
37269
- key = directive.substring(0, keyValueDelimiter).trimStart();
37270
- value = directive.substring(keyValueDelimiter + 1);
37677
+ const rawKey = directive.substring(0, keyValueDelimiter);
37678
+ const rawValue = directive.substring(keyValueDelimiter + 1);
37679
+ keyHasTrailingWhitespace = trimOWSEnd(rawKey) !== rawKey;
37680
+ valueHasLeadingWhitespace = trimOWSStart(rawValue) !== rawValue;
37681
+ key = trimOWS(rawKey);
37682
+ value = trimOWSStart(rawValue);
37271
37683
  } else {
37272
- key = directive.trim();
37684
+ key = trimOWS(directive);
37685
+ }
37686
+ const malformedRestrictiveDirectiveName = getMalformedRestrictiveDirectiveName(key);
37687
+ if (malformedRestrictiveDirectiveName !== void 0) {
37688
+ output[malformedRestrictiveDirectiveName] = true;
37689
+ continue;
37273
37690
  }
37274
37691
  switch (key) {
37275
37692
  case "min-fresh":
@@ -37278,45 +37695,85 @@ var require_cache = __commonJS({
37278
37695
  case "s-maxage":
37279
37696
  case "stale-while-revalidate":
37280
37697
  case "stale-if-error": {
37281
- if (value === void 0 || value[0] === " ") {
37698
+ if (fromMalformedQuote || invalidNumericDirectives.has(key)) {
37699
+ continue;
37700
+ }
37701
+ if (value === void 0 || keyHasTrailingWhitespace || valueHasLeadingWhitespace) {
37702
+ delete output[key];
37703
+ invalidNumericDirectives.add(key);
37704
+ markInvalidCacheControlDirective(output, key);
37282
37705
  continue;
37283
37706
  }
37284
37707
  if (value.length >= 2 && value[0] === '"' && value[value.length - 1] === '"') {
37285
37708
  value = value.substring(1, value.length - 1);
37286
37709
  }
37287
- const parsedValue = parseInt(value, 10);
37288
- if (parsedValue !== parsedValue) {
37710
+ if (!/^[0-9]+$/.test(value)) {
37711
+ delete output[key];
37712
+ invalidNumericDirectives.add(key);
37713
+ markInvalidCacheControlDirective(output, key);
37289
37714
  continue;
37290
37715
  }
37291
- if (key === "max-age" && key in output && output[key] >= parsedValue) {
37292
- continue;
37716
+ const parsedValue = Math.min(parseInt(value, 10), MAX_DELTA_SECONDS);
37717
+ if (key === "min-fresh") {
37718
+ if (!(key in output) || output[key] < parsedValue) {
37719
+ output[key] = parsedValue;
37720
+ }
37721
+ } else if (!(key in output) || output[key] > parsedValue) {
37722
+ output[key] = parsedValue;
37293
37723
  }
37294
- output[key] = parsedValue;
37295
37724
  break;
37296
37725
  }
37297
37726
  case "private":
37298
37727
  case "no-cache": {
37728
+ if (fromMalformedQuote) {
37729
+ output[key] = true;
37730
+ break;
37731
+ }
37732
+ if (value !== void 0 && value.length === 0) {
37733
+ output[key] = true;
37734
+ break;
37735
+ }
37299
37736
  if (value) {
37300
37737
  if (value[0] === '"') {
37301
- const headers = [value.substring(1)];
37302
- let foundEndingQuote = value[value.length - 1] === '"';
37303
- if (!foundEndingQuote) {
37738
+ value = trimOWSEnd(value);
37739
+ let fieldList = "";
37740
+ let lastQuotedPart = i;
37741
+ let foundEndingQuote = false;
37742
+ const closingQuote = findUnescapedQuote(value, 1);
37743
+ if (closingQuote !== -1) {
37744
+ fieldList = value.substring(1, closingQuote);
37745
+ foundEndingQuote = true;
37746
+ } else {
37747
+ const fieldListParts = [value.substring(1)];
37304
37748
  for (let j = i + 1; j < directives.length; j++) {
37305
- const nextPart = directives[j];
37306
- const nextPartLength = nextPart.length;
37307
- headers.push(nextPart.trim());
37308
- if (nextPartLength !== 0 && nextPart[nextPartLength - 1] === '"') {
37749
+ const nextPart = trimOWS(directives[j].value);
37750
+ const closingQuote2 = findUnescapedQuote(nextPart, 0);
37751
+ lastQuotedPart = j;
37752
+ if (closingQuote2 !== -1) {
37753
+ fieldListParts.push(nextPart.substring(0, closingQuote2));
37309
37754
  foundEndingQuote = true;
37310
37755
  break;
37311
37756
  }
37757
+ fieldListParts.push(nextPart);
37312
37758
  }
37759
+ fieldList = fieldListParts.join(",");
37313
37760
  }
37314
- if (foundEndingQuote) {
37315
- let lastHeader = headers[headers.length - 1];
37316
- if (lastHeader[lastHeader.length - 1] === '"') {
37317
- lastHeader = lastHeader.substring(0, lastHeader.length - 1);
37318
- headers[headers.length - 1] = lastHeader;
37761
+ if (!foundEndingQuote) {
37762
+ output[key] = true;
37763
+ break;
37764
+ }
37765
+ i = lastQuotedPart;
37766
+ const headers = fieldList.split(",");
37767
+ let validFieldNames = true;
37768
+ for (let j = 0; j < headers.length; j++) {
37769
+ headers[j] = trimOWS(headers[j]);
37770
+ if (!isValidHTTPToken(headers[j])) {
37771
+ validFieldNames = false;
37319
37772
  }
37773
+ }
37774
+ if (!validFieldNames) {
37775
+ output[key] = true;
37776
+ } else if (output[key] !== true) {
37320
37777
  if (key in output) {
37321
37778
  output[key] = output[key].concat(headers);
37322
37779
  } else {
@@ -37324,10 +37781,15 @@ var require_cache = __commonJS({
37324
37781
  }
37325
37782
  }
37326
37783
  } else {
37327
- if (key in output) {
37328
- output[key] = output[key].concat(value);
37329
- } else {
37330
- output[key] = [value];
37784
+ const fieldName = trimOWS(value);
37785
+ if (!isValidHTTPToken(fieldName)) {
37786
+ output[key] = true;
37787
+ } else if (output[key] !== true) {
37788
+ if (key in output) {
37789
+ output[key] = output[key].concat(fieldName);
37790
+ } else {
37791
+ output[key] = [fieldName];
37792
+ }
37331
37793
  }
37332
37794
  }
37333
37795
  break;
@@ -37335,39 +37797,76 @@ var require_cache = __commonJS({
37335
37797
  }
37336
37798
  // eslint-disable-next-line no-fallthrough
37337
37799
  case "public":
37338
- case "no-store":
37339
37800
  case "must-revalidate":
37340
37801
  case "proxy-revalidate":
37341
37802
  case "immutable":
37342
37803
  case "no-transform":
37343
37804
  case "must-understand":
37344
37805
  case "only-if-cached":
37345
- if (value) {
37806
+ if (fromMalformedQuote || invalidNoArgumentDirectives.has(key)) {
37807
+ continue;
37808
+ }
37809
+ if (value !== void 0) {
37810
+ delete output[key];
37811
+ invalidNoArgumentDirectives.add(key);
37346
37812
  continue;
37347
37813
  }
37348
37814
  output[key] = true;
37349
37815
  break;
37816
+ case "no-store":
37817
+ output[key] = true;
37818
+ break;
37350
37819
  default:
37351
37820
  continue;
37352
37821
  }
37353
37822
  }
37354
37823
  return output;
37355
37824
  }
37825
+ function splitVaryHeader(varyHeader) {
37826
+ const values = Array.isArray(varyHeader) ? varyHeader : [varyHeader];
37827
+ const output = [];
37828
+ for (let i = 0; i < values.length; i++) {
37829
+ const parts = values[i].split(",");
37830
+ for (let j = 0; j < parts.length; j++) {
37831
+ output.push(parts[j]);
37832
+ }
37833
+ }
37834
+ return output;
37835
+ }
37836
+ function hasVaryStar(varyHeader) {
37837
+ const values = splitVaryHeader(varyHeader);
37838
+ for (let i = 0; i < values.length; i++) {
37839
+ if (trimOWS(values[i]).indexOf("*") !== -1) {
37840
+ return true;
37841
+ }
37842
+ }
37843
+ return false;
37844
+ }
37356
37845
  function parseVaryHeader(varyHeader, headers) {
37357
- if (typeof varyHeader === "string" && varyHeader.includes("*")) {
37846
+ if (hasVaryStar(varyHeader)) {
37358
37847
  return headers;
37359
37848
  }
37360
37849
  const output = (
37361
37850
  /** @type {Record<string, string | string[] | null>} */
37362
37851
  {}
37363
37852
  );
37364
- const varyingHeaders = typeof varyHeader === "string" ? varyHeader.split(",") : varyHeader;
37853
+ const varyingHeaders = splitVaryHeader(varyHeader);
37365
37854
  for (const header of varyingHeaders) {
37366
- const trimmedHeader = header.trim().toLowerCase();
37367
- output[trimmedHeader] = headers[trimmedHeader] ?? null;
37855
+ const trimmedHeader = trimOWS(header).toLowerCase();
37856
+ if (trimmedHeader.length === 0) {
37857
+ continue;
37858
+ }
37859
+ if (!isValidHTTPToken(trimmedHeader)) {
37860
+ return void 0;
37861
+ }
37862
+ const headerValue = headers[trimmedHeader];
37863
+ output[trimmedHeader] = Array.isArray(headerValue) ? headerValue.slice() : headerValue ?? null;
37368
37864
  }
37369
37865
  return output;
37370
37866
  }
37867
+ function isInvalidOrWildcardVaryHeader(varyHeader) {
37868
+ return hasVaryStar(varyHeader) || parseVaryHeader(varyHeader, {}) === void 0;
37869
+ }
37371
37870
  function isEtagUsable(etag) {
37372
37871
  if (etag.length <= 2) {
37373
37872
  return false;
@@ -37398,24 +37897,23 @@ var require_cache = __commonJS({
37398
37897
  throw new TypeError(`${name} needs to have at least one method`);
37399
37898
  }
37400
37899
  for (const method of methods) {
37401
- if (!safeHTTPMethods.includes(method)) {
37900
+ if (!arrayIncludes(safeHTTPMethods, method)) {
37402
37901
  throw new TypeError(`element of ${name}-array needs to be one of following values: ${safeHTTPMethods.join(", ")}, got ${method}`);
37403
37902
  }
37404
37903
  }
37405
37904
  }
37406
37905
  function makeDeduplicationKey(cacheKey, excludeHeaders) {
37407
- let key = `${cacheKey.origin}:${cacheKey.method}:${cacheKey.path}`;
37906
+ const headers = {};
37408
37907
  if (cacheKey.headers) {
37409
37908
  const sortedHeaders = Object.keys(cacheKey.headers).sort();
37410
37909
  for (const header of sortedHeaders) {
37411
37910
  if (excludeHeaders?.has(header.toLowerCase())) {
37412
37911
  continue;
37413
37912
  }
37414
- const value = cacheKey.headers[header];
37415
- key += `:${header}=${Array.isArray(value) ? value.join(",") : value}`;
37913
+ headers[header] = cacheKey.headers[header];
37416
37914
  }
37417
37915
  }
37418
- return key;
37916
+ return JSON.stringify([cacheKey.origin, cacheKey.method, cacheKey.path, headers]);
37419
37917
  }
37420
37918
  module.exports = {
37421
37919
  makeCacheKey,
@@ -37423,7 +37921,10 @@ var require_cache = __commonJS({
37423
37921
  assertCacheKey,
37424
37922
  assertCacheValue,
37425
37923
  parseCacheControlHeader,
37924
+ hasInvalidCacheControlDirective,
37426
37925
  parseVaryHeader,
37926
+ hasVaryStar,
37927
+ isInvalidOrWildcardVaryHeader,
37427
37928
  isEtagUsable,
37428
37929
  assertCacheMethods,
37429
37930
  assertCacheStore,
@@ -37446,6 +37947,13 @@ var require_date = __commonJS({
37446
37947
  return parseRfc850Date(date);
37447
37948
  }
37448
37949
  }
37950
+ function makeDate(year, monthIdx, day, hour, minute, second, weekday) {
37951
+ const result = new Date(Date.UTC(year, monthIdx, day, hour, minute, second));
37952
+ if (year >= 0 && year <= 99) {
37953
+ result.setUTCFullYear(year);
37954
+ }
37955
+ return result.getUTCFullYear() === year && result.getUTCMonth() === monthIdx && result.getUTCDate() === day && result.getUTCHours() === hour && result.getUTCMinutes() === minute && result.getUTCSeconds() === second && result.getUTCDay() === weekday ? result : void 0;
37956
+ }
37449
37957
  function parseImfDate(date) {
37450
37958
  if (date.length !== 29 || date[4] !== " " || date[7] !== " " || date[11] !== " " || date[16] !== " " || date[19] !== ":" || date[22] !== ":" || date[25] !== " " || date[26] !== "G" || date[27] !== "M" || date[28] !== "T") {
37451
37959
  return void 0;
@@ -37606,8 +38114,7 @@ var require_date = __commonJS({
37606
38114
  }
37607
38115
  second = (code1 - 48) * 10 + (code2 - 48);
37608
38116
  }
37609
- const result = new Date(Date.UTC(year, monthIdx, day, hour, minute, second));
37610
- return result.getUTCDay() === weekday ? result : void 0;
38117
+ return makeDate(year, monthIdx, day, hour, minute, second, weekday);
37611
38118
  }
37612
38119
  function parseAscTimeDate(date) {
37613
38120
  if (date.length !== 24 || date[7] !== " " || date[10] !== " " || date[19] !== " ") {
@@ -37769,8 +38276,7 @@ var require_date = __commonJS({
37769
38276
  return void 0;
37770
38277
  }
37771
38278
  const year = (yearDigit1 - 48) * 1e3 + (yearDigit2 - 48) * 100 + (yearDigit3 - 48) * 10 + (yearDigit4 - 48);
37772
- const result = new Date(Date.UTC(year, monthIdx, day, hour, minute, second));
37773
- return result.getUTCDay() === weekday ? result : void 0;
38279
+ return makeDate(year, monthIdx, day, hour, minute, second, weekday);
37774
38280
  }
37775
38281
  function parseRfc850Date(date) {
37776
38282
  let commaIndex = -1;
@@ -37919,8 +38425,7 @@ var require_date = __commonJS({
37919
38425
  }
37920
38426
  second = (code1 - 48) * 10 + (code2 - 48);
37921
38427
  }
37922
- const result = new Date(Date.UTC(year, monthIdx, day, hour, minute, second));
37923
- return result.getUTCDay() === weekday ? result : void 0;
38428
+ return makeDate(year, monthIdx, day, hour, minute, second, weekday);
37924
38429
  }
37925
38430
  module.exports = {
37926
38431
  parseHttpDate
@@ -37935,7 +38440,10 @@ var require_cache_handler = __commonJS({
37935
38440
  var util = require_util();
37936
38441
  var {
37937
38442
  parseCacheControlHeader,
38443
+ hasInvalidCacheControlDirective,
37938
38444
  parseVaryHeader,
38445
+ hasVaryStar,
38446
+ isInvalidOrWildcardVaryHeader,
37939
38447
  isEtagUsable
37940
38448
  } = require_cache();
37941
38449
  var { parseHttpDate } = require_date();
@@ -37959,6 +38467,78 @@ var require_cache_handler = __commonJS({
37959
38467
  206
37960
38468
  ];
37961
38469
  var MAX_RESPONSE_AGE = 2147483647e3;
38470
+ function trimOWS(value) {
38471
+ return value.replace(/^[\t ]+|[\t ]+$/g, "");
38472
+ }
38473
+ function arrayIncludes(array, value) {
38474
+ for (let i = 0; i < array.length; i++) {
38475
+ if (array[i] === value) {
38476
+ return true;
38477
+ }
38478
+ }
38479
+ return false;
38480
+ }
38481
+ function appendConnectionHeaderTokens(headersToRemove, connectionHeader) {
38482
+ const values = Array.isArray(connectionHeader) ? connectionHeader : [connectionHeader];
38483
+ for (let i = 0; i < values.length; i++) {
38484
+ const tokens = values[i].split(",");
38485
+ for (let j = 0; j < tokens.length; j++) {
38486
+ headersToRemove.push(trimOWS(tokens[j]).toLowerCase());
38487
+ }
38488
+ }
38489
+ }
38490
+ function getSameOriginPath(cacheKey, location) {
38491
+ if (typeof location !== "string") {
38492
+ return void 0;
38493
+ }
38494
+ let originUrl;
38495
+ let requestUrl;
38496
+ let locationUrl;
38497
+ try {
38498
+ originUrl = new URL(cacheKey.origin);
38499
+ requestUrl = new URL(cacheKey.path, originUrl);
38500
+ locationUrl = new URL(location, requestUrl);
38501
+ } catch {
38502
+ return void 0;
38503
+ }
38504
+ if (locationUrl.origin !== originUrl.origin) {
38505
+ return void 0;
38506
+ }
38507
+ return locationUrl.pathname + locationUrl.search;
38508
+ }
38509
+ function deleteCachedUri(store, cacheKey, path74) {
38510
+ deleteCachedValue(store, {
38511
+ ...cacheKey,
38512
+ path: path74
38513
+ });
38514
+ for (let i = 0; i < util.safeHTTPMethods.length; i++) {
38515
+ const method = util.safeHTTPMethods[i];
38516
+ if (method !== cacheKey.method) {
38517
+ deleteCachedValue(store, {
38518
+ ...cacheKey,
38519
+ method,
38520
+ path: path74
38521
+ });
38522
+ }
38523
+ }
38524
+ }
38525
+ function deleteLocationTargets(store, cacheKey, headerValue) {
38526
+ if (headerValue === void 0) {
38527
+ return;
38528
+ }
38529
+ const values = Array.isArray(headerValue) ? headerValue : [headerValue];
38530
+ for (let i = 0; i < values.length; i++) {
38531
+ const path74 = getSameOriginPath(cacheKey, values[i]);
38532
+ if (path74 !== void 0) {
38533
+ deleteCachedUri(store, cacheKey, path74);
38534
+ }
38535
+ }
38536
+ }
38537
+ function invalidateUnsafeRequest(store, cacheKey, resHeaders) {
38538
+ deleteCachedUri(store, cacheKey, cacheKey.path);
38539
+ deleteLocationTargets(store, cacheKey, resHeaders.location);
38540
+ deleteLocationTargets(store, cacheKey, resHeaders["content-location"]);
38541
+ }
37962
38542
  var CacheHandler = class {
37963
38543
  /**
37964
38544
  * @type {import('../../types/cache-interceptor.d.ts').default.CacheKey}
@@ -38018,35 +38598,53 @@ var require_cache_handler = __commonJS({
38018
38598
  statusMessage
38019
38599
  );
38020
38600
  const handler = this;
38021
- if (!util.safeHTTPMethods.includes(this.#cacheKey.method) && statusCode >= 200 && statusCode <= 399) {
38022
- try {
38023
- this.#store.delete(this.#cacheKey)?.catch?.(noop);
38024
- } catch {
38025
- }
38601
+ if (!arrayIncludes(util.safeHTTPMethods, this.#cacheKey.method) && statusCode >= 200 && statusCode <= 399) {
38602
+ invalidateUnsafeRequest(this.#store, this.#cacheKey, resHeaders);
38026
38603
  return downstreamOnHeaders();
38027
38604
  }
38028
38605
  const cacheControlHeader = resHeaders["cache-control"];
38029
- const heuristicallyCacheable = resHeaders["last-modified"] && HEURISTICALLY_CACHEABLE_STATUS_CODES.includes(statusCode);
38606
+ const cacheControlDirectives = cacheControlHeader ? parseCacheControlHeader(cacheControlHeader) : {};
38607
+ if (revalidationResponseDisallowsCachedReuse(this.#cacheType, resHeaders, cacheControlDirectives)) {
38608
+ deleteCachedValue(this.#store, this.#cacheKey);
38609
+ return downstreamOnHeaders();
38610
+ }
38611
+ const heuristicallyCacheable = resHeaders["last-modified"] && arrayIncludes(HEURISTICALLY_CACHEABLE_STATUS_CODES, statusCode);
38030
38612
  if (!cacheControlHeader && !resHeaders["expires"] && !heuristicallyCacheable && !this.#cacheByDefault) {
38613
+ if (statusCode === 304 && resHeaders.vary && isInvalidOrWildcardVaryHeader(resHeaders.vary)) {
38614
+ deleteCachedValue(this.#store, this.#cacheKey);
38615
+ }
38031
38616
  return downstreamOnHeaders();
38032
38617
  }
38033
- const cacheControlDirectives = cacheControlHeader ? parseCacheControlHeader(cacheControlHeader) : {};
38034
- if (!canCacheResponse(this.#cacheType, statusCode, resHeaders, cacheControlDirectives, this.#cacheKey.headers)) {
38618
+ if (!canCacheResponse(this.#cacheType, this.#cacheKey.method, statusCode, resHeaders, cacheControlDirectives, this.#cacheKey.headers)) {
38619
+ if (statusCode === 304 && (cacheControlHeader || revalidationResponseDisallowsCachedReuse(this.#cacheType, resHeaders, cacheControlDirectives))) {
38620
+ deleteCachedValue(this.#store, this.#cacheKey);
38621
+ }
38035
38622
  return downstreamOnHeaders();
38036
38623
  }
38037
38624
  const now = Date.now();
38038
- const resAge = resHeaders.age ? getAge(resHeaders.age) : void 0;
38039
- if (resAge && resAge >= MAX_RESPONSE_AGE) {
38625
+ const resAge = Object.hasOwn(resHeaders, "age") ? getAge(resHeaders.age) : void 0;
38626
+ if (resAge !== void 0 && resAge >= MAX_RESPONSE_AGE) {
38627
+ deleteCachedValueIfNotModified(statusCode, this.#store, this.#cacheKey);
38040
38628
  return downstreamOnHeaders();
38041
38629
  }
38042
- const resDate = typeof resHeaders.date === "string" ? parseHttpDate(resHeaders.date) : void 0;
38630
+ const resDate = Object.hasOwn(resHeaders, "date") ? getDate(resHeaders.date) : void 0;
38631
+ if (resDate === null) {
38632
+ deleteCachedValueIfNotModified(statusCode, this.#store, this.#cacheKey);
38633
+ return downstreamOnHeaders();
38634
+ }
38635
+ const apparentAge = resDate ? Math.max(0, now - resDate.getTime()) : 0;
38636
+ const currentAge = Math.max(apparentAge, resAge ?? 0);
38043
38637
  const staleAt = determineStaleAt(this.#cacheType, now, resAge, resHeaders, resDate, cacheControlDirectives) ?? this.#cacheByDefault;
38044
- if (staleAt === void 0 || resAge && resAge > staleAt) {
38638
+ if (staleAt === void 0 || currentAge >= staleAt) {
38639
+ if (cacheControlHeader || staleAt !== void 0) {
38640
+ deleteCachedValueIfNotModified(statusCode, this.#store, this.#cacheKey);
38641
+ }
38045
38642
  return downstreamOnHeaders();
38046
38643
  }
38047
- const baseTime = resDate ? resDate.getTime() : now;
38644
+ const baseTime = now - currentAge;
38048
38645
  const absoluteStaleAt = staleAt + baseTime;
38049
38646
  if (now >= absoluteStaleAt) {
38647
+ deleteCachedValueIfNotModified(statusCode, this.#store, this.#cacheKey);
38050
38648
  return downstreamOnHeaders();
38051
38649
  }
38052
38650
  let varyDirectives;
@@ -38056,7 +38654,8 @@ var require_cache_handler = __commonJS({
38056
38654
  return downstreamOnHeaders();
38057
38655
  }
38058
38656
  }
38059
- const deleteAt = determineDeleteAt(baseTime, cacheControlDirectives, absoluteStaleAt);
38657
+ const cachedAt = baseTime;
38658
+ const deleteAt = determineDeleteAt(baseTime, now, cacheControlDirectives, absoluteStaleAt);
38060
38659
  const strippedHeaders = stripNecessaryHeaders(resHeaders, cacheControlDirectives);
38061
38660
  const value = {
38062
38661
  statusCode,
@@ -38064,7 +38663,7 @@ var require_cache_handler = __commonJS({
38064
38663
  headers: strippedHeaders,
38065
38664
  vary: varyDirectives,
38066
38665
  cacheControlDirectives,
38067
- cachedAt: resAge ? now - resAge : now,
38666
+ cachedAt,
38068
38667
  staleAt: absoluteStaleAt,
38069
38668
  deleteAt
38070
38669
  };
@@ -38076,6 +38675,7 @@ var require_cache_handler = __commonJS({
38076
38675
  value.statusCode = cachedValue.statusCode;
38077
38676
  value.statusMessage = cachedValue.statusMessage;
38078
38677
  value.etag = cachedValue.etag;
38678
+ value.vary = varyDirectives ?? cachedValue.vary;
38079
38679
  value.headers = { ...cachedValue.headers, ...strippedHeaders };
38080
38680
  downstreamOnHeaders();
38081
38681
  this.#writeStream = this.#store.createWriteStream(this.#cacheKey, value);
@@ -38166,74 +38766,129 @@ var require_cache_handler = __commonJS({
38166
38766
  this.#handler.onResponseError?.(controller, err2);
38167
38767
  }
38168
38768
  };
38169
- function canCacheResponse(cacheType, statusCode, resHeaders, cacheControlDirectives, reqHeaders) {
38170
- if (statusCode < 200 || NOT_UNDERSTOOD_STATUS_CODES.includes(statusCode)) {
38769
+ function deleteCachedValue(store, cacheKey) {
38770
+ try {
38771
+ store.delete(cacheKey)?.catch?.(noop);
38772
+ } catch {
38773
+ }
38774
+ }
38775
+ function deleteCachedValueIfNotModified(statusCode, store, cacheKey) {
38776
+ if (statusCode === 304) {
38777
+ deleteCachedValue(store, cacheKey);
38778
+ }
38779
+ }
38780
+ function revalidationResponseDisallowsCachedReuse(cacheType, resHeaders, cacheControlDirectives) {
38781
+ return cacheControlDirectives["no-store"] === true || cacheType === "shared" && (cacheControlDirectives.private === true || Object.hasOwn(resHeaders, "set-cookie")) || (resHeaders.vary ? isInvalidOrWildcardVaryHeader(resHeaders.vary) : false);
38782
+ }
38783
+ function canCacheResponse(cacheType, method, statusCode, resHeaders, cacheControlDirectives, reqHeaders) {
38784
+ if (!arrayIncludes(util.safeHTTPMethods, method)) {
38171
38785
  return false;
38172
38786
  }
38173
- if (!HEURISTICALLY_CACHEABLE_STATUS_CODES.includes(statusCode) && !resHeaders["expires"] && !cacheControlDirectives.public && cacheControlDirectives["max-age"] === void 0 && // RFC 9111: a private response directive, if the cache is not shared
38787
+ if (statusCode < 200 || arrayIncludes(NOT_UNDERSTOOD_STATUS_CODES, statusCode)) {
38788
+ return false;
38789
+ }
38790
+ if (!arrayIncludes(HEURISTICALLY_CACHEABLE_STATUS_CODES, statusCode) && !resHeaders["expires"] && !cacheControlDirectives.public && cacheControlDirectives["max-age"] === void 0 && // RFC 9111: a private response directive, if the cache is not shared
38174
38791
  !(cacheControlDirectives.private && cacheType === "private") && !(cacheControlDirectives["s-maxage"] !== void 0 && cacheType === "shared")) {
38175
38792
  return false;
38176
38793
  }
38177
38794
  if (cacheControlDirectives["no-store"]) {
38178
38795
  return false;
38179
38796
  }
38180
- if (cacheType === "shared" && cacheControlDirectives.private === true) {
38797
+ if (cacheType === "shared" && (cacheControlDirectives.private === true || Object.hasOwn(resHeaders, "set-cookie"))) {
38181
38798
  return false;
38182
38799
  }
38183
- if (resHeaders.vary?.includes("*")) {
38800
+ if (resHeaders.vary && hasVaryStar(resHeaders.vary)) {
38184
38801
  return false;
38185
38802
  }
38186
- if (reqHeaders?.authorization) {
38803
+ if (reqHeaders != null && Object.hasOwn(reqHeaders, "authorization")) {
38187
38804
  if (!cacheControlDirectives.public && !cacheControlDirectives["s-maxage"] && !cacheControlDirectives["must-revalidate"]) {
38188
38805
  return false;
38189
38806
  }
38190
38807
  if (typeof reqHeaders.authorization !== "string") {
38191
38808
  return false;
38192
38809
  }
38193
- if (Array.isArray(cacheControlDirectives["no-cache"]) && cacheControlDirectives["no-cache"].includes("authorization")) {
38810
+ if (Array.isArray(cacheControlDirectives["no-cache"]) && arrayIncludes(cacheControlDirectives["no-cache"], "authorization")) {
38194
38811
  return false;
38195
38812
  }
38196
- if (Array.isArray(cacheControlDirectives["private"]) && cacheControlDirectives["private"].includes("authorization")) {
38813
+ if (Array.isArray(cacheControlDirectives["private"]) && arrayIncludes(cacheControlDirectives["private"], "authorization")) {
38197
38814
  return false;
38198
38815
  }
38199
38816
  }
38200
38817
  return true;
38201
38818
  }
38819
+ function getDate(dateHeader) {
38820
+ let dateValue = dateHeader;
38821
+ if (Array.isArray(dateValue)) {
38822
+ if (dateValue.length !== 1) {
38823
+ return null;
38824
+ }
38825
+ dateValue = dateValue[0];
38826
+ }
38827
+ if (typeof dateValue !== "string") {
38828
+ return null;
38829
+ }
38830
+ return parseHttpDate(dateValue);
38831
+ }
38202
38832
  function getAge(ageHeader) {
38203
- const age = parseInt(Array.isArray(ageHeader) ? ageHeader[0] : ageHeader);
38204
- return isNaN(age) ? void 0 : age * 1e3;
38833
+ let ageValue = ageHeader;
38834
+ if (Array.isArray(ageValue)) {
38835
+ if (ageValue.length !== 1) {
38836
+ return MAX_RESPONSE_AGE;
38837
+ }
38838
+ ageValue = ageValue[0];
38839
+ }
38840
+ if (typeof ageValue !== "string" || !/^[\t ]*[0-9]+[\t ]*$/.test(ageValue)) {
38841
+ return MAX_RESPONSE_AGE;
38842
+ }
38843
+ const age = BigInt(ageValue.replace(/^[\t ]+|[\t ]+$/g, ""));
38844
+ if (age >= BigInt(MAX_RESPONSE_AGE / 1e3)) {
38845
+ return MAX_RESPONSE_AGE;
38846
+ }
38847
+ return Number(age) * 1e3;
38205
38848
  }
38206
38849
  function determineStaleAt(cacheType, now, age, resHeaders, responseDate, cacheControlDirectives) {
38207
38850
  if (cacheType === "shared") {
38851
+ if (hasInvalidCacheControlDirective(cacheControlDirectives, "s-maxage")) {
38852
+ return 0;
38853
+ }
38208
38854
  const sMaxAge = cacheControlDirectives["s-maxage"];
38209
38855
  if (sMaxAge !== void 0) {
38210
- return sMaxAge > 0 ? sMaxAge * 1e3 : void 0;
38856
+ return sMaxAge * 1e3;
38211
38857
  }
38212
38858
  }
38859
+ if (hasInvalidCacheControlDirective(cacheControlDirectives, "max-age")) {
38860
+ return 0;
38861
+ }
38213
38862
  const maxAge = cacheControlDirectives["max-age"];
38214
38863
  if (maxAge !== void 0) {
38215
- return maxAge > 0 ? maxAge * 1e3 : void 0;
38864
+ return maxAge * 1e3;
38216
38865
  }
38217
- if (typeof resHeaders.expires === "string") {
38866
+ if (Object.hasOwn(resHeaders, "expires")) {
38867
+ if (typeof resHeaders.expires !== "string") {
38868
+ return 0;
38869
+ }
38218
38870
  const expiresDate = parseHttpDate(resHeaders.expires);
38219
- if (expiresDate) {
38220
- if (now >= expiresDate.getTime()) {
38221
- return void 0;
38871
+ if (!expiresDate) {
38872
+ return 0;
38873
+ }
38874
+ if (now >= expiresDate.getTime()) {
38875
+ return 0;
38876
+ }
38877
+ if (responseDate) {
38878
+ if (responseDate >= expiresDate) {
38879
+ return 0;
38222
38880
  }
38223
- if (responseDate) {
38224
- if (responseDate >= expiresDate) {
38225
- return void 0;
38226
- }
38227
- if (age !== void 0 && age > expiresDate - responseDate) {
38228
- return void 0;
38229
- }
38881
+ const freshnessLifetime = expiresDate.getTime() - responseDate.getTime();
38882
+ if (age !== void 0 && age >= freshnessLifetime) {
38883
+ return 0;
38230
38884
  }
38231
- return expiresDate.getTime() - now;
38885
+ return freshnessLifetime;
38232
38886
  }
38887
+ return expiresDate.getTime() - now;
38233
38888
  }
38234
38889
  if (typeof resHeaders["last-modified"] === "string") {
38235
- const lastModified = new Date(resHeaders["last-modified"]);
38236
- if (isValidDate(lastModified)) {
38890
+ const lastModified = parseHttpDate(resHeaders["last-modified"]);
38891
+ if (lastModified) {
38237
38892
  if (lastModified.getTime() >= now) {
38238
38893
  return void 0;
38239
38894
  }
@@ -38242,11 +38897,11 @@ var require_cache_handler = __commonJS({
38242
38897
  }
38243
38898
  }
38244
38899
  if (cacheControlDirectives.immutable) {
38245
- return 31536e3;
38900
+ return 31536e6;
38246
38901
  }
38247
38902
  return void 0;
38248
38903
  }
38249
- function determineDeleteAt(now, cacheControlDirectives, staleAt) {
38904
+ function determineDeleteAt(baseTime, cachedAt, cacheControlDirectives, staleAt) {
38250
38905
  let staleWhileRevalidate = -Infinity;
38251
38906
  let staleIfError = -Infinity;
38252
38907
  let immutable = -Infinity;
@@ -38257,11 +38912,12 @@ var require_cache_handler = __commonJS({
38257
38912
  staleIfError = staleAt + cacheControlDirectives["stale-if-error"] * 1e3;
38258
38913
  }
38259
38914
  if (cacheControlDirectives.immutable && staleWhileRevalidate === -Infinity && staleIfError === -Infinity) {
38260
- immutable = now + 31536e6;
38915
+ immutable = cachedAt + 31536e6;
38261
38916
  }
38262
38917
  if (staleWhileRevalidate === -Infinity && staleIfError === -Infinity && immutable === -Infinity) {
38263
- const freshnessLifetime = staleAt - now;
38264
- return staleAt + freshnessLifetime;
38918
+ const freshnessLifetime = staleAt - baseTime;
38919
+ const datePrecisionPadding = Math.min(Math.max(cachedAt - baseTime, 0), 1e3);
38920
+ return staleAt + freshnessLifetime + datePrecisionPadding;
38265
38921
  }
38266
38922
  return Math.max(staleAt, staleWhileRevalidate, staleIfError, immutable);
38267
38923
  }
@@ -38279,11 +38935,7 @@ var require_cache_handler = __commonJS({
38279
38935
  "age"
38280
38936
  ];
38281
38937
  if (resHeaders["connection"]) {
38282
- if (Array.isArray(resHeaders["connection"])) {
38283
- headersToRemove.push(...resHeaders["connection"].map((header) => header.trim()));
38284
- } else {
38285
- headersToRemove.push(...resHeaders["connection"].split(",").map((header) => header.trim()));
38286
- }
38938
+ appendConnectionHeaderTokens(headersToRemove, resHeaders["connection"]);
38287
38939
  }
38288
38940
  if (Array.isArray(cacheControlDirectives["no-cache"])) {
38289
38941
  headersToRemove.push(...cacheControlDirectives["no-cache"]);
@@ -38293,16 +38945,13 @@ var require_cache_handler = __commonJS({
38293
38945
  }
38294
38946
  let strippedHeaders;
38295
38947
  for (const headerName of headersToRemove) {
38296
- if (resHeaders[headerName]) {
38948
+ if (Object.hasOwn(resHeaders, headerName)) {
38297
38949
  strippedHeaders ??= { ...resHeaders };
38298
38950
  delete strippedHeaders[headerName];
38299
38951
  }
38300
38952
  }
38301
38953
  return strippedHeaders ?? resHeaders;
38302
38954
  }
38303
- function isValidDate(date) {
38304
- return date instanceof Date && Number.isFinite(date.valueOf());
38305
- }
38306
38955
  module.exports = CacheHandler;
38307
38956
  }
38308
38957
  });
@@ -38473,12 +39122,43 @@ var require_memory_cache_store = __commonJS({
38473
39122
  }
38474
39123
  };
38475
39124
  function findEntry(key, entries, now) {
38476
- return entries.find((entry) => entry.deleteAt > now && entry.method === key.method && (entry.vary == null || Object.keys(entry.vary).every((headerName) => {
38477
- if (entry.vary[headerName] === null) {
38478
- return key.headers[headerName] === void 0;
39125
+ for (let i = 0; i < entries.length; i++) {
39126
+ const entry = entries[i];
39127
+ if (entry.deleteAt > now && entry.method === key.method && varyMatches(key, entry)) {
39128
+ return entry;
39129
+ }
39130
+ }
39131
+ }
39132
+ function varyMatches(key, entry) {
39133
+ if (entry.vary == null) {
39134
+ return true;
39135
+ }
39136
+ for (const headerName in entry.vary) {
39137
+ if (Object.hasOwn(entry.vary, headerName) && !headerValueEquals(key.headers?.[headerName], entry.vary[headerName])) {
39138
+ return false;
39139
+ }
39140
+ }
39141
+ return true;
39142
+ }
39143
+ function headerValueEquals(lhs, rhs) {
39144
+ if (lhs == null && rhs == null) {
39145
+ return true;
39146
+ }
39147
+ if (lhs == null && rhs != null || lhs != null && rhs == null) {
39148
+ return false;
39149
+ }
39150
+ if (Array.isArray(lhs) && Array.isArray(rhs)) {
39151
+ if (lhs.length !== rhs.length) {
39152
+ return false;
38479
39153
  }
38480
- return entry.vary[headerName] === key.headers[headerName];
38481
- })));
39154
+ for (let i = 0; i < lhs.length; i++) {
39155
+ if (lhs[i] !== rhs[i]) {
39156
+ return false;
39157
+ }
39158
+ }
39159
+ return true;
39160
+ }
39161
+ return lhs === rhs;
38482
39162
  }
38483
39163
  module.exports = MemoryCacheStore;
38484
39164
  }
@@ -38492,7 +39172,7 @@ var require_cache_revalidation_handler = __commonJS({
38492
39172
  var CacheRevalidationHandler = class {
38493
39173
  #successful = false;
38494
39174
  /**
38495
- * @type {((boolean, any) => void) | null}
39175
+ * @type {((success: boolean, context?: any, statusCode?: number, headers?: import('../../types/header.d.ts').IncomingHttpHeaders) => void) | null}
38496
39176
  */
38497
39177
  #callback;
38498
39178
  /**
@@ -38505,7 +39185,7 @@ var require_cache_revalidation_handler = __commonJS({
38505
39185
  */
38506
39186
  #allowErrorStatusCodes;
38507
39187
  /**
38508
- * @param {(boolean) => void} callback Function to call if the cached value is valid
39188
+ * @param {(success: boolean, context?: any, statusCode?: number, headers?: import('../../types/header.d.ts').IncomingHttpHeaders) => void} callback Function to call if the cached value is valid
38509
39189
  * @param {import('../../types/dispatcher.d.ts').default.DispatchHandlers} handler
38510
39190
  * @param {boolean} allowErrorStatusCodes
38511
39191
  */
@@ -38527,7 +39207,7 @@ var require_cache_revalidation_handler = __commonJS({
38527
39207
  onResponseStart(controller, statusCode, headers, statusMessage) {
38528
39208
  assert(this.#callback != null);
38529
39209
  this.#successful = statusCode === 304 || this.#allowErrorStatusCodes && statusCode >= 500 && statusCode <= 504;
38530
- this.#callback(this.#successful, this.#context);
39210
+ this.#callback(this.#successful, this.#context, statusCode, headers);
38531
39211
  this.#callback = null;
38532
39212
  if (this.#successful) {
38533
39213
  return true;
@@ -38581,8 +39261,9 @@ var require_cache2 = __commonJS({
38581
39261
  var CacheHandler = require_cache_handler();
38582
39262
  var MemoryCacheStore = require_memory_cache_store();
38583
39263
  var CacheRevalidationHandler = require_cache_revalidation_handler();
38584
- var { assertCacheStore, assertCacheMethods, makeCacheKey, normalizeHeaders, parseCacheControlHeader } = require_cache();
39264
+ var { assertCacheStore, assertCacheMethods, makeCacheKey, normalizeHeaders, parseCacheControlHeader, isInvalidOrWildcardVaryHeader } = require_cache();
38585
39265
  var { AbortError } = require_errors();
39266
+ var { parseHttpDate } = require_date();
38586
39267
  function assertCacheOrigins(origins, name) {
38587
39268
  if (origins === void 0) return;
38588
39269
  if (!Array.isArray(origins)) {
@@ -38597,6 +39278,37 @@ var require_cache2 = __commonJS({
38597
39278
  }
38598
39279
  var nop = () => {
38599
39280
  };
39281
+ function trimOWS(value) {
39282
+ return value.replace(/^[\t ]+|[\t ]+$/g, "");
39283
+ }
39284
+ function arrayIncludes(array, value) {
39285
+ for (let i = 0; i < array.length; i++) {
39286
+ if (array[i] === value) {
39287
+ return true;
39288
+ }
39289
+ }
39290
+ return false;
39291
+ }
39292
+ function hasPragmaNoCache(headers) {
39293
+ const pragma = headers?.pragma;
39294
+ if (!pragma) {
39295
+ return false;
39296
+ }
39297
+ const values = Array.isArray(pragma) ? pragma : [pragma];
39298
+ for (let i = 0; i < values.length; i++) {
39299
+ const value = values[i];
39300
+ if (typeof value !== "string") {
39301
+ continue;
39302
+ }
39303
+ const directives = value.split(",");
39304
+ for (let j = 0; j < directives.length; j++) {
39305
+ if (trimOWS(directives[j]).toLowerCase() === "no-cache") {
39306
+ return true;
39307
+ }
39308
+ }
39309
+ }
39310
+ return false;
39311
+ }
38600
39312
  function needsRevalidation(result, cacheControlDirectives, { headers = {} }) {
38601
39313
  if (cacheControlDirectives?.["no-cache"]) {
38602
39314
  return true;
@@ -38609,10 +39321,58 @@ var require_cache2 = __commonJS({
38609
39321
  }
38610
39322
  return false;
38611
39323
  }
38612
- function isStale(result, cacheControlDirectives) {
39324
+ function staleResponseRequiresRevalidation(result, cacheType) {
39325
+ return result.cacheControlDirectives?.["must-revalidate"] === true || cacheType === "shared" && (result.cacheControlDirectives?.["proxy-revalidate"] === true || // https://www.rfc-editor.org/rfc/rfc9111.html#section-5.2.2.10
39326
+ // s-maxage implies proxy-revalidate for shared caches.
39327
+ result.cacheControlDirectives?.["s-maxage"] !== void 0);
39328
+ }
39329
+ function revalidationResponseDisallowsCachedReuse(cacheType, headers) {
39330
+ if (headers.vary && isInvalidOrWildcardVaryHeader(headers.vary) || cacheType === "shared" && Object.hasOwn(headers, "set-cookie")) {
39331
+ return true;
39332
+ }
39333
+ const cacheControl = headers["cache-control"];
39334
+ if (!cacheControl) {
39335
+ return false;
39336
+ }
39337
+ const cacheControlDirectives = parseCacheControlHeader(cacheControl);
39338
+ return cacheControlDirectives["no-store"] === true || cacheType === "shared" && cacheControlDirectives.private === true;
39339
+ }
39340
+ function revalidationResponseUpdatesCacheControl(headers) {
39341
+ return headers["cache-control"] !== void 0;
39342
+ }
39343
+ function deleteCachedValue(store, cacheKey) {
39344
+ try {
39345
+ store.delete(cacheKey)?.catch?.(nop);
39346
+ } catch {
39347
+ }
39348
+ }
39349
+ function getUsableLastModified(headers) {
39350
+ const lastModified = headers?.["last-modified"];
39351
+ if (typeof lastModified === "string" && parseHttpDate(lastModified)) {
39352
+ return lastModified;
39353
+ }
39354
+ }
39355
+ function makeRevalidationHeaders(opts, result) {
39356
+ const headers = {
39357
+ ...opts.headers,
39358
+ "if-modified-since": getUsableLastModified(result.headers) ?? new Date(result.cachedAt).toUTCString()
39359
+ };
39360
+ if (result.etag) {
39361
+ headers["if-none-match"] = result.etag;
39362
+ }
39363
+ if (result.vary) {
39364
+ for (const key in result.vary) {
39365
+ if (result.vary[key] != null) {
39366
+ headers[key] = result.vary[key];
39367
+ }
39368
+ }
39369
+ }
39370
+ return headers;
39371
+ }
39372
+ function isStale(result, cacheControlDirectives, cacheType) {
38613
39373
  const now = Date.now();
38614
39374
  if (now > result.staleAt) {
38615
- if (cacheControlDirectives?.["max-stale"]) {
39375
+ if (!staleResponseRequiresRevalidation(result, cacheType) && cacheControlDirectives?.["max-stale"]) {
38616
39376
  const gracePeriod = result.staleAt + cacheControlDirectives["max-stale"] * 1e3;
38617
39377
  return now > gracePeriod;
38618
39378
  }
@@ -38625,9 +39385,9 @@ var require_cache2 = __commonJS({
38625
39385
  }
38626
39386
  return false;
38627
39387
  }
38628
- function withinStaleWhileRevalidateWindow(result) {
39388
+ function withinStaleWhileRevalidateWindow(result, cacheType) {
38629
39389
  const staleWhileRevalidate = result.cacheControlDirectives?.["stale-while-revalidate"];
38630
- if (!staleWhileRevalidate) {
39390
+ if (!staleWhileRevalidate || staleResponseRequiresRevalidation(result, cacheType)) {
38631
39391
  return false;
38632
39392
  }
38633
39393
  const now = Date.now();
@@ -38722,37 +39482,29 @@ var require_cache2 = __commonJS({
38722
39482
  if (!result) {
38723
39483
  return handleUncachedResponse(dispatch, globalOpts, cacheKey, handler, opts, reqCacheControl);
38724
39484
  }
39485
+ if (globalOpts.type === "shared" && Object.hasOwn(result.headers, "set-cookie")) {
39486
+ if (util.isStream(result.body)) {
39487
+ result.body.on("error", nop).destroy();
39488
+ }
39489
+ deleteCachedValue(globalOpts.store, cacheKey);
39490
+ return handleUncachedResponse(dispatch, globalOpts, cacheKey, handler, opts, reqCacheControl);
39491
+ }
38725
39492
  const now = Date.now();
38726
39493
  if (now > result.deleteAt) {
38727
39494
  return dispatch(opts, new CacheHandler(globalOpts, cacheKey, handler));
38728
39495
  }
38729
39496
  const age = Math.round((now - result.cachedAt) / 1e3);
38730
- if (reqCacheControl?.["max-age"] && age >= reqCacheControl["max-age"]) {
38731
- return dispatch(opts, handler);
38732
- }
38733
- const stale = isStale(result, reqCacheControl);
38734
- const revalidate = needsRevalidation(result, reqCacheControl, opts);
39497
+ const requestMaxAgeExpired = reqCacheControl?.["max-age"] !== void 0 && age >= reqCacheControl["max-age"];
39498
+ const stale = requestMaxAgeExpired || isStale(result, reqCacheControl, globalOpts.type);
39499
+ const revalidate = requestMaxAgeExpired || needsRevalidation(result, reqCacheControl, opts);
38735
39500
  if (stale || revalidate) {
38736
39501
  if (util.isStream(opts.body) && util.bodyLength(opts.body) !== 0) {
38737
39502
  return dispatch(opts, new CacheHandler(globalOpts, cacheKey, handler));
38738
39503
  }
38739
- if (!revalidate && withinStaleWhileRevalidateWindow(result)) {
39504
+ if (!revalidate && withinStaleWhileRevalidateWindow(result, globalOpts.type)) {
38740
39505
  sendCachedValue(handler, opts, result, age, null, true);
38741
39506
  queueMicrotask(() => {
38742
- const headers2 = {
38743
- ...opts.headers,
38744
- "if-modified-since": new Date(result.cachedAt).toUTCString()
38745
- };
38746
- if (result.etag) {
38747
- headers2["if-none-match"] = result.etag;
38748
- }
38749
- if (result.vary) {
38750
- for (const key in result.vary) {
38751
- if (result.vary[key] != null) {
38752
- headers2[key] = result.vary[key];
38753
- }
38754
- }
38755
- }
39507
+ const headers2 = makeRevalidationHeaders(opts, result);
38756
39508
  dispatch(
38757
39509
  {
38758
39510
  ...opts,
@@ -38778,32 +39530,33 @@ var require_cache2 = __commonJS({
38778
39530
  return true;
38779
39531
  }
38780
39532
  let withinStaleIfErrorThreshold = false;
38781
- const staleIfErrorExpiry = result.cacheControlDirectives["stale-if-error"] ?? reqCacheControl?.["stale-if-error"];
38782
- if (staleIfErrorExpiry) {
38783
- withinStaleIfErrorThreshold = now < result.staleAt + staleIfErrorExpiry * 1e3;
38784
- }
38785
- const headers = {
38786
- ...opts.headers,
38787
- "if-modified-since": new Date(result.cachedAt).toUTCString()
38788
- };
38789
- if (result.etag) {
38790
- headers["if-none-match"] = result.etag;
38791
- }
38792
- if (result.vary) {
38793
- for (const key in result.vary) {
38794
- if (result.vary[key] != null) {
38795
- headers[key] = result.vary[key];
38796
- }
39533
+ if (!staleResponseRequiresRevalidation(result, globalOpts.type)) {
39534
+ const staleIfErrorExpiry = result.cacheControlDirectives["stale-if-error"] ?? reqCacheControl?.["stale-if-error"];
39535
+ if (staleIfErrorExpiry) {
39536
+ withinStaleIfErrorThreshold = now < result.staleAt + staleIfErrorExpiry * 1e3;
38797
39537
  }
38798
39538
  }
39539
+ const headers = makeRevalidationHeaders(opts, result);
38799
39540
  return dispatch(
38800
39541
  {
38801
39542
  ...opts,
38802
39543
  headers
38803
39544
  },
38804
39545
  new CacheRevalidationHandler(
38805
- (success, context) => {
39546
+ (success, context, statusCode, headers2) => {
38806
39547
  if (success) {
39548
+ if (statusCode === 304) {
39549
+ if (revalidationResponseDisallowsCachedReuse(globalOpts.type, headers2)) {
39550
+ if (util.isStream(result.body)) {
39551
+ result.body.on("error", nop).destroy();
39552
+ }
39553
+ deleteCachedValue(globalOpts.store, cacheKey);
39554
+ return dispatch(opts, new CacheHandler(globalOpts, cacheKey, handler));
39555
+ }
39556
+ if (revalidationResponseUpdatesCacheControl(headers2)) {
39557
+ deleteCachedValue(globalOpts.store, cacheKey);
39558
+ }
39559
+ }
38807
39560
  sendCachedValue(handler, opts, result, age, context, stale);
38808
39561
  } else if (util.isStream(result.body)) {
38809
39562
  result.body.on("error", nop).destroy();
@@ -38845,10 +39598,16 @@ var require_cache2 = __commonJS({
38845
39598
  cacheByDefault,
38846
39599
  type
38847
39600
  };
38848
- const safeMethodsToNotCache = util.safeHTTPMethods.filter((method) => methods.includes(method) === false);
39601
+ const safeMethodsToNotCache = [];
39602
+ for (let i = 0; i < util.safeHTTPMethods.length; i++) {
39603
+ const method = util.safeHTTPMethods[i];
39604
+ if (!arrayIncludes(methods, method)) {
39605
+ safeMethodsToNotCache.push(method);
39606
+ }
39607
+ }
38849
39608
  return (dispatch) => {
38850
39609
  return (opts2, handler) => {
38851
- if (!opts2.origin || safeMethodsToNotCache.includes(opts2.method)) {
39610
+ if (!opts2.origin || arrayIncludes(safeMethodsToNotCache, opts2.method)) {
38852
39611
  return dispatch(opts2, handler);
38853
39612
  }
38854
39613
  if (origins !== void 0) {
@@ -38874,11 +39633,14 @@ var require_cache2 = __commonJS({
38874
39633
  ...opts2,
38875
39634
  headers: normalizeHeaders(opts2)
38876
39635
  };
38877
- const reqCacheControl = opts2.headers?.["cache-control"] ? parseCacheControlHeader(opts2.headers["cache-control"]) : void 0;
39636
+ const reqCacheControl = opts2.headers?.["cache-control"] ? parseCacheControlHeader(opts2.headers["cache-control"]) : hasPragmaNoCache(opts2.headers) ? { "no-cache": true } : void 0;
38878
39637
  if (reqCacheControl?.["no-store"]) {
38879
39638
  return dispatch(opts2, handler);
38880
39639
  }
38881
39640
  const cacheKey = makeCacheKey(opts2);
39641
+ if (!arrayIncludes(util.safeHTTPMethods, opts2.method)) {
39642
+ return dispatch(opts2, new CacheHandler(globalOpts, cacheKey, handler));
39643
+ }
38882
39644
  const result = store.get(cacheKey);
38883
39645
  if (result && typeof result.then === "function") {
38884
39646
  return result.then((result2) => handleResult(
@@ -38912,7 +39674,8 @@ var require_decompress = __commonJS({
38912
39674
  "node_modules/undici/lib/interceptor/decompress.js"(exports, module) {
38913
39675
  "use strict";
38914
39676
  var { createInflate, createGunzip, createBrotliDecompress, createZstdDecompress } = __require("zlib");
38915
- var { pipeline } = __require("stream");
39677
+ var { pipeline, Transform: TransformStream2 } = __require("stream");
39678
+ var { InvalidArgumentError, ResponseExceededMaxSizeError } = require_errors();
38916
39679
  var DecoratorHandler = require_decorator_handler();
38917
39680
  var { runtimeFeatures } = require_runtime_features();
38918
39681
  var supportedEncodings = {
@@ -38928,6 +39691,23 @@ var require_decompress = __commonJS({
38928
39691
  /** @type {const} */
38929
39692
  [204, 304]
38930
39693
  );
39694
+ var defaultMaxSize = 64 * 1024 * 1024;
39695
+ function createMaxSizeLimiter(maxSize) {
39696
+ let size = 0;
39697
+ return new TransformStream2({
39698
+ transform(chunk2, _encoding, callback) {
39699
+ const decompressedSize = size + chunk2.length;
39700
+ if (decompressedSize > maxSize) {
39701
+ callback(new ResponseExceededMaxSizeError(
39702
+ `Decompressed response size (${decompressedSize}) exceeded maxSize (${maxSize})`
39703
+ ));
39704
+ return;
39705
+ }
39706
+ size = decompressedSize;
39707
+ callback(null, chunk2);
39708
+ }
39709
+ });
39710
+ }
38931
39711
  var warningEmitted = (
38932
39712
  /** @type {boolean} */
38933
39713
  false
@@ -38935,14 +39715,28 @@ var require_decompress = __commonJS({
38935
39715
  var DecompressHandler = class extends DecoratorHandler {
38936
39716
  /** @type {Transform[]} */
38937
39717
  #decompressors = [];
39718
+ /** @type {Record<string, string | string[]> | undefined} */
39719
+ #trailers;
38938
39720
  /** @type {Readonly<number[]>} */
38939
39721
  #skipStatusCodes;
38940
39722
  /** @type {boolean} */
38941
39723
  #skipErrorResponses;
38942
- constructor(handler, { skipStatusCodes = defaultSkipStatusCodes, skipErrorResponses = true } = {}) {
39724
+ /** @type {number} */
39725
+ #maxSize;
39726
+ /** @type {number} */
39727
+ #decompressedSize = 0;
39728
+ /** @type {boolean} */
39729
+ #terminated = false;
39730
+ /** @type {boolean} */
39731
+ #inputEnded = false;
39732
+ constructor(handler, { skipStatusCodes = defaultSkipStatusCodes, skipErrorResponses = true, maxSize = defaultMaxSize } = {}) {
39733
+ if (!Number.isSafeInteger(maxSize) || maxSize < 1) {
39734
+ throw new InvalidArgumentError("maxSize must be a positive integer");
39735
+ }
38943
39736
  super(handler);
38944
39737
  this.#skipStatusCodes = skipStatusCodes;
38945
39738
  this.#skipErrorResponses = skipErrorResponses;
39739
+ this.#maxSize = maxSize;
38946
39740
  }
38947
39741
  /**
38948
39742
  * Determines if decompression should be skipped based on encoding and status code
@@ -38960,7 +39754,7 @@ var require_decompress = __commonJS({
38960
39754
  * Creates a chain of decompressors for multiple content encodings
38961
39755
  *
38962
39756
  * @param {string} encodings - Comma-separated list of content encodings
38963
- * @returns {Array<DecompressorStream>} - Array of decompressor streams
39757
+ * @returns {Array<Transform>} - Array of decompressor and limiting streams
38964
39758
  * @throws {Error} - If the number of content-encodings exceeds the maximum allowed
38965
39759
  */
38966
39760
  #createDecompressionChain(encodings) {
@@ -38979,7 +39773,33 @@ var require_decompress = __commonJS({
38979
39773
  }
38980
39774
  decompressors.push(supportedEncodings[encoding]());
38981
39775
  }
38982
- return decompressors;
39776
+ if (decompressors.length < 2) {
39777
+ return decompressors;
39778
+ }
39779
+ const streams = [];
39780
+ for (let i = 0; i < decompressors.length; i++) {
39781
+ streams.push(decompressors[i]);
39782
+ if (i < decompressors.length - 1) {
39783
+ streams.push(createMaxSizeLimiter(this.#maxSize));
39784
+ }
39785
+ }
39786
+ return streams;
39787
+ }
39788
+ /**
39789
+ * Stops decompression and reports an error.
39790
+ * @param {Controller} controller - The controller to coordinate with
39791
+ * @param {Error} error - The decompression error
39792
+ * @returns {void}
39793
+ */
39794
+ #fail(controller, error) {
39795
+ if (this.#terminated) {
39796
+ return;
39797
+ }
39798
+ if (this.#inputEnded) {
39799
+ this.onResponseError(controller, error);
39800
+ } else {
39801
+ controller.abort(error);
39802
+ }
38983
39803
  }
38984
39804
  /**
38985
39805
  * Sets up event handlers for a decompressor stream using readable events
@@ -38989,8 +39809,19 @@ var require_decompress = __commonJS({
38989
39809
  */
38990
39810
  #setupDecompressorEvents(decompressor, controller) {
38991
39811
  decompressor.on("readable", () => {
39812
+ if (this.#terminated) {
39813
+ return;
39814
+ }
38992
39815
  let chunk2;
38993
39816
  while ((chunk2 = decompressor.read()) !== null) {
39817
+ const decompressedSize = this.#decompressedSize + chunk2.length;
39818
+ if (decompressedSize > this.#maxSize) {
39819
+ this.#fail(controller, new ResponseExceededMaxSizeError(
39820
+ `Decompressed response size (${decompressedSize}) exceeded maxSize (${this.#maxSize})`
39821
+ ));
39822
+ return;
39823
+ }
39824
+ this.#decompressedSize = decompressedSize;
38994
39825
  const result = super.onResponseData(controller, chunk2);
38995
39826
  if (result === false) {
38996
39827
  break;
@@ -38998,7 +39829,7 @@ var require_decompress = __commonJS({
38998
39829
  }
38999
39830
  });
39000
39831
  decompressor.on("error", (error) => {
39001
- super.onResponseError(controller, error);
39832
+ this.#fail(controller, error);
39002
39833
  });
39003
39834
  }
39004
39835
  /**
@@ -39010,7 +39841,12 @@ var require_decompress = __commonJS({
39010
39841
  const decompressor = this.#decompressors[0];
39011
39842
  this.#setupDecompressorEvents(decompressor, controller);
39012
39843
  decompressor.on("end", () => {
39013
- super.onResponseEnd(controller, {});
39844
+ if (this.#terminated) {
39845
+ return;
39846
+ }
39847
+ this.#terminated = true;
39848
+ this.#cleanupDecompressors();
39849
+ super.onResponseEnd(controller, this.#trailers);
39014
39850
  });
39015
39851
  }
39016
39852
  /**
@@ -39022,11 +39858,16 @@ var require_decompress = __commonJS({
39022
39858
  const lastDecompressor = this.#decompressors[this.#decompressors.length - 1];
39023
39859
  this.#setupDecompressorEvents(lastDecompressor, controller);
39024
39860
  pipeline(this.#decompressors, (err2) => {
39861
+ if (this.#terminated) {
39862
+ return;
39863
+ }
39025
39864
  if (err2) {
39026
- super.onResponseError(controller, err2);
39865
+ this.#fail(controller, err2);
39027
39866
  return;
39028
39867
  }
39029
- super.onResponseEnd(controller, {});
39868
+ this.#terminated = true;
39869
+ this.#cleanupDecompressors();
39870
+ super.onResponseEnd(controller, this.#trailers);
39030
39871
  });
39031
39872
  }
39032
39873
  /**
@@ -39055,6 +39896,29 @@ var require_decompress = __commonJS({
39055
39896
  }
39056
39897
  this.#decompressors = decompressors;
39057
39898
  const { "content-encoding": _, "content-length": __, ...newHeaders } = headers;
39899
+ if (controller?.rawHeaders) {
39900
+ const rawHeaders = controller.rawHeaders;
39901
+ if (Array.isArray(rawHeaders)) {
39902
+ const filteredHeaders = [];
39903
+ for (let i = 0; i < rawHeaders.length; i += 2) {
39904
+ const headerName = rawHeaders[i];
39905
+ const name = Buffer.isBuffer(headerName) ? headerName.toString("latin1") : `${headerName}`;
39906
+ const lowerName = name.toLowerCase();
39907
+ if (lowerName === "content-encoding" || lowerName === "content-length") {
39908
+ continue;
39909
+ }
39910
+ filteredHeaders.push(rawHeaders[i], rawHeaders[i + 1]);
39911
+ }
39912
+ rawHeaders.splice(0, rawHeaders.length, ...filteredHeaders);
39913
+ } else if (typeof rawHeaders === "object") {
39914
+ for (const name of Object.keys(rawHeaders)) {
39915
+ const lowerName = name.toLowerCase();
39916
+ if (lowerName === "content-encoding" || lowerName === "content-length") {
39917
+ delete rawHeaders[name];
39918
+ }
39919
+ }
39920
+ }
39921
+ }
39058
39922
  if (this.#decompressors.length === 1) {
39059
39923
  this.#setupSingleDecompressor(controller);
39060
39924
  } else {
@@ -39081,8 +39945,9 @@ var require_decompress = __commonJS({
39081
39945
  */
39082
39946
  onResponseEnd(controller, trailers) {
39083
39947
  if (this.#decompressors.length > 0) {
39948
+ this.#inputEnded = true;
39949
+ this.#trailers = trailers;
39084
39950
  this.#decompressors[0].end();
39085
- this.#cleanupDecompressors();
39086
39951
  return;
39087
39952
  }
39088
39953
  super.onResponseEnd(controller, trailers);
@@ -39093,12 +39958,14 @@ var require_decompress = __commonJS({
39093
39958
  * @returns {void}
39094
39959
  */
39095
39960
  onResponseError(controller, err2) {
39096
- if (this.#decompressors.length > 0) {
39097
- for (const decompressor of this.#decompressors) {
39098
- decompressor.destroy(err2);
39099
- }
39100
- this.#cleanupDecompressors();
39961
+ if (this.#terminated) {
39962
+ return;
39101
39963
  }
39964
+ this.#terminated = true;
39965
+ for (const decompressor of this.#decompressors) {
39966
+ decompressor.destroy();
39967
+ }
39968
+ this.#cleanupDecompressors();
39102
39969
  super.onResponseError(controller, err2);
39103
39970
  }
39104
39971
  };
@@ -39730,7 +40597,7 @@ var require_sqlite_cache_store = __commonJS({
39730
40597
  SELECT
39731
40598
  id
39732
40599
  FROM cacheInterceptorV${VERSION}
39733
- ORDER BY cachedAt DESC
40600
+ ORDER BY cachedAt ASC
39734
40601
  LIMIT ?
39735
40602
  )
39736
40603
  `);
@@ -39785,7 +40652,6 @@ var require_sqlite_cache_store = __commonJS({
39785
40652
  existingValue.id
39786
40653
  );
39787
40654
  } else {
39788
- this.#prune();
39789
40655
  this.#insertValueQuery.run(
39790
40656
  url,
39791
40657
  key.method,
@@ -39800,6 +40666,7 @@ var require_sqlite_cache_store = __commonJS({
39800
40666
  value.cachedAt,
39801
40667
  value.staleAt
39802
40668
  );
40669
+ this.#prune();
39803
40670
  }
39804
40671
  }
39805
40672
  /**
@@ -39887,7 +40754,7 @@ var require_sqlite_cache_store = __commonJS({
39887
40754
  const now = Date.now();
39888
40755
  for (const value of values) {
39889
40756
  if (now >= value.deleteAt && !canBeExpired) {
39890
- return void 0;
40757
+ continue;
39891
40758
  }
39892
40759
  let matches = true;
39893
40760
  if (value.vary) {
@@ -39917,7 +40784,12 @@ var require_sqlite_cache_store = __commonJS({
39917
40784
  if (lhs.length !== rhs.length) {
39918
40785
  return false;
39919
40786
  }
39920
- return lhs.every((x, i) => x === rhs[i]);
40787
+ for (let i = 0; i < lhs.length; i++) {
40788
+ if (lhs[i] !== rhs[i]) {
40789
+ return false;
40790
+ }
40791
+ }
40792
+ return true;
39921
40793
  }
39922
40794
  return lhs === rhs;
39923
40795
  }
@@ -42206,7 +43078,7 @@ var require_fetch = __commonJS({
42206
43078
  cacheState = "";
42207
43079
  }
42208
43080
  let responseStatus = 0;
42209
- if (fetchParams.request.mode !== "navigator" || !response.hasCrossOriginRedirects) {
43081
+ if (fetchParams.request.mode !== "navigate" || !response.hasCrossOriginRedirects) {
42210
43082
  responseStatus = response.status;
42211
43083
  const mimeType = extractMimeType(response.headersList);
42212
43084
  if (mimeType !== "failure") {
@@ -42370,7 +43242,7 @@ var require_fetch = __commonJS({
42370
43242
  if (contentLength != null) {
42371
43243
  contentLengthHeaderValue = isomorphicEncode(`${contentLength}`);
42372
43244
  }
42373
- if (contentLengthHeaderValue != null) {
43245
+ if (contentLengthHeaderValue != null && !httpRequest.headersList.contains("content-length", true)) {
42374
43246
  httpRequest.headersList.append("content-length", contentLengthHeaderValue, true);
42375
43247
  }
42376
43248
  if (contentLength != null && httpRequest.keepalive) {
@@ -42448,10 +43320,10 @@ var require_fetch = __commonJS({
42448
43320
  response.rangeRequested = true;
42449
43321
  }
42450
43322
  response.requestIncludesCredentials = includeCredentials;
42451
- if (response.status === 401 && httpRequest.responseTainting !== "cors" && includeCredentials && isTraversableNavigable(request2.traversableForUserPrompts)) {
43323
+ if (response.status === 401 && httpRequest.responseTainting !== "cors" && includeCredentials && (request2.useURLCredentials !== void 0 || isTraversableNavigable(request2.traversableForUserPrompts))) {
42452
43324
  if (request2.body != null) {
42453
43325
  if (request2.body.source == null) {
42454
- return makeNetworkError("expected non-null body source");
43326
+ return response;
42455
43327
  }
42456
43328
  request2.body = safelyExtractBody(request2.body.source)[0];
42457
43329
  }
@@ -42693,7 +43565,15 @@ var require_fetch = __commonJS({
42693
43565
  }
42694
43566
  const headersList = new HeadersList();
42695
43567
  for (let i = 0; i < rawHeaders.length; i += 2) {
42696
- headersList.append(bufferToLowerCasedHeaderName(rawHeaders[i]), rawHeaders[i + 1].toString("latin1"), true);
43568
+ const nameStr = bufferToLowerCasedHeaderName(rawHeaders[i]);
43569
+ const value = rawHeaders[i + 1];
43570
+ if (Array.isArray(value) && !Buffer.isBuffer(rawHeaders[i + 1])) {
43571
+ for (const val of value) {
43572
+ headersList.append(nameStr, val.toString("latin1"), true);
43573
+ }
43574
+ } else {
43575
+ headersList.append(nameStr, value.toString("latin1"), true);
43576
+ }
42697
43577
  }
42698
43578
  const location = headersList.get("location", true);
42699
43579
  this.body = new Readable({ read: resume });
@@ -42807,7 +43687,15 @@ var require_fetch = __commonJS({
42807
43687
  }
42808
43688
  const headersList = new HeadersList();
42809
43689
  for (let i = 0; i < rawHeaders.length; i += 2) {
42810
- headersList.append(bufferToLowerCasedHeaderName(rawHeaders[i]), rawHeaders[i + 1].toString("latin1"), true);
43690
+ const nameStr = bufferToLowerCasedHeaderName(rawHeaders[i]);
43691
+ const value = rawHeaders[i + 1];
43692
+ if (Array.isArray(value) && !Buffer.isBuffer(rawHeaders[i + 1])) {
43693
+ for (const val of value) {
43694
+ headersList.append(nameStr, val.toString("latin1"), true);
43695
+ }
43696
+ } else {
43697
+ headersList.append(nameStr, value.toString("latin1"), true);
43698
+ }
42811
43699
  }
42812
43700
  resolve2({
42813
43701
  status,
@@ -43597,14 +44485,48 @@ var require_util4 = __commonJS({
43597
44485
  for (let i = 0; i < path74.length; ++i) {
43598
44486
  const code = path74.charCodeAt(i);
43599
44487
  if (code < 32 || // exclude CTLs (0-31)
43600
- code === 127 || // DEL
44488
+ code > 126 || // exclude DEL and non-ascii
43601
44489
  code === 59) {
43602
44490
  throw new Error("Invalid cookie path");
43603
44491
  }
43604
44492
  }
43605
44493
  }
44494
+ function isLetterOrDigit(code) {
44495
+ return code >= 48 && code <= 57 || // 0-9
44496
+ code >= 65 && code <= 90 || // A-Z
44497
+ code >= 97 && code <= 122;
44498
+ }
43606
44499
  function validateCookieDomain(domain) {
43607
- if (domain.startsWith("-") || domain.endsWith(".") || domain.endsWith("-")) {
44500
+ if (domain === " ") {
44501
+ return;
44502
+ }
44503
+ if (domain.length > 255) {
44504
+ throw new Error("Invalid cookie domain");
44505
+ }
44506
+ let labelLength = 0;
44507
+ for (let i = 0; i < domain.length; ++i) {
44508
+ const code = domain.charCodeAt(i);
44509
+ if (code === 46) {
44510
+ if (labelLength === 0) {
44511
+ throw new Error("Invalid cookie domain");
44512
+ }
44513
+ if (domain.charCodeAt(i - 1) === 45) {
44514
+ throw new Error("Invalid cookie domain");
44515
+ }
44516
+ labelLength = 0;
44517
+ continue;
44518
+ }
44519
+ if (labelLength === 0 && !isLetterOrDigit(code)) {
44520
+ throw new Error("Invalid cookie domain");
44521
+ }
44522
+ if (!isLetterOrDigit(code) && code !== 45) {
44523
+ throw new Error("Invalid cookie domain");
44524
+ }
44525
+ if (++labelLength > 63) {
44526
+ throw new Error("Invalid cookie domain");
44527
+ }
44528
+ }
44529
+ if (labelLength === 0 || domain.charCodeAt(domain.length - 1) === 45) {
43608
44530
  throw new Error("Invalid cookie domain");
43609
44531
  }
43610
44532
  }
@@ -43687,7 +44609,11 @@ var require_util4 = __commonJS({
43687
44609
  throw new Error("Invalid unparsed");
43688
44610
  }
43689
44611
  const [key, ...value] = part.split("=");
43690
- out.push(`${key.trim()}=${value.join("=")}`);
44612
+ const trimmedKey = key.trim();
44613
+ const joinedValue = value.join("=");
44614
+ validateCookieName(trimmedKey);
44615
+ validateCookieValue(joinedValue);
44616
+ out.push(`${trimmedKey}=${joinedValue}`);
43691
44617
  }
43692
44618
  return out.join("; ");
43693
44619
  }
@@ -43710,7 +44636,6 @@ var require_parse = __commonJS({
43710
44636
  var { maxNameValuePairSize, maxAttributeValueSize } = require_constants4();
43711
44637
  var { isCTLExcludingHtab } = require_util4();
43712
44638
  var assert = __require("assert");
43713
- var { unescape: qsUnescape } = __require("querystring");
43714
44639
  function parseSetCookie(header) {
43715
44640
  if (isCTLExcludingHtab(header)) {
43716
44641
  return null;
@@ -43744,7 +44669,7 @@ var require_parse = __commonJS({
43744
44669
  }
43745
44670
  return {
43746
44671
  name,
43747
- value: qsUnescape(value),
44672
+ value,
43748
44673
  ...parseUnparsedAttributes(unparsedAttributes)
43749
44674
  };
43750
44675
  }
@@ -43818,18 +44743,14 @@ var require_parse = __commonJS({
43818
44743
  } else if (attributeNameLowercase === "httponly") {
43819
44744
  cookieAttributeList.httpOnly = true;
43820
44745
  } else if (attributeNameLowercase === "samesite") {
43821
- let enforcement = "Default";
43822
44746
  const attributeValueLowercase = attributeValue.toLowerCase();
43823
- if (attributeValueLowercase.includes("none")) {
43824
- enforcement = "None";
43825
- }
43826
- if (attributeValueLowercase.includes("strict")) {
43827
- enforcement = "Strict";
43828
- }
43829
- if (attributeValueLowercase.includes("lax")) {
43830
- enforcement = "Lax";
44747
+ if (attributeValueLowercase === "none") {
44748
+ cookieAttributeList.sameSite = "None";
44749
+ } else if (attributeValueLowercase === "strict") {
44750
+ cookieAttributeList.sameSite = "Strict";
44751
+ } else if (attributeValueLowercase === "lax") {
44752
+ cookieAttributeList.sameSite = "Lax";
43831
44753
  }
43832
- cookieAttributeList.sameSite = enforcement;
43833
44754
  } else {
43834
44755
  cookieAttributeList.unparsed ??= [];
43835
44756
  cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`);
@@ -44674,7 +45595,7 @@ var require_connection = __commonJS({
44674
45595
  const secProtocol = response.headersList.get("Sec-WebSocket-Protocol");
44675
45596
  if (secProtocol !== null) {
44676
45597
  const requestProtocols = getDecodeSplit("sec-websocket-protocol", request2.headersList);
44677
- if (!requestProtocols.includes(secProtocol)) {
45598
+ if (requestProtocols === null || !requestProtocols.includes(secProtocol)) {
44678
45599
  failWebsocketConnection(handler, 1002, "Protocol was not set in the opening handshake.");
44679
45600
  return;
44680
45601
  }
@@ -44750,27 +45671,26 @@ var require_permessage_deflate = __commonJS({
44750
45671
  var tail = Buffer.from([0, 0, 255, 255]);
44751
45672
  var kBuffer = /* @__PURE__ */ Symbol("kBuffer");
44752
45673
  var kLength = /* @__PURE__ */ Symbol("kLength");
44753
- var kDefaultMaxDecompressedSize = 4 * 1024 * 1024;
44754
45674
  var PerMessageDeflate = class {
44755
45675
  /** @type {import('node:zlib').InflateRaw} */
44756
45676
  #inflate;
44757
45677
  #options = {};
44758
- /** @type {boolean} */
44759
- #aborted = false;
44760
- /** @type {Function|null} */
44761
- #currentCallback = null;
45678
+ #maxPayloadSize = 0;
44762
45679
  /**
44763
45680
  * @param {Map<string, string>} extensions
44764
45681
  */
44765
- constructor(extensions) {
45682
+ constructor(extensions, options) {
44766
45683
  this.#options.serverNoContextTakeover = extensions.has("server_no_context_takeover");
44767
45684
  this.#options.serverMaxWindowBits = extensions.get("server_max_window_bits");
45685
+ this.#maxPayloadSize = options.maxPayloadSize;
44768
45686
  }
45687
+ /**
45688
+ * Decompress a compressed payload.
45689
+ * @param {Buffer} chunk Compressed data
45690
+ * @param {boolean} fin Final fragment flag
45691
+ * @param {Function} callback Callback function
45692
+ */
44769
45693
  decompress(chunk2, fin, callback) {
44770
- if (this.#aborted) {
44771
- callback(new MessageSizeExceededError());
44772
- return;
44773
- }
44774
45694
  if (!this.#inflate) {
44775
45695
  let windowBits = Z_DEFAULT_WINDOWBITS;
44776
45696
  if (this.#options.serverMaxWindowBits) {
@@ -44789,20 +45709,12 @@ var require_permessage_deflate = __commonJS({
44789
45709
  this.#inflate[kBuffer] = [];
44790
45710
  this.#inflate[kLength] = 0;
44791
45711
  this.#inflate.on("data", (data) => {
44792
- if (this.#aborted) {
44793
- return;
44794
- }
44795
45712
  this.#inflate[kLength] += data.length;
44796
- if (this.#inflate[kLength] > kDefaultMaxDecompressedSize) {
44797
- this.#aborted = true;
45713
+ if (this.#maxPayloadSize > 0 && this.#inflate[kLength] > this.#maxPayloadSize) {
45714
+ callback(new MessageSizeExceededError());
44798
45715
  this.#inflate.removeAllListeners();
44799
45716
  this.#inflate.destroy();
44800
45717
  this.#inflate = null;
44801
- if (this.#currentCallback) {
44802
- const cb = this.#currentCallback;
44803
- this.#currentCallback = null;
44804
- cb(new MessageSizeExceededError());
44805
- }
44806
45718
  return;
44807
45719
  }
44808
45720
  this.#inflate[kBuffer].push(data);
@@ -44812,19 +45724,17 @@ var require_permessage_deflate = __commonJS({
44812
45724
  callback(err2);
44813
45725
  });
44814
45726
  }
44815
- this.#currentCallback = callback;
44816
45727
  this.#inflate.write(chunk2);
44817
45728
  if (fin) {
44818
45729
  this.#inflate.write(tail);
44819
45730
  }
44820
45731
  this.#inflate.flush(() => {
44821
- if (this.#aborted || !this.#inflate) {
45732
+ if (!this.#inflate) {
44822
45733
  return;
44823
45734
  }
44824
45735
  const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]);
44825
45736
  this.#inflate[kBuffer].length = 0;
44826
45737
  this.#inflate[kLength] = 0;
44827
- this.#currentCallback = null;
44828
45738
  callback(null, full);
44829
45739
  });
44830
45740
  }
@@ -44865,16 +45775,23 @@ var require_receiver = __commonJS({
44865
45775
  #extensions;
44866
45776
  /** @type {import('./websocket').Handler} */
44867
45777
  #handler;
45778
+ /** @type {number} */
45779
+ #maxFragments;
45780
+ /** @type {number} */
45781
+ #maxPayloadSize;
44868
45782
  /**
44869
45783
  * @param {import('./websocket').Handler} handler
44870
45784
  * @param {Map<string, string>|null} extensions
45785
+ * @param {{ maxFragments?: number, maxPayloadSize?: number }} [options]
44871
45786
  */
44872
- constructor(handler, extensions) {
45787
+ constructor(handler, extensions, options = {}) {
44873
45788
  super();
44874
45789
  this.#handler = handler;
44875
45790
  this.#extensions = extensions == null ? /* @__PURE__ */ new Map() : extensions;
45791
+ this.#maxFragments = options.maxFragments ?? 0;
45792
+ this.#maxPayloadSize = options.maxPayloadSize ?? 0;
44876
45793
  if (this.#extensions.has("permessage-deflate")) {
44877
- this.#extensions.set("permessage-deflate", new PerMessageDeflate(extensions));
45794
+ this.#extensions.set("permessage-deflate", new PerMessageDeflate(extensions, options));
44878
45795
  }
44879
45796
  }
44880
45797
  /**
@@ -44887,6 +45804,13 @@ var require_receiver = __commonJS({
44887
45804
  this.#loop = true;
44888
45805
  this.run(callback);
44889
45806
  }
45807
+ #validatePayloadLength() {
45808
+ if (this.#maxPayloadSize > 0 && !isControlFrame(this.#info.opcode) && this.#info.payloadLength + this.#fragmentsBytes > this.#maxPayloadSize) {
45809
+ failWebsocketConnection(this.#handler, 1009, "Payload size exceeds maximum allowed size");
45810
+ return false;
45811
+ }
45812
+ return true;
45813
+ }
44890
45814
  /**
44891
45815
  * Runs whenever a new chunk is received.
44892
45816
  * Callback is called whenever there are no more chunks buffering,
@@ -44946,6 +45870,9 @@ var require_receiver = __commonJS({
44946
45870
  if (payloadLength <= 125) {
44947
45871
  this.#info.payloadLength = payloadLength;
44948
45872
  this.#state = parserStates.READ_DATA;
45873
+ if (!this.#validatePayloadLength()) {
45874
+ return;
45875
+ }
44949
45876
  } else if (payloadLength === 126) {
44950
45877
  this.#state = parserStates.PAYLOADLENGTH_16;
44951
45878
  } else if (payloadLength === 127) {
@@ -44966,6 +45893,9 @@ var require_receiver = __commonJS({
44966
45893
  const buffer = this.consume(2);
44967
45894
  this.#info.payloadLength = buffer.readUInt16BE(0);
44968
45895
  this.#state = parserStates.READ_DATA;
45896
+ if (!this.#validatePayloadLength()) {
45897
+ return;
45898
+ }
44969
45899
  } else if (this.#state === parserStates.PAYLOADLENGTH_64) {
44970
45900
  if (this.#byteOffset < 8) {
44971
45901
  return callback();
@@ -44979,6 +45909,9 @@ var require_receiver = __commonJS({
44979
45909
  }
44980
45910
  this.#info.payloadLength = lower;
44981
45911
  this.#state = parserStates.READ_DATA;
45912
+ if (!this.#validatePayloadLength()) {
45913
+ return;
45914
+ }
44982
45915
  } else if (this.#state === parserStates.READ_DATA) {
44983
45916
  if (this.#byteOffset < this.#info.payloadLength) {
44984
45917
  return callback();
@@ -44989,30 +45922,43 @@ var require_receiver = __commonJS({
44989
45922
  this.#state = parserStates.INFO;
44990
45923
  } else {
44991
45924
  if (!this.#info.compressed) {
44992
- this.writeFragments(body);
45925
+ if (!this.writeFragments(body)) {
45926
+ return;
45927
+ }
44993
45928
  if (!this.#info.fragmented && this.#info.fin) {
44994
45929
  websocketMessageReceived(this.#handler, this.#info.binaryType, this.consumeFragments());
44995
45930
  }
44996
45931
  this.#state = parserStates.INFO;
44997
45932
  } else {
44998
- this.#extensions.get("permessage-deflate").decompress(body, this.#info.fin, (error, data) => {
44999
- if (error) {
45000
- const code = error instanceof MessageSizeExceededError ? 1009 : 1007;
45001
- failWebsocketConnection(this.#handler, code, error.message);
45002
- return;
45003
- }
45004
- this.writeFragments(data);
45005
- if (!this.#info.fin) {
45006
- this.#state = parserStates.INFO;
45933
+ this.#extensions.get("permessage-deflate").decompress(
45934
+ body,
45935
+ this.#info.fin,
45936
+ (error, data) => {
45937
+ if (error) {
45938
+ const code = error instanceof MessageSizeExceededError ? 1009 : 1007;
45939
+ failWebsocketConnection(this.#handler, code, error.message);
45940
+ return;
45941
+ }
45942
+ if (!this.writeFragments(data)) {
45943
+ return;
45944
+ }
45945
+ if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) {
45946
+ failWebsocketConnection(this.#handler, 1009, new MessageSizeExceededError().message);
45947
+ return;
45948
+ }
45949
+ if (!this.#info.fin) {
45950
+ this.#state = parserStates.INFO;
45951
+ this.#loop = true;
45952
+ this.run(callback);
45953
+ return;
45954
+ }
45955
+ websocketMessageReceived(this.#handler, this.#info.binaryType, this.consumeFragments());
45007
45956
  this.#loop = true;
45957
+ this.#state = parserStates.INFO;
45008
45958
  this.run(callback);
45009
- return;
45010
- }
45011
- websocketMessageReceived(this.#handler, this.#info.binaryType, this.consumeFragments());
45012
- this.#loop = true;
45013
- this.#state = parserStates.INFO;
45014
- this.run(callback);
45015
- });
45959
+ },
45960
+ this.#fragmentsBytes
45961
+ );
45016
45962
  this.#loop = false;
45017
45963
  break;
45018
45964
  }
@@ -45060,8 +46006,13 @@ var require_receiver = __commonJS({
45060
46006
  }
45061
46007
  }
45062
46008
  writeFragments(fragment) {
46009
+ if (this.#maxFragments > 0 && this.#fragments.length === this.#maxFragments) {
46010
+ failWebsocketConnection(this.#handler, 1008, "Too many message fragments");
46011
+ return false;
46012
+ }
45063
46013
  this.#fragmentsBytes += fragment.length;
45064
46014
  this.#fragments.push(fragment);
46015
+ return true;
45065
46016
  }
45066
46017
  consumeFragments() {
45067
46018
  const fragments = this.#fragments;
@@ -45528,7 +46479,13 @@ var require_websocket = __commonJS({
45528
46479
  */
45529
46480
  #onConnectionEstablished(response, parsedExtensions) {
45530
46481
  this.#handler.socket = response.socket;
45531
- const parser = new ByteParser(this.#handler, parsedExtensions);
46482
+ const webSocketOptions = this.#handler.controller.dispatcher?.webSocketOptions;
46483
+ const maxFragments = webSocketOptions?.maxFragments;
46484
+ const maxPayloadSize = webSocketOptions?.maxPayloadSize;
46485
+ const parser = new ByteParser(this.#handler, parsedExtensions, {
46486
+ maxFragments,
46487
+ maxPayloadSize
46488
+ });
45532
46489
  parser.on("drain", () => this.#handler.onParserDrain());
45533
46490
  parser.on("error", (err2) => this.#handler.onParserError(err2));
45534
46491
  this.#parser = parser;
@@ -45834,9 +46791,9 @@ var require_websocketstream = __commonJS({
45834
46791
  #readableStream;
45835
46792
  /** @type {ReadableStreamDefaultController} */
45836
46793
  #readableStreamController;
45837
- // Each WebSocketStream object has an associated writable stream , which is a WritableStream .
45838
- /** @type {WritableStream} */
45839
- #writableStream;
46794
+ // Retain the controller so the writable stream can be errored while locked.
46795
+ /** @type {WritableStreamDefaultController} */
46796
+ #writableStreamController;
45840
46797
  // Each WebSocketStream object has an associated boolean handshake aborted , which is initially false.
45841
46798
  #handshakeAborted = false;
45842
46799
  /** @type {import('../websocket').Handler} */
@@ -45972,7 +46929,12 @@ var require_websocketstream = __commonJS({
45972
46929
  /** @type {import('../websocket').Handler['onConnectionEstablished']} */
45973
46930
  #onConnectionEstablished(response, parsedExtensions) {
45974
46931
  this.#handler.socket = response.socket;
45975
- const parser = new ByteParser(this.#handler, parsedExtensions);
46932
+ const maxFragments = this.#handler.controller.dispatcher?.webSocketOptions?.maxFragments;
46933
+ const maxPayloadSize = this.#handler.controller.dispatcher?.webSocketOptions?.maxPayloadSize;
46934
+ const parser = new ByteParser(this.#handler, parsedExtensions, {
46935
+ maxFragments,
46936
+ maxPayloadSize
46937
+ });
45976
46938
  parser.on("drain", () => this.#handler.onParserDrain());
45977
46939
  parser.on("error", (err2) => this.#handler.onParserError(err2));
45978
46940
  this.#parser = parser;
@@ -45983,21 +46945,17 @@ var require_websocketstream = __commonJS({
45983
46945
  start: (controller) => {
45984
46946
  this.#readableStreamController = controller;
45985
46947
  },
45986
- pull(controller) {
45987
- let chunk2;
45988
- while (controller.desiredSize > 0 && (chunk2 = response.socket.read()) !== null) {
45989
- controller.enqueue(chunk2);
45990
- }
45991
- },
45992
46948
  cancel: (reason) => this.#cancel(reason)
45993
46949
  });
45994
46950
  const writable = new WritableStream({
46951
+ start: (controller) => {
46952
+ this.#writableStreamController = controller;
46953
+ },
45995
46954
  write: (chunk2) => this.#write(chunk2),
45996
46955
  close: () => closeWebSocketConnection(this.#handler, null, null),
45997
46956
  abort: (reason) => this.#closeUsingReason(reason)
45998
46957
  });
45999
46958
  this.#readableStream = readable;
46000
- this.#writableStream = writable;
46001
46959
  this.#openedPromise.resolve({
46002
46960
  extensions,
46003
46961
  protocol,
@@ -46015,7 +46973,7 @@ var require_websocketstream = __commonJS({
46015
46973
  try {
46016
46974
  chunk2 = utf8Decode(data);
46017
46975
  } catch {
46018
- failWebsocketConnection(this.#handler, "Received invalid UTF-8 in text frame.");
46976
+ failWebsocketConnection(this.#handler, 1007, "Received invalid UTF-8 in text frame.");
46019
46977
  return;
46020
46978
  }
46021
46979
  } else if (type === opcodes.BINARY) {
@@ -46041,9 +46999,7 @@ var require_websocketstream = __commonJS({
46041
46999
  const reason = result?.reason == null ? "" : utf8DecodeBytes(Buffer.from(result.reason));
46042
47000
  if (wasClean) {
46043
47001
  this.#readableStreamController.close();
46044
- if (!this.#writableStream.locked) {
46045
- this.#writableStream.abort(new DOMException("A closed WebSocketStream cannot be written to", "InvalidStateError"));
46046
- }
47002
+ this.#writableStreamController.error(new DOMException("A closed WebSocketStream cannot be written to", "InvalidStateError"));
46047
47003
  this.#closedPromise.resolve({
46048
47004
  closeCode: code,
46049
47005
  reason
@@ -46051,7 +47007,7 @@ var require_websocketstream = __commonJS({
46051
47007
  } else {
46052
47008
  const error = createUnvalidatedWebSocketError("unclean close", code, reason);
46053
47009
  this.#readableStreamController?.error(error);
46054
- this.#writableStream?.abort(error);
47010
+ this.#writableStreamController?.error(error);
46055
47011
  this.#closedPromise.reject(error);
46056
47012
  }
46057
47013
  }
@@ -46146,6 +47102,40 @@ var require_eventsource_stream = __commonJS({
46146
47102
  var CR = 13;
46147
47103
  var COLON = 58;
46148
47104
  var SPACE = 32;
47105
+ var DATA = Buffer.from("data");
47106
+ var EVENT = Buffer.from("event");
47107
+ var ID = Buffer.from("id");
47108
+ var RETRY = Buffer.from("retry");
47109
+ function isASCIINumberBytes(buffer, start) {
47110
+ if (start >= buffer.length) {
47111
+ return false;
47112
+ }
47113
+ for (let i = start; i < buffer.length; i++) {
47114
+ if (buffer[i] < 48 || buffer[i] > 57) {
47115
+ return false;
47116
+ }
47117
+ }
47118
+ return true;
47119
+ }
47120
+ function isValidLastEventIdBytes(buffer, start) {
47121
+ for (let i = start; i < buffer.length; i++) {
47122
+ if (buffer[i] === 0) {
47123
+ return false;
47124
+ }
47125
+ }
47126
+ return true;
47127
+ }
47128
+ function isFieldName(line, length, field) {
47129
+ if (length !== field.length) {
47130
+ return false;
47131
+ }
47132
+ for (let i = 0; i < length; i++) {
47133
+ if (line[i] !== field[i]) {
47134
+ return false;
47135
+ }
47136
+ }
47137
+ return true;
47138
+ }
46149
47139
  var EventSourceStream = class extends Transform {
46150
47140
  /**
46151
47141
  * @type {eventSourceSettings}
@@ -46165,10 +47155,13 @@ var require_eventsource_stream = __commonJS({
46165
47155
  */
46166
47156
  eventEndCheck = false;
46167
47157
  /**
46168
- * @type {Buffer|null}
47158
+ * @type {Buffer[]}
46169
47159
  */
46170
- buffer = null;
47160
+ chunks = [];
47161
+ chunkIndex = 0;
46171
47162
  pos = 0;
47163
+ lineChunkIndex = 0;
47164
+ linePos = 0;
46172
47165
  event = {
46173
47166
  data: void 0,
46174
47167
  event: void 0,
@@ -46200,63 +47193,30 @@ var require_eventsource_stream = __commonJS({
46200
47193
  callback();
46201
47194
  return;
46202
47195
  }
46203
- if (this.buffer) {
46204
- this.buffer = Buffer.concat([this.buffer, chunk2]);
46205
- } else {
46206
- this.buffer = chunk2;
46207
- }
47196
+ this.chunks.push(chunk2);
46208
47197
  if (this.checkBOM) {
46209
- switch (this.buffer.length) {
46210
- case 1:
46211
- if (this.buffer[0] === BOM[0]) {
46212
- callback();
46213
- return;
46214
- }
46215
- this.checkBOM = false;
46216
- callback();
46217
- return;
46218
- case 2:
46219
- if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1]) {
46220
- callback();
46221
- return;
46222
- }
46223
- this.checkBOM = false;
46224
- break;
46225
- case 3:
46226
- if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) {
46227
- this.buffer = Buffer.alloc(0);
46228
- this.checkBOM = false;
46229
- callback();
46230
- return;
46231
- }
46232
- this.checkBOM = false;
46233
- break;
46234
- default:
46235
- if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) {
46236
- this.buffer = this.buffer.subarray(3);
46237
- }
46238
- this.checkBOM = false;
46239
- break;
47198
+ if (this.handleBOM()) {
47199
+ callback();
47200
+ return;
46240
47201
  }
46241
47202
  }
46242
- while (this.pos < this.buffer.length) {
47203
+ while (this.hasCurrentByte()) {
47204
+ const byte = this.currentByte();
46243
47205
  if (this.eventEndCheck) {
46244
47206
  if (this.crlfCheck) {
46245
- if (this.buffer[this.pos] === LF) {
46246
- this.buffer = this.buffer.subarray(this.pos + 1);
46247
- this.pos = 0;
47207
+ if (byte === LF) {
46248
47208
  this.crlfCheck = false;
47209
+ this.consumeCurrentByte();
46249
47210
  continue;
46250
47211
  }
46251
47212
  this.crlfCheck = false;
46252
47213
  }
46253
- if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) {
46254
- if (this.buffer[this.pos] === CR) {
47214
+ if (byte === LF || byte === CR) {
47215
+ if (byte === CR) {
46255
47216
  this.crlfCheck = true;
46256
47217
  }
46257
- this.buffer = this.buffer.subarray(this.pos + 1);
46258
- this.pos = 0;
46259
- if (this.event.data !== void 0 || this.event.event || this.event.id !== void 0 || this.event.retry) {
47218
+ this.consumeCurrentByte();
47219
+ if (this.hasPendingEvent()) {
46260
47220
  this.processEvent(this.event);
46261
47221
  }
46262
47222
  this.clearEvent();
@@ -46265,17 +47225,16 @@ var require_eventsource_stream = __commonJS({
46265
47225
  this.eventEndCheck = false;
46266
47226
  continue;
46267
47227
  }
46268
- if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) {
46269
- if (this.buffer[this.pos] === CR) {
47228
+ if (byte === LF || byte === CR) {
47229
+ if (byte === CR) {
46270
47230
  this.crlfCheck = true;
46271
47231
  }
46272
- this.parseLine(this.buffer.subarray(0, this.pos), this.event);
46273
- this.buffer = this.buffer.subarray(this.pos + 1);
46274
- this.pos = 0;
47232
+ this.parseLine(this.readLine(), this.event);
47233
+ this.consumeCurrentByte();
46275
47234
  this.eventEndCheck = true;
46276
47235
  continue;
46277
47236
  }
46278
- this.pos++;
47237
+ this.advanceCursor();
46279
47238
  }
46280
47239
  callback();
46281
47240
  }
@@ -46291,43 +47250,42 @@ var require_eventsource_stream = __commonJS({
46291
47250
  if (colonPosition === 0) {
46292
47251
  return;
46293
47252
  }
46294
- let field = "";
46295
- let value = "";
47253
+ let fieldLength = line.length;
47254
+ let valueStart = line.length;
46296
47255
  if (colonPosition !== -1) {
46297
- field = line.subarray(0, colonPosition).toString("utf8");
46298
- let valueStart = colonPosition + 1;
47256
+ fieldLength = colonPosition;
47257
+ valueStart = colonPosition + 1;
46299
47258
  if (line[valueStart] === SPACE) {
46300
47259
  ++valueStart;
46301
47260
  }
46302
- value = line.subarray(valueStart).toString("utf8");
46303
- } else {
46304
- field = line.toString("utf8");
46305
- value = "";
46306
47261
  }
46307
- switch (field) {
46308
- case "data":
46309
- if (event[field] === void 0) {
46310
- event[field] = value;
46311
- } else {
46312
- event[field] += `
47262
+ if (isFieldName(line, fieldLength, DATA)) {
47263
+ const value = line.toString("utf8", valueStart);
47264
+ if (event.data === void 0) {
47265
+ event.data = value;
47266
+ } else {
47267
+ event.data += `
46313
47268
  ${value}`;
46314
- }
46315
- break;
46316
- case "retry":
46317
- if (isASCIINumber(value)) {
46318
- event[field] = value;
46319
- }
46320
- break;
46321
- case "id":
46322
- if (isValidLastEventId(value)) {
46323
- event[field] = value;
46324
- }
46325
- break;
46326
- case "event":
46327
- if (value.length > 0) {
46328
- event[field] = value;
46329
- }
46330
- break;
47269
+ }
47270
+ return;
47271
+ }
47272
+ if (isFieldName(line, fieldLength, RETRY)) {
47273
+ if (isASCIINumberBytes(line, valueStart)) {
47274
+ event.retry = line.toString("utf8", valueStart);
47275
+ }
47276
+ return;
47277
+ }
47278
+ if (isFieldName(line, fieldLength, ID)) {
47279
+ if (isValidLastEventIdBytes(line, valueStart)) {
47280
+ event.id = line.toString("utf8", valueStart);
47281
+ }
47282
+ return;
47283
+ }
47284
+ if (isFieldName(line, fieldLength, EVENT)) {
47285
+ const value = line.toString("utf8", valueStart);
47286
+ if (value.length > 0) {
47287
+ event.event = value;
47288
+ }
46331
47289
  }
46332
47290
  }
46333
47291
  /**
@@ -46352,12 +47310,120 @@ ${value}`;
46352
47310
  }
46353
47311
  }
46354
47312
  clearEvent() {
46355
- this.event = {
46356
- data: void 0,
46357
- event: void 0,
46358
- id: void 0,
46359
- retry: void 0
46360
- };
47313
+ this.event.data = void 0;
47314
+ this.event.event = void 0;
47315
+ this.event.id = void 0;
47316
+ this.event.retry = void 0;
47317
+ }
47318
+ hasPendingEvent() {
47319
+ return this.event.data !== void 0 || this.event.event !== void 0 || this.event.id !== void 0 || this.event.retry !== void 0;
47320
+ }
47321
+ hasCurrentByte() {
47322
+ return this.chunkIndex < this.chunks.length && this.pos < this.chunks[this.chunkIndex].length;
47323
+ }
47324
+ currentByte() {
47325
+ return this.chunks[this.chunkIndex][this.pos];
47326
+ }
47327
+ consumeCurrentByte() {
47328
+ this.advanceCursor();
47329
+ this.syncLineStartToCursor();
47330
+ }
47331
+ advanceCursor() {
47332
+ this.pos++;
47333
+ while (this.chunkIndex < this.chunks.length && this.pos >= this.chunks[this.chunkIndex].length) {
47334
+ this.chunkIndex++;
47335
+ this.pos = 0;
47336
+ }
47337
+ }
47338
+ syncLineStartToCursor() {
47339
+ this.lineChunkIndex = this.chunkIndex;
47340
+ this.linePos = this.pos;
47341
+ this.dropConsumedChunks();
47342
+ }
47343
+ dropConsumedChunks() {
47344
+ while (this.lineChunkIndex > 0) {
47345
+ this.chunks.shift();
47346
+ this.lineChunkIndex--;
47347
+ this.chunkIndex--;
47348
+ }
47349
+ if (this.chunkIndex === this.chunks.length) {
47350
+ this.chunks.length = 0;
47351
+ this.chunkIndex = 0;
47352
+ this.pos = 0;
47353
+ this.lineChunkIndex = 0;
47354
+ this.linePos = 0;
47355
+ }
47356
+ }
47357
+ readLine() {
47358
+ if (this.lineChunkIndex === this.chunkIndex) {
47359
+ return this.chunks[this.chunkIndex].subarray(this.linePos, this.pos);
47360
+ }
47361
+ const chunks = [];
47362
+ let length = 0;
47363
+ for (let i = this.lineChunkIndex; i <= this.chunkIndex; i++) {
47364
+ const chunk2 = this.chunks[i];
47365
+ const start = i === this.lineChunkIndex ? this.linePos : 0;
47366
+ const end = i === this.chunkIndex ? this.pos : chunk2.length;
47367
+ const slice = chunk2.subarray(start, end);
47368
+ length += slice.length;
47369
+ chunks.push(slice);
47370
+ }
47371
+ return Buffer.concat(chunks, length);
47372
+ }
47373
+ peekBufferedByte(offset) {
47374
+ let chunkIndex = this.lineChunkIndex;
47375
+ let pos = this.linePos;
47376
+ while (chunkIndex < this.chunks.length) {
47377
+ const chunk2 = this.chunks[chunkIndex];
47378
+ const remaining = chunk2.length - pos;
47379
+ if (offset < remaining) {
47380
+ return chunk2[pos + offset];
47381
+ }
47382
+ offset -= remaining;
47383
+ chunkIndex++;
47384
+ pos = 0;
47385
+ }
47386
+ }
47387
+ discardLeadingBytes(count) {
47388
+ while (count > 0 && this.lineChunkIndex < this.chunks.length) {
47389
+ const chunk2 = this.chunks[this.lineChunkIndex];
47390
+ const remaining = chunk2.length - this.linePos;
47391
+ if (count < remaining) {
47392
+ this.linePos += count;
47393
+ count = 0;
47394
+ } else {
47395
+ count -= remaining;
47396
+ this.lineChunkIndex++;
47397
+ this.linePos = 0;
47398
+ }
47399
+ }
47400
+ this.chunkIndex = this.lineChunkIndex;
47401
+ this.pos = this.linePos;
47402
+ this.dropConsumedChunks();
47403
+ }
47404
+ handleBOM() {
47405
+ const first = this.peekBufferedByte(0);
47406
+ const second = this.peekBufferedByte(1);
47407
+ const third = this.peekBufferedByte(2);
47408
+ if (second === void 0) {
47409
+ if (first === BOM[0]) {
47410
+ return true;
47411
+ }
47412
+ this.checkBOM = false;
47413
+ return true;
47414
+ }
47415
+ if (third === void 0) {
47416
+ if (first === BOM[0] && second === BOM[1]) {
47417
+ return true;
47418
+ }
47419
+ this.checkBOM = false;
47420
+ return false;
47421
+ }
47422
+ if (first === BOM[0] && second === BOM[1] && third === BOM[2]) {
47423
+ this.discardLeadingBytes(3);
47424
+ }
47425
+ this.checkBOM = false;
47426
+ return !this.hasCurrentByte();
46361
47427
  }
46362
47428
  };
46363
47429
  module.exports = {