@node9/proxy 2.8.3 → 2.8.5

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.
package/dist/cli.mjs CHANGED
@@ -3513,6 +3513,10 @@ var init_dist = __esm({
3513
3513
  deriveRedirOp("cat <<-X\nX")
3514
3514
  ]);
3515
3515
  DEFAULT_EGRESS_ALLOWLIST = [
3516
+ // node9's own control plane (api, app, dev-api, staging and the apex).
3517
+ // Without it, turning egress on asks the user to approve node9 itself.
3518
+ // A user `deny` entry still wins over this list, see evaluateEgress.
3519
+ "*.node9.ai",
3516
3520
  "*.github.com",
3517
3521
  "*.githubusercontent.com",
3518
3522
  "*.npmjs.org",
@@ -24179,6 +24183,18 @@ var require_request = __commonJS({
24179
24183
  var { channels } = require_diagnostics();
24180
24184
  var { headerNameLowerCasedRecord } = require_constants();
24181
24185
  var invalidPathRegex = /[^\u0021-\u00ff]/;
24186
+ function isValidContentLengthHeaderValue(val) {
24187
+ if (typeof val !== "string" || val.length === 0) {
24188
+ return false;
24189
+ }
24190
+ for (let i = 0; i < val.length; i++) {
24191
+ const charCode = val.charCodeAt(i);
24192
+ if (charCode < 48 || charCode > 57) {
24193
+ return false;
24194
+ }
24195
+ }
24196
+ return true;
24197
+ }
24182
24198
  var kHandler = /* @__PURE__ */ Symbol("handler");
24183
24199
  var Request = class {
24184
24200
  constructor(origin, {
@@ -24453,7 +24469,11 @@ var require_request = __commonJS({
24453
24469
  } else if (typeof val[i] === "object") {
24454
24470
  throw new InvalidArgumentError(`invalid ${key} header`);
24455
24471
  } else {
24456
- arr.push(`${val[i]}`);
24472
+ const str2 = `${val[i]}`;
24473
+ if (!isValidHeaderValue(str2)) {
24474
+ throw new InvalidArgumentError(`invalid ${key} header`);
24475
+ }
24476
+ arr.push(str2);
24457
24477
  }
24458
24478
  }
24459
24479
  val = arr;
@@ -24465,6 +24485,9 @@ var require_request = __commonJS({
24465
24485
  val = "";
24466
24486
  } else {
24467
24487
  val = `${val}`;
24488
+ if (!isValidHeaderValue(val)) {
24489
+ throw new InvalidArgumentError(`invalid ${key} header`);
24490
+ }
24468
24491
  }
24469
24492
  if (headerName === "host") {
24470
24493
  if (request2.host !== null) {
@@ -24478,10 +24501,10 @@ var require_request = __commonJS({
24478
24501
  if (request2.contentLength !== null) {
24479
24502
  throw new InvalidArgumentError("duplicate content-length header");
24480
24503
  }
24481
- request2.contentLength = parseInt(val, 10);
24482
- if (!Number.isFinite(request2.contentLength)) {
24504
+ if (!isValidContentLengthHeaderValue(val)) {
24483
24505
  throw new InvalidArgumentError("invalid content-length header");
24484
24506
  }
24507
+ request2.contentLength = parseInt(val, 10);
24485
24508
  } else if (request2.contentType === null && headerName === "content-type") {
24486
24509
  request2.contentType = val;
24487
24510
  request2.headers.push(key, val);
@@ -24649,6 +24672,8 @@ var require_unwrap_handler = __commonJS({
24649
24672
  #aborted = false;
24650
24673
  #abort;
24651
24674
  [kResume] = null;
24675
+ rawHeaders = null;
24676
+ rawTrailers = null;
24652
24677
  constructor(abort) {
24653
24678
  this.#abort = abort;
24654
24679
  }
@@ -24695,10 +24720,12 @@ var require_unwrap_handler = __commonJS({
24695
24720
  return this.#handler.onResponseStarted?.();
24696
24721
  }
24697
24722
  onUpgrade(statusCode, rawHeaders, socket) {
24723
+ this.#controller.rawHeaders = rawHeaders;
24698
24724
  this.#handler.onRequestUpgrade?.(this.#controller, statusCode, parseHeaders(rawHeaders), socket);
24699
24725
  }
24700
24726
  onHeaders(statusCode, rawHeaders, resume, statusMessage) {
24701
24727
  this.#controller[kResume] = resume;
24728
+ this.#controller.rawHeaders = rawHeaders;
24702
24729
  this.#handler.onResponseStart?.(this.#controller, statusCode, parseHeaders(rawHeaders), statusMessage);
24703
24730
  return !this.#controller.paused;
24704
24731
  }
@@ -24707,6 +24734,7 @@ var require_unwrap_handler = __commonJS({
24707
24734
  return !this.#controller.paused;
24708
24735
  }
24709
24736
  onComplete(rawTrailers) {
24737
+ this.#controller.rawTrailers = rawTrailers;
24710
24738
  this.#handler.onResponseEnd?.(this.#controller, parseHeaders(rawTrailers));
24711
24739
  }
24712
24740
  onError(err2) {
@@ -24733,6 +24761,7 @@ var require_dispatcher_base = __commonJS({
24733
24761
  var { kDestroy, kClose, kClosed, kDestroyed, kDispatch } = require_symbols();
24734
24762
  var kOnDestroyed = /* @__PURE__ */ Symbol("onDestroyed");
24735
24763
  var kOnClosed = /* @__PURE__ */ Symbol("onClosed");
24764
+ var kWebSocketOptions = /* @__PURE__ */ Symbol("webSocketOptions");
24736
24765
  var DispatcherBase = class extends Dispatcher {
24737
24766
  /** @type {boolean} */
24738
24767
  [kDestroyed] = false;
@@ -24742,6 +24771,23 @@ var require_dispatcher_base = __commonJS({
24742
24771
  [kClosed] = false;
24743
24772
  /** @type {Array<Function>|null} */
24744
24773
  [kOnClosed] = null;
24774
+ /**
24775
+ * @param {import('../../types/dispatcher').DispatcherOptions} [opts]
24776
+ */
24777
+ constructor(opts) {
24778
+ super();
24779
+ this[kWebSocketOptions] = opts?.webSocket ?? {};
24780
+ }
24781
+ /**
24782
+ * @returns {import('../../types/dispatcher').WebSocketOptions}
24783
+ */
24784
+ get webSocketOptions() {
24785
+ return {
24786
+ maxFragments: this[kWebSocketOptions].maxFragments ?? 131072,
24787
+ maxPayloadSize: this[kWebSocketOptions].maxPayloadSize ?? 128 * 1024 * 1024
24788
+ // 128 MB default
24789
+ };
24790
+ }
24745
24791
  /** @returns {boolean} */
24746
24792
  get destroyed() {
24747
24793
  return this[kDestroyed];
@@ -24884,6 +24930,20 @@ var require_connect = __commonJS({
24884
24930
  if (this._maxCachedSessions === 0) {
24885
24931
  return;
24886
24932
  }
24933
+ if (this._sessionCache.has(sessionKey)) {
24934
+ this._sessionCache.delete(sessionKey);
24935
+ } else if (this._sessionCache.size >= this._maxCachedSessions) {
24936
+ for (const [key, ref] of this._sessionCache) {
24937
+ if (ref.deref() === void 0) {
24938
+ this._sessionCache.delete(key);
24939
+ return;
24940
+ }
24941
+ }
24942
+ const oldest = this._sessionCache.keys().next();
24943
+ if (!oldest.done) {
24944
+ this._sessionCache.delete(oldest.value);
24945
+ }
24946
+ }
24887
24947
  this._sessionCache.set(sessionKey, new WeakRef(session));
24888
24948
  this._sessionRegistry.register(session, sessionKey);
24889
24949
  }
@@ -26551,7 +26611,7 @@ var require_webidl = __commonJS({
26551
26611
  lowerBound = 0;
26552
26612
  upperBound = Math.pow(2, bitLength) - 1;
26553
26613
  } else {
26554
- lowerBound = Math.pow(-2, bitLength) - 1;
26614
+ lowerBound = -Math.pow(2, bitLength - 1);
26555
26615
  upperBound = Math.pow(2, bitLength - 1) - 1;
26556
26616
  }
26557
26617
  let x = Number(V);
@@ -26588,7 +26648,7 @@ var require_webidl = __commonJS({
26588
26648
  }
26589
26649
  x = webidl.util.IntegerPart(x);
26590
26650
  x = x % Math.pow(2, bitLength);
26591
- if (signedness === "signed" && x >= Math.pow(2, bitLength) - 1) {
26651
+ if (signedness === "signed" && x >= Math.pow(2, bitLength - 1)) {
26592
26652
  return x - Math.pow(2, bitLength);
26593
26653
  }
26594
26654
  return x;
@@ -27711,7 +27771,7 @@ var require_util2 = __commonJS({
27711
27771
  return !!(url.username || url.password);
27712
27772
  }
27713
27773
  function isTraversableNavigable(navigable) {
27714
- return true;
27774
+ return navigable != null && navigable !== "client" && navigable !== "no-traversable";
27715
27775
  }
27716
27776
  var EnvironmentSettingsObjectBase = class {
27717
27777
  get baseUrl() {
@@ -28106,7 +28166,7 @@ var require_formdata_parser = __commonJS({
28106
28166
  );
28107
28167
  value = decoder.decode(tokenValue);
28108
28168
  }
28109
- return { name: attrNameStr, value };
28169
+ return { name: attrNameStr, value, extended: isExtended };
28110
28170
  }
28111
28171
  function parseMultipartFormDataHeaders(input, position) {
28112
28172
  let name = null;
@@ -28141,6 +28201,7 @@ var require_formdata_parser = __commonJS({
28141
28201
  switch (bufferToLowerCasedHeaderName(headerName)) {
28142
28202
  case "content-disposition": {
28143
28203
  name = filename = null;
28204
+ let filenameIsExtended = false;
28144
28205
  const dispositionType = collectASequenceOfBytes(
28145
28206
  (char) => isToken(char),
28146
28207
  input,
@@ -28149,7 +28210,7 @@ var require_formdata_parser = __commonJS({
28149
28210
  if (dispositionType.toString("ascii").toLowerCase() !== "form-data") {
28150
28211
  throw parsingError("expected form-data for content-disposition header");
28151
28212
  }
28152
- while (position.position < input.length && input[position.position] !== 13 && input[position.position + 1] !== 10) {
28213
+ while (position.position < input.length && (input[position.position] !== 13 || input[position.position + 1] !== 10)) {
28153
28214
  const attribute = parseContentDispositionAttribute(input, position);
28154
28215
  if (!attribute) {
28155
28216
  break;
@@ -28157,7 +28218,12 @@ var require_formdata_parser = __commonJS({
28157
28218
  if (attribute.name === "name") {
28158
28219
  name = attribute.value;
28159
28220
  } else if (attribute.name === "filename") {
28160
- filename = attribute.value;
28221
+ if (attribute.extended) {
28222
+ filename = attribute.value;
28223
+ filenameIsExtended = true;
28224
+ } else if (!filenameIsExtended) {
28225
+ filename = attribute.value;
28226
+ }
28161
28227
  }
28162
28228
  }
28163
28229
  if (name === null) {
@@ -28193,7 +28259,7 @@ var require_formdata_parser = __commonJS({
28193
28259
  );
28194
28260
  }
28195
28261
  }
28196
- if (input[position.position] !== 13 && input[position.position + 1] !== 10) {
28262
+ if (input[position.position] !== 13 || input[position.position + 1] !== 10) {
28197
28263
  throw parsingError("expected CRLF");
28198
28264
  } else {
28199
28265
  position.position += 2;
@@ -28578,6 +28644,7 @@ var require_client_h1 = __commonJS({
28578
28644
  RequestContentLengthMismatchError,
28579
28645
  ResponseContentLengthMismatchError,
28580
28646
  RequestAbortedError,
28647
+ InvalidArgumentError,
28581
28648
  HeadersTimeoutError,
28582
28649
  HeadersOverflowError,
28583
28650
  SocketError,
@@ -28624,15 +28691,18 @@ var require_client_h1 = __commonJS({
28624
28691
  var EMPTY_BUF = Buffer.alloc(0);
28625
28692
  var FastBuffer = Buffer[Symbol.species];
28626
28693
  var removeAllListeners = util.removeAllListeners;
28694
+ var kIdleSocketValidation = /* @__PURE__ */ Symbol("kIdleSocketValidation");
28695
+ var kIdleSocketValidationTimeout = /* @__PURE__ */ Symbol("kIdleSocketValidationTimeout");
28696
+ var kSocketUsed = /* @__PURE__ */ Symbol("kSocketUsed");
28627
28697
  var extractBody;
28628
28698
  function lazyllhttp() {
28629
28699
  const llhttpWasmData = process.env.JEST_WORKER_ID ? require_llhttp_wasm() : void 0;
28630
28700
  let mod;
28631
28701
  let useWasmSIMD = process.arch !== "ppc64";
28632
28702
  if (process.env.UNDICI_NO_WASM_SIMD === "1") {
28633
- useWasmSIMD = true;
28634
- } else if (process.env.UNDICI_NO_WASM_SIMD === "0") {
28635
28703
  useWasmSIMD = false;
28704
+ } else if (process.env.UNDICI_NO_WASM_SIMD === "0") {
28705
+ useWasmSIMD = true;
28636
28706
  }
28637
28707
  if (useWasmSIMD) {
28638
28708
  try {
@@ -28750,6 +28820,7 @@ var require_client_h1 = __commonJS({
28750
28820
  this.client = client;
28751
28821
  this.socket = socket;
28752
28822
  this.timeout = null;
28823
+ this.timeoutWeakRef = new WeakRef(this);
28753
28824
  this.timeoutValue = null;
28754
28825
  this.timeoutType = null;
28755
28826
  this.statusCode = 0;
@@ -28775,9 +28846,9 @@ var require_client_h1 = __commonJS({
28775
28846
  }
28776
28847
  if (delay) {
28777
28848
  if (type & USE_FAST_TIMER) {
28778
- this.timeout = timers.setFastTimeout(onParserTimeout, delay, new WeakRef(this));
28849
+ this.timeout = timers.setFastTimeout(onParserTimeout, delay, this.timeoutWeakRef);
28779
28850
  } else {
28780
- this.timeout = setTimeout(onParserTimeout, delay, new WeakRef(this));
28851
+ this.timeout = setTimeout(onParserTimeout, delay, this.timeoutWeakRef);
28781
28852
  this.timeout?.unref();
28782
28853
  }
28783
28854
  }
@@ -28849,19 +28920,47 @@ var require_client_h1 = __commonJS({
28849
28920
  this.paused = true;
28850
28921
  socket.unshift(data);
28851
28922
  } 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);
28923
+ throw this.createError(ret, data);
28859
28924
  }
28860
28925
  }
28861
28926
  } catch (err2) {
28862
28927
  util.destroy(socket, err2);
28863
28928
  }
28864
28929
  }
28930
+ finish() {
28931
+ assert(currentParser === null);
28932
+ assert(this.ptr != null);
28933
+ assert(!this.paused);
28934
+ const { llhttp } = this;
28935
+ let ret;
28936
+ try {
28937
+ currentParser = this;
28938
+ ret = llhttp.llhttp_finish(this.ptr);
28939
+ } finally {
28940
+ currentParser = null;
28941
+ }
28942
+ if (ret === constants.ERROR.OK) {
28943
+ return null;
28944
+ }
28945
+ if (ret === constants.ERROR.PAUSED || ret === constants.ERROR.PAUSED_UPGRADE) {
28946
+ this.paused = true;
28947
+ return null;
28948
+ }
28949
+ return this.createError(ret, EMPTY_BUF);
28950
+ }
28951
+ createError(ret, data) {
28952
+ const { llhttp, contentLength, bytesRead } = this;
28953
+ if (contentLength && bytesRead !== parseInt(contentLength, 10)) {
28954
+ return new ResponseContentLengthMismatchError();
28955
+ }
28956
+ const ptr = llhttp.llhttp_get_error_reason(this.ptr);
28957
+ let message = "";
28958
+ if (ptr) {
28959
+ const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0);
28960
+ message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")";
28961
+ }
28962
+ return new HTTPParserError(message, constants.ERROR[ret], data);
28963
+ }
28865
28964
  destroy() {
28866
28965
  assert(currentParser === null);
28867
28966
  assert(this.ptr != null);
@@ -28889,6 +28988,10 @@ var require_client_h1 = __commonJS({
28889
28988
  if (socket.destroyed) {
28890
28989
  return -1;
28891
28990
  }
28991
+ if (client[kRunning] === 0) {
28992
+ util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket)));
28993
+ return -1;
28994
+ }
28892
28995
  const request2 = client[kQueue][client[kRunningIdx]];
28893
28996
  if (!request2) {
28894
28997
  return -1;
@@ -28991,6 +29094,10 @@ var require_client_h1 = __commonJS({
28991
29094
  if (socket.destroyed) {
28992
29095
  return -1;
28993
29096
  }
29097
+ if (client[kRunning] === 0) {
29098
+ util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket)));
29099
+ return -1;
29100
+ }
28994
29101
  const request2 = client[kQueue][client[kRunningIdx]];
28995
29102
  if (!request2) {
28996
29103
  return -1;
@@ -29124,6 +29231,7 @@ var require_client_h1 = __commonJS({
29124
29231
  }
29125
29232
  request2.onComplete(headers);
29126
29233
  client[kQueue][client[kRunningIdx]++] = null;
29234
+ socket[kSocketUsed] = client[kPending] === 0;
29127
29235
  if (socket[kWriting]) {
29128
29236
  assert(client[kRunning] === 0);
29129
29237
  util.destroy(socket, new InformationalError("reset"));
@@ -29177,6 +29285,9 @@ var require_client_h1 = __commonJS({
29177
29285
  socket[kWriting] = false;
29178
29286
  socket[kReset] = false;
29179
29287
  socket[kBlocking] = false;
29288
+ socket[kIdleSocketValidation] = 0;
29289
+ socket[kIdleSocketValidationTimeout] = null;
29290
+ socket[kSocketUsed] = false;
29180
29291
  socket[kParser] = new Parser(client, socket, llhttpInstance);
29181
29292
  util.addListener(socket, "error", onHttpSocketError);
29182
29293
  util.addListener(socket, "readable", onHttpSocketReadable);
@@ -29216,7 +29327,7 @@ var require_client_h1 = __commonJS({
29216
29327
  * @returns {boolean}
29217
29328
  */
29218
29329
  busy(request2) {
29219
- if (socket[kWriting] || socket[kReset] || socket[kBlocking]) {
29330
+ if (socket[kWriting] || socket[kReset] || socket[kBlocking] || socket[kIdleSocketValidation] === 1) {
29220
29331
  return true;
29221
29332
  }
29222
29333
  if (request2) {
@@ -29238,7 +29349,11 @@ var require_client_h1 = __commonJS({
29238
29349
  assert(err2.code !== "ERR_TLS_CERT_ALTNAME_INVALID");
29239
29350
  const parser = this[kParser];
29240
29351
  if (err2.code === "ECONNRESET" && parser.statusCode && !parser.shouldKeepAlive) {
29241
- parser.onMessageComplete();
29352
+ const parserErr = parser.finish();
29353
+ if (parserErr) {
29354
+ this[kError] = parserErr;
29355
+ this[kClient][kOnError](parserErr);
29356
+ }
29242
29357
  return;
29243
29358
  }
29244
29359
  this[kError] = err2;
@@ -29250,16 +29365,20 @@ var require_client_h1 = __commonJS({
29250
29365
  function onHttpSocketEnd() {
29251
29366
  const parser = this[kParser];
29252
29367
  if (parser.statusCode && !parser.shouldKeepAlive) {
29253
- parser.onMessageComplete();
29368
+ const parserErr = parser.finish();
29369
+ if (parserErr) {
29370
+ util.destroy(this, parserErr);
29371
+ }
29254
29372
  return;
29255
29373
  }
29256
29374
  util.destroy(this, new SocketError("other side closed", util.getSocketInfo(this)));
29257
29375
  }
29258
29376
  function onHttpSocketClose() {
29259
29377
  const parser = this[kParser];
29378
+ clearIdleSocketValidation(this);
29260
29379
  if (parser) {
29261
29380
  if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) {
29262
- parser.onMessageComplete();
29381
+ this[kError] = parser.finish() || this[kError];
29263
29382
  }
29264
29383
  this[kParser].destroy();
29265
29384
  this[kParser] = null;
@@ -29288,6 +29407,23 @@ var require_client_h1 = __commonJS({
29288
29407
  function onSocketClose() {
29289
29408
  this[kClosed] = true;
29290
29409
  }
29410
+ function clearIdleSocketValidation(socket) {
29411
+ if (socket[kIdleSocketValidationTimeout]) {
29412
+ clearImmediate(socket[kIdleSocketValidationTimeout]);
29413
+ socket[kIdleSocketValidationTimeout] = null;
29414
+ }
29415
+ socket[kIdleSocketValidation] = 0;
29416
+ }
29417
+ function scheduleIdleSocketValidation(client, socket) {
29418
+ socket[kIdleSocketValidation] = 1;
29419
+ socket[kIdleSocketValidationTimeout] = setImmediate(() => {
29420
+ socket[kIdleSocketValidationTimeout] = null;
29421
+ socket[kIdleSocketValidation] = 2;
29422
+ if (client[kSocket] === socket && !socket.destroyed) {
29423
+ client[kResume]();
29424
+ }
29425
+ });
29426
+ }
29291
29427
  function resumeH1(client) {
29292
29428
  const socket = client[kSocket];
29293
29429
  if (socket && !socket.destroyed) {
@@ -29300,6 +29436,29 @@ var require_client_h1 = __commonJS({
29300
29436
  socket.ref();
29301
29437
  socket[kNoRef] = false;
29302
29438
  }
29439
+ if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) {
29440
+ if (socket[kIdleSocketValidation] === 0) {
29441
+ scheduleIdleSocketValidation(client, socket);
29442
+ socket[kParser].readMore();
29443
+ if (socket.destroyed) {
29444
+ return;
29445
+ }
29446
+ return;
29447
+ }
29448
+ if (socket[kIdleSocketValidation] === 1) {
29449
+ socket[kParser].readMore();
29450
+ if (socket.destroyed) {
29451
+ return;
29452
+ }
29453
+ return;
29454
+ }
29455
+ }
29456
+ if (client[kRunning] === 0) {
29457
+ socket[kParser].readMore();
29458
+ if (socket.destroyed) {
29459
+ return;
29460
+ }
29461
+ }
29303
29462
  if (client[kSize] === 0) {
29304
29463
  if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) {
29305
29464
  socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE);
@@ -29330,8 +29489,16 @@ var require_client_h1 = __commonJS({
29330
29489
  }
29331
29490
  body = bodyStream.stream;
29332
29491
  contentLength = bodyStream.length;
29333
- } else if (util.isBlobLike(body) && request2.contentType == null && body.type) {
29334
- headers.push("content-type", body.type);
29492
+ } else if (util.isBlobLike(body) && request2.contentType == null) {
29493
+ const contentType = body.type;
29494
+ if (contentType) {
29495
+ const contentTypeValue = `${contentType}`;
29496
+ if (!util.isValidHeaderValue(contentTypeValue)) {
29497
+ util.errorRequest(client, request2, new InvalidArgumentError("invalid content-type header"));
29498
+ return false;
29499
+ }
29500
+ headers.push("content-type", contentTypeValue);
29501
+ }
29335
29502
  }
29336
29503
  if (body && typeof body.read === "function") {
29337
29504
  body.read(0);
@@ -29352,6 +29519,7 @@ var require_client_h1 = __commonJS({
29352
29519
  process.emitWarning(new RequestContentLengthMismatchError());
29353
29520
  }
29354
29521
  const socket = client[kSocket];
29522
+ clearIdleSocketValidation(socket);
29355
29523
  const abort = (err2) => {
29356
29524
  if (request2.aborted || request2.completed) {
29357
29525
  return;
@@ -29744,7 +29912,9 @@ var require_client_h2 = __commonJS({
29744
29912
  RequestAbortedError,
29745
29913
  SocketError,
29746
29914
  InformationalError,
29747
- InvalidArgumentError
29915
+ InvalidArgumentError,
29916
+ HeadersTimeoutError,
29917
+ BodyTimeoutError
29748
29918
  } = require_errors();
29749
29919
  var {
29750
29920
  kUrl,
@@ -29769,6 +29939,7 @@ var require_client_h2 = __commonJS({
29769
29939
  kHTTPContext,
29770
29940
  kClosed,
29771
29941
  kBodyTimeout,
29942
+ kHeadersTimeout,
29772
29943
  kEnableConnectProtocol,
29773
29944
  kRemoteSettings,
29774
29945
  kHTTP2Stream,
@@ -29905,7 +30076,7 @@ var require_client_h2 = __commonJS({
29905
30076
  function resumeH2(client) {
29906
30077
  const socket = client[kSocket];
29907
30078
  if (socket?.destroyed === false) {
29908
- if (client[kSize] === 0 || client[kMaxConcurrentStreams] === 0) {
30079
+ if (client[kSize] === 0) {
29909
30080
  socket.unref();
29910
30081
  client[kHTTP2Session].unref();
29911
30082
  } else {
@@ -29971,6 +30142,24 @@ var require_client_h2 = __commonJS({
29971
30142
  this.destroy(err2);
29972
30143
  util.destroy(this[kSocket], err2);
29973
30144
  }
30145
+ function completeRequest(client, request2, resetPendingIdx = false) {
30146
+ const queue = client[kQueue];
30147
+ const runningIdx = client[kRunningIdx];
30148
+ if (runningIdx < client[kPendingIdx] && queue[runningIdx] === request2) {
30149
+ queue[runningIdx] = null;
30150
+ client[kRunningIdx] = runningIdx + 1;
30151
+ return;
30152
+ }
30153
+ const index = queue.indexOf(request2, runningIdx);
30154
+ if (index === -1 || index >= client[kPendingIdx]) {
30155
+ return;
30156
+ }
30157
+ queue.splice(index, 1);
30158
+ client[kPendingIdx]--;
30159
+ if (resetPendingIdx && client[kPendingIdx] < client[kRunningIdx]) {
30160
+ client[kPendingIdx] = client[kRunningIdx];
30161
+ }
30162
+ }
29974
30163
  function onHttp2SessionGoAway(errorCode) {
29975
30164
  const err2 = this[kError] || new SocketError(`HTTP/2: "GOAWAY" frame received with code ${errorCode}`, util.getSocketInfo(this[kSocket]));
29976
30165
  const client = this[kClient];
@@ -29982,7 +30171,9 @@ var require_client_h2 = __commonJS({
29982
30171
  if (client[kRunningIdx] < client[kQueue].length) {
29983
30172
  const request2 = client[kQueue][client[kRunningIdx]];
29984
30173
  client[kQueue][client[kRunningIdx]++] = null;
29985
- util.errorRequest(client, request2, err2);
30174
+ if (request2 != null) {
30175
+ util.errorRequest(client, request2, err2);
30176
+ }
29986
30177
  client[kPendingIdx] = client[kRunningIdx];
29987
30178
  }
29988
30179
  assert(client[kRunning] === 0);
@@ -30005,7 +30196,9 @@ var require_client_h2 = __commonJS({
30005
30196
  const requests = client[kQueue].splice(client[kRunningIdx]);
30006
30197
  for (let i = 0; i < requests.length; i++) {
30007
30198
  const request2 = requests[i];
30008
- util.errorRequest(client, request2, err2);
30199
+ if (request2 != null) {
30200
+ util.errorRequest(client, request2, err2);
30201
+ }
30009
30202
  }
30010
30203
  }
30011
30204
  }
@@ -30037,7 +30230,8 @@ var require_client_h2 = __commonJS({
30037
30230
  return method !== "GET" && method !== "HEAD" && method !== "OPTIONS" && method !== "TRACE" && method !== "CONNECT";
30038
30231
  }
30039
30232
  function writeH2(client, request2) {
30040
- const requestTimeout = request2.bodyTimeout ?? client[kBodyTimeout];
30233
+ const headersTimeout = request2.headersTimeout ?? client[kHeadersTimeout];
30234
+ const bodyTimeout = request2.bodyTimeout ?? client[kBodyTimeout];
30041
30235
  const session = client[kHTTP2Session];
30042
30236
  const { method, path: path74, host, upgrade, expectContinue, signal, protocol, headers: reqHeaders } = request2;
30043
30237
  let { body } = request2;
@@ -30085,6 +30279,7 @@ var require_client_h2 = __commonJS({
30085
30279
  stream.removeAllListeners("data");
30086
30280
  stream.close();
30087
30281
  client[kOnError](err2);
30282
+ completeRequest(client, request2);
30088
30283
  client[kResume]();
30089
30284
  }
30090
30285
  util.destroy(body, err2);
@@ -30119,7 +30314,7 @@ var require_client_h2 = __commonJS({
30119
30314
  const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers2;
30120
30315
  request2.onUpgrade(statusCode, parseH2Headers(realHeaders), stream);
30121
30316
  ++session[kOpenStreams];
30122
- client[kQueue][client[kRunningIdx]++] = null;
30317
+ completeRequest(client, request2);
30123
30318
  });
30124
30319
  stream.on("error", () => {
30125
30320
  if (stream.rstCode === NGHTTP2_REFUSED_STREAM || stream.rstCode === NGHTTP2_CANCEL) {
@@ -30130,7 +30325,7 @@ var require_client_h2 = __commonJS({
30130
30325
  session[kOpenStreams] -= 1;
30131
30326
  if (session[kOpenStreams] === 0) session.unref();
30132
30327
  });
30133
- stream.setTimeout(requestTimeout);
30328
+ stream.setTimeout(headersTimeout);
30134
30329
  return true;
30135
30330
  }
30136
30331
  stream = session.request(headers, { endStream: false, signal });
@@ -30139,13 +30334,14 @@ var require_client_h2 = __commonJS({
30139
30334
  const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers2;
30140
30335
  request2.onUpgrade(statusCode, parseH2Headers(realHeaders), stream);
30141
30336
  ++session[kOpenStreams];
30142
- client[kQueue][client[kRunningIdx]++] = null;
30337
+ completeRequest(client, request2);
30143
30338
  });
30339
+ stream.on("error", abort);
30144
30340
  stream.once("close", () => {
30145
30341
  session[kOpenStreams] -= 1;
30146
30342
  if (session[kOpenStreams] === 0) session.unref();
30147
30343
  });
30148
- stream.setTimeout(requestTimeout);
30344
+ stream.setTimeout(headersTimeout);
30149
30345
  return true;
30150
30346
  }
30151
30347
  headers[HTTP2_HEADER_PATH] = path74;
@@ -30203,12 +30399,13 @@ var require_client_h2 = __commonJS({
30203
30399
  writeBodyH2();
30204
30400
  }
30205
30401
  ++session[kOpenStreams];
30206
- stream.setTimeout(requestTimeout);
30402
+ stream.setTimeout(headersTimeout);
30207
30403
  let responseReceived = false;
30208
30404
  stream.once("response", (headers2) => {
30209
30405
  const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers2;
30210
30406
  request2.onResponseStarted();
30211
30407
  responseReceived = true;
30408
+ stream.setTimeout(bodyTimeout);
30212
30409
  if (request2.aborted) {
30213
30410
  stream.removeAllListeners("data");
30214
30411
  return;
@@ -30231,12 +30428,11 @@ var require_client_h2 = __commonJS({
30231
30428
  if (!request2.aborted && !request2.completed) {
30232
30429
  request2.onComplete({});
30233
30430
  }
30234
- client[kQueue][client[kRunningIdx]++] = null;
30431
+ completeRequest(client, request2);
30235
30432
  client[kResume]();
30236
30433
  } else {
30237
30434
  abort(new InformationalError("HTTP/2: stream half-closed (remote)"));
30238
- client[kQueue][client[kRunningIdx]++] = null;
30239
- client[kPendingIdx] = client[kRunningIdx];
30435
+ completeRequest(client, request2, true);
30240
30436
  client[kResume]();
30241
30437
  }
30242
30438
  });
@@ -30246,6 +30442,9 @@ var require_client_h2 = __commonJS({
30246
30442
  if (session[kOpenStreams] === 0) {
30247
30443
  session.unref();
30248
30444
  }
30445
+ if (!request2.aborted && !request2.completed) {
30446
+ abort(new InformationalError("HTTP/2: stream closed before the response was complete"));
30447
+ }
30249
30448
  });
30250
30449
  stream.once("error", function(err2) {
30251
30450
  stream.removeAllListeners("data");
@@ -30259,7 +30458,7 @@ var require_client_h2 = __commonJS({
30259
30458
  stream.removeAllListeners("data");
30260
30459
  });
30261
30460
  stream.on("timeout", () => {
30262
- const err2 = new InformationalError(`HTTP/2: "stream timeout after ${requestTimeout}"`);
30461
+ const err2 = responseReceived ? new BodyTimeoutError(`HTTP/2: "body timeout after ${bodyTimeout}"`) : new HeadersTimeoutError(`HTTP/2: "headers timeout after ${headersTimeout}"`);
30263
30462
  stream.removeAllListeners("data");
30264
30463
  session[kOpenStreams] -= 1;
30265
30464
  if (session[kOpenStreams] === 0) {
@@ -30567,7 +30766,8 @@ var require_client = __commonJS({
30567
30766
  useH2c,
30568
30767
  initialWindowSize,
30569
30768
  connectionWindowSize,
30570
- pingInterval
30769
+ pingInterval,
30770
+ webSocket
30571
30771
  } = {}) {
30572
30772
  if (keepAlive !== void 0) {
30573
30773
  throw new InvalidArgumentError("unsupported keepAlive, use pipelining=0 instead");
@@ -30645,7 +30845,7 @@ var require_client = __commonJS({
30645
30845
  if (pingInterval != null && (typeof pingInterval !== "number" || !Number.isInteger(pingInterval) || pingInterval < 0)) {
30646
30846
  throw new InvalidArgumentError("pingInterval must be a positive integer, greater or equal to 0");
30647
30847
  }
30648
- super();
30848
+ super({ webSocket });
30649
30849
  if (typeof connect2 !== "function") {
30650
30850
  connect2 = buildConnector({
30651
30851
  ...tls,
@@ -30657,9 +30857,13 @@ var require_client = __commonJS({
30657
30857
  ...typeof autoSelectFamily === "boolean" ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : void 0,
30658
30858
  ...connect2
30659
30859
  });
30660
- } else if (socketPath != null) {
30860
+ } else {
30661
30861
  const customConnect = connect2;
30662
- connect2 = (opts, callback) => customConnect({ ...opts, socketPath }, callback);
30862
+ connect2 = (opts, callback) => customConnect({
30863
+ ...opts,
30864
+ ...socketPath != null ? { socketPath } : null,
30865
+ ...allowH2 != null ? { allowH2 } : null
30866
+ }, callback);
30663
30867
  }
30664
30868
  this[kUrl] = util.parseOrigin(url);
30665
30869
  this[kConnector] = connect2;
@@ -30752,7 +30956,9 @@ var require_client = __commonJS({
30752
30956
  const requests = this[kQueue].splice(this[kPendingIdx]);
30753
30957
  for (let i = 0; i < requests.length; i++) {
30754
30958
  const request2 = requests[i];
30755
- util.errorRequest(this, request2, err2);
30959
+ if (request2 != null) {
30960
+ util.errorRequest(this, request2, err2);
30961
+ }
30756
30962
  }
30757
30963
  const callback = () => {
30758
30964
  if (this[kClosedResolve]) {
@@ -30777,7 +30983,9 @@ var require_client = __commonJS({
30777
30983
  const requests = client[kQueue].splice(client[kRunningIdx]);
30778
30984
  for (let i = 0; i < requests.length; i++) {
30779
30985
  const request2 = requests[i];
30780
- util.errorRequest(client, request2, err2);
30986
+ if (request2 != null) {
30987
+ util.errorRequest(client, request2, err2);
30988
+ }
30781
30989
  }
30782
30990
  assert(client[kSize] === 0);
30783
30991
  }
@@ -31288,7 +31496,7 @@ var require_pool = __commonJS({
31288
31496
  ...connect
31289
31497
  });
31290
31498
  }
31291
- super();
31499
+ super(options);
31292
31500
  this[kConnections] = connections || null;
31293
31501
  this[kUrl] = util.parseOrigin(origin);
31294
31502
  this[kOptions] = { ...util.deepClone(options), connect, allowH2, clientTtl, socketPath };
@@ -31370,12 +31578,14 @@ var require_balanced_pool = __commonJS({
31370
31578
  return new Pool(origin, opts);
31371
31579
  }
31372
31580
  var BalancedPool = class extends PoolBase {
31373
- constructor(upstreams = [], { factory = defaultFactory, ...opts } = {}) {
31581
+ constructor(upstreams = [], { factory = defaultFactory, connect, tls, ...opts } = {}) {
31374
31582
  if (typeof factory !== "function") {
31375
31583
  throw new InvalidArgumentError("factory must be a function.");
31376
31584
  }
31377
- super();
31378
- this[kOptions] = { ...util.deepClone(opts) };
31585
+ super(opts);
31586
+ if (connect && typeof connect !== "function") connect = { ...connect };
31587
+ if (tls && typeof tls !== "function") tls = { ...tls };
31588
+ this[kOptions] = { ...util.deepClone(opts), connect, tls };
31379
31589
  this[kOptions].interceptors = opts.interceptors ? { ...opts.interceptors } : void 0;
31380
31590
  this[kIndex] = -1;
31381
31591
  this[kCurrentWeight] = 0;
@@ -31626,7 +31836,7 @@ var require_agent = __commonJS({
31626
31836
  if (typeof maxOrigins !== "number" || Number.isNaN(maxOrigins) || maxOrigins <= 0) {
31627
31837
  throw new InvalidArgumentError("maxOrigins must be a number greater than 0");
31628
31838
  }
31629
- super();
31839
+ super(options);
31630
31840
  if (connect && typeof connect !== "function") {
31631
31841
  connect = { ...connect };
31632
31842
  }
@@ -31763,28 +31973,37 @@ var require_socks5_utils = __commonJS({
31763
31973
  }
31764
31974
  function parseIPv6(address) {
31765
31975
  const buffer = Buffer2.alloc(16);
31766
- const parts = address.split(":");
31767
- let partIndex = 0;
31768
- let bufferIndex = 0;
31769
- const doubleColonIndex = address.indexOf("::");
31976
+ let normalizedAddress = address;
31977
+ if (address.includes(".")) {
31978
+ const lastColonIndex = address.lastIndexOf(":");
31979
+ const ipv4Part = address.slice(lastColonIndex + 1);
31980
+ if (net3.isIPv4(ipv4Part)) {
31981
+ const octets = ipv4Part.split(".").map(Number);
31982
+ const high = (octets[0] << 8 | octets[1]).toString(16);
31983
+ const low = (octets[2] << 8 | octets[3]).toString(16);
31984
+ normalizedAddress = `${address.slice(0, lastColonIndex)}:${high}:${low}`;
31985
+ }
31986
+ }
31987
+ const doubleColonIndex = normalizedAddress.indexOf("::");
31770
31988
  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
- }
31989
+ const before = normalizedAddress.slice(0, doubleColonIndex);
31990
+ const after = normalizedAddress.slice(doubleColonIndex + 2);
31991
+ const beforeParts = before === "" ? [] : before.split(":");
31992
+ const afterParts = after === "" ? [] : after.split(":");
31993
+ let bufferIndex = 0;
31994
+ for (const part of beforeParts) {
31995
+ buffer.writeUInt16BE(parseInt(part, 16), bufferIndex);
31996
+ bufferIndex += 2;
31997
+ }
31998
+ bufferIndex = 16 - afterParts.length * 2;
31999
+ for (const part of afterParts) {
32000
+ buffer.writeUInt16BE(parseInt(part, 16), bufferIndex);
32001
+ bufferIndex += 2;
31781
32002
  }
31782
32003
  } 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++;
32004
+ const parts = normalizedAddress.split(":");
32005
+ for (let i = 0; i < parts.length; i++) {
32006
+ buffer.writeUInt16BE(parseInt(parts[i], 16), i * 2);
31788
32007
  }
31789
32008
  }
31790
32009
  return buffer;
@@ -31890,6 +32109,7 @@ var require_socks5_client = __commonJS({
31890
32109
  var { debuglog } = __require("util");
31891
32110
  var { parseAddress } = require_socks5_utils();
31892
32111
  var debug = debuglog("undici:socks5");
32112
+ var EMPTY_BUFFER = Buffer2.alloc(0);
31893
32113
  var SOCKS_VERSION = 5;
31894
32114
  var AUTH_METHODS = {
31895
32115
  NO_AUTH: 0,
@@ -31922,6 +32142,7 @@ var require_socks5_client = __commonJS({
31922
32142
  INITIAL: "initial",
31923
32143
  HANDSHAKING: "handshaking",
31924
32144
  AUTHENTICATING: "authenticating",
32145
+ AUTHENTICATED: "authenticated",
31925
32146
  CONNECTING: "connecting",
31926
32147
  CONNECTED: "connected",
31927
32148
  ERROR: "error",
@@ -31936,15 +32157,18 @@ var require_socks5_client = __commonJS({
31936
32157
  this.socket = socket;
31937
32158
  this.options = options;
31938
32159
  this.state = STATES.INITIAL;
31939
- this.buffer = Buffer2.alloc(0);
32160
+ this.buffer = EMPTY_BUFFER;
32161
+ this.onSocketData = this.onData.bind(this);
32162
+ this.onSocketError = this.onError.bind(this);
32163
+ this.onSocketClose = this.onClose.bind(this);
31940
32164
  this.authMethods = [];
31941
32165
  if (options.username && options.password) {
31942
32166
  this.authMethods.push(AUTH_METHODS.USERNAME_PASSWORD);
31943
32167
  }
31944
32168
  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));
32169
+ this.socket.on("data", this.onSocketData);
32170
+ this.socket.on("error", this.onSocketError);
32171
+ this.socket.on("close", this.onSocketClose);
31948
32172
  }
31949
32173
  /**
31950
32174
  * Handle incoming data from the socket
@@ -31993,6 +32217,10 @@ var require_socks5_client = __commonJS({
31993
32217
  this.socket.destroy();
31994
32218
  }
31995
32219
  }
32220
+ markAuthenticated() {
32221
+ this.state = STATES.AUTHENTICATED;
32222
+ this.emit("authenticated");
32223
+ }
31996
32224
  /**
31997
32225
  * Start the SOCKS5 handshake
31998
32226
  */
@@ -32028,7 +32256,7 @@ var require_socks5_client = __commonJS({
32028
32256
  this.buffer = this.buffer.subarray(2);
32029
32257
  debug("server selected auth method", method);
32030
32258
  if (method === AUTH_METHODS.NO_AUTH) {
32031
- this.emit("authenticated");
32259
+ this.markAuthenticated();
32032
32260
  } else if (method === AUTH_METHODS.USERNAME_PASSWORD) {
32033
32261
  this.state = STATES.AUTHENTICATING;
32034
32262
  this.sendAuthRequest();
@@ -32075,7 +32303,7 @@ var require_socks5_client = __commonJS({
32075
32303
  }
32076
32304
  this.buffer = this.buffer.subarray(2);
32077
32305
  debug("authentication successful");
32078
- this.emit("authenticated");
32306
+ this.markAuthenticated();
32079
32307
  }
32080
32308
  /**
32081
32309
  * Send CONNECT command
@@ -32083,8 +32311,11 @@ var require_socks5_client = __commonJS({
32083
32311
  * @param {number} port - Target port
32084
32312
  */
32085
32313
  connect(address, port) {
32086
- if (this.state === STATES.CONNECTED) {
32087
- throw new InvalidArgumentError("Already connected");
32314
+ if (this.state === STATES.CONNECTING || this.state === STATES.CONNECTED) {
32315
+ throw new InvalidArgumentError("Connection already in progress");
32316
+ }
32317
+ if (this.state !== STATES.AUTHENTICATED) {
32318
+ throw new InvalidArgumentError("Client must be authenticated before CONNECT");
32088
32319
  }
32089
32320
  debug("connecting to", address, port);
32090
32321
  this.state = STATES.CONNECTING;
@@ -32158,8 +32389,9 @@ var require_socks5_client = __commonJS({
32158
32389
  offset += 16;
32159
32390
  }
32160
32391
  const boundPort = this.buffer.readUInt16BE(offset);
32161
- this.buffer = this.buffer.subarray(responseLength);
32392
+ this.buffer = EMPTY_BUFFER;
32162
32393
  this.state = STATES.CONNECTED;
32394
+ this.socket.removeListener("data", this.onSocketData);
32163
32395
  debug("connected, bound address:", boundAddress, "port:", boundPort);
32164
32396
  this.emit("connected", { address: boundAddress, port: boundPort });
32165
32397
  }
@@ -32204,12 +32436,11 @@ var require_socks5_client = __commonJS({
32204
32436
  var require_socks5_proxy_agent = __commonJS({
32205
32437
  "node_modules/undici/lib/dispatcher/socks5-proxy-agent.js"(exports, module) {
32206
32438
  "use strict";
32207
- var net3 = __require("net");
32208
32439
  var { URL: URL6 } = __require("url");
32209
32440
  var tls;
32210
32441
  var DispatcherBase = require_dispatcher_base();
32211
32442
  var { InvalidArgumentError } = require_errors();
32212
- var { Socks5Client } = require_socks5_client();
32443
+ var { Socks5Client, STATES } = require_socks5_client();
32213
32444
  var { kDispatch, kClose, kDestroy } = require_symbols();
32214
32445
  var Pool = require_pool();
32215
32446
  var buildConnector = require_connect();
@@ -32218,8 +32449,10 @@ var require_socks5_proxy_agent = __commonJS({
32218
32449
  var kProxyUrl = /* @__PURE__ */ Symbol("proxy url");
32219
32450
  var kProxyHeaders = /* @__PURE__ */ Symbol("proxy headers");
32220
32451
  var kProxyAuth = /* @__PURE__ */ Symbol("proxy auth");
32221
- var kPool = /* @__PURE__ */ Symbol("pool");
32452
+ var kProxyProtocol = /* @__PURE__ */ Symbol("proxy protocol");
32453
+ var kPools = /* @__PURE__ */ Symbol("pools");
32222
32454
  var kConnector = /* @__PURE__ */ Symbol("connector");
32455
+ var kRequestTls = /* @__PURE__ */ Symbol("request tls settings");
32223
32456
  var experimentalWarningEmitted = false;
32224
32457
  var Socks5ProxyAgent = class extends DispatcherBase {
32225
32458
  constructor(proxyUrl, options = {}) {
@@ -32240,6 +32473,8 @@ var require_socks5_proxy_agent = __commonJS({
32240
32473
  }
32241
32474
  this[kProxyUrl] = url;
32242
32475
  this[kProxyHeaders] = options.headers || {};
32476
+ this[kProxyProtocol] = options.proxyTls ? "https:" : "http:";
32477
+ this[kRequestTls] = options.requestTls;
32243
32478
  this[kProxyAuth] = {
32244
32479
  username: options.username || (url.username ? decodeURIComponent(url.username) : null),
32245
32480
  password: options.password || (url.password ? decodeURIComponent(url.password) : null)
@@ -32248,7 +32483,7 @@ var require_socks5_proxy_agent = __commonJS({
32248
32483
  ...options.proxyTls,
32249
32484
  servername: options.proxyTls?.servername || url.hostname
32250
32485
  });
32251
- this[kPool] = null;
32486
+ this[kPools] = /* @__PURE__ */ new Map();
32252
32487
  }
32253
32488
  /**
32254
32489
  * Create a SOCKS5 connection to the proxy
@@ -32258,20 +32493,18 @@ var require_socks5_proxy_agent = __commonJS({
32258
32493
  const proxyPort = parseInt(this[kProxyUrl].port) || 1080;
32259
32494
  debug("creating SOCKS5 connection to", proxyHost, proxyPort);
32260
32495
  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({
32496
+ this[kConnector]({
32497
+ hostname: proxyHost,
32270
32498
  host: proxyHost,
32271
- port: proxyPort
32499
+ port: proxyPort,
32500
+ protocol: this[kProxyProtocol]
32501
+ }, (err2, socket2) => {
32502
+ if (err2) {
32503
+ reject(err2);
32504
+ } else {
32505
+ resolve2(socket2);
32506
+ }
32272
32507
  });
32273
- socket2.once("connect", onConnect);
32274
- socket2.once("error", onError);
32275
32508
  });
32276
32509
  const socks5Client = new Socks5Client(socket, this[kProxyAuth]);
32277
32510
  socks5Client.on("error", (err2) => {
@@ -32293,7 +32526,7 @@ var require_socks5_proxy_agent = __commonJS({
32293
32526
  socks5Client.removeListener("authenticated", onAuthenticated);
32294
32527
  reject(err2);
32295
32528
  };
32296
- if (socks5Client.state === "authenticated") {
32529
+ if (socks5Client.state === STATES.AUTHENTICATED) {
32297
32530
  clearTimeout(timeout);
32298
32531
  resolve2();
32299
32532
  } else {
@@ -32325,12 +32558,14 @@ var require_socks5_proxy_agent = __commonJS({
32325
32558
  /**
32326
32559
  * Dispatch a request through the SOCKS5 proxy
32327
32560
  */
32328
- async [kDispatch](opts, handler) {
32561
+ [kDispatch](opts, handler) {
32329
32562
  const { origin } = opts;
32330
32563
  debug("dispatching request to", origin, "via SOCKS5");
32331
32564
  try {
32332
- if (!this[kPool] || this[kPool].destroyed || this[kPool].closed) {
32333
- this[kPool] = new Pool(origin, {
32565
+ const originKey = String(origin);
32566
+ let pool = this[kPools].get(originKey);
32567
+ if (!pool || pool.destroyed || pool.closed) {
32568
+ pool = new Pool(origin, {
32334
32569
  pipelining: opts.pipelining,
32335
32570
  connections: opts.connections,
32336
32571
  connect: async (connectOpts, callback) => {
@@ -32347,9 +32582,9 @@ var require_socks5_proxy_agent = __commonJS({
32347
32582
  }
32348
32583
  debug("upgrading to TLS");
32349
32584
  finalSocket = tls.connect({
32585
+ ...this[kRequestTls],
32350
32586
  socket,
32351
- servername: targetHost,
32352
- ...connectOpts.tls || {}
32587
+ servername: this[kRequestTls]?.servername || targetHost
32353
32588
  });
32354
32589
  await new Promise((resolve2, reject) => {
32355
32590
  finalSocket.once("secureConnect", resolve2);
@@ -32363,26 +32598,37 @@ var require_socks5_proxy_agent = __commonJS({
32363
32598
  }
32364
32599
  }
32365
32600
  });
32601
+ this[kPools].set(originKey, pool);
32366
32602
  }
32367
- return this[kPool][kDispatch](opts, handler);
32603
+ return pool[kDispatch](opts, handler);
32368
32604
  } catch (err2) {
32369
32605
  debug("dispatch error:", err2);
32370
- if (typeof handler.onError === "function") {
32606
+ if (typeof handler.onResponseError === "function") {
32607
+ handler.onResponseError(null, err2);
32608
+ return false;
32609
+ } else if (typeof handler.onError === "function") {
32371
32610
  handler.onError(err2);
32611
+ return false;
32372
32612
  } else {
32373
32613
  throw err2;
32374
32614
  }
32375
32615
  }
32376
32616
  }
32377
32617
  async [kClose]() {
32378
- if (this[kPool]) {
32379
- await this[kPool].close();
32618
+ const closePromises = [];
32619
+ for (const pool of this[kPools].values()) {
32620
+ closePromises.push(pool.close());
32380
32621
  }
32622
+ this[kPools].clear();
32623
+ await Promise.all(closePromises);
32381
32624
  }
32382
32625
  async [kDestroy](err2) {
32383
- if (this[kPool]) {
32384
- await this[kPool].destroy(err2);
32626
+ const destroyPromises = [];
32627
+ for (const pool of this[kPools].values()) {
32628
+ destroyPromises.push(pool.destroy(err2));
32385
32629
  }
32630
+ this[kPools].clear();
32631
+ await Promise.all(destroyPromises);
32386
32632
  }
32387
32633
  };
32388
32634
  module.exports = Socks5ProxyAgent;
@@ -32507,7 +32753,8 @@ var require_proxy_agent = __commonJS({
32507
32753
  factory: agentFactory,
32508
32754
  username: opts.username || username,
32509
32755
  password: opts.password || password,
32510
- proxyTls: opts.proxyTls
32756
+ proxyTls: opts.proxyTls,
32757
+ requestTls: opts.requestTls
32511
32758
  });
32512
32759
  }
32513
32760
  if (!this[kTunnelProxy] && protocol2 === "http:" && this[kProxy].protocol === "http:") {
@@ -32785,6 +33032,23 @@ var require_retry_handler = __commonJS({
32785
33032
  const retryTime = new Date(retryAfter).getTime();
32786
33033
  return isNaN(retryTime) ? 0 : retryTime - Date.now();
32787
33034
  }
33035
+ function validatePartialResponseContentLength(headers, range, statusCode, retryCount) {
33036
+ const contentLength = headers["content-length"];
33037
+ if (contentLength == null) {
33038
+ return;
33039
+ }
33040
+ if (!Number.isFinite(range.start) || !Number.isFinite(range.end)) {
33041
+ return;
33042
+ }
33043
+ const length = Number(contentLength);
33044
+ const expectedLength = range.end - range.start + 1;
33045
+ if (!Number.isFinite(length) || length !== expectedLength) {
33046
+ throw new RequestRetryError("Content-Length mismatch", statusCode, {
33047
+ headers,
33048
+ data: { count: retryCount }
33049
+ });
33050
+ }
33051
+ }
32788
33052
  var RetryHandler = class _RetryHandler {
32789
33053
  constructor(opts, { dispatch, handler }) {
32790
33054
  const { retryOptions, ...dispatchOpts } = opts;
@@ -32843,8 +33107,13 @@ var require_retry_handler = __commonJS({
32843
33107
  onResponseStartWithRetry(controller, statusCode, headers, statusMessage, err2) {
32844
33108
  if (this.retryOpts.throwOnError) {
32845
33109
  if (this.retryOpts.statusCodes.includes(statusCode) === false) {
32846
- this.headersSent = true;
32847
- this.handler.onResponseStart?.(controller, statusCode, headers, statusMessage);
33110
+ if (this.headersSent) {
33111
+ this.handler.onResponseError?.(controller, err2);
33112
+ } else {
33113
+ this.headersSent = true;
33114
+ this.checkpointResponseEnd(headers);
33115
+ this.handler.onResponseStart?.(controller, statusCode, headers, statusMessage);
33116
+ }
32848
33117
  } else {
32849
33118
  this.error = err2;
32850
33119
  }
@@ -32852,13 +33121,19 @@ var require_retry_handler = __commonJS({
32852
33121
  }
32853
33122
  if (isDisturbed(this.opts.body)) {
32854
33123
  this.headersSent = true;
33124
+ this.checkpointResponseEnd(headers);
32855
33125
  this.handler.onResponseStart?.(controller, statusCode, headers, statusMessage);
32856
33126
  return;
32857
33127
  }
32858
33128
  function shouldRetry(passedErr) {
32859
33129
  if (passedErr) {
32860
- this.headersSent = true;
32861
- this.handler.onResponseStart?.(controller, statusCode, headers, statusMessage);
33130
+ if (this.headersSent) {
33131
+ this.handler.onResponseError?.(controller, passedErr);
33132
+ } else {
33133
+ this.headersSent = true;
33134
+ this.checkpointResponseEnd(headers);
33135
+ this.handler.onResponseStart?.(controller, statusCode, headers, statusMessage);
33136
+ }
32862
33137
  controller.resume();
32863
33138
  return;
32864
33139
  }
@@ -32875,6 +33150,17 @@ var require_retry_handler = __commonJS({
32875
33150
  shouldRetry.bind(this)
32876
33151
  );
32877
33152
  }
33153
+ checkpointResponseEnd(headers) {
33154
+ if (this.end == null && this.opts.method !== "HEAD") {
33155
+ const contentLength = headers["content-length"];
33156
+ this.end = contentLength != null ? Number(contentLength) - 1 : null;
33157
+ assert(
33158
+ this.end == null || Number.isFinite(this.end),
33159
+ "invalid content-length"
33160
+ );
33161
+ this.resume = this.end != null;
33162
+ }
33163
+ }
32878
33164
  onRequestStart(controller, context) {
32879
33165
  if (!this.headersSent) {
32880
33166
  this.handler.onRequestStart?.(controller, context);
@@ -32953,9 +33239,14 @@ var require_retry_handler = __commonJS({
32953
33239
  data: { count: this.retryCount }
32954
33240
  });
32955
33241
  }
33242
+ validatePartialResponseContentLength(headers, contentRange, statusCode, this.retryCount);
32956
33243
  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");
33244
+ if (this.start !== start || this.end != null && this.end !== end) {
33245
+ throw new RequestRetryError("Content-Range mismatch", statusCode, {
33246
+ headers,
33247
+ data: { count: this.retryCount }
33248
+ });
33249
+ }
32959
33250
  return;
32960
33251
  }
32961
33252
  if (this.end == null) {
@@ -32971,6 +33262,7 @@ var require_retry_handler = __commonJS({
32971
33262
  );
32972
33263
  return;
32973
33264
  }
33265
+ validatePartialResponseContentLength(headers, range, statusCode, this.retryCount);
32974
33266
  const { start, size, end = size ? size - 1 : null } = range;
32975
33267
  assert(
32976
33268
  start != null && Number.isFinite(start),
@@ -33047,7 +33339,7 @@ var require_retry_handler = __commonJS({
33047
33339
  }
33048
33340
  }
33049
33341
  onResponseError(controller, err2) {
33050
- if (controller?.aborted || isDisturbed(this.opts.body)) {
33342
+ if (controller?.aborted || isDisturbed(this.opts.body) || this.headersSent && !this.resume) {
33051
33343
  this.handler.onResponseError?.(controller, err2);
33052
33344
  return;
33053
33345
  }
@@ -33128,7 +33420,7 @@ var require_h2c_client = __commonJS({
33128
33420
  "h2c-client: Only h2c protocol is supported"
33129
33421
  );
33130
33422
  }
33131
- const { connect, maxConcurrentStreams, pipelining, ...opts } = clientOpts ?? {};
33423
+ const { maxConcurrentStreams, pipelining, ...opts } = clientOpts ?? {};
33132
33424
  let defaultMaxConcurrentStreams = 100;
33133
33425
  let defaultPipelining = 100;
33134
33426
  if (maxConcurrentStreams != null && Number.isInteger(maxConcurrentStreams) && maxConcurrentStreams > 0) {
@@ -33578,7 +33870,7 @@ var require_api_request = __commonJS({
33578
33870
  if (typeof callback !== "function") {
33579
33871
  throw new InvalidArgumentError("invalid callback");
33580
33872
  }
33581
- if (highWaterMark && (typeof highWaterMark !== "number" || highWaterMark < 0)) {
33873
+ if (highWaterMark != null && (!Number.isFinite(highWaterMark) || highWaterMark < 0)) {
33582
33874
  throw new InvalidArgumentError("invalid highWaterMark");
33583
33875
  }
33584
33876
  if (signal && typeof signal.on !== "function" && typeof signal.addEventListener !== "function") {
@@ -35017,13 +35309,13 @@ var require_mock_call_history = __commonJS({
35017
35309
  "use strict";
35018
35310
  var { kMockCallHistoryAddLog } = require_mock_symbols();
35019
35311
  var { InvalidArgumentError } = require_errors();
35020
- function handleFilterCallsWithOptions(criteria, options, handler, store) {
35312
+ function handleFilterCallsWithOptions(criteria, options, handler, store, allLogs) {
35021
35313
  switch (options.operator) {
35022
35314
  case "OR":
35023
- store.push(...handler(criteria));
35315
+ store.push(...handler(criteria, allLogs));
35024
35316
  return store;
35025
35317
  case "AND":
35026
- return handler.call({ logs: store }, criteria);
35318
+ return handler(criteria, store);
35027
35319
  default:
35028
35320
  throw new InvalidArgumentError("options.operator must to be a case insensitive string equal to 'OR' or 'AND'");
35029
35321
  }
@@ -35042,14 +35334,14 @@ var require_mock_call_history = __commonJS({
35042
35334
  return finalOptions;
35043
35335
  }
35044
35336
  function makeFilterCalls(parameterName) {
35045
- return (parameterValue) => {
35337
+ return (parameterValue, logs) => {
35046
35338
  if (typeof parameterValue === "string" || parameterValue == null) {
35047
- return this.logs.filter((log) => {
35339
+ return logs.filter((log) => {
35048
35340
  return log[parameterName] === parameterValue;
35049
35341
  });
35050
35342
  }
35051
35343
  if (parameterValue instanceof RegExp) {
35052
- return this.logs.filter((log) => {
35344
+ return logs.filter((log) => {
35053
35345
  return parameterValue.test(log[parameterName]);
35054
35346
  });
35055
35347
  }
@@ -35154,30 +35446,30 @@ var require_mock_call_history = __commonJS({
35154
35446
  return this.logs;
35155
35447
  }
35156
35448
  const finalOptions = { operator: "OR", ...buildAndValidateFilterCallsOptions(options) };
35157
- let maybeDuplicatedLogsFiltered = [];
35449
+ let maybeDuplicatedLogsFiltered = finalOptions.operator === "AND" ? this.logs : [];
35158
35450
  if ("protocol" in criteria) {
35159
- maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.protocol, finalOptions, this.filterCallsByProtocol, maybeDuplicatedLogsFiltered);
35451
+ maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.protocol, finalOptions, this.filterCallsByProtocol, maybeDuplicatedLogsFiltered, this.logs);
35160
35452
  }
35161
35453
  if ("host" in criteria) {
35162
- maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.host, finalOptions, this.filterCallsByHost, maybeDuplicatedLogsFiltered);
35454
+ maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.host, finalOptions, this.filterCallsByHost, maybeDuplicatedLogsFiltered, this.logs);
35163
35455
  }
35164
35456
  if ("port" in criteria) {
35165
- maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.port, finalOptions, this.filterCallsByPort, maybeDuplicatedLogsFiltered);
35457
+ maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.port, finalOptions, this.filterCallsByPort, maybeDuplicatedLogsFiltered, this.logs);
35166
35458
  }
35167
35459
  if ("origin" in criteria) {
35168
- maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.origin, finalOptions, this.filterCallsByOrigin, maybeDuplicatedLogsFiltered);
35460
+ maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.origin, finalOptions, this.filterCallsByOrigin, maybeDuplicatedLogsFiltered, this.logs);
35169
35461
  }
35170
35462
  if ("path" in criteria) {
35171
- maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.path, finalOptions, this.filterCallsByPath, maybeDuplicatedLogsFiltered);
35463
+ maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.path, finalOptions, this.filterCallsByPath, maybeDuplicatedLogsFiltered, this.logs);
35172
35464
  }
35173
35465
  if ("hash" in criteria) {
35174
- maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.hash, finalOptions, this.filterCallsByHash, maybeDuplicatedLogsFiltered);
35466
+ maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.hash, finalOptions, this.filterCallsByHash, maybeDuplicatedLogsFiltered, this.logs);
35175
35467
  }
35176
35468
  if ("fullUrl" in criteria) {
35177
- maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.fullUrl, finalOptions, this.filterCallsByFullUrl, maybeDuplicatedLogsFiltered);
35469
+ maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.fullUrl, finalOptions, this.filterCallsByFullUrl, maybeDuplicatedLogsFiltered, this.logs);
35178
35470
  }
35179
35471
  if ("method" in criteria) {
35180
- maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.method, finalOptions, this.filterCallsByMethod, maybeDuplicatedLogsFiltered);
35472
+ maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.method, finalOptions, this.filterCallsByMethod, maybeDuplicatedLogsFiltered, this.logs);
35181
35473
  }
35182
35474
  const uniqLogsFiltered = [...new Set(maybeDuplicatedLogsFiltered)];
35183
35475
  return uniqLogsFiltered;
@@ -36250,7 +36542,8 @@ var require_snapshot_agent = __commonJS({
36250
36542
  var require_global2 = __commonJS({
36251
36543
  "node_modules/undici/lib/global.js"(exports, module) {
36252
36544
  "use strict";
36253
- var globalDispatcher = /* @__PURE__ */ Symbol.for("undici.globalDispatcher.1");
36545
+ var globalDispatcher = /* @__PURE__ */ Symbol.for("undici.globalDispatcher.2");
36546
+ var legacyGlobalDispatcher = /* @__PURE__ */ Symbol.for("undici.globalDispatcher.1");
36254
36547
  var { InvalidArgumentError } = require_errors();
36255
36548
  var Agent = require_agent();
36256
36549
  if (getGlobalDispatcher() === void 0) {
@@ -36266,9 +36559,15 @@ var require_global2 = __commonJS({
36266
36559
  enumerable: false,
36267
36560
  configurable: false
36268
36561
  });
36562
+ Object.defineProperty(globalThis, legacyGlobalDispatcher, {
36563
+ value: agent,
36564
+ writable: true,
36565
+ enumerable: false,
36566
+ configurable: false
36567
+ });
36269
36568
  }
36270
36569
  function getGlobalDispatcher() {
36271
- return globalThis[globalDispatcher];
36570
+ return globalThis[legacyGlobalDispatcher];
36272
36571
  }
36273
36572
  var installedExports = (
36274
36573
  /** @type {const} */
@@ -36647,7 +36946,6 @@ var require_dump = __commonJS({
36647
36946
  #maxSize = 1024 * 1024;
36648
36947
  #dumped = false;
36649
36948
  #size = 0;
36650
- #controller = null;
36651
36949
  aborted = false;
36652
36950
  reason = false;
36653
36951
  constructor({ maxSize, signal }, handler) {
@@ -36663,7 +36961,6 @@ var require_dump = __commonJS({
36663
36961
  }
36664
36962
  onRequestStart(controller, context) {
36665
36963
  controller.abort = this.#abort.bind(this);
36666
- this.#controller = controller;
36667
36964
  return super.onRequestStart(controller, context);
36668
36965
  }
36669
36966
  onResponseStart(controller, statusCode, headers, statusMessage) {
@@ -36679,33 +36976,26 @@ var require_dump = __commonJS({
36679
36976
  return super.onResponseStart(controller, statusCode, headers, statusMessage);
36680
36977
  }
36681
36978
  onResponseError(controller, err2) {
36682
- if (this.#dumped) {
36683
- return;
36684
- }
36685
- err2 = this.#controller?.reason ?? err2;
36686
- super.onResponseError(controller, err2);
36979
+ super.onResponseError(controller, this.aborted === true ? this.reason : err2);
36687
36980
  }
36688
36981
  onResponseData(controller, chunk2) {
36689
36982
  this.#size = this.#size + chunk2.length;
36690
- if (this.#size >= this.#maxSize) {
36983
+ if (this.#size > this.#maxSize) {
36984
+ throw new RequestAbortedError(
36985
+ `Response size (${this.#size}) larger than maxSize (${this.#maxSize})`
36986
+ );
36987
+ }
36988
+ if (this.#size === this.#maxSize) {
36691
36989
  this.#dumped = true;
36692
- if (this.aborted === true) {
36693
- super.onResponseError(controller, this.reason);
36694
- } else {
36695
- super.onResponseEnd(controller, {});
36696
- }
36697
36990
  }
36698
36991
  return true;
36699
36992
  }
36700
36993
  onResponseEnd(controller, trailers) {
36701
- if (this.#dumped) {
36702
- return;
36703
- }
36704
- if (this.#controller.aborted === true) {
36994
+ if (this.aborted === true) {
36705
36995
  super.onResponseError(controller, this.reason);
36706
36996
  return;
36707
36997
  }
36708
- super.onResponseEnd(controller, trailers);
36998
+ super.onResponseEnd(controller, this.#dumped ? {} : trailers);
36709
36999
  }
36710
37000
  };
36711
37001
  function createDumpInterceptor({ maxSize: defaultMaxSize } = {
@@ -37169,15 +37459,127 @@ var require_cache = __commonJS({
37169
37459
  var {
37170
37460
  safeHTTPMethods,
37171
37461
  pathHasQueryOrFragment,
37172
- hasSafeIterator
37462
+ hasSafeIterator,
37463
+ isValidHTTPToken
37173
37464
  } = require_util();
37174
37465
  var { serializePathWithQuery } = require_util();
37466
+ var MAX_DELTA_SECONDS = 2147483647;
37467
+ var RESTRICTIVE_DIRECTIVE_NAMES = ["no-store", "private", "no-cache"];
37468
+ var kInvalidCacheControlDirectives = /* @__PURE__ */ Symbol("invalid cache-control directives");
37469
+ function trimOWS(value) {
37470
+ return value.replace(/^[\t ]+|[\t ]+$/g, "");
37471
+ }
37472
+ function arrayIncludes(array, value) {
37473
+ for (let i = 0; i < array.length; i++) {
37474
+ if (array[i] === value) {
37475
+ return true;
37476
+ }
37477
+ }
37478
+ return false;
37479
+ }
37480
+ function trimOWSStart(value) {
37481
+ return value.replace(/^[\t ]+/, "");
37482
+ }
37483
+ function trimOWSEnd(value) {
37484
+ return value.replace(/[\t ]+$/, "");
37485
+ }
37486
+ function findUnescapedQuote(value, start) {
37487
+ let escaped = false;
37488
+ for (let i = start; i < value.length; i++) {
37489
+ if (escaped) {
37490
+ escaped = false;
37491
+ } else if (value[i] === "\\") {
37492
+ escaped = true;
37493
+ } else if (value[i] === '"') {
37494
+ return i;
37495
+ }
37496
+ }
37497
+ return -1;
37498
+ }
37499
+ function splitCacheControlHeaderValue(value) {
37500
+ const directives = [];
37501
+ let start = 0;
37502
+ let quoteStart = -1;
37503
+ let inQuote = false;
37504
+ let escaped = false;
37505
+ for (let i = 0; i < value.length; i++) {
37506
+ if (inQuote) {
37507
+ if (escaped) {
37508
+ escaped = false;
37509
+ } else if (value[i] === "\\") {
37510
+ escaped = true;
37511
+ } else if (value[i] === '"') {
37512
+ inQuote = false;
37513
+ quoteStart = -1;
37514
+ }
37515
+ } else if (value[i] === '"') {
37516
+ inQuote = true;
37517
+ quoteStart = i;
37518
+ } else if (value[i] === ",") {
37519
+ directives.push({ value: value.substring(start, i), fromMalformedQuote: false });
37520
+ start = i + 1;
37521
+ }
37522
+ }
37523
+ if (!inQuote) {
37524
+ directives.push({ value: value.substring(start), fromMalformedQuote: false });
37525
+ return directives;
37526
+ }
37527
+ const tail = value.substring(start);
37528
+ const quoteOffset = quoteStart - start;
37529
+ let tailStart = 0;
37530
+ for (let i = 0; i < tail.length; i++) {
37531
+ if (tail[i] === ",") {
37532
+ directives.push({
37533
+ value: tail.substring(tailStart, i),
37534
+ fromMalformedQuote: tailStart > quoteOffset
37535
+ });
37536
+ tailStart = i + 1;
37537
+ }
37538
+ }
37539
+ directives.push({
37540
+ value: tail.substring(tailStart),
37541
+ fromMalformedQuote: tailStart > quoteOffset
37542
+ });
37543
+ return directives;
37544
+ }
37545
+ function markInvalidCacheControlDirective(directives, key) {
37546
+ let invalidDirectives = directives[kInvalidCacheControlDirectives];
37547
+ if (invalidDirectives === void 0) {
37548
+ invalidDirectives = /* @__PURE__ */ new Set();
37549
+ Object.defineProperty(directives, kInvalidCacheControlDirectives, {
37550
+ value: invalidDirectives
37551
+ });
37552
+ }
37553
+ invalidDirectives.add(key);
37554
+ }
37555
+ function hasInvalidCacheControlDirective(directives, key) {
37556
+ return directives[kInvalidCacheControlDirectives]?.has(key) === true;
37557
+ }
37558
+ function getMalformedRestrictiveDirectiveName(key) {
37559
+ for (const directiveName of RESTRICTIVE_DIRECTIVE_NAMES) {
37560
+ if (key.startsWith(directiveName) && key.length > directiveName.length && !isValidHTTPToken(key[directiveName.length])) {
37561
+ return directiveName;
37562
+ }
37563
+ }
37564
+ let tokenOnlyKey = "";
37565
+ let hasInvalidTokenChar = false;
37566
+ for (let i = 0; i < key.length; i++) {
37567
+ if (isValidHTTPToken(key[i])) {
37568
+ tokenOnlyKey += key[i];
37569
+ } else {
37570
+ hasInvalidTokenChar = true;
37571
+ }
37572
+ }
37573
+ if (hasInvalidTokenChar && arrayIncludes(RESTRICTIVE_DIRECTIVE_NAMES, tokenOnlyKey)) {
37574
+ return tokenOnlyKey;
37575
+ }
37576
+ }
37175
37577
  function makeCacheKey(opts) {
37176
37578
  if (!opts.origin) {
37177
37579
  throw new Error("opts.origin is undefined");
37178
37580
  }
37179
37581
  let fullPath = opts.path || "/";
37180
- if (opts.query && !pathHasQueryOrFragment(opts.path)) {
37582
+ if (opts.query && !pathHasQueryOrFragment(fullPath)) {
37181
37583
  fullPath = serializePathWithQuery(fullPath, opts.query);
37182
37584
  }
37183
37585
  return {
@@ -37187,6 +37589,18 @@ var require_cache = __commonJS({
37187
37589
  headers: opts.headers
37188
37590
  };
37189
37591
  }
37592
+ function appendHeader(headers, key, val) {
37593
+ const headerName = key.toLowerCase();
37594
+ const current = headers[headerName];
37595
+ const values = Array.isArray(val) ? val : [val];
37596
+ if (current === void 0) {
37597
+ headers[headerName] = Array.isArray(val) ? val.slice() : val;
37598
+ } else if (Array.isArray(current)) {
37599
+ current.push(...values);
37600
+ } else {
37601
+ headers[headerName] = [current, ...values];
37602
+ }
37603
+ }
37190
37604
  function normalizeHeaders(opts) {
37191
37605
  let headers;
37192
37606
  if (opts.headers == null) {
@@ -37202,11 +37616,11 @@ var require_cache = __commonJS({
37202
37616
  if (typeof key !== "string" || typeof val !== "string") {
37203
37617
  throw new Error("opts.headers is not a valid header map");
37204
37618
  }
37205
- headers[key.toLowerCase()] = val;
37619
+ appendHeader(headers, key, val);
37206
37620
  }
37207
37621
  } else {
37208
37622
  for (const key of Object.keys(opts.headers)) {
37209
- headers[key.toLowerCase()] = opts.headers[key];
37623
+ appendHeader(headers, key, opts.headers[key]);
37210
37624
  }
37211
37625
  }
37212
37626
  } else {
@@ -37251,25 +37665,32 @@ var require_cache = __commonJS({
37251
37665
  }
37252
37666
  function parseCacheControlHeader(header) {
37253
37667
  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
- }
37668
+ const invalidNumericDirectives = /* @__PURE__ */ new Set();
37669
+ const invalidNoArgumentDirectives = /* @__PURE__ */ new Set();
37670
+ const directives = splitCacheControlHeaderValue(Array.isArray(header) ? header.join(",") : header);
37263
37671
  for (let i = 0; i < directives.length; i++) {
37264
- const directive = directives[i].toLowerCase();
37672
+ const directiveRecord = directives[i];
37673
+ const directive = directiveRecord.value.toLowerCase();
37674
+ const fromMalformedQuote = directiveRecord.fromMalformedQuote;
37265
37675
  const keyValueDelimiter = directive.indexOf("=");
37266
37676
  let key;
37267
37677
  let value;
37678
+ let keyHasTrailingWhitespace = false;
37679
+ let valueHasLeadingWhitespace = false;
37268
37680
  if (keyValueDelimiter !== -1) {
37269
- key = directive.substring(0, keyValueDelimiter).trimStart();
37270
- value = directive.substring(keyValueDelimiter + 1);
37681
+ const rawKey = directive.substring(0, keyValueDelimiter);
37682
+ const rawValue = directive.substring(keyValueDelimiter + 1);
37683
+ keyHasTrailingWhitespace = trimOWSEnd(rawKey) !== rawKey;
37684
+ valueHasLeadingWhitespace = trimOWSStart(rawValue) !== rawValue;
37685
+ key = trimOWS(rawKey);
37686
+ value = trimOWSStart(rawValue);
37271
37687
  } else {
37272
- key = directive.trim();
37688
+ key = trimOWS(directive);
37689
+ }
37690
+ const malformedRestrictiveDirectiveName = getMalformedRestrictiveDirectiveName(key);
37691
+ if (malformedRestrictiveDirectiveName !== void 0) {
37692
+ output[malformedRestrictiveDirectiveName] = true;
37693
+ continue;
37273
37694
  }
37274
37695
  switch (key) {
37275
37696
  case "min-fresh":
@@ -37278,45 +37699,85 @@ var require_cache = __commonJS({
37278
37699
  case "s-maxage":
37279
37700
  case "stale-while-revalidate":
37280
37701
  case "stale-if-error": {
37281
- if (value === void 0 || value[0] === " ") {
37702
+ if (fromMalformedQuote || invalidNumericDirectives.has(key)) {
37703
+ continue;
37704
+ }
37705
+ if (value === void 0 || keyHasTrailingWhitespace || valueHasLeadingWhitespace) {
37706
+ delete output[key];
37707
+ invalidNumericDirectives.add(key);
37708
+ markInvalidCacheControlDirective(output, key);
37282
37709
  continue;
37283
37710
  }
37284
37711
  if (value.length >= 2 && value[0] === '"' && value[value.length - 1] === '"') {
37285
37712
  value = value.substring(1, value.length - 1);
37286
37713
  }
37287
- const parsedValue = parseInt(value, 10);
37288
- if (parsedValue !== parsedValue) {
37714
+ if (!/^[0-9]+$/.test(value)) {
37715
+ delete output[key];
37716
+ invalidNumericDirectives.add(key);
37717
+ markInvalidCacheControlDirective(output, key);
37289
37718
  continue;
37290
37719
  }
37291
- if (key === "max-age" && key in output && output[key] >= parsedValue) {
37292
- continue;
37720
+ const parsedValue = Math.min(parseInt(value, 10), MAX_DELTA_SECONDS);
37721
+ if (key === "min-fresh") {
37722
+ if (!(key in output) || output[key] < parsedValue) {
37723
+ output[key] = parsedValue;
37724
+ }
37725
+ } else if (!(key in output) || output[key] > parsedValue) {
37726
+ output[key] = parsedValue;
37293
37727
  }
37294
- output[key] = parsedValue;
37295
37728
  break;
37296
37729
  }
37297
37730
  case "private":
37298
37731
  case "no-cache": {
37732
+ if (fromMalformedQuote) {
37733
+ output[key] = true;
37734
+ break;
37735
+ }
37736
+ if (value !== void 0 && value.length === 0) {
37737
+ output[key] = true;
37738
+ break;
37739
+ }
37299
37740
  if (value) {
37300
37741
  if (value[0] === '"') {
37301
- const headers = [value.substring(1)];
37302
- let foundEndingQuote = value[value.length - 1] === '"';
37303
- if (!foundEndingQuote) {
37742
+ value = trimOWSEnd(value);
37743
+ let fieldList = "";
37744
+ let lastQuotedPart = i;
37745
+ let foundEndingQuote = false;
37746
+ const closingQuote = findUnescapedQuote(value, 1);
37747
+ if (closingQuote !== -1) {
37748
+ fieldList = value.substring(1, closingQuote);
37749
+ foundEndingQuote = true;
37750
+ } else {
37751
+ const fieldListParts = [value.substring(1)];
37304
37752
  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] === '"') {
37753
+ const nextPart = trimOWS(directives[j].value);
37754
+ const closingQuote2 = findUnescapedQuote(nextPart, 0);
37755
+ lastQuotedPart = j;
37756
+ if (closingQuote2 !== -1) {
37757
+ fieldListParts.push(nextPart.substring(0, closingQuote2));
37309
37758
  foundEndingQuote = true;
37310
37759
  break;
37311
37760
  }
37761
+ fieldListParts.push(nextPart);
37312
37762
  }
37763
+ fieldList = fieldListParts.join(",");
37764
+ }
37765
+ if (!foundEndingQuote) {
37766
+ output[key] = true;
37767
+ break;
37313
37768
  }
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;
37769
+ i = lastQuotedPart;
37770
+ const headers = fieldList.split(",");
37771
+ let validFieldNames = true;
37772
+ for (let j = 0; j < headers.length; j++) {
37773
+ headers[j] = trimOWS(headers[j]);
37774
+ if (!isValidHTTPToken(headers[j])) {
37775
+ validFieldNames = false;
37319
37776
  }
37777
+ }
37778
+ if (!validFieldNames) {
37779
+ output[key] = true;
37780
+ } else if (output[key] !== true) {
37320
37781
  if (key in output) {
37321
37782
  output[key] = output[key].concat(headers);
37322
37783
  } else {
@@ -37324,10 +37785,15 @@ var require_cache = __commonJS({
37324
37785
  }
37325
37786
  }
37326
37787
  } else {
37327
- if (key in output) {
37328
- output[key] = output[key].concat(value);
37329
- } else {
37330
- output[key] = [value];
37788
+ const fieldName = trimOWS(value);
37789
+ if (!isValidHTTPToken(fieldName)) {
37790
+ output[key] = true;
37791
+ } else if (output[key] !== true) {
37792
+ if (key in output) {
37793
+ output[key] = output[key].concat(fieldName);
37794
+ } else {
37795
+ output[key] = [fieldName];
37796
+ }
37331
37797
  }
37332
37798
  }
37333
37799
  break;
@@ -37335,39 +37801,76 @@ var require_cache = __commonJS({
37335
37801
  }
37336
37802
  // eslint-disable-next-line no-fallthrough
37337
37803
  case "public":
37338
- case "no-store":
37339
37804
  case "must-revalidate":
37340
37805
  case "proxy-revalidate":
37341
37806
  case "immutable":
37342
37807
  case "no-transform":
37343
37808
  case "must-understand":
37344
37809
  case "only-if-cached":
37345
- if (value) {
37810
+ if (fromMalformedQuote || invalidNoArgumentDirectives.has(key)) {
37811
+ continue;
37812
+ }
37813
+ if (value !== void 0) {
37814
+ delete output[key];
37815
+ invalidNoArgumentDirectives.add(key);
37346
37816
  continue;
37347
37817
  }
37348
37818
  output[key] = true;
37349
37819
  break;
37820
+ case "no-store":
37821
+ output[key] = true;
37822
+ break;
37350
37823
  default:
37351
37824
  continue;
37352
37825
  }
37353
37826
  }
37354
37827
  return output;
37355
37828
  }
37829
+ function splitVaryHeader(varyHeader) {
37830
+ const values = Array.isArray(varyHeader) ? varyHeader : [varyHeader];
37831
+ const output = [];
37832
+ for (let i = 0; i < values.length; i++) {
37833
+ const parts = values[i].split(",");
37834
+ for (let j = 0; j < parts.length; j++) {
37835
+ output.push(parts[j]);
37836
+ }
37837
+ }
37838
+ return output;
37839
+ }
37840
+ function hasVaryStar(varyHeader) {
37841
+ const values = splitVaryHeader(varyHeader);
37842
+ for (let i = 0; i < values.length; i++) {
37843
+ if (trimOWS(values[i]).indexOf("*") !== -1) {
37844
+ return true;
37845
+ }
37846
+ }
37847
+ return false;
37848
+ }
37356
37849
  function parseVaryHeader(varyHeader, headers) {
37357
- if (typeof varyHeader === "string" && varyHeader.includes("*")) {
37850
+ if (hasVaryStar(varyHeader)) {
37358
37851
  return headers;
37359
37852
  }
37360
37853
  const output = (
37361
37854
  /** @type {Record<string, string | string[] | null>} */
37362
37855
  {}
37363
37856
  );
37364
- const varyingHeaders = typeof varyHeader === "string" ? varyHeader.split(",") : varyHeader;
37857
+ const varyingHeaders = splitVaryHeader(varyHeader);
37365
37858
  for (const header of varyingHeaders) {
37366
- const trimmedHeader = header.trim().toLowerCase();
37367
- output[trimmedHeader] = headers[trimmedHeader] ?? null;
37859
+ const trimmedHeader = trimOWS(header).toLowerCase();
37860
+ if (trimmedHeader.length === 0) {
37861
+ continue;
37862
+ }
37863
+ if (!isValidHTTPToken(trimmedHeader)) {
37864
+ return void 0;
37865
+ }
37866
+ const headerValue = headers[trimmedHeader];
37867
+ output[trimmedHeader] = Array.isArray(headerValue) ? headerValue.slice() : headerValue ?? null;
37368
37868
  }
37369
37869
  return output;
37370
37870
  }
37871
+ function isInvalidOrWildcardVaryHeader(varyHeader) {
37872
+ return hasVaryStar(varyHeader) || parseVaryHeader(varyHeader, {}) === void 0;
37873
+ }
37371
37874
  function isEtagUsable(etag) {
37372
37875
  if (etag.length <= 2) {
37373
37876
  return false;
@@ -37398,24 +37901,23 @@ var require_cache = __commonJS({
37398
37901
  throw new TypeError(`${name} needs to have at least one method`);
37399
37902
  }
37400
37903
  for (const method of methods) {
37401
- if (!safeHTTPMethods.includes(method)) {
37904
+ if (!arrayIncludes(safeHTTPMethods, method)) {
37402
37905
  throw new TypeError(`element of ${name}-array needs to be one of following values: ${safeHTTPMethods.join(", ")}, got ${method}`);
37403
37906
  }
37404
37907
  }
37405
37908
  }
37406
37909
  function makeDeduplicationKey(cacheKey, excludeHeaders) {
37407
- let key = `${cacheKey.origin}:${cacheKey.method}:${cacheKey.path}`;
37910
+ const headers = {};
37408
37911
  if (cacheKey.headers) {
37409
37912
  const sortedHeaders = Object.keys(cacheKey.headers).sort();
37410
37913
  for (const header of sortedHeaders) {
37411
37914
  if (excludeHeaders?.has(header.toLowerCase())) {
37412
37915
  continue;
37413
37916
  }
37414
- const value = cacheKey.headers[header];
37415
- key += `:${header}=${Array.isArray(value) ? value.join(",") : value}`;
37917
+ headers[header] = cacheKey.headers[header];
37416
37918
  }
37417
37919
  }
37418
- return key;
37920
+ return JSON.stringify([cacheKey.origin, cacheKey.method, cacheKey.path, headers]);
37419
37921
  }
37420
37922
  module.exports = {
37421
37923
  makeCacheKey,
@@ -37423,7 +37925,10 @@ var require_cache = __commonJS({
37423
37925
  assertCacheKey,
37424
37926
  assertCacheValue,
37425
37927
  parseCacheControlHeader,
37928
+ hasInvalidCacheControlDirective,
37426
37929
  parseVaryHeader,
37930
+ hasVaryStar,
37931
+ isInvalidOrWildcardVaryHeader,
37427
37932
  isEtagUsable,
37428
37933
  assertCacheMethods,
37429
37934
  assertCacheStore,
@@ -37446,6 +37951,13 @@ var require_date = __commonJS({
37446
37951
  return parseRfc850Date(date);
37447
37952
  }
37448
37953
  }
37954
+ function makeDate(year, monthIdx, day, hour, minute, second, weekday) {
37955
+ const result = new Date(Date.UTC(year, monthIdx, day, hour, minute, second));
37956
+ if (year >= 0 && year <= 99) {
37957
+ result.setUTCFullYear(year);
37958
+ }
37959
+ 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;
37960
+ }
37449
37961
  function parseImfDate(date) {
37450
37962
  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
37963
  return void 0;
@@ -37606,8 +38118,7 @@ var require_date = __commonJS({
37606
38118
  }
37607
38119
  second = (code1 - 48) * 10 + (code2 - 48);
37608
38120
  }
37609
- const result = new Date(Date.UTC(year, monthIdx, day, hour, minute, second));
37610
- return result.getUTCDay() === weekday ? result : void 0;
38121
+ return makeDate(year, monthIdx, day, hour, minute, second, weekday);
37611
38122
  }
37612
38123
  function parseAscTimeDate(date) {
37613
38124
  if (date.length !== 24 || date[7] !== " " || date[10] !== " " || date[19] !== " ") {
@@ -37769,8 +38280,7 @@ var require_date = __commonJS({
37769
38280
  return void 0;
37770
38281
  }
37771
38282
  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;
38283
+ return makeDate(year, monthIdx, day, hour, minute, second, weekday);
37774
38284
  }
37775
38285
  function parseRfc850Date(date) {
37776
38286
  let commaIndex = -1;
@@ -37919,8 +38429,7 @@ var require_date = __commonJS({
37919
38429
  }
37920
38430
  second = (code1 - 48) * 10 + (code2 - 48);
37921
38431
  }
37922
- const result = new Date(Date.UTC(year, monthIdx, day, hour, minute, second));
37923
- return result.getUTCDay() === weekday ? result : void 0;
38432
+ return makeDate(year, monthIdx, day, hour, minute, second, weekday);
37924
38433
  }
37925
38434
  module.exports = {
37926
38435
  parseHttpDate
@@ -37935,7 +38444,10 @@ var require_cache_handler = __commonJS({
37935
38444
  var util = require_util();
37936
38445
  var {
37937
38446
  parseCacheControlHeader,
38447
+ hasInvalidCacheControlDirective,
37938
38448
  parseVaryHeader,
38449
+ hasVaryStar,
38450
+ isInvalidOrWildcardVaryHeader,
37939
38451
  isEtagUsable
37940
38452
  } = require_cache();
37941
38453
  var { parseHttpDate } = require_date();
@@ -37959,6 +38471,78 @@ var require_cache_handler = __commonJS({
37959
38471
  206
37960
38472
  ];
37961
38473
  var MAX_RESPONSE_AGE = 2147483647e3;
38474
+ function trimOWS(value) {
38475
+ return value.replace(/^[\t ]+|[\t ]+$/g, "");
38476
+ }
38477
+ function arrayIncludes(array, value) {
38478
+ for (let i = 0; i < array.length; i++) {
38479
+ if (array[i] === value) {
38480
+ return true;
38481
+ }
38482
+ }
38483
+ return false;
38484
+ }
38485
+ function appendConnectionHeaderTokens(headersToRemove, connectionHeader) {
38486
+ const values = Array.isArray(connectionHeader) ? connectionHeader : [connectionHeader];
38487
+ for (let i = 0; i < values.length; i++) {
38488
+ const tokens = values[i].split(",");
38489
+ for (let j = 0; j < tokens.length; j++) {
38490
+ headersToRemove.push(trimOWS(tokens[j]).toLowerCase());
38491
+ }
38492
+ }
38493
+ }
38494
+ function getSameOriginPath(cacheKey, location) {
38495
+ if (typeof location !== "string") {
38496
+ return void 0;
38497
+ }
38498
+ let originUrl;
38499
+ let requestUrl;
38500
+ let locationUrl;
38501
+ try {
38502
+ originUrl = new URL(cacheKey.origin);
38503
+ requestUrl = new URL(cacheKey.path, originUrl);
38504
+ locationUrl = new URL(location, requestUrl);
38505
+ } catch {
38506
+ return void 0;
38507
+ }
38508
+ if (locationUrl.origin !== originUrl.origin) {
38509
+ return void 0;
38510
+ }
38511
+ return locationUrl.pathname + locationUrl.search;
38512
+ }
38513
+ function deleteCachedUri(store, cacheKey, path74) {
38514
+ deleteCachedValue(store, {
38515
+ ...cacheKey,
38516
+ path: path74
38517
+ });
38518
+ for (let i = 0; i < util.safeHTTPMethods.length; i++) {
38519
+ const method = util.safeHTTPMethods[i];
38520
+ if (method !== cacheKey.method) {
38521
+ deleteCachedValue(store, {
38522
+ ...cacheKey,
38523
+ method,
38524
+ path: path74
38525
+ });
38526
+ }
38527
+ }
38528
+ }
38529
+ function deleteLocationTargets(store, cacheKey, headerValue) {
38530
+ if (headerValue === void 0) {
38531
+ return;
38532
+ }
38533
+ const values = Array.isArray(headerValue) ? headerValue : [headerValue];
38534
+ for (let i = 0; i < values.length; i++) {
38535
+ const path74 = getSameOriginPath(cacheKey, values[i]);
38536
+ if (path74 !== void 0) {
38537
+ deleteCachedUri(store, cacheKey, path74);
38538
+ }
38539
+ }
38540
+ }
38541
+ function invalidateUnsafeRequest(store, cacheKey, resHeaders) {
38542
+ deleteCachedUri(store, cacheKey, cacheKey.path);
38543
+ deleteLocationTargets(store, cacheKey, resHeaders.location);
38544
+ deleteLocationTargets(store, cacheKey, resHeaders["content-location"]);
38545
+ }
37962
38546
  var CacheHandler = class {
37963
38547
  /**
37964
38548
  * @type {import('../../types/cache-interceptor.d.ts').default.CacheKey}
@@ -38018,35 +38602,53 @@ var require_cache_handler = __commonJS({
38018
38602
  statusMessage
38019
38603
  );
38020
38604
  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
- }
38605
+ if (!arrayIncludes(util.safeHTTPMethods, this.#cacheKey.method) && statusCode >= 200 && statusCode <= 399) {
38606
+ invalidateUnsafeRequest(this.#store, this.#cacheKey, resHeaders);
38026
38607
  return downstreamOnHeaders();
38027
38608
  }
38028
38609
  const cacheControlHeader = resHeaders["cache-control"];
38029
- const heuristicallyCacheable = resHeaders["last-modified"] && HEURISTICALLY_CACHEABLE_STATUS_CODES.includes(statusCode);
38610
+ const cacheControlDirectives = cacheControlHeader ? parseCacheControlHeader(cacheControlHeader) : {};
38611
+ if (revalidationResponseDisallowsCachedReuse(this.#cacheType, resHeaders, cacheControlDirectives)) {
38612
+ deleteCachedValue(this.#store, this.#cacheKey);
38613
+ return downstreamOnHeaders();
38614
+ }
38615
+ const heuristicallyCacheable = resHeaders["last-modified"] && arrayIncludes(HEURISTICALLY_CACHEABLE_STATUS_CODES, statusCode);
38030
38616
  if (!cacheControlHeader && !resHeaders["expires"] && !heuristicallyCacheable && !this.#cacheByDefault) {
38617
+ if (statusCode === 304 && resHeaders.vary && isInvalidOrWildcardVaryHeader(resHeaders.vary)) {
38618
+ deleteCachedValue(this.#store, this.#cacheKey);
38619
+ }
38031
38620
  return downstreamOnHeaders();
38032
38621
  }
38033
- const cacheControlDirectives = cacheControlHeader ? parseCacheControlHeader(cacheControlHeader) : {};
38034
- if (!canCacheResponse(this.#cacheType, statusCode, resHeaders, cacheControlDirectives, this.#cacheKey.headers)) {
38622
+ if (!canCacheResponse(this.#cacheType, this.#cacheKey.method, statusCode, resHeaders, cacheControlDirectives, this.#cacheKey.headers)) {
38623
+ if (statusCode === 304 && (cacheControlHeader || revalidationResponseDisallowsCachedReuse(this.#cacheType, resHeaders, cacheControlDirectives))) {
38624
+ deleteCachedValue(this.#store, this.#cacheKey);
38625
+ }
38035
38626
  return downstreamOnHeaders();
38036
38627
  }
38037
38628
  const now = Date.now();
38038
- const resAge = resHeaders.age ? getAge(resHeaders.age) : void 0;
38039
- if (resAge && resAge >= MAX_RESPONSE_AGE) {
38629
+ const resAge = Object.hasOwn(resHeaders, "age") ? getAge(resHeaders.age) : void 0;
38630
+ if (resAge !== void 0 && resAge >= MAX_RESPONSE_AGE) {
38631
+ deleteCachedValueIfNotModified(statusCode, this.#store, this.#cacheKey);
38632
+ return downstreamOnHeaders();
38633
+ }
38634
+ const resDate = Object.hasOwn(resHeaders, "date") ? getDate(resHeaders.date) : void 0;
38635
+ if (resDate === null) {
38636
+ deleteCachedValueIfNotModified(statusCode, this.#store, this.#cacheKey);
38040
38637
  return downstreamOnHeaders();
38041
38638
  }
38042
- const resDate = typeof resHeaders.date === "string" ? parseHttpDate(resHeaders.date) : void 0;
38639
+ const apparentAge = resDate ? Math.max(0, now - resDate.getTime()) : 0;
38640
+ const currentAge = Math.max(apparentAge, resAge ?? 0);
38043
38641
  const staleAt = determineStaleAt(this.#cacheType, now, resAge, resHeaders, resDate, cacheControlDirectives) ?? this.#cacheByDefault;
38044
- if (staleAt === void 0 || resAge && resAge > staleAt) {
38642
+ if (staleAt === void 0 || currentAge >= staleAt) {
38643
+ if (cacheControlHeader || staleAt !== void 0) {
38644
+ deleteCachedValueIfNotModified(statusCode, this.#store, this.#cacheKey);
38645
+ }
38045
38646
  return downstreamOnHeaders();
38046
38647
  }
38047
- const baseTime = resDate ? resDate.getTime() : now;
38648
+ const baseTime = now - currentAge;
38048
38649
  const absoluteStaleAt = staleAt + baseTime;
38049
38650
  if (now >= absoluteStaleAt) {
38651
+ deleteCachedValueIfNotModified(statusCode, this.#store, this.#cacheKey);
38050
38652
  return downstreamOnHeaders();
38051
38653
  }
38052
38654
  let varyDirectives;
@@ -38056,7 +38658,8 @@ var require_cache_handler = __commonJS({
38056
38658
  return downstreamOnHeaders();
38057
38659
  }
38058
38660
  }
38059
- const deleteAt = determineDeleteAt(baseTime, cacheControlDirectives, absoluteStaleAt);
38661
+ const cachedAt = baseTime;
38662
+ const deleteAt = determineDeleteAt(baseTime, now, cacheControlDirectives, absoluteStaleAt);
38060
38663
  const strippedHeaders = stripNecessaryHeaders(resHeaders, cacheControlDirectives);
38061
38664
  const value = {
38062
38665
  statusCode,
@@ -38064,7 +38667,7 @@ var require_cache_handler = __commonJS({
38064
38667
  headers: strippedHeaders,
38065
38668
  vary: varyDirectives,
38066
38669
  cacheControlDirectives,
38067
- cachedAt: resAge ? now - resAge : now,
38670
+ cachedAt,
38068
38671
  staleAt: absoluteStaleAt,
38069
38672
  deleteAt
38070
38673
  };
@@ -38076,6 +38679,7 @@ var require_cache_handler = __commonJS({
38076
38679
  value.statusCode = cachedValue.statusCode;
38077
38680
  value.statusMessage = cachedValue.statusMessage;
38078
38681
  value.etag = cachedValue.etag;
38682
+ value.vary = varyDirectives ?? cachedValue.vary;
38079
38683
  value.headers = { ...cachedValue.headers, ...strippedHeaders };
38080
38684
  downstreamOnHeaders();
38081
38685
  this.#writeStream = this.#store.createWriteStream(this.#cacheKey, value);
@@ -38166,74 +38770,129 @@ var require_cache_handler = __commonJS({
38166
38770
  this.#handler.onResponseError?.(controller, err2);
38167
38771
  }
38168
38772
  };
38169
- function canCacheResponse(cacheType, statusCode, resHeaders, cacheControlDirectives, reqHeaders) {
38170
- if (statusCode < 200 || NOT_UNDERSTOOD_STATUS_CODES.includes(statusCode)) {
38773
+ function deleteCachedValue(store, cacheKey) {
38774
+ try {
38775
+ store.delete(cacheKey)?.catch?.(noop);
38776
+ } catch {
38777
+ }
38778
+ }
38779
+ function deleteCachedValueIfNotModified(statusCode, store, cacheKey) {
38780
+ if (statusCode === 304) {
38781
+ deleteCachedValue(store, cacheKey);
38782
+ }
38783
+ }
38784
+ function revalidationResponseDisallowsCachedReuse(cacheType, resHeaders, cacheControlDirectives) {
38785
+ return cacheControlDirectives["no-store"] === true || cacheType === "shared" && (cacheControlDirectives.private === true || Object.hasOwn(resHeaders, "set-cookie")) || (resHeaders.vary ? isInvalidOrWildcardVaryHeader(resHeaders.vary) : false);
38786
+ }
38787
+ function canCacheResponse(cacheType, method, statusCode, resHeaders, cacheControlDirectives, reqHeaders) {
38788
+ if (!arrayIncludes(util.safeHTTPMethods, method)) {
38789
+ return false;
38790
+ }
38791
+ if (statusCode < 200 || arrayIncludes(NOT_UNDERSTOOD_STATUS_CODES, statusCode)) {
38171
38792
  return false;
38172
38793
  }
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
38794
+ 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
38795
  !(cacheControlDirectives.private && cacheType === "private") && !(cacheControlDirectives["s-maxage"] !== void 0 && cacheType === "shared")) {
38175
38796
  return false;
38176
38797
  }
38177
38798
  if (cacheControlDirectives["no-store"]) {
38178
38799
  return false;
38179
38800
  }
38180
- if (cacheType === "shared" && cacheControlDirectives.private === true) {
38801
+ if (cacheType === "shared" && (cacheControlDirectives.private === true || Object.hasOwn(resHeaders, "set-cookie"))) {
38181
38802
  return false;
38182
38803
  }
38183
- if (resHeaders.vary?.includes("*")) {
38804
+ if (resHeaders.vary && hasVaryStar(resHeaders.vary)) {
38184
38805
  return false;
38185
38806
  }
38186
- if (reqHeaders?.authorization) {
38807
+ if (reqHeaders != null && Object.hasOwn(reqHeaders, "authorization")) {
38187
38808
  if (!cacheControlDirectives.public && !cacheControlDirectives["s-maxage"] && !cacheControlDirectives["must-revalidate"]) {
38188
38809
  return false;
38189
38810
  }
38190
38811
  if (typeof reqHeaders.authorization !== "string") {
38191
38812
  return false;
38192
38813
  }
38193
- if (Array.isArray(cacheControlDirectives["no-cache"]) && cacheControlDirectives["no-cache"].includes("authorization")) {
38814
+ if (Array.isArray(cacheControlDirectives["no-cache"]) && arrayIncludes(cacheControlDirectives["no-cache"], "authorization")) {
38194
38815
  return false;
38195
38816
  }
38196
- if (Array.isArray(cacheControlDirectives["private"]) && cacheControlDirectives["private"].includes("authorization")) {
38817
+ if (Array.isArray(cacheControlDirectives["private"]) && arrayIncludes(cacheControlDirectives["private"], "authorization")) {
38197
38818
  return false;
38198
38819
  }
38199
38820
  }
38200
38821
  return true;
38201
38822
  }
38823
+ function getDate(dateHeader) {
38824
+ let dateValue = dateHeader;
38825
+ if (Array.isArray(dateValue)) {
38826
+ if (dateValue.length !== 1) {
38827
+ return null;
38828
+ }
38829
+ dateValue = dateValue[0];
38830
+ }
38831
+ if (typeof dateValue !== "string") {
38832
+ return null;
38833
+ }
38834
+ return parseHttpDate(dateValue);
38835
+ }
38202
38836
  function getAge(ageHeader) {
38203
- const age = parseInt(Array.isArray(ageHeader) ? ageHeader[0] : ageHeader);
38204
- return isNaN(age) ? void 0 : age * 1e3;
38837
+ let ageValue = ageHeader;
38838
+ if (Array.isArray(ageValue)) {
38839
+ if (ageValue.length !== 1) {
38840
+ return MAX_RESPONSE_AGE;
38841
+ }
38842
+ ageValue = ageValue[0];
38843
+ }
38844
+ if (typeof ageValue !== "string" || !/^[\t ]*[0-9]+[\t ]*$/.test(ageValue)) {
38845
+ return MAX_RESPONSE_AGE;
38846
+ }
38847
+ const age = BigInt(ageValue.replace(/^[\t ]+|[\t ]+$/g, ""));
38848
+ if (age >= BigInt(MAX_RESPONSE_AGE / 1e3)) {
38849
+ return MAX_RESPONSE_AGE;
38850
+ }
38851
+ return Number(age) * 1e3;
38205
38852
  }
38206
38853
  function determineStaleAt(cacheType, now, age, resHeaders, responseDate, cacheControlDirectives) {
38207
38854
  if (cacheType === "shared") {
38855
+ if (hasInvalidCacheControlDirective(cacheControlDirectives, "s-maxage")) {
38856
+ return 0;
38857
+ }
38208
38858
  const sMaxAge = cacheControlDirectives["s-maxage"];
38209
38859
  if (sMaxAge !== void 0) {
38210
- return sMaxAge > 0 ? sMaxAge * 1e3 : void 0;
38860
+ return sMaxAge * 1e3;
38211
38861
  }
38212
38862
  }
38863
+ if (hasInvalidCacheControlDirective(cacheControlDirectives, "max-age")) {
38864
+ return 0;
38865
+ }
38213
38866
  const maxAge = cacheControlDirectives["max-age"];
38214
38867
  if (maxAge !== void 0) {
38215
- return maxAge > 0 ? maxAge * 1e3 : void 0;
38868
+ return maxAge * 1e3;
38216
38869
  }
38217
- if (typeof resHeaders.expires === "string") {
38870
+ if (Object.hasOwn(resHeaders, "expires")) {
38871
+ if (typeof resHeaders.expires !== "string") {
38872
+ return 0;
38873
+ }
38218
38874
  const expiresDate = parseHttpDate(resHeaders.expires);
38219
- if (expiresDate) {
38220
- if (now >= expiresDate.getTime()) {
38221
- return void 0;
38875
+ if (!expiresDate) {
38876
+ return 0;
38877
+ }
38878
+ if (now >= expiresDate.getTime()) {
38879
+ return 0;
38880
+ }
38881
+ if (responseDate) {
38882
+ if (responseDate >= expiresDate) {
38883
+ return 0;
38222
38884
  }
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
- }
38885
+ const freshnessLifetime = expiresDate.getTime() - responseDate.getTime();
38886
+ if (age !== void 0 && age >= freshnessLifetime) {
38887
+ return 0;
38230
38888
  }
38231
- return expiresDate.getTime() - now;
38889
+ return freshnessLifetime;
38232
38890
  }
38891
+ return expiresDate.getTime() - now;
38233
38892
  }
38234
38893
  if (typeof resHeaders["last-modified"] === "string") {
38235
- const lastModified = new Date(resHeaders["last-modified"]);
38236
- if (isValidDate(lastModified)) {
38894
+ const lastModified = parseHttpDate(resHeaders["last-modified"]);
38895
+ if (lastModified) {
38237
38896
  if (lastModified.getTime() >= now) {
38238
38897
  return void 0;
38239
38898
  }
@@ -38242,11 +38901,11 @@ var require_cache_handler = __commonJS({
38242
38901
  }
38243
38902
  }
38244
38903
  if (cacheControlDirectives.immutable) {
38245
- return 31536e3;
38904
+ return 31536e6;
38246
38905
  }
38247
38906
  return void 0;
38248
38907
  }
38249
- function determineDeleteAt(now, cacheControlDirectives, staleAt) {
38908
+ function determineDeleteAt(baseTime, cachedAt, cacheControlDirectives, staleAt) {
38250
38909
  let staleWhileRevalidate = -Infinity;
38251
38910
  let staleIfError = -Infinity;
38252
38911
  let immutable = -Infinity;
@@ -38257,11 +38916,12 @@ var require_cache_handler = __commonJS({
38257
38916
  staleIfError = staleAt + cacheControlDirectives["stale-if-error"] * 1e3;
38258
38917
  }
38259
38918
  if (cacheControlDirectives.immutable && staleWhileRevalidate === -Infinity && staleIfError === -Infinity) {
38260
- immutable = now + 31536e6;
38919
+ immutable = cachedAt + 31536e6;
38261
38920
  }
38262
38921
  if (staleWhileRevalidate === -Infinity && staleIfError === -Infinity && immutable === -Infinity) {
38263
- const freshnessLifetime = staleAt - now;
38264
- return staleAt + freshnessLifetime;
38922
+ const freshnessLifetime = staleAt - baseTime;
38923
+ const datePrecisionPadding = Math.min(Math.max(cachedAt - baseTime, 0), 1e3);
38924
+ return staleAt + freshnessLifetime + datePrecisionPadding;
38265
38925
  }
38266
38926
  return Math.max(staleAt, staleWhileRevalidate, staleIfError, immutable);
38267
38927
  }
@@ -38279,11 +38939,7 @@ var require_cache_handler = __commonJS({
38279
38939
  "age"
38280
38940
  ];
38281
38941
  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
- }
38942
+ appendConnectionHeaderTokens(headersToRemove, resHeaders["connection"]);
38287
38943
  }
38288
38944
  if (Array.isArray(cacheControlDirectives["no-cache"])) {
38289
38945
  headersToRemove.push(...cacheControlDirectives["no-cache"]);
@@ -38293,16 +38949,13 @@ var require_cache_handler = __commonJS({
38293
38949
  }
38294
38950
  let strippedHeaders;
38295
38951
  for (const headerName of headersToRemove) {
38296
- if (resHeaders[headerName]) {
38952
+ if (Object.hasOwn(resHeaders, headerName)) {
38297
38953
  strippedHeaders ??= { ...resHeaders };
38298
38954
  delete strippedHeaders[headerName];
38299
38955
  }
38300
38956
  }
38301
38957
  return strippedHeaders ?? resHeaders;
38302
38958
  }
38303
- function isValidDate(date) {
38304
- return date instanceof Date && Number.isFinite(date.valueOf());
38305
- }
38306
38959
  module.exports = CacheHandler;
38307
38960
  }
38308
38961
  });
@@ -38473,12 +39126,43 @@ var require_memory_cache_store = __commonJS({
38473
39126
  }
38474
39127
  };
38475
39128
  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;
39129
+ for (let i = 0; i < entries.length; i++) {
39130
+ const entry = entries[i];
39131
+ if (entry.deleteAt > now && entry.method === key.method && varyMatches(key, entry)) {
39132
+ return entry;
38479
39133
  }
38480
- return entry.vary[headerName] === key.headers[headerName];
38481
- })));
39134
+ }
39135
+ }
39136
+ function varyMatches(key, entry) {
39137
+ if (entry.vary == null) {
39138
+ return true;
39139
+ }
39140
+ for (const headerName in entry.vary) {
39141
+ if (Object.hasOwn(entry.vary, headerName) && !headerValueEquals(key.headers?.[headerName], entry.vary[headerName])) {
39142
+ return false;
39143
+ }
39144
+ }
39145
+ return true;
39146
+ }
39147
+ function headerValueEquals(lhs, rhs) {
39148
+ if (lhs == null && rhs == null) {
39149
+ return true;
39150
+ }
39151
+ if (lhs == null && rhs != null || lhs != null && rhs == null) {
39152
+ return false;
39153
+ }
39154
+ if (Array.isArray(lhs) && Array.isArray(rhs)) {
39155
+ if (lhs.length !== rhs.length) {
39156
+ return false;
39157
+ }
39158
+ for (let i = 0; i < lhs.length; i++) {
39159
+ if (lhs[i] !== rhs[i]) {
39160
+ return false;
39161
+ }
39162
+ }
39163
+ return true;
39164
+ }
39165
+ return lhs === rhs;
38482
39166
  }
38483
39167
  module.exports = MemoryCacheStore;
38484
39168
  }
@@ -38492,7 +39176,7 @@ var require_cache_revalidation_handler = __commonJS({
38492
39176
  var CacheRevalidationHandler = class {
38493
39177
  #successful = false;
38494
39178
  /**
38495
- * @type {((boolean, any) => void) | null}
39179
+ * @type {((success: boolean, context?: any, statusCode?: number, headers?: import('../../types/header.d.ts').IncomingHttpHeaders) => void) | null}
38496
39180
  */
38497
39181
  #callback;
38498
39182
  /**
@@ -38505,7 +39189,7 @@ var require_cache_revalidation_handler = __commonJS({
38505
39189
  */
38506
39190
  #allowErrorStatusCodes;
38507
39191
  /**
38508
- * @param {(boolean) => void} callback Function to call if the cached value is valid
39192
+ * @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
39193
  * @param {import('../../types/dispatcher.d.ts').default.DispatchHandlers} handler
38510
39194
  * @param {boolean} allowErrorStatusCodes
38511
39195
  */
@@ -38527,7 +39211,7 @@ var require_cache_revalidation_handler = __commonJS({
38527
39211
  onResponseStart(controller, statusCode, headers, statusMessage) {
38528
39212
  assert(this.#callback != null);
38529
39213
  this.#successful = statusCode === 304 || this.#allowErrorStatusCodes && statusCode >= 500 && statusCode <= 504;
38530
- this.#callback(this.#successful, this.#context);
39214
+ this.#callback(this.#successful, this.#context, statusCode, headers);
38531
39215
  this.#callback = null;
38532
39216
  if (this.#successful) {
38533
39217
  return true;
@@ -38581,8 +39265,9 @@ var require_cache2 = __commonJS({
38581
39265
  var CacheHandler = require_cache_handler();
38582
39266
  var MemoryCacheStore = require_memory_cache_store();
38583
39267
  var CacheRevalidationHandler = require_cache_revalidation_handler();
38584
- var { assertCacheStore, assertCacheMethods, makeCacheKey, normalizeHeaders, parseCacheControlHeader } = require_cache();
39268
+ var { assertCacheStore, assertCacheMethods, makeCacheKey, normalizeHeaders, parseCacheControlHeader, isInvalidOrWildcardVaryHeader } = require_cache();
38585
39269
  var { AbortError } = require_errors();
39270
+ var { parseHttpDate } = require_date();
38586
39271
  function assertCacheOrigins(origins, name) {
38587
39272
  if (origins === void 0) return;
38588
39273
  if (!Array.isArray(origins)) {
@@ -38597,6 +39282,37 @@ var require_cache2 = __commonJS({
38597
39282
  }
38598
39283
  var nop = () => {
38599
39284
  };
39285
+ function trimOWS(value) {
39286
+ return value.replace(/^[\t ]+|[\t ]+$/g, "");
39287
+ }
39288
+ function arrayIncludes(array, value) {
39289
+ for (let i = 0; i < array.length; i++) {
39290
+ if (array[i] === value) {
39291
+ return true;
39292
+ }
39293
+ }
39294
+ return false;
39295
+ }
39296
+ function hasPragmaNoCache(headers) {
39297
+ const pragma = headers?.pragma;
39298
+ if (!pragma) {
39299
+ return false;
39300
+ }
39301
+ const values = Array.isArray(pragma) ? pragma : [pragma];
39302
+ for (let i = 0; i < values.length; i++) {
39303
+ const value = values[i];
39304
+ if (typeof value !== "string") {
39305
+ continue;
39306
+ }
39307
+ const directives = value.split(",");
39308
+ for (let j = 0; j < directives.length; j++) {
39309
+ if (trimOWS(directives[j]).toLowerCase() === "no-cache") {
39310
+ return true;
39311
+ }
39312
+ }
39313
+ }
39314
+ return false;
39315
+ }
38600
39316
  function needsRevalidation(result, cacheControlDirectives, { headers = {} }) {
38601
39317
  if (cacheControlDirectives?.["no-cache"]) {
38602
39318
  return true;
@@ -38609,10 +39325,58 @@ var require_cache2 = __commonJS({
38609
39325
  }
38610
39326
  return false;
38611
39327
  }
38612
- function isStale(result, cacheControlDirectives) {
39328
+ function staleResponseRequiresRevalidation(result, cacheType) {
39329
+ 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
39330
+ // s-maxage implies proxy-revalidate for shared caches.
39331
+ result.cacheControlDirectives?.["s-maxage"] !== void 0);
39332
+ }
39333
+ function revalidationResponseDisallowsCachedReuse(cacheType, headers) {
39334
+ if (headers.vary && isInvalidOrWildcardVaryHeader(headers.vary) || cacheType === "shared" && Object.hasOwn(headers, "set-cookie")) {
39335
+ return true;
39336
+ }
39337
+ const cacheControl = headers["cache-control"];
39338
+ if (!cacheControl) {
39339
+ return false;
39340
+ }
39341
+ const cacheControlDirectives = parseCacheControlHeader(cacheControl);
39342
+ return cacheControlDirectives["no-store"] === true || cacheType === "shared" && cacheControlDirectives.private === true;
39343
+ }
39344
+ function revalidationResponseUpdatesCacheControl(headers) {
39345
+ return headers["cache-control"] !== void 0;
39346
+ }
39347
+ function deleteCachedValue(store, cacheKey) {
39348
+ try {
39349
+ store.delete(cacheKey)?.catch?.(nop);
39350
+ } catch {
39351
+ }
39352
+ }
39353
+ function getUsableLastModified(headers) {
39354
+ const lastModified = headers?.["last-modified"];
39355
+ if (typeof lastModified === "string" && parseHttpDate(lastModified)) {
39356
+ return lastModified;
39357
+ }
39358
+ }
39359
+ function makeRevalidationHeaders(opts, result) {
39360
+ const headers = {
39361
+ ...opts.headers,
39362
+ "if-modified-since": getUsableLastModified(result.headers) ?? new Date(result.cachedAt).toUTCString()
39363
+ };
39364
+ if (result.etag) {
39365
+ headers["if-none-match"] = result.etag;
39366
+ }
39367
+ if (result.vary) {
39368
+ for (const key in result.vary) {
39369
+ if (result.vary[key] != null) {
39370
+ headers[key] = result.vary[key];
39371
+ }
39372
+ }
39373
+ }
39374
+ return headers;
39375
+ }
39376
+ function isStale(result, cacheControlDirectives, cacheType) {
38613
39377
  const now = Date.now();
38614
39378
  if (now > result.staleAt) {
38615
- if (cacheControlDirectives?.["max-stale"]) {
39379
+ if (!staleResponseRequiresRevalidation(result, cacheType) && cacheControlDirectives?.["max-stale"]) {
38616
39380
  const gracePeriod = result.staleAt + cacheControlDirectives["max-stale"] * 1e3;
38617
39381
  return now > gracePeriod;
38618
39382
  }
@@ -38625,9 +39389,9 @@ var require_cache2 = __commonJS({
38625
39389
  }
38626
39390
  return false;
38627
39391
  }
38628
- function withinStaleWhileRevalidateWindow(result) {
39392
+ function withinStaleWhileRevalidateWindow(result, cacheType) {
38629
39393
  const staleWhileRevalidate = result.cacheControlDirectives?.["stale-while-revalidate"];
38630
- if (!staleWhileRevalidate) {
39394
+ if (!staleWhileRevalidate || staleResponseRequiresRevalidation(result, cacheType)) {
38631
39395
  return false;
38632
39396
  }
38633
39397
  const now = Date.now();
@@ -38722,37 +39486,29 @@ var require_cache2 = __commonJS({
38722
39486
  if (!result) {
38723
39487
  return handleUncachedResponse(dispatch, globalOpts, cacheKey, handler, opts, reqCacheControl);
38724
39488
  }
39489
+ if (globalOpts.type === "shared" && Object.hasOwn(result.headers, "set-cookie")) {
39490
+ if (util.isStream(result.body)) {
39491
+ result.body.on("error", nop).destroy();
39492
+ }
39493
+ deleteCachedValue(globalOpts.store, cacheKey);
39494
+ return handleUncachedResponse(dispatch, globalOpts, cacheKey, handler, opts, reqCacheControl);
39495
+ }
38725
39496
  const now = Date.now();
38726
39497
  if (now > result.deleteAt) {
38727
39498
  return dispatch(opts, new CacheHandler(globalOpts, cacheKey, handler));
38728
39499
  }
38729
39500
  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);
39501
+ const requestMaxAgeExpired = reqCacheControl?.["max-age"] !== void 0 && age >= reqCacheControl["max-age"];
39502
+ const stale = requestMaxAgeExpired || isStale(result, reqCacheControl, globalOpts.type);
39503
+ const revalidate = requestMaxAgeExpired || needsRevalidation(result, reqCacheControl, opts);
38735
39504
  if (stale || revalidate) {
38736
39505
  if (util.isStream(opts.body) && util.bodyLength(opts.body) !== 0) {
38737
39506
  return dispatch(opts, new CacheHandler(globalOpts, cacheKey, handler));
38738
39507
  }
38739
- if (!revalidate && withinStaleWhileRevalidateWindow(result)) {
39508
+ if (!revalidate && withinStaleWhileRevalidateWindow(result, globalOpts.type)) {
38740
39509
  sendCachedValue(handler, opts, result, age, null, true);
38741
39510
  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
- }
39511
+ const headers2 = makeRevalidationHeaders(opts, result);
38756
39512
  dispatch(
38757
39513
  {
38758
39514
  ...opts,
@@ -38778,32 +39534,33 @@ var require_cache2 = __commonJS({
38778
39534
  return true;
38779
39535
  }
38780
39536
  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
- }
39537
+ if (!staleResponseRequiresRevalidation(result, globalOpts.type)) {
39538
+ const staleIfErrorExpiry = result.cacheControlDirectives["stale-if-error"] ?? reqCacheControl?.["stale-if-error"];
39539
+ if (staleIfErrorExpiry) {
39540
+ withinStaleIfErrorThreshold = now < result.staleAt + staleIfErrorExpiry * 1e3;
38797
39541
  }
38798
39542
  }
39543
+ const headers = makeRevalidationHeaders(opts, result);
38799
39544
  return dispatch(
38800
39545
  {
38801
39546
  ...opts,
38802
39547
  headers
38803
39548
  },
38804
39549
  new CacheRevalidationHandler(
38805
- (success, context) => {
39550
+ (success, context, statusCode, headers2) => {
38806
39551
  if (success) {
39552
+ if (statusCode === 304) {
39553
+ if (revalidationResponseDisallowsCachedReuse(globalOpts.type, headers2)) {
39554
+ if (util.isStream(result.body)) {
39555
+ result.body.on("error", nop).destroy();
39556
+ }
39557
+ deleteCachedValue(globalOpts.store, cacheKey);
39558
+ return dispatch(opts, new CacheHandler(globalOpts, cacheKey, handler));
39559
+ }
39560
+ if (revalidationResponseUpdatesCacheControl(headers2)) {
39561
+ deleteCachedValue(globalOpts.store, cacheKey);
39562
+ }
39563
+ }
38807
39564
  sendCachedValue(handler, opts, result, age, context, stale);
38808
39565
  } else if (util.isStream(result.body)) {
38809
39566
  result.body.on("error", nop).destroy();
@@ -38845,10 +39602,16 @@ var require_cache2 = __commonJS({
38845
39602
  cacheByDefault,
38846
39603
  type
38847
39604
  };
38848
- const safeMethodsToNotCache = util.safeHTTPMethods.filter((method) => methods.includes(method) === false);
39605
+ const safeMethodsToNotCache = [];
39606
+ for (let i = 0; i < util.safeHTTPMethods.length; i++) {
39607
+ const method = util.safeHTTPMethods[i];
39608
+ if (!arrayIncludes(methods, method)) {
39609
+ safeMethodsToNotCache.push(method);
39610
+ }
39611
+ }
38849
39612
  return (dispatch) => {
38850
39613
  return (opts2, handler) => {
38851
- if (!opts2.origin || safeMethodsToNotCache.includes(opts2.method)) {
39614
+ if (!opts2.origin || arrayIncludes(safeMethodsToNotCache, opts2.method)) {
38852
39615
  return dispatch(opts2, handler);
38853
39616
  }
38854
39617
  if (origins !== void 0) {
@@ -38874,11 +39637,14 @@ var require_cache2 = __commonJS({
38874
39637
  ...opts2,
38875
39638
  headers: normalizeHeaders(opts2)
38876
39639
  };
38877
- const reqCacheControl = opts2.headers?.["cache-control"] ? parseCacheControlHeader(opts2.headers["cache-control"]) : void 0;
39640
+ const reqCacheControl = opts2.headers?.["cache-control"] ? parseCacheControlHeader(opts2.headers["cache-control"]) : hasPragmaNoCache(opts2.headers) ? { "no-cache": true } : void 0;
38878
39641
  if (reqCacheControl?.["no-store"]) {
38879
39642
  return dispatch(opts2, handler);
38880
39643
  }
38881
39644
  const cacheKey = makeCacheKey(opts2);
39645
+ if (!arrayIncludes(util.safeHTTPMethods, opts2.method)) {
39646
+ return dispatch(opts2, new CacheHandler(globalOpts, cacheKey, handler));
39647
+ }
38882
39648
  const result = store.get(cacheKey);
38883
39649
  if (result && typeof result.then === "function") {
38884
39650
  return result.then((result2) => handleResult(
@@ -38912,7 +39678,8 @@ var require_decompress = __commonJS({
38912
39678
  "node_modules/undici/lib/interceptor/decompress.js"(exports, module) {
38913
39679
  "use strict";
38914
39680
  var { createInflate, createGunzip, createBrotliDecompress, createZstdDecompress } = __require("zlib");
38915
- var { pipeline } = __require("stream");
39681
+ var { pipeline, Transform: TransformStream2 } = __require("stream");
39682
+ var { InvalidArgumentError, ResponseExceededMaxSizeError } = require_errors();
38916
39683
  var DecoratorHandler = require_decorator_handler();
38917
39684
  var { runtimeFeatures } = require_runtime_features();
38918
39685
  var supportedEncodings = {
@@ -38928,6 +39695,23 @@ var require_decompress = __commonJS({
38928
39695
  /** @type {const} */
38929
39696
  [204, 304]
38930
39697
  );
39698
+ var defaultMaxSize = 64 * 1024 * 1024;
39699
+ function createMaxSizeLimiter(maxSize) {
39700
+ let size = 0;
39701
+ return new TransformStream2({
39702
+ transform(chunk2, _encoding, callback) {
39703
+ const decompressedSize = size + chunk2.length;
39704
+ if (decompressedSize > maxSize) {
39705
+ callback(new ResponseExceededMaxSizeError(
39706
+ `Decompressed response size (${decompressedSize}) exceeded maxSize (${maxSize})`
39707
+ ));
39708
+ return;
39709
+ }
39710
+ size = decompressedSize;
39711
+ callback(null, chunk2);
39712
+ }
39713
+ });
39714
+ }
38931
39715
  var warningEmitted = (
38932
39716
  /** @type {boolean} */
38933
39717
  false
@@ -38935,14 +39719,28 @@ var require_decompress = __commonJS({
38935
39719
  var DecompressHandler = class extends DecoratorHandler {
38936
39720
  /** @type {Transform[]} */
38937
39721
  #decompressors = [];
39722
+ /** @type {Record<string, string | string[]> | undefined} */
39723
+ #trailers;
38938
39724
  /** @type {Readonly<number[]>} */
38939
39725
  #skipStatusCodes;
38940
39726
  /** @type {boolean} */
38941
39727
  #skipErrorResponses;
38942
- constructor(handler, { skipStatusCodes = defaultSkipStatusCodes, skipErrorResponses = true } = {}) {
39728
+ /** @type {number} */
39729
+ #maxSize;
39730
+ /** @type {number} */
39731
+ #decompressedSize = 0;
39732
+ /** @type {boolean} */
39733
+ #terminated = false;
39734
+ /** @type {boolean} */
39735
+ #inputEnded = false;
39736
+ constructor(handler, { skipStatusCodes = defaultSkipStatusCodes, skipErrorResponses = true, maxSize = defaultMaxSize } = {}) {
39737
+ if (!Number.isSafeInteger(maxSize) || maxSize < 1) {
39738
+ throw new InvalidArgumentError("maxSize must be a positive integer");
39739
+ }
38943
39740
  super(handler);
38944
39741
  this.#skipStatusCodes = skipStatusCodes;
38945
39742
  this.#skipErrorResponses = skipErrorResponses;
39743
+ this.#maxSize = maxSize;
38946
39744
  }
38947
39745
  /**
38948
39746
  * Determines if decompression should be skipped based on encoding and status code
@@ -38960,7 +39758,7 @@ var require_decompress = __commonJS({
38960
39758
  * Creates a chain of decompressors for multiple content encodings
38961
39759
  *
38962
39760
  * @param {string} encodings - Comma-separated list of content encodings
38963
- * @returns {Array<DecompressorStream>} - Array of decompressor streams
39761
+ * @returns {Array<Transform>} - Array of decompressor and limiting streams
38964
39762
  * @throws {Error} - If the number of content-encodings exceeds the maximum allowed
38965
39763
  */
38966
39764
  #createDecompressionChain(encodings) {
@@ -38979,7 +39777,33 @@ var require_decompress = __commonJS({
38979
39777
  }
38980
39778
  decompressors.push(supportedEncodings[encoding]());
38981
39779
  }
38982
- return decompressors;
39780
+ if (decompressors.length < 2) {
39781
+ return decompressors;
39782
+ }
39783
+ const streams = [];
39784
+ for (let i = 0; i < decompressors.length; i++) {
39785
+ streams.push(decompressors[i]);
39786
+ if (i < decompressors.length - 1) {
39787
+ streams.push(createMaxSizeLimiter(this.#maxSize));
39788
+ }
39789
+ }
39790
+ return streams;
39791
+ }
39792
+ /**
39793
+ * Stops decompression and reports an error.
39794
+ * @param {Controller} controller - The controller to coordinate with
39795
+ * @param {Error} error - The decompression error
39796
+ * @returns {void}
39797
+ */
39798
+ #fail(controller, error) {
39799
+ if (this.#terminated) {
39800
+ return;
39801
+ }
39802
+ if (this.#inputEnded) {
39803
+ this.onResponseError(controller, error);
39804
+ } else {
39805
+ controller.abort(error);
39806
+ }
38983
39807
  }
38984
39808
  /**
38985
39809
  * Sets up event handlers for a decompressor stream using readable events
@@ -38989,8 +39813,19 @@ var require_decompress = __commonJS({
38989
39813
  */
38990
39814
  #setupDecompressorEvents(decompressor, controller) {
38991
39815
  decompressor.on("readable", () => {
39816
+ if (this.#terminated) {
39817
+ return;
39818
+ }
38992
39819
  let chunk2;
38993
39820
  while ((chunk2 = decompressor.read()) !== null) {
39821
+ const decompressedSize = this.#decompressedSize + chunk2.length;
39822
+ if (decompressedSize > this.#maxSize) {
39823
+ this.#fail(controller, new ResponseExceededMaxSizeError(
39824
+ `Decompressed response size (${decompressedSize}) exceeded maxSize (${this.#maxSize})`
39825
+ ));
39826
+ return;
39827
+ }
39828
+ this.#decompressedSize = decompressedSize;
38994
39829
  const result = super.onResponseData(controller, chunk2);
38995
39830
  if (result === false) {
38996
39831
  break;
@@ -38998,7 +39833,7 @@ var require_decompress = __commonJS({
38998
39833
  }
38999
39834
  });
39000
39835
  decompressor.on("error", (error) => {
39001
- super.onResponseError(controller, error);
39836
+ this.#fail(controller, error);
39002
39837
  });
39003
39838
  }
39004
39839
  /**
@@ -39010,7 +39845,12 @@ var require_decompress = __commonJS({
39010
39845
  const decompressor = this.#decompressors[0];
39011
39846
  this.#setupDecompressorEvents(decompressor, controller);
39012
39847
  decompressor.on("end", () => {
39013
- super.onResponseEnd(controller, {});
39848
+ if (this.#terminated) {
39849
+ return;
39850
+ }
39851
+ this.#terminated = true;
39852
+ this.#cleanupDecompressors();
39853
+ super.onResponseEnd(controller, this.#trailers);
39014
39854
  });
39015
39855
  }
39016
39856
  /**
@@ -39022,11 +39862,16 @@ var require_decompress = __commonJS({
39022
39862
  const lastDecompressor = this.#decompressors[this.#decompressors.length - 1];
39023
39863
  this.#setupDecompressorEvents(lastDecompressor, controller);
39024
39864
  pipeline(this.#decompressors, (err2) => {
39865
+ if (this.#terminated) {
39866
+ return;
39867
+ }
39025
39868
  if (err2) {
39026
- super.onResponseError(controller, err2);
39869
+ this.#fail(controller, err2);
39027
39870
  return;
39028
39871
  }
39029
- super.onResponseEnd(controller, {});
39872
+ this.#terminated = true;
39873
+ this.#cleanupDecompressors();
39874
+ super.onResponseEnd(controller, this.#trailers);
39030
39875
  });
39031
39876
  }
39032
39877
  /**
@@ -39055,6 +39900,29 @@ var require_decompress = __commonJS({
39055
39900
  }
39056
39901
  this.#decompressors = decompressors;
39057
39902
  const { "content-encoding": _, "content-length": __, ...newHeaders } = headers;
39903
+ if (controller?.rawHeaders) {
39904
+ const rawHeaders = controller.rawHeaders;
39905
+ if (Array.isArray(rawHeaders)) {
39906
+ const filteredHeaders = [];
39907
+ for (let i = 0; i < rawHeaders.length; i += 2) {
39908
+ const headerName = rawHeaders[i];
39909
+ const name = Buffer.isBuffer(headerName) ? headerName.toString("latin1") : `${headerName}`;
39910
+ const lowerName = name.toLowerCase();
39911
+ if (lowerName === "content-encoding" || lowerName === "content-length") {
39912
+ continue;
39913
+ }
39914
+ filteredHeaders.push(rawHeaders[i], rawHeaders[i + 1]);
39915
+ }
39916
+ rawHeaders.splice(0, rawHeaders.length, ...filteredHeaders);
39917
+ } else if (typeof rawHeaders === "object") {
39918
+ for (const name of Object.keys(rawHeaders)) {
39919
+ const lowerName = name.toLowerCase();
39920
+ if (lowerName === "content-encoding" || lowerName === "content-length") {
39921
+ delete rawHeaders[name];
39922
+ }
39923
+ }
39924
+ }
39925
+ }
39058
39926
  if (this.#decompressors.length === 1) {
39059
39927
  this.#setupSingleDecompressor(controller);
39060
39928
  } else {
@@ -39081,8 +39949,9 @@ var require_decompress = __commonJS({
39081
39949
  */
39082
39950
  onResponseEnd(controller, trailers) {
39083
39951
  if (this.#decompressors.length > 0) {
39952
+ this.#inputEnded = true;
39953
+ this.#trailers = trailers;
39084
39954
  this.#decompressors[0].end();
39085
- this.#cleanupDecompressors();
39086
39955
  return;
39087
39956
  }
39088
39957
  super.onResponseEnd(controller, trailers);
@@ -39093,12 +39962,14 @@ var require_decompress = __commonJS({
39093
39962
  * @returns {void}
39094
39963
  */
39095
39964
  onResponseError(controller, err2) {
39096
- if (this.#decompressors.length > 0) {
39097
- for (const decompressor of this.#decompressors) {
39098
- decompressor.destroy(err2);
39099
- }
39100
- this.#cleanupDecompressors();
39965
+ if (this.#terminated) {
39966
+ return;
39101
39967
  }
39968
+ this.#terminated = true;
39969
+ for (const decompressor of this.#decompressors) {
39970
+ decompressor.destroy();
39971
+ }
39972
+ this.#cleanupDecompressors();
39102
39973
  super.onResponseError(controller, err2);
39103
39974
  }
39104
39975
  };
@@ -39730,7 +40601,7 @@ var require_sqlite_cache_store = __commonJS({
39730
40601
  SELECT
39731
40602
  id
39732
40603
  FROM cacheInterceptorV${VERSION}
39733
- ORDER BY cachedAt DESC
40604
+ ORDER BY cachedAt ASC
39734
40605
  LIMIT ?
39735
40606
  )
39736
40607
  `);
@@ -39785,7 +40656,6 @@ var require_sqlite_cache_store = __commonJS({
39785
40656
  existingValue.id
39786
40657
  );
39787
40658
  } else {
39788
- this.#prune();
39789
40659
  this.#insertValueQuery.run(
39790
40660
  url,
39791
40661
  key.method,
@@ -39800,6 +40670,7 @@ var require_sqlite_cache_store = __commonJS({
39800
40670
  value.cachedAt,
39801
40671
  value.staleAt
39802
40672
  );
40673
+ this.#prune();
39803
40674
  }
39804
40675
  }
39805
40676
  /**
@@ -39887,7 +40758,7 @@ var require_sqlite_cache_store = __commonJS({
39887
40758
  const now = Date.now();
39888
40759
  for (const value of values) {
39889
40760
  if (now >= value.deleteAt && !canBeExpired) {
39890
- return void 0;
40761
+ continue;
39891
40762
  }
39892
40763
  let matches = true;
39893
40764
  if (value.vary) {
@@ -39917,7 +40788,12 @@ var require_sqlite_cache_store = __commonJS({
39917
40788
  if (lhs.length !== rhs.length) {
39918
40789
  return false;
39919
40790
  }
39920
- return lhs.every((x, i) => x === rhs[i]);
40791
+ for (let i = 0; i < lhs.length; i++) {
40792
+ if (lhs[i] !== rhs[i]) {
40793
+ return false;
40794
+ }
40795
+ }
40796
+ return true;
39921
40797
  }
39922
40798
  return lhs === rhs;
39923
40799
  }
@@ -42206,7 +43082,7 @@ var require_fetch = __commonJS({
42206
43082
  cacheState = "";
42207
43083
  }
42208
43084
  let responseStatus = 0;
42209
- if (fetchParams.request.mode !== "navigator" || !response.hasCrossOriginRedirects) {
43085
+ if (fetchParams.request.mode !== "navigate" || !response.hasCrossOriginRedirects) {
42210
43086
  responseStatus = response.status;
42211
43087
  const mimeType = extractMimeType(response.headersList);
42212
43088
  if (mimeType !== "failure") {
@@ -42370,7 +43246,7 @@ var require_fetch = __commonJS({
42370
43246
  if (contentLength != null) {
42371
43247
  contentLengthHeaderValue = isomorphicEncode(`${contentLength}`);
42372
43248
  }
42373
- if (contentLengthHeaderValue != null) {
43249
+ if (contentLengthHeaderValue != null && !httpRequest.headersList.contains("content-length", true)) {
42374
43250
  httpRequest.headersList.append("content-length", contentLengthHeaderValue, true);
42375
43251
  }
42376
43252
  if (contentLength != null && httpRequest.keepalive) {
@@ -42448,10 +43324,10 @@ var require_fetch = __commonJS({
42448
43324
  response.rangeRequested = true;
42449
43325
  }
42450
43326
  response.requestIncludesCredentials = includeCredentials;
42451
- if (response.status === 401 && httpRequest.responseTainting !== "cors" && includeCredentials && isTraversableNavigable(request2.traversableForUserPrompts)) {
43327
+ if (response.status === 401 && httpRequest.responseTainting !== "cors" && includeCredentials && (request2.useURLCredentials !== void 0 || isTraversableNavigable(request2.traversableForUserPrompts))) {
42452
43328
  if (request2.body != null) {
42453
43329
  if (request2.body.source == null) {
42454
- return makeNetworkError("expected non-null body source");
43330
+ return response;
42455
43331
  }
42456
43332
  request2.body = safelyExtractBody(request2.body.source)[0];
42457
43333
  }
@@ -42693,7 +43569,15 @@ var require_fetch = __commonJS({
42693
43569
  }
42694
43570
  const headersList = new HeadersList();
42695
43571
  for (let i = 0; i < rawHeaders.length; i += 2) {
42696
- headersList.append(bufferToLowerCasedHeaderName(rawHeaders[i]), rawHeaders[i + 1].toString("latin1"), true);
43572
+ const nameStr = bufferToLowerCasedHeaderName(rawHeaders[i]);
43573
+ const value = rawHeaders[i + 1];
43574
+ if (Array.isArray(value) && !Buffer.isBuffer(rawHeaders[i + 1])) {
43575
+ for (const val of value) {
43576
+ headersList.append(nameStr, val.toString("latin1"), true);
43577
+ }
43578
+ } else {
43579
+ headersList.append(nameStr, value.toString("latin1"), true);
43580
+ }
42697
43581
  }
42698
43582
  const location = headersList.get("location", true);
42699
43583
  this.body = new Readable({ read: resume });
@@ -42807,7 +43691,15 @@ var require_fetch = __commonJS({
42807
43691
  }
42808
43692
  const headersList = new HeadersList();
42809
43693
  for (let i = 0; i < rawHeaders.length; i += 2) {
42810
- headersList.append(bufferToLowerCasedHeaderName(rawHeaders[i]), rawHeaders[i + 1].toString("latin1"), true);
43694
+ const nameStr = bufferToLowerCasedHeaderName(rawHeaders[i]);
43695
+ const value = rawHeaders[i + 1];
43696
+ if (Array.isArray(value) && !Buffer.isBuffer(rawHeaders[i + 1])) {
43697
+ for (const val of value) {
43698
+ headersList.append(nameStr, val.toString("latin1"), true);
43699
+ }
43700
+ } else {
43701
+ headersList.append(nameStr, value.toString("latin1"), true);
43702
+ }
42811
43703
  }
42812
43704
  resolve2({
42813
43705
  status,
@@ -43597,14 +44489,48 @@ var require_util4 = __commonJS({
43597
44489
  for (let i = 0; i < path74.length; ++i) {
43598
44490
  const code = path74.charCodeAt(i);
43599
44491
  if (code < 32 || // exclude CTLs (0-31)
43600
- code === 127 || // DEL
44492
+ code > 126 || // exclude DEL and non-ascii
43601
44493
  code === 59) {
43602
44494
  throw new Error("Invalid cookie path");
43603
44495
  }
43604
44496
  }
43605
44497
  }
44498
+ function isLetterOrDigit(code) {
44499
+ return code >= 48 && code <= 57 || // 0-9
44500
+ code >= 65 && code <= 90 || // A-Z
44501
+ code >= 97 && code <= 122;
44502
+ }
43606
44503
  function validateCookieDomain(domain) {
43607
- if (domain.startsWith("-") || domain.endsWith(".") || domain.endsWith("-")) {
44504
+ if (domain === " ") {
44505
+ return;
44506
+ }
44507
+ if (domain.length > 255) {
44508
+ throw new Error("Invalid cookie domain");
44509
+ }
44510
+ let labelLength = 0;
44511
+ for (let i = 0; i < domain.length; ++i) {
44512
+ const code = domain.charCodeAt(i);
44513
+ if (code === 46) {
44514
+ if (labelLength === 0) {
44515
+ throw new Error("Invalid cookie domain");
44516
+ }
44517
+ if (domain.charCodeAt(i - 1) === 45) {
44518
+ throw new Error("Invalid cookie domain");
44519
+ }
44520
+ labelLength = 0;
44521
+ continue;
44522
+ }
44523
+ if (labelLength === 0 && !isLetterOrDigit(code)) {
44524
+ throw new Error("Invalid cookie domain");
44525
+ }
44526
+ if (!isLetterOrDigit(code) && code !== 45) {
44527
+ throw new Error("Invalid cookie domain");
44528
+ }
44529
+ if (++labelLength > 63) {
44530
+ throw new Error("Invalid cookie domain");
44531
+ }
44532
+ }
44533
+ if (labelLength === 0 || domain.charCodeAt(domain.length - 1) === 45) {
43608
44534
  throw new Error("Invalid cookie domain");
43609
44535
  }
43610
44536
  }
@@ -43687,7 +44613,11 @@ var require_util4 = __commonJS({
43687
44613
  throw new Error("Invalid unparsed");
43688
44614
  }
43689
44615
  const [key, ...value] = part.split("=");
43690
- out.push(`${key.trim()}=${value.join("=")}`);
44616
+ const trimmedKey = key.trim();
44617
+ const joinedValue = value.join("=");
44618
+ validateCookieName(trimmedKey);
44619
+ validateCookieValue(joinedValue);
44620
+ out.push(`${trimmedKey}=${joinedValue}`);
43691
44621
  }
43692
44622
  return out.join("; ");
43693
44623
  }
@@ -43710,7 +44640,6 @@ var require_parse = __commonJS({
43710
44640
  var { maxNameValuePairSize, maxAttributeValueSize } = require_constants4();
43711
44641
  var { isCTLExcludingHtab } = require_util4();
43712
44642
  var assert = __require("assert");
43713
- var { unescape: qsUnescape } = __require("querystring");
43714
44643
  function parseSetCookie(header) {
43715
44644
  if (isCTLExcludingHtab(header)) {
43716
44645
  return null;
@@ -43744,7 +44673,7 @@ var require_parse = __commonJS({
43744
44673
  }
43745
44674
  return {
43746
44675
  name,
43747
- value: qsUnescape(value),
44676
+ value,
43748
44677
  ...parseUnparsedAttributes(unparsedAttributes)
43749
44678
  };
43750
44679
  }
@@ -43818,18 +44747,14 @@ var require_parse = __commonJS({
43818
44747
  } else if (attributeNameLowercase === "httponly") {
43819
44748
  cookieAttributeList.httpOnly = true;
43820
44749
  } else if (attributeNameLowercase === "samesite") {
43821
- let enforcement = "Default";
43822
44750
  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";
44751
+ if (attributeValueLowercase === "none") {
44752
+ cookieAttributeList.sameSite = "None";
44753
+ } else if (attributeValueLowercase === "strict") {
44754
+ cookieAttributeList.sameSite = "Strict";
44755
+ } else if (attributeValueLowercase === "lax") {
44756
+ cookieAttributeList.sameSite = "Lax";
43831
44757
  }
43832
- cookieAttributeList.sameSite = enforcement;
43833
44758
  } else {
43834
44759
  cookieAttributeList.unparsed ??= [];
43835
44760
  cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`);
@@ -44674,7 +45599,7 @@ var require_connection = __commonJS({
44674
45599
  const secProtocol = response.headersList.get("Sec-WebSocket-Protocol");
44675
45600
  if (secProtocol !== null) {
44676
45601
  const requestProtocols = getDecodeSplit("sec-websocket-protocol", request2.headersList);
44677
- if (!requestProtocols.includes(secProtocol)) {
45602
+ if (requestProtocols === null || !requestProtocols.includes(secProtocol)) {
44678
45603
  failWebsocketConnection(handler, 1002, "Protocol was not set in the opening handshake.");
44679
45604
  return;
44680
45605
  }
@@ -44750,27 +45675,26 @@ var require_permessage_deflate = __commonJS({
44750
45675
  var tail = Buffer.from([0, 0, 255, 255]);
44751
45676
  var kBuffer = /* @__PURE__ */ Symbol("kBuffer");
44752
45677
  var kLength = /* @__PURE__ */ Symbol("kLength");
44753
- var kDefaultMaxDecompressedSize = 4 * 1024 * 1024;
44754
45678
  var PerMessageDeflate = class {
44755
45679
  /** @type {import('node:zlib').InflateRaw} */
44756
45680
  #inflate;
44757
45681
  #options = {};
44758
- /** @type {boolean} */
44759
- #aborted = false;
44760
- /** @type {Function|null} */
44761
- #currentCallback = null;
45682
+ #maxPayloadSize = 0;
44762
45683
  /**
44763
45684
  * @param {Map<string, string>} extensions
44764
45685
  */
44765
- constructor(extensions) {
45686
+ constructor(extensions, options) {
44766
45687
  this.#options.serverNoContextTakeover = extensions.has("server_no_context_takeover");
44767
45688
  this.#options.serverMaxWindowBits = extensions.get("server_max_window_bits");
45689
+ this.#maxPayloadSize = options.maxPayloadSize;
44768
45690
  }
45691
+ /**
45692
+ * Decompress a compressed payload.
45693
+ * @param {Buffer} chunk Compressed data
45694
+ * @param {boolean} fin Final fragment flag
45695
+ * @param {Function} callback Callback function
45696
+ */
44769
45697
  decompress(chunk2, fin, callback) {
44770
- if (this.#aborted) {
44771
- callback(new MessageSizeExceededError());
44772
- return;
44773
- }
44774
45698
  if (!this.#inflate) {
44775
45699
  let windowBits = Z_DEFAULT_WINDOWBITS;
44776
45700
  if (this.#options.serverMaxWindowBits) {
@@ -44789,20 +45713,12 @@ var require_permessage_deflate = __commonJS({
44789
45713
  this.#inflate[kBuffer] = [];
44790
45714
  this.#inflate[kLength] = 0;
44791
45715
  this.#inflate.on("data", (data) => {
44792
- if (this.#aborted) {
44793
- return;
44794
- }
44795
45716
  this.#inflate[kLength] += data.length;
44796
- if (this.#inflate[kLength] > kDefaultMaxDecompressedSize) {
44797
- this.#aborted = true;
45717
+ if (this.#maxPayloadSize > 0 && this.#inflate[kLength] > this.#maxPayloadSize) {
45718
+ callback(new MessageSizeExceededError());
44798
45719
  this.#inflate.removeAllListeners();
44799
45720
  this.#inflate.destroy();
44800
45721
  this.#inflate = null;
44801
- if (this.#currentCallback) {
44802
- const cb = this.#currentCallback;
44803
- this.#currentCallback = null;
44804
- cb(new MessageSizeExceededError());
44805
- }
44806
45722
  return;
44807
45723
  }
44808
45724
  this.#inflate[kBuffer].push(data);
@@ -44812,19 +45728,17 @@ var require_permessage_deflate = __commonJS({
44812
45728
  callback(err2);
44813
45729
  });
44814
45730
  }
44815
- this.#currentCallback = callback;
44816
45731
  this.#inflate.write(chunk2);
44817
45732
  if (fin) {
44818
45733
  this.#inflate.write(tail);
44819
45734
  }
44820
45735
  this.#inflate.flush(() => {
44821
- if (this.#aborted || !this.#inflate) {
45736
+ if (!this.#inflate) {
44822
45737
  return;
44823
45738
  }
44824
45739
  const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]);
44825
45740
  this.#inflate[kBuffer].length = 0;
44826
45741
  this.#inflate[kLength] = 0;
44827
- this.#currentCallback = null;
44828
45742
  callback(null, full);
44829
45743
  });
44830
45744
  }
@@ -44865,16 +45779,23 @@ var require_receiver = __commonJS({
44865
45779
  #extensions;
44866
45780
  /** @type {import('./websocket').Handler} */
44867
45781
  #handler;
45782
+ /** @type {number} */
45783
+ #maxFragments;
45784
+ /** @type {number} */
45785
+ #maxPayloadSize;
44868
45786
  /**
44869
45787
  * @param {import('./websocket').Handler} handler
44870
45788
  * @param {Map<string, string>|null} extensions
45789
+ * @param {{ maxFragments?: number, maxPayloadSize?: number }} [options]
44871
45790
  */
44872
- constructor(handler, extensions) {
45791
+ constructor(handler, extensions, options = {}) {
44873
45792
  super();
44874
45793
  this.#handler = handler;
44875
45794
  this.#extensions = extensions == null ? /* @__PURE__ */ new Map() : extensions;
45795
+ this.#maxFragments = options.maxFragments ?? 0;
45796
+ this.#maxPayloadSize = options.maxPayloadSize ?? 0;
44876
45797
  if (this.#extensions.has("permessage-deflate")) {
44877
- this.#extensions.set("permessage-deflate", new PerMessageDeflate(extensions));
45798
+ this.#extensions.set("permessage-deflate", new PerMessageDeflate(extensions, options));
44878
45799
  }
44879
45800
  }
44880
45801
  /**
@@ -44887,6 +45808,13 @@ var require_receiver = __commonJS({
44887
45808
  this.#loop = true;
44888
45809
  this.run(callback);
44889
45810
  }
45811
+ #validatePayloadLength() {
45812
+ if (this.#maxPayloadSize > 0 && !isControlFrame(this.#info.opcode) && this.#info.payloadLength + this.#fragmentsBytes > this.#maxPayloadSize) {
45813
+ failWebsocketConnection(this.#handler, 1009, "Payload size exceeds maximum allowed size");
45814
+ return false;
45815
+ }
45816
+ return true;
45817
+ }
44890
45818
  /**
44891
45819
  * Runs whenever a new chunk is received.
44892
45820
  * Callback is called whenever there are no more chunks buffering,
@@ -44946,6 +45874,9 @@ var require_receiver = __commonJS({
44946
45874
  if (payloadLength <= 125) {
44947
45875
  this.#info.payloadLength = payloadLength;
44948
45876
  this.#state = parserStates.READ_DATA;
45877
+ if (!this.#validatePayloadLength()) {
45878
+ return;
45879
+ }
44949
45880
  } else if (payloadLength === 126) {
44950
45881
  this.#state = parserStates.PAYLOADLENGTH_16;
44951
45882
  } else if (payloadLength === 127) {
@@ -44966,6 +45897,9 @@ var require_receiver = __commonJS({
44966
45897
  const buffer = this.consume(2);
44967
45898
  this.#info.payloadLength = buffer.readUInt16BE(0);
44968
45899
  this.#state = parserStates.READ_DATA;
45900
+ if (!this.#validatePayloadLength()) {
45901
+ return;
45902
+ }
44969
45903
  } else if (this.#state === parserStates.PAYLOADLENGTH_64) {
44970
45904
  if (this.#byteOffset < 8) {
44971
45905
  return callback();
@@ -44979,6 +45913,9 @@ var require_receiver = __commonJS({
44979
45913
  }
44980
45914
  this.#info.payloadLength = lower;
44981
45915
  this.#state = parserStates.READ_DATA;
45916
+ if (!this.#validatePayloadLength()) {
45917
+ return;
45918
+ }
44982
45919
  } else if (this.#state === parserStates.READ_DATA) {
44983
45920
  if (this.#byteOffset < this.#info.payloadLength) {
44984
45921
  return callback();
@@ -44989,30 +45926,43 @@ var require_receiver = __commonJS({
44989
45926
  this.#state = parserStates.INFO;
44990
45927
  } else {
44991
45928
  if (!this.#info.compressed) {
44992
- this.writeFragments(body);
45929
+ if (!this.writeFragments(body)) {
45930
+ return;
45931
+ }
44993
45932
  if (!this.#info.fragmented && this.#info.fin) {
44994
45933
  websocketMessageReceived(this.#handler, this.#info.binaryType, this.consumeFragments());
44995
45934
  }
44996
45935
  this.#state = parserStates.INFO;
44997
45936
  } 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;
45937
+ this.#extensions.get("permessage-deflate").decompress(
45938
+ body,
45939
+ this.#info.fin,
45940
+ (error, data) => {
45941
+ if (error) {
45942
+ const code = error instanceof MessageSizeExceededError ? 1009 : 1007;
45943
+ failWebsocketConnection(this.#handler, code, error.message);
45944
+ return;
45945
+ }
45946
+ if (!this.writeFragments(data)) {
45947
+ return;
45948
+ }
45949
+ if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) {
45950
+ failWebsocketConnection(this.#handler, 1009, new MessageSizeExceededError().message);
45951
+ return;
45952
+ }
45953
+ if (!this.#info.fin) {
45954
+ this.#state = parserStates.INFO;
45955
+ this.#loop = true;
45956
+ this.run(callback);
45957
+ return;
45958
+ }
45959
+ websocketMessageReceived(this.#handler, this.#info.binaryType, this.consumeFragments());
45007
45960
  this.#loop = true;
45961
+ this.#state = parserStates.INFO;
45008
45962
  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
- });
45963
+ },
45964
+ this.#fragmentsBytes
45965
+ );
45016
45966
  this.#loop = false;
45017
45967
  break;
45018
45968
  }
@@ -45060,8 +46010,13 @@ var require_receiver = __commonJS({
45060
46010
  }
45061
46011
  }
45062
46012
  writeFragments(fragment) {
46013
+ if (this.#maxFragments > 0 && this.#fragments.length === this.#maxFragments) {
46014
+ failWebsocketConnection(this.#handler, 1008, "Too many message fragments");
46015
+ return false;
46016
+ }
45063
46017
  this.#fragmentsBytes += fragment.length;
45064
46018
  this.#fragments.push(fragment);
46019
+ return true;
45065
46020
  }
45066
46021
  consumeFragments() {
45067
46022
  const fragments = this.#fragments;
@@ -45528,7 +46483,13 @@ var require_websocket = __commonJS({
45528
46483
  */
45529
46484
  #onConnectionEstablished(response, parsedExtensions) {
45530
46485
  this.#handler.socket = response.socket;
45531
- const parser = new ByteParser(this.#handler, parsedExtensions);
46486
+ const webSocketOptions = this.#handler.controller.dispatcher?.webSocketOptions;
46487
+ const maxFragments = webSocketOptions?.maxFragments;
46488
+ const maxPayloadSize = webSocketOptions?.maxPayloadSize;
46489
+ const parser = new ByteParser(this.#handler, parsedExtensions, {
46490
+ maxFragments,
46491
+ maxPayloadSize
46492
+ });
45532
46493
  parser.on("drain", () => this.#handler.onParserDrain());
45533
46494
  parser.on("error", (err2) => this.#handler.onParserError(err2));
45534
46495
  this.#parser = parser;
@@ -45834,9 +46795,9 @@ var require_websocketstream = __commonJS({
45834
46795
  #readableStream;
45835
46796
  /** @type {ReadableStreamDefaultController} */
45836
46797
  #readableStreamController;
45837
- // Each WebSocketStream object has an associated writable stream , which is a WritableStream .
45838
- /** @type {WritableStream} */
45839
- #writableStream;
46798
+ // Retain the controller so the writable stream can be errored while locked.
46799
+ /** @type {WritableStreamDefaultController} */
46800
+ #writableStreamController;
45840
46801
  // Each WebSocketStream object has an associated boolean handshake aborted , which is initially false.
45841
46802
  #handshakeAborted = false;
45842
46803
  /** @type {import('../websocket').Handler} */
@@ -45972,7 +46933,12 @@ var require_websocketstream = __commonJS({
45972
46933
  /** @type {import('../websocket').Handler['onConnectionEstablished']} */
45973
46934
  #onConnectionEstablished(response, parsedExtensions) {
45974
46935
  this.#handler.socket = response.socket;
45975
- const parser = new ByteParser(this.#handler, parsedExtensions);
46936
+ const maxFragments = this.#handler.controller.dispatcher?.webSocketOptions?.maxFragments;
46937
+ const maxPayloadSize = this.#handler.controller.dispatcher?.webSocketOptions?.maxPayloadSize;
46938
+ const parser = new ByteParser(this.#handler, parsedExtensions, {
46939
+ maxFragments,
46940
+ maxPayloadSize
46941
+ });
45976
46942
  parser.on("drain", () => this.#handler.onParserDrain());
45977
46943
  parser.on("error", (err2) => this.#handler.onParserError(err2));
45978
46944
  this.#parser = parser;
@@ -45983,21 +46949,17 @@ var require_websocketstream = __commonJS({
45983
46949
  start: (controller) => {
45984
46950
  this.#readableStreamController = controller;
45985
46951
  },
45986
- pull(controller) {
45987
- let chunk2;
45988
- while (controller.desiredSize > 0 && (chunk2 = response.socket.read()) !== null) {
45989
- controller.enqueue(chunk2);
45990
- }
45991
- },
45992
46952
  cancel: (reason) => this.#cancel(reason)
45993
46953
  });
45994
46954
  const writable = new WritableStream({
46955
+ start: (controller) => {
46956
+ this.#writableStreamController = controller;
46957
+ },
45995
46958
  write: (chunk2) => this.#write(chunk2),
45996
46959
  close: () => closeWebSocketConnection(this.#handler, null, null),
45997
46960
  abort: (reason) => this.#closeUsingReason(reason)
45998
46961
  });
45999
46962
  this.#readableStream = readable;
46000
- this.#writableStream = writable;
46001
46963
  this.#openedPromise.resolve({
46002
46964
  extensions,
46003
46965
  protocol,
@@ -46015,7 +46977,7 @@ var require_websocketstream = __commonJS({
46015
46977
  try {
46016
46978
  chunk2 = utf8Decode(data);
46017
46979
  } catch {
46018
- failWebsocketConnection(this.#handler, "Received invalid UTF-8 in text frame.");
46980
+ failWebsocketConnection(this.#handler, 1007, "Received invalid UTF-8 in text frame.");
46019
46981
  return;
46020
46982
  }
46021
46983
  } else if (type === opcodes.BINARY) {
@@ -46041,9 +47003,7 @@ var require_websocketstream = __commonJS({
46041
47003
  const reason = result?.reason == null ? "" : utf8DecodeBytes(Buffer.from(result.reason));
46042
47004
  if (wasClean) {
46043
47005
  this.#readableStreamController.close();
46044
- if (!this.#writableStream.locked) {
46045
- this.#writableStream.abort(new DOMException("A closed WebSocketStream cannot be written to", "InvalidStateError"));
46046
- }
47006
+ this.#writableStreamController.error(new DOMException("A closed WebSocketStream cannot be written to", "InvalidStateError"));
46047
47007
  this.#closedPromise.resolve({
46048
47008
  closeCode: code,
46049
47009
  reason
@@ -46051,7 +47011,7 @@ var require_websocketstream = __commonJS({
46051
47011
  } else {
46052
47012
  const error = createUnvalidatedWebSocketError("unclean close", code, reason);
46053
47013
  this.#readableStreamController?.error(error);
46054
- this.#writableStream?.abort(error);
47014
+ this.#writableStreamController?.error(error);
46055
47015
  this.#closedPromise.reject(error);
46056
47016
  }
46057
47017
  }
@@ -46146,6 +47106,40 @@ var require_eventsource_stream = __commonJS({
46146
47106
  var CR = 13;
46147
47107
  var COLON = 58;
46148
47108
  var SPACE = 32;
47109
+ var DATA = Buffer.from("data");
47110
+ var EVENT = Buffer.from("event");
47111
+ var ID = Buffer.from("id");
47112
+ var RETRY = Buffer.from("retry");
47113
+ function isASCIINumberBytes(buffer, start) {
47114
+ if (start >= buffer.length) {
47115
+ return false;
47116
+ }
47117
+ for (let i = start; i < buffer.length; i++) {
47118
+ if (buffer[i] < 48 || buffer[i] > 57) {
47119
+ return false;
47120
+ }
47121
+ }
47122
+ return true;
47123
+ }
47124
+ function isValidLastEventIdBytes(buffer, start) {
47125
+ for (let i = start; i < buffer.length; i++) {
47126
+ if (buffer[i] === 0) {
47127
+ return false;
47128
+ }
47129
+ }
47130
+ return true;
47131
+ }
47132
+ function isFieldName(line, length, field) {
47133
+ if (length !== field.length) {
47134
+ return false;
47135
+ }
47136
+ for (let i = 0; i < length; i++) {
47137
+ if (line[i] !== field[i]) {
47138
+ return false;
47139
+ }
47140
+ }
47141
+ return true;
47142
+ }
46149
47143
  var EventSourceStream = class extends Transform {
46150
47144
  /**
46151
47145
  * @type {eventSourceSettings}
@@ -46165,10 +47159,13 @@ var require_eventsource_stream = __commonJS({
46165
47159
  */
46166
47160
  eventEndCheck = false;
46167
47161
  /**
46168
- * @type {Buffer|null}
47162
+ * @type {Buffer[]}
46169
47163
  */
46170
- buffer = null;
47164
+ chunks = [];
47165
+ chunkIndex = 0;
46171
47166
  pos = 0;
47167
+ lineChunkIndex = 0;
47168
+ linePos = 0;
46172
47169
  event = {
46173
47170
  data: void 0,
46174
47171
  event: void 0,
@@ -46200,63 +47197,30 @@ var require_eventsource_stream = __commonJS({
46200
47197
  callback();
46201
47198
  return;
46202
47199
  }
46203
- if (this.buffer) {
46204
- this.buffer = Buffer.concat([this.buffer, chunk2]);
46205
- } else {
46206
- this.buffer = chunk2;
46207
- }
47200
+ this.chunks.push(chunk2);
46208
47201
  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;
47202
+ if (this.handleBOM()) {
47203
+ callback();
47204
+ return;
46240
47205
  }
46241
47206
  }
46242
- while (this.pos < this.buffer.length) {
47207
+ while (this.hasCurrentByte()) {
47208
+ const byte = this.currentByte();
46243
47209
  if (this.eventEndCheck) {
46244
47210
  if (this.crlfCheck) {
46245
- if (this.buffer[this.pos] === LF) {
46246
- this.buffer = this.buffer.subarray(this.pos + 1);
46247
- this.pos = 0;
47211
+ if (byte === LF) {
46248
47212
  this.crlfCheck = false;
47213
+ this.consumeCurrentByte();
46249
47214
  continue;
46250
47215
  }
46251
47216
  this.crlfCheck = false;
46252
47217
  }
46253
- if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) {
46254
- if (this.buffer[this.pos] === CR) {
47218
+ if (byte === LF || byte === CR) {
47219
+ if (byte === CR) {
46255
47220
  this.crlfCheck = true;
46256
47221
  }
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) {
47222
+ this.consumeCurrentByte();
47223
+ if (this.hasPendingEvent()) {
46260
47224
  this.processEvent(this.event);
46261
47225
  }
46262
47226
  this.clearEvent();
@@ -46265,17 +47229,16 @@ var require_eventsource_stream = __commonJS({
46265
47229
  this.eventEndCheck = false;
46266
47230
  continue;
46267
47231
  }
46268
- if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) {
46269
- if (this.buffer[this.pos] === CR) {
47232
+ if (byte === LF || byte === CR) {
47233
+ if (byte === CR) {
46270
47234
  this.crlfCheck = true;
46271
47235
  }
46272
- this.parseLine(this.buffer.subarray(0, this.pos), this.event);
46273
- this.buffer = this.buffer.subarray(this.pos + 1);
46274
- this.pos = 0;
47236
+ this.parseLine(this.readLine(), this.event);
47237
+ this.consumeCurrentByte();
46275
47238
  this.eventEndCheck = true;
46276
47239
  continue;
46277
47240
  }
46278
- this.pos++;
47241
+ this.advanceCursor();
46279
47242
  }
46280
47243
  callback();
46281
47244
  }
@@ -46291,43 +47254,42 @@ var require_eventsource_stream = __commonJS({
46291
47254
  if (colonPosition === 0) {
46292
47255
  return;
46293
47256
  }
46294
- let field = "";
46295
- let value = "";
47257
+ let fieldLength = line.length;
47258
+ let valueStart = line.length;
46296
47259
  if (colonPosition !== -1) {
46297
- field = line.subarray(0, colonPosition).toString("utf8");
46298
- let valueStart = colonPosition + 1;
47260
+ fieldLength = colonPosition;
47261
+ valueStart = colonPosition + 1;
46299
47262
  if (line[valueStart] === SPACE) {
46300
47263
  ++valueStart;
46301
47264
  }
46302
- value = line.subarray(valueStart).toString("utf8");
46303
- } else {
46304
- field = line.toString("utf8");
46305
- value = "";
46306
47265
  }
46307
- switch (field) {
46308
- case "data":
46309
- if (event[field] === void 0) {
46310
- event[field] = value;
46311
- } else {
46312
- event[field] += `
47266
+ if (isFieldName(line, fieldLength, DATA)) {
47267
+ const value = line.toString("utf8", valueStart);
47268
+ if (event.data === void 0) {
47269
+ event.data = value;
47270
+ } else {
47271
+ event.data += `
46313
47272
  ${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;
47273
+ }
47274
+ return;
47275
+ }
47276
+ if (isFieldName(line, fieldLength, RETRY)) {
47277
+ if (isASCIINumberBytes(line, valueStart)) {
47278
+ event.retry = line.toString("utf8", valueStart);
47279
+ }
47280
+ return;
47281
+ }
47282
+ if (isFieldName(line, fieldLength, ID)) {
47283
+ if (isValidLastEventIdBytes(line, valueStart)) {
47284
+ event.id = line.toString("utf8", valueStart);
47285
+ }
47286
+ return;
47287
+ }
47288
+ if (isFieldName(line, fieldLength, EVENT)) {
47289
+ const value = line.toString("utf8", valueStart);
47290
+ if (value.length > 0) {
47291
+ event.event = value;
47292
+ }
46331
47293
  }
46332
47294
  }
46333
47295
  /**
@@ -46352,12 +47314,120 @@ ${value}`;
46352
47314
  }
46353
47315
  }
46354
47316
  clearEvent() {
46355
- this.event = {
46356
- data: void 0,
46357
- event: void 0,
46358
- id: void 0,
46359
- retry: void 0
46360
- };
47317
+ this.event.data = void 0;
47318
+ this.event.event = void 0;
47319
+ this.event.id = void 0;
47320
+ this.event.retry = void 0;
47321
+ }
47322
+ hasPendingEvent() {
47323
+ return this.event.data !== void 0 || this.event.event !== void 0 || this.event.id !== void 0 || this.event.retry !== void 0;
47324
+ }
47325
+ hasCurrentByte() {
47326
+ return this.chunkIndex < this.chunks.length && this.pos < this.chunks[this.chunkIndex].length;
47327
+ }
47328
+ currentByte() {
47329
+ return this.chunks[this.chunkIndex][this.pos];
47330
+ }
47331
+ consumeCurrentByte() {
47332
+ this.advanceCursor();
47333
+ this.syncLineStartToCursor();
47334
+ }
47335
+ advanceCursor() {
47336
+ this.pos++;
47337
+ while (this.chunkIndex < this.chunks.length && this.pos >= this.chunks[this.chunkIndex].length) {
47338
+ this.chunkIndex++;
47339
+ this.pos = 0;
47340
+ }
47341
+ }
47342
+ syncLineStartToCursor() {
47343
+ this.lineChunkIndex = this.chunkIndex;
47344
+ this.linePos = this.pos;
47345
+ this.dropConsumedChunks();
47346
+ }
47347
+ dropConsumedChunks() {
47348
+ while (this.lineChunkIndex > 0) {
47349
+ this.chunks.shift();
47350
+ this.lineChunkIndex--;
47351
+ this.chunkIndex--;
47352
+ }
47353
+ if (this.chunkIndex === this.chunks.length) {
47354
+ this.chunks.length = 0;
47355
+ this.chunkIndex = 0;
47356
+ this.pos = 0;
47357
+ this.lineChunkIndex = 0;
47358
+ this.linePos = 0;
47359
+ }
47360
+ }
47361
+ readLine() {
47362
+ if (this.lineChunkIndex === this.chunkIndex) {
47363
+ return this.chunks[this.chunkIndex].subarray(this.linePos, this.pos);
47364
+ }
47365
+ const chunks = [];
47366
+ let length = 0;
47367
+ for (let i = this.lineChunkIndex; i <= this.chunkIndex; i++) {
47368
+ const chunk2 = this.chunks[i];
47369
+ const start = i === this.lineChunkIndex ? this.linePos : 0;
47370
+ const end = i === this.chunkIndex ? this.pos : chunk2.length;
47371
+ const slice = chunk2.subarray(start, end);
47372
+ length += slice.length;
47373
+ chunks.push(slice);
47374
+ }
47375
+ return Buffer.concat(chunks, length);
47376
+ }
47377
+ peekBufferedByte(offset) {
47378
+ let chunkIndex = this.lineChunkIndex;
47379
+ let pos = this.linePos;
47380
+ while (chunkIndex < this.chunks.length) {
47381
+ const chunk2 = this.chunks[chunkIndex];
47382
+ const remaining = chunk2.length - pos;
47383
+ if (offset < remaining) {
47384
+ return chunk2[pos + offset];
47385
+ }
47386
+ offset -= remaining;
47387
+ chunkIndex++;
47388
+ pos = 0;
47389
+ }
47390
+ }
47391
+ discardLeadingBytes(count) {
47392
+ while (count > 0 && this.lineChunkIndex < this.chunks.length) {
47393
+ const chunk2 = this.chunks[this.lineChunkIndex];
47394
+ const remaining = chunk2.length - this.linePos;
47395
+ if (count < remaining) {
47396
+ this.linePos += count;
47397
+ count = 0;
47398
+ } else {
47399
+ count -= remaining;
47400
+ this.lineChunkIndex++;
47401
+ this.linePos = 0;
47402
+ }
47403
+ }
47404
+ this.chunkIndex = this.lineChunkIndex;
47405
+ this.pos = this.linePos;
47406
+ this.dropConsumedChunks();
47407
+ }
47408
+ handleBOM() {
47409
+ const first = this.peekBufferedByte(0);
47410
+ const second = this.peekBufferedByte(1);
47411
+ const third = this.peekBufferedByte(2);
47412
+ if (second === void 0) {
47413
+ if (first === BOM[0]) {
47414
+ return true;
47415
+ }
47416
+ this.checkBOM = false;
47417
+ return true;
47418
+ }
47419
+ if (third === void 0) {
47420
+ if (first === BOM[0] && second === BOM[1]) {
47421
+ return true;
47422
+ }
47423
+ this.checkBOM = false;
47424
+ return false;
47425
+ }
47426
+ if (first === BOM[0] && second === BOM[1] && third === BOM[2]) {
47427
+ this.discardLeadingBytes(3);
47428
+ }
47429
+ this.checkBOM = false;
47430
+ return !this.hasCurrentByte();
46361
47431
  }
46362
47432
  };
46363
47433
  module.exports = {