@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.js CHANGED
@@ -3509,6 +3509,10 @@ var init_dist = __esm({
3509
3509
  deriveRedirOp("cat <<-X\nX")
3510
3510
  ]);
3511
3511
  DEFAULT_EGRESS_ALLOWLIST = [
3512
+ // node9's own control plane (api, app, dev-api, staging and the apex).
3513
+ // Without it, turning egress on asks the user to approve node9 itself.
3514
+ // A user `deny` entry still wins over this list, see evaluateEgress.
3515
+ "*.node9.ai",
3512
3516
  "*.github.com",
3513
3517
  "*.githubusercontent.com",
3514
3518
  "*.npmjs.org",
@@ -24187,6 +24191,18 @@ var require_request = __commonJS({
24187
24191
  var { channels } = require_diagnostics();
24188
24192
  var { headerNameLowerCasedRecord } = require_constants();
24189
24193
  var invalidPathRegex = /[^\u0021-\u00ff]/;
24194
+ function isValidContentLengthHeaderValue(val) {
24195
+ if (typeof val !== "string" || val.length === 0) {
24196
+ return false;
24197
+ }
24198
+ for (let i = 0; i < val.length; i++) {
24199
+ const charCode = val.charCodeAt(i);
24200
+ if (charCode < 48 || charCode > 57) {
24201
+ return false;
24202
+ }
24203
+ }
24204
+ return true;
24205
+ }
24190
24206
  var kHandler = /* @__PURE__ */ Symbol("handler");
24191
24207
  var Request = class {
24192
24208
  constructor(origin, {
@@ -24461,7 +24477,11 @@ var require_request = __commonJS({
24461
24477
  } else if (typeof val[i] === "object") {
24462
24478
  throw new InvalidArgumentError(`invalid ${key} header`);
24463
24479
  } else {
24464
- arr.push(`${val[i]}`);
24480
+ const str2 = `${val[i]}`;
24481
+ if (!isValidHeaderValue(str2)) {
24482
+ throw new InvalidArgumentError(`invalid ${key} header`);
24483
+ }
24484
+ arr.push(str2);
24465
24485
  }
24466
24486
  }
24467
24487
  val = arr;
@@ -24473,6 +24493,9 @@ var require_request = __commonJS({
24473
24493
  val = "";
24474
24494
  } else {
24475
24495
  val = `${val}`;
24496
+ if (!isValidHeaderValue(val)) {
24497
+ throw new InvalidArgumentError(`invalid ${key} header`);
24498
+ }
24476
24499
  }
24477
24500
  if (headerName === "host") {
24478
24501
  if (request2.host !== null) {
@@ -24486,10 +24509,10 @@ var require_request = __commonJS({
24486
24509
  if (request2.contentLength !== null) {
24487
24510
  throw new InvalidArgumentError("duplicate content-length header");
24488
24511
  }
24489
- request2.contentLength = parseInt(val, 10);
24490
- if (!Number.isFinite(request2.contentLength)) {
24512
+ if (!isValidContentLengthHeaderValue(val)) {
24491
24513
  throw new InvalidArgumentError("invalid content-length header");
24492
24514
  }
24515
+ request2.contentLength = parseInt(val, 10);
24493
24516
  } else if (request2.contentType === null && headerName === "content-type") {
24494
24517
  request2.contentType = val;
24495
24518
  request2.headers.push(key, val);
@@ -24657,6 +24680,8 @@ var require_unwrap_handler = __commonJS({
24657
24680
  #aborted = false;
24658
24681
  #abort;
24659
24682
  [kResume] = null;
24683
+ rawHeaders = null;
24684
+ rawTrailers = null;
24660
24685
  constructor(abort) {
24661
24686
  this.#abort = abort;
24662
24687
  }
@@ -24703,10 +24728,12 @@ var require_unwrap_handler = __commonJS({
24703
24728
  return this.#handler.onResponseStarted?.();
24704
24729
  }
24705
24730
  onUpgrade(statusCode, rawHeaders, socket) {
24731
+ this.#controller.rawHeaders = rawHeaders;
24706
24732
  this.#handler.onRequestUpgrade?.(this.#controller, statusCode, parseHeaders(rawHeaders), socket);
24707
24733
  }
24708
24734
  onHeaders(statusCode, rawHeaders, resume, statusMessage) {
24709
24735
  this.#controller[kResume] = resume;
24736
+ this.#controller.rawHeaders = rawHeaders;
24710
24737
  this.#handler.onResponseStart?.(this.#controller, statusCode, parseHeaders(rawHeaders), statusMessage);
24711
24738
  return !this.#controller.paused;
24712
24739
  }
@@ -24715,6 +24742,7 @@ var require_unwrap_handler = __commonJS({
24715
24742
  return !this.#controller.paused;
24716
24743
  }
24717
24744
  onComplete(rawTrailers) {
24745
+ this.#controller.rawTrailers = rawTrailers;
24718
24746
  this.#handler.onResponseEnd?.(this.#controller, parseHeaders(rawTrailers));
24719
24747
  }
24720
24748
  onError(err2) {
@@ -24741,6 +24769,7 @@ var require_dispatcher_base = __commonJS({
24741
24769
  var { kDestroy, kClose, kClosed, kDestroyed, kDispatch } = require_symbols();
24742
24770
  var kOnDestroyed = /* @__PURE__ */ Symbol("onDestroyed");
24743
24771
  var kOnClosed = /* @__PURE__ */ Symbol("onClosed");
24772
+ var kWebSocketOptions = /* @__PURE__ */ Symbol("webSocketOptions");
24744
24773
  var DispatcherBase = class extends Dispatcher {
24745
24774
  /** @type {boolean} */
24746
24775
  [kDestroyed] = false;
@@ -24750,6 +24779,23 @@ var require_dispatcher_base = __commonJS({
24750
24779
  [kClosed] = false;
24751
24780
  /** @type {Array<Function>|null} */
24752
24781
  [kOnClosed] = null;
24782
+ /**
24783
+ * @param {import('../../types/dispatcher').DispatcherOptions} [opts]
24784
+ */
24785
+ constructor(opts) {
24786
+ super();
24787
+ this[kWebSocketOptions] = opts?.webSocket ?? {};
24788
+ }
24789
+ /**
24790
+ * @returns {import('../../types/dispatcher').WebSocketOptions}
24791
+ */
24792
+ get webSocketOptions() {
24793
+ return {
24794
+ maxFragments: this[kWebSocketOptions].maxFragments ?? 131072,
24795
+ maxPayloadSize: this[kWebSocketOptions].maxPayloadSize ?? 128 * 1024 * 1024
24796
+ // 128 MB default
24797
+ };
24798
+ }
24753
24799
  /** @returns {boolean} */
24754
24800
  get destroyed() {
24755
24801
  return this[kDestroyed];
@@ -24892,6 +24938,20 @@ var require_connect = __commonJS({
24892
24938
  if (this._maxCachedSessions === 0) {
24893
24939
  return;
24894
24940
  }
24941
+ if (this._sessionCache.has(sessionKey)) {
24942
+ this._sessionCache.delete(sessionKey);
24943
+ } else if (this._sessionCache.size >= this._maxCachedSessions) {
24944
+ for (const [key, ref] of this._sessionCache) {
24945
+ if (ref.deref() === void 0) {
24946
+ this._sessionCache.delete(key);
24947
+ return;
24948
+ }
24949
+ }
24950
+ const oldest = this._sessionCache.keys().next();
24951
+ if (!oldest.done) {
24952
+ this._sessionCache.delete(oldest.value);
24953
+ }
24954
+ }
24895
24955
  this._sessionCache.set(sessionKey, new WeakRef(session));
24896
24956
  this._sessionRegistry.register(session, sessionKey);
24897
24957
  }
@@ -26559,7 +26619,7 @@ var require_webidl = __commonJS({
26559
26619
  lowerBound = 0;
26560
26620
  upperBound = Math.pow(2, bitLength) - 1;
26561
26621
  } else {
26562
- lowerBound = Math.pow(-2, bitLength) - 1;
26622
+ lowerBound = -Math.pow(2, bitLength - 1);
26563
26623
  upperBound = Math.pow(2, bitLength - 1) - 1;
26564
26624
  }
26565
26625
  let x = Number(V);
@@ -26596,7 +26656,7 @@ var require_webidl = __commonJS({
26596
26656
  }
26597
26657
  x = webidl.util.IntegerPart(x);
26598
26658
  x = x % Math.pow(2, bitLength);
26599
- if (signedness === "signed" && x >= Math.pow(2, bitLength) - 1) {
26659
+ if (signedness === "signed" && x >= Math.pow(2, bitLength - 1)) {
26600
26660
  return x - Math.pow(2, bitLength);
26601
26661
  }
26602
26662
  return x;
@@ -27719,7 +27779,7 @@ var require_util2 = __commonJS({
27719
27779
  return !!(url.username || url.password);
27720
27780
  }
27721
27781
  function isTraversableNavigable(navigable) {
27722
- return true;
27782
+ return navigable != null && navigable !== "client" && navigable !== "no-traversable";
27723
27783
  }
27724
27784
  var EnvironmentSettingsObjectBase = class {
27725
27785
  get baseUrl() {
@@ -28114,7 +28174,7 @@ var require_formdata_parser = __commonJS({
28114
28174
  );
28115
28175
  value = decoder.decode(tokenValue);
28116
28176
  }
28117
- return { name: attrNameStr, value };
28177
+ return { name: attrNameStr, value, extended: isExtended };
28118
28178
  }
28119
28179
  function parseMultipartFormDataHeaders(input, position) {
28120
28180
  let name = null;
@@ -28149,6 +28209,7 @@ var require_formdata_parser = __commonJS({
28149
28209
  switch (bufferToLowerCasedHeaderName(headerName)) {
28150
28210
  case "content-disposition": {
28151
28211
  name = filename = null;
28212
+ let filenameIsExtended = false;
28152
28213
  const dispositionType = collectASequenceOfBytes(
28153
28214
  (char) => isToken(char),
28154
28215
  input,
@@ -28157,7 +28218,7 @@ var require_formdata_parser = __commonJS({
28157
28218
  if (dispositionType.toString("ascii").toLowerCase() !== "form-data") {
28158
28219
  throw parsingError("expected form-data for content-disposition header");
28159
28220
  }
28160
- while (position.position < input.length && input[position.position] !== 13 && input[position.position + 1] !== 10) {
28221
+ while (position.position < input.length && (input[position.position] !== 13 || input[position.position + 1] !== 10)) {
28161
28222
  const attribute = parseContentDispositionAttribute(input, position);
28162
28223
  if (!attribute) {
28163
28224
  break;
@@ -28165,7 +28226,12 @@ var require_formdata_parser = __commonJS({
28165
28226
  if (attribute.name === "name") {
28166
28227
  name = attribute.value;
28167
28228
  } else if (attribute.name === "filename") {
28168
- filename = attribute.value;
28229
+ if (attribute.extended) {
28230
+ filename = attribute.value;
28231
+ filenameIsExtended = true;
28232
+ } else if (!filenameIsExtended) {
28233
+ filename = attribute.value;
28234
+ }
28169
28235
  }
28170
28236
  }
28171
28237
  if (name === null) {
@@ -28201,7 +28267,7 @@ var require_formdata_parser = __commonJS({
28201
28267
  );
28202
28268
  }
28203
28269
  }
28204
- if (input[position.position] !== 13 && input[position.position + 1] !== 10) {
28270
+ if (input[position.position] !== 13 || input[position.position + 1] !== 10) {
28205
28271
  throw parsingError("expected CRLF");
28206
28272
  } else {
28207
28273
  position.position += 2;
@@ -28586,6 +28652,7 @@ var require_client_h1 = __commonJS({
28586
28652
  RequestContentLengthMismatchError,
28587
28653
  ResponseContentLengthMismatchError,
28588
28654
  RequestAbortedError,
28655
+ InvalidArgumentError,
28589
28656
  HeadersTimeoutError,
28590
28657
  HeadersOverflowError,
28591
28658
  SocketError,
@@ -28632,15 +28699,18 @@ var require_client_h1 = __commonJS({
28632
28699
  var EMPTY_BUF = Buffer.alloc(0);
28633
28700
  var FastBuffer = Buffer[Symbol.species];
28634
28701
  var removeAllListeners = util.removeAllListeners;
28702
+ var kIdleSocketValidation = /* @__PURE__ */ Symbol("kIdleSocketValidation");
28703
+ var kIdleSocketValidationTimeout = /* @__PURE__ */ Symbol("kIdleSocketValidationTimeout");
28704
+ var kSocketUsed = /* @__PURE__ */ Symbol("kSocketUsed");
28635
28705
  var extractBody;
28636
28706
  function lazyllhttp() {
28637
28707
  const llhttpWasmData = process.env.JEST_WORKER_ID ? require_llhttp_wasm() : void 0;
28638
28708
  let mod;
28639
28709
  let useWasmSIMD = process.arch !== "ppc64";
28640
28710
  if (process.env.UNDICI_NO_WASM_SIMD === "1") {
28641
- useWasmSIMD = true;
28642
- } else if (process.env.UNDICI_NO_WASM_SIMD === "0") {
28643
28711
  useWasmSIMD = false;
28712
+ } else if (process.env.UNDICI_NO_WASM_SIMD === "0") {
28713
+ useWasmSIMD = true;
28644
28714
  }
28645
28715
  if (useWasmSIMD) {
28646
28716
  try {
@@ -28758,6 +28828,7 @@ var require_client_h1 = __commonJS({
28758
28828
  this.client = client;
28759
28829
  this.socket = socket;
28760
28830
  this.timeout = null;
28831
+ this.timeoutWeakRef = new WeakRef(this);
28761
28832
  this.timeoutValue = null;
28762
28833
  this.timeoutType = null;
28763
28834
  this.statusCode = 0;
@@ -28783,9 +28854,9 @@ var require_client_h1 = __commonJS({
28783
28854
  }
28784
28855
  if (delay) {
28785
28856
  if (type & USE_FAST_TIMER) {
28786
- this.timeout = timers.setFastTimeout(onParserTimeout, delay, new WeakRef(this));
28857
+ this.timeout = timers.setFastTimeout(onParserTimeout, delay, this.timeoutWeakRef);
28787
28858
  } else {
28788
- this.timeout = setTimeout(onParserTimeout, delay, new WeakRef(this));
28859
+ this.timeout = setTimeout(onParserTimeout, delay, this.timeoutWeakRef);
28789
28860
  this.timeout?.unref();
28790
28861
  }
28791
28862
  }
@@ -28857,19 +28928,47 @@ var require_client_h1 = __commonJS({
28857
28928
  this.paused = true;
28858
28929
  socket.unshift(data);
28859
28930
  } else {
28860
- const ptr = llhttp.llhttp_get_error_reason(this.ptr);
28861
- let message = "";
28862
- if (ptr) {
28863
- const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0);
28864
- message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")";
28865
- }
28866
- throw new HTTPParserError(message, constants.ERROR[ret], data);
28931
+ throw this.createError(ret, data);
28867
28932
  }
28868
28933
  }
28869
28934
  } catch (err2) {
28870
28935
  util.destroy(socket, err2);
28871
28936
  }
28872
28937
  }
28938
+ finish() {
28939
+ assert(currentParser === null);
28940
+ assert(this.ptr != null);
28941
+ assert(!this.paused);
28942
+ const { llhttp } = this;
28943
+ let ret;
28944
+ try {
28945
+ currentParser = this;
28946
+ ret = llhttp.llhttp_finish(this.ptr);
28947
+ } finally {
28948
+ currentParser = null;
28949
+ }
28950
+ if (ret === constants.ERROR.OK) {
28951
+ return null;
28952
+ }
28953
+ if (ret === constants.ERROR.PAUSED || ret === constants.ERROR.PAUSED_UPGRADE) {
28954
+ this.paused = true;
28955
+ return null;
28956
+ }
28957
+ return this.createError(ret, EMPTY_BUF);
28958
+ }
28959
+ createError(ret, data) {
28960
+ const { llhttp, contentLength, bytesRead } = this;
28961
+ if (contentLength && bytesRead !== parseInt(contentLength, 10)) {
28962
+ return new ResponseContentLengthMismatchError();
28963
+ }
28964
+ const ptr = llhttp.llhttp_get_error_reason(this.ptr);
28965
+ let message = "";
28966
+ if (ptr) {
28967
+ const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0);
28968
+ message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")";
28969
+ }
28970
+ return new HTTPParserError(message, constants.ERROR[ret], data);
28971
+ }
28873
28972
  destroy() {
28874
28973
  assert(currentParser === null);
28875
28974
  assert(this.ptr != null);
@@ -28897,6 +28996,10 @@ var require_client_h1 = __commonJS({
28897
28996
  if (socket.destroyed) {
28898
28997
  return -1;
28899
28998
  }
28999
+ if (client[kRunning] === 0) {
29000
+ util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket)));
29001
+ return -1;
29002
+ }
28900
29003
  const request2 = client[kQueue][client[kRunningIdx]];
28901
29004
  if (!request2) {
28902
29005
  return -1;
@@ -28999,6 +29102,10 @@ var require_client_h1 = __commonJS({
28999
29102
  if (socket.destroyed) {
29000
29103
  return -1;
29001
29104
  }
29105
+ if (client[kRunning] === 0) {
29106
+ util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket)));
29107
+ return -1;
29108
+ }
29002
29109
  const request2 = client[kQueue][client[kRunningIdx]];
29003
29110
  if (!request2) {
29004
29111
  return -1;
@@ -29132,6 +29239,7 @@ var require_client_h1 = __commonJS({
29132
29239
  }
29133
29240
  request2.onComplete(headers);
29134
29241
  client[kQueue][client[kRunningIdx]++] = null;
29242
+ socket[kSocketUsed] = client[kPending] === 0;
29135
29243
  if (socket[kWriting]) {
29136
29244
  assert(client[kRunning] === 0);
29137
29245
  util.destroy(socket, new InformationalError("reset"));
@@ -29185,6 +29293,9 @@ var require_client_h1 = __commonJS({
29185
29293
  socket[kWriting] = false;
29186
29294
  socket[kReset] = false;
29187
29295
  socket[kBlocking] = false;
29296
+ socket[kIdleSocketValidation] = 0;
29297
+ socket[kIdleSocketValidationTimeout] = null;
29298
+ socket[kSocketUsed] = false;
29188
29299
  socket[kParser] = new Parser(client, socket, llhttpInstance);
29189
29300
  util.addListener(socket, "error", onHttpSocketError);
29190
29301
  util.addListener(socket, "readable", onHttpSocketReadable);
@@ -29224,7 +29335,7 @@ var require_client_h1 = __commonJS({
29224
29335
  * @returns {boolean}
29225
29336
  */
29226
29337
  busy(request2) {
29227
- if (socket[kWriting] || socket[kReset] || socket[kBlocking]) {
29338
+ if (socket[kWriting] || socket[kReset] || socket[kBlocking] || socket[kIdleSocketValidation] === 1) {
29228
29339
  return true;
29229
29340
  }
29230
29341
  if (request2) {
@@ -29246,7 +29357,11 @@ var require_client_h1 = __commonJS({
29246
29357
  assert(err2.code !== "ERR_TLS_CERT_ALTNAME_INVALID");
29247
29358
  const parser = this[kParser];
29248
29359
  if (err2.code === "ECONNRESET" && parser.statusCode && !parser.shouldKeepAlive) {
29249
- parser.onMessageComplete();
29360
+ const parserErr = parser.finish();
29361
+ if (parserErr) {
29362
+ this[kError] = parserErr;
29363
+ this[kClient][kOnError](parserErr);
29364
+ }
29250
29365
  return;
29251
29366
  }
29252
29367
  this[kError] = err2;
@@ -29258,16 +29373,20 @@ var require_client_h1 = __commonJS({
29258
29373
  function onHttpSocketEnd() {
29259
29374
  const parser = this[kParser];
29260
29375
  if (parser.statusCode && !parser.shouldKeepAlive) {
29261
- parser.onMessageComplete();
29376
+ const parserErr = parser.finish();
29377
+ if (parserErr) {
29378
+ util.destroy(this, parserErr);
29379
+ }
29262
29380
  return;
29263
29381
  }
29264
29382
  util.destroy(this, new SocketError("other side closed", util.getSocketInfo(this)));
29265
29383
  }
29266
29384
  function onHttpSocketClose() {
29267
29385
  const parser = this[kParser];
29386
+ clearIdleSocketValidation(this);
29268
29387
  if (parser) {
29269
29388
  if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) {
29270
- parser.onMessageComplete();
29389
+ this[kError] = parser.finish() || this[kError];
29271
29390
  }
29272
29391
  this[kParser].destroy();
29273
29392
  this[kParser] = null;
@@ -29296,6 +29415,23 @@ var require_client_h1 = __commonJS({
29296
29415
  function onSocketClose() {
29297
29416
  this[kClosed] = true;
29298
29417
  }
29418
+ function clearIdleSocketValidation(socket) {
29419
+ if (socket[kIdleSocketValidationTimeout]) {
29420
+ clearImmediate(socket[kIdleSocketValidationTimeout]);
29421
+ socket[kIdleSocketValidationTimeout] = null;
29422
+ }
29423
+ socket[kIdleSocketValidation] = 0;
29424
+ }
29425
+ function scheduleIdleSocketValidation(client, socket) {
29426
+ socket[kIdleSocketValidation] = 1;
29427
+ socket[kIdleSocketValidationTimeout] = setImmediate(() => {
29428
+ socket[kIdleSocketValidationTimeout] = null;
29429
+ socket[kIdleSocketValidation] = 2;
29430
+ if (client[kSocket] === socket && !socket.destroyed) {
29431
+ client[kResume]();
29432
+ }
29433
+ });
29434
+ }
29299
29435
  function resumeH1(client) {
29300
29436
  const socket = client[kSocket];
29301
29437
  if (socket && !socket.destroyed) {
@@ -29308,6 +29444,29 @@ var require_client_h1 = __commonJS({
29308
29444
  socket.ref();
29309
29445
  socket[kNoRef] = false;
29310
29446
  }
29447
+ if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) {
29448
+ if (socket[kIdleSocketValidation] === 0) {
29449
+ scheduleIdleSocketValidation(client, socket);
29450
+ socket[kParser].readMore();
29451
+ if (socket.destroyed) {
29452
+ return;
29453
+ }
29454
+ return;
29455
+ }
29456
+ if (socket[kIdleSocketValidation] === 1) {
29457
+ socket[kParser].readMore();
29458
+ if (socket.destroyed) {
29459
+ return;
29460
+ }
29461
+ return;
29462
+ }
29463
+ }
29464
+ if (client[kRunning] === 0) {
29465
+ socket[kParser].readMore();
29466
+ if (socket.destroyed) {
29467
+ return;
29468
+ }
29469
+ }
29311
29470
  if (client[kSize] === 0) {
29312
29471
  if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) {
29313
29472
  socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE);
@@ -29338,8 +29497,16 @@ var require_client_h1 = __commonJS({
29338
29497
  }
29339
29498
  body = bodyStream.stream;
29340
29499
  contentLength = bodyStream.length;
29341
- } else if (util.isBlobLike(body) && request2.contentType == null && body.type) {
29342
- headers.push("content-type", body.type);
29500
+ } else if (util.isBlobLike(body) && request2.contentType == null) {
29501
+ const contentType = body.type;
29502
+ if (contentType) {
29503
+ const contentTypeValue = `${contentType}`;
29504
+ if (!util.isValidHeaderValue(contentTypeValue)) {
29505
+ util.errorRequest(client, request2, new InvalidArgumentError("invalid content-type header"));
29506
+ return false;
29507
+ }
29508
+ headers.push("content-type", contentTypeValue);
29509
+ }
29343
29510
  }
29344
29511
  if (body && typeof body.read === "function") {
29345
29512
  body.read(0);
@@ -29360,6 +29527,7 @@ var require_client_h1 = __commonJS({
29360
29527
  process.emitWarning(new RequestContentLengthMismatchError());
29361
29528
  }
29362
29529
  const socket = client[kSocket];
29530
+ clearIdleSocketValidation(socket);
29363
29531
  const abort = (err2) => {
29364
29532
  if (request2.aborted || request2.completed) {
29365
29533
  return;
@@ -29752,7 +29920,9 @@ var require_client_h2 = __commonJS({
29752
29920
  RequestAbortedError,
29753
29921
  SocketError,
29754
29922
  InformationalError,
29755
- InvalidArgumentError
29923
+ InvalidArgumentError,
29924
+ HeadersTimeoutError,
29925
+ BodyTimeoutError
29756
29926
  } = require_errors();
29757
29927
  var {
29758
29928
  kUrl,
@@ -29777,6 +29947,7 @@ var require_client_h2 = __commonJS({
29777
29947
  kHTTPContext,
29778
29948
  kClosed,
29779
29949
  kBodyTimeout,
29950
+ kHeadersTimeout,
29780
29951
  kEnableConnectProtocol,
29781
29952
  kRemoteSettings,
29782
29953
  kHTTP2Stream,
@@ -29913,7 +30084,7 @@ var require_client_h2 = __commonJS({
29913
30084
  function resumeH2(client) {
29914
30085
  const socket = client[kSocket];
29915
30086
  if (socket?.destroyed === false) {
29916
- if (client[kSize] === 0 || client[kMaxConcurrentStreams] === 0) {
30087
+ if (client[kSize] === 0) {
29917
30088
  socket.unref();
29918
30089
  client[kHTTP2Session].unref();
29919
30090
  } else {
@@ -29979,6 +30150,24 @@ var require_client_h2 = __commonJS({
29979
30150
  this.destroy(err2);
29980
30151
  util.destroy(this[kSocket], err2);
29981
30152
  }
30153
+ function completeRequest(client, request2, resetPendingIdx = false) {
30154
+ const queue = client[kQueue];
30155
+ const runningIdx = client[kRunningIdx];
30156
+ if (runningIdx < client[kPendingIdx] && queue[runningIdx] === request2) {
30157
+ queue[runningIdx] = null;
30158
+ client[kRunningIdx] = runningIdx + 1;
30159
+ return;
30160
+ }
30161
+ const index = queue.indexOf(request2, runningIdx);
30162
+ if (index === -1 || index >= client[kPendingIdx]) {
30163
+ return;
30164
+ }
30165
+ queue.splice(index, 1);
30166
+ client[kPendingIdx]--;
30167
+ if (resetPendingIdx && client[kPendingIdx] < client[kRunningIdx]) {
30168
+ client[kPendingIdx] = client[kRunningIdx];
30169
+ }
30170
+ }
29982
30171
  function onHttp2SessionGoAway(errorCode) {
29983
30172
  const err2 = this[kError] || new SocketError(`HTTP/2: "GOAWAY" frame received with code ${errorCode}`, util.getSocketInfo(this[kSocket]));
29984
30173
  const client = this[kClient];
@@ -29990,7 +30179,9 @@ var require_client_h2 = __commonJS({
29990
30179
  if (client[kRunningIdx] < client[kQueue].length) {
29991
30180
  const request2 = client[kQueue][client[kRunningIdx]];
29992
30181
  client[kQueue][client[kRunningIdx]++] = null;
29993
- util.errorRequest(client, request2, err2);
30182
+ if (request2 != null) {
30183
+ util.errorRequest(client, request2, err2);
30184
+ }
29994
30185
  client[kPendingIdx] = client[kRunningIdx];
29995
30186
  }
29996
30187
  assert(client[kRunning] === 0);
@@ -30013,7 +30204,9 @@ var require_client_h2 = __commonJS({
30013
30204
  const requests = client[kQueue].splice(client[kRunningIdx]);
30014
30205
  for (let i = 0; i < requests.length; i++) {
30015
30206
  const request2 = requests[i];
30016
- util.errorRequest(client, request2, err2);
30207
+ if (request2 != null) {
30208
+ util.errorRequest(client, request2, err2);
30209
+ }
30017
30210
  }
30018
30211
  }
30019
30212
  }
@@ -30045,7 +30238,8 @@ var require_client_h2 = __commonJS({
30045
30238
  return method !== "GET" && method !== "HEAD" && method !== "OPTIONS" && method !== "TRACE" && method !== "CONNECT";
30046
30239
  }
30047
30240
  function writeH2(client, request2) {
30048
- const requestTimeout = request2.bodyTimeout ?? client[kBodyTimeout];
30241
+ const headersTimeout = request2.headersTimeout ?? client[kHeadersTimeout];
30242
+ const bodyTimeout = request2.bodyTimeout ?? client[kBodyTimeout];
30049
30243
  const session = client[kHTTP2Session];
30050
30244
  const { method, path: path74, host, upgrade, expectContinue, signal, protocol, headers: reqHeaders } = request2;
30051
30245
  let { body } = request2;
@@ -30093,6 +30287,7 @@ var require_client_h2 = __commonJS({
30093
30287
  stream.removeAllListeners("data");
30094
30288
  stream.close();
30095
30289
  client[kOnError](err2);
30290
+ completeRequest(client, request2);
30096
30291
  client[kResume]();
30097
30292
  }
30098
30293
  util.destroy(body, err2);
@@ -30127,7 +30322,7 @@ var require_client_h2 = __commonJS({
30127
30322
  const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers2;
30128
30323
  request2.onUpgrade(statusCode, parseH2Headers(realHeaders), stream);
30129
30324
  ++session[kOpenStreams];
30130
- client[kQueue][client[kRunningIdx]++] = null;
30325
+ completeRequest(client, request2);
30131
30326
  });
30132
30327
  stream.on("error", () => {
30133
30328
  if (stream.rstCode === NGHTTP2_REFUSED_STREAM || stream.rstCode === NGHTTP2_CANCEL) {
@@ -30138,7 +30333,7 @@ var require_client_h2 = __commonJS({
30138
30333
  session[kOpenStreams] -= 1;
30139
30334
  if (session[kOpenStreams] === 0) session.unref();
30140
30335
  });
30141
- stream.setTimeout(requestTimeout);
30336
+ stream.setTimeout(headersTimeout);
30142
30337
  return true;
30143
30338
  }
30144
30339
  stream = session.request(headers, { endStream: false, signal });
@@ -30147,13 +30342,14 @@ var require_client_h2 = __commonJS({
30147
30342
  const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers2;
30148
30343
  request2.onUpgrade(statusCode, parseH2Headers(realHeaders), stream);
30149
30344
  ++session[kOpenStreams];
30150
- client[kQueue][client[kRunningIdx]++] = null;
30345
+ completeRequest(client, request2);
30151
30346
  });
30347
+ stream.on("error", abort);
30152
30348
  stream.once("close", () => {
30153
30349
  session[kOpenStreams] -= 1;
30154
30350
  if (session[kOpenStreams] === 0) session.unref();
30155
30351
  });
30156
- stream.setTimeout(requestTimeout);
30352
+ stream.setTimeout(headersTimeout);
30157
30353
  return true;
30158
30354
  }
30159
30355
  headers[HTTP2_HEADER_PATH] = path74;
@@ -30211,12 +30407,13 @@ var require_client_h2 = __commonJS({
30211
30407
  writeBodyH2();
30212
30408
  }
30213
30409
  ++session[kOpenStreams];
30214
- stream.setTimeout(requestTimeout);
30410
+ stream.setTimeout(headersTimeout);
30215
30411
  let responseReceived = false;
30216
30412
  stream.once("response", (headers2) => {
30217
30413
  const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers2;
30218
30414
  request2.onResponseStarted();
30219
30415
  responseReceived = true;
30416
+ stream.setTimeout(bodyTimeout);
30220
30417
  if (request2.aborted) {
30221
30418
  stream.removeAllListeners("data");
30222
30419
  return;
@@ -30239,12 +30436,11 @@ var require_client_h2 = __commonJS({
30239
30436
  if (!request2.aborted && !request2.completed) {
30240
30437
  request2.onComplete({});
30241
30438
  }
30242
- client[kQueue][client[kRunningIdx]++] = null;
30439
+ completeRequest(client, request2);
30243
30440
  client[kResume]();
30244
30441
  } else {
30245
30442
  abort(new InformationalError("HTTP/2: stream half-closed (remote)"));
30246
- client[kQueue][client[kRunningIdx]++] = null;
30247
- client[kPendingIdx] = client[kRunningIdx];
30443
+ completeRequest(client, request2, true);
30248
30444
  client[kResume]();
30249
30445
  }
30250
30446
  });
@@ -30254,6 +30450,9 @@ var require_client_h2 = __commonJS({
30254
30450
  if (session[kOpenStreams] === 0) {
30255
30451
  session.unref();
30256
30452
  }
30453
+ if (!request2.aborted && !request2.completed) {
30454
+ abort(new InformationalError("HTTP/2: stream closed before the response was complete"));
30455
+ }
30257
30456
  });
30258
30457
  stream.once("error", function(err2) {
30259
30458
  stream.removeAllListeners("data");
@@ -30267,7 +30466,7 @@ var require_client_h2 = __commonJS({
30267
30466
  stream.removeAllListeners("data");
30268
30467
  });
30269
30468
  stream.on("timeout", () => {
30270
- const err2 = new InformationalError(`HTTP/2: "stream timeout after ${requestTimeout}"`);
30469
+ const err2 = responseReceived ? new BodyTimeoutError(`HTTP/2: "body timeout after ${bodyTimeout}"`) : new HeadersTimeoutError(`HTTP/2: "headers timeout after ${headersTimeout}"`);
30271
30470
  stream.removeAllListeners("data");
30272
30471
  session[kOpenStreams] -= 1;
30273
30472
  if (session[kOpenStreams] === 0) {
@@ -30575,7 +30774,8 @@ var require_client = __commonJS({
30575
30774
  useH2c,
30576
30775
  initialWindowSize,
30577
30776
  connectionWindowSize,
30578
- pingInterval
30777
+ pingInterval,
30778
+ webSocket
30579
30779
  } = {}) {
30580
30780
  if (keepAlive !== void 0) {
30581
30781
  throw new InvalidArgumentError("unsupported keepAlive, use pipelining=0 instead");
@@ -30653,7 +30853,7 @@ var require_client = __commonJS({
30653
30853
  if (pingInterval != null && (typeof pingInterval !== "number" || !Number.isInteger(pingInterval) || pingInterval < 0)) {
30654
30854
  throw new InvalidArgumentError("pingInterval must be a positive integer, greater or equal to 0");
30655
30855
  }
30656
- super();
30856
+ super({ webSocket });
30657
30857
  if (typeof connect2 !== "function") {
30658
30858
  connect2 = buildConnector({
30659
30859
  ...tls,
@@ -30665,9 +30865,13 @@ var require_client = __commonJS({
30665
30865
  ...typeof autoSelectFamily === "boolean" ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : void 0,
30666
30866
  ...connect2
30667
30867
  });
30668
- } else if (socketPath != null) {
30868
+ } else {
30669
30869
  const customConnect = connect2;
30670
- connect2 = (opts, callback) => customConnect({ ...opts, socketPath }, callback);
30870
+ connect2 = (opts, callback) => customConnect({
30871
+ ...opts,
30872
+ ...socketPath != null ? { socketPath } : null,
30873
+ ...allowH2 != null ? { allowH2 } : null
30874
+ }, callback);
30671
30875
  }
30672
30876
  this[kUrl] = util.parseOrigin(url);
30673
30877
  this[kConnector] = connect2;
@@ -30760,7 +30964,9 @@ var require_client = __commonJS({
30760
30964
  const requests = this[kQueue].splice(this[kPendingIdx]);
30761
30965
  for (let i = 0; i < requests.length; i++) {
30762
30966
  const request2 = requests[i];
30763
- util.errorRequest(this, request2, err2);
30967
+ if (request2 != null) {
30968
+ util.errorRequest(this, request2, err2);
30969
+ }
30764
30970
  }
30765
30971
  const callback = () => {
30766
30972
  if (this[kClosedResolve]) {
@@ -30785,7 +30991,9 @@ var require_client = __commonJS({
30785
30991
  const requests = client[kQueue].splice(client[kRunningIdx]);
30786
30992
  for (let i = 0; i < requests.length; i++) {
30787
30993
  const request2 = requests[i];
30788
- util.errorRequest(client, request2, err2);
30994
+ if (request2 != null) {
30995
+ util.errorRequest(client, request2, err2);
30996
+ }
30789
30997
  }
30790
30998
  assert(client[kSize] === 0);
30791
30999
  }
@@ -31296,7 +31504,7 @@ var require_pool = __commonJS({
31296
31504
  ...connect
31297
31505
  });
31298
31506
  }
31299
- super();
31507
+ super(options);
31300
31508
  this[kConnections] = connections || null;
31301
31509
  this[kUrl] = util.parseOrigin(origin);
31302
31510
  this[kOptions] = { ...util.deepClone(options), connect, allowH2, clientTtl, socketPath };
@@ -31378,12 +31586,14 @@ var require_balanced_pool = __commonJS({
31378
31586
  return new Pool(origin, opts);
31379
31587
  }
31380
31588
  var BalancedPool = class extends PoolBase {
31381
- constructor(upstreams = [], { factory = defaultFactory, ...opts } = {}) {
31589
+ constructor(upstreams = [], { factory = defaultFactory, connect, tls, ...opts } = {}) {
31382
31590
  if (typeof factory !== "function") {
31383
31591
  throw new InvalidArgumentError("factory must be a function.");
31384
31592
  }
31385
- super();
31386
- this[kOptions] = { ...util.deepClone(opts) };
31593
+ super(opts);
31594
+ if (connect && typeof connect !== "function") connect = { ...connect };
31595
+ if (tls && typeof tls !== "function") tls = { ...tls };
31596
+ this[kOptions] = { ...util.deepClone(opts), connect, tls };
31387
31597
  this[kOptions].interceptors = opts.interceptors ? { ...opts.interceptors } : void 0;
31388
31598
  this[kIndex] = -1;
31389
31599
  this[kCurrentWeight] = 0;
@@ -31634,7 +31844,7 @@ var require_agent = __commonJS({
31634
31844
  if (typeof maxOrigins !== "number" || Number.isNaN(maxOrigins) || maxOrigins <= 0) {
31635
31845
  throw new InvalidArgumentError("maxOrigins must be a number greater than 0");
31636
31846
  }
31637
- super();
31847
+ super(options);
31638
31848
  if (connect && typeof connect !== "function") {
31639
31849
  connect = { ...connect };
31640
31850
  }
@@ -31771,28 +31981,37 @@ var require_socks5_utils = __commonJS({
31771
31981
  }
31772
31982
  function parseIPv6(address) {
31773
31983
  const buffer = Buffer2.alloc(16);
31774
- const parts = address.split(":");
31775
- let partIndex = 0;
31776
- let bufferIndex = 0;
31777
- const doubleColonIndex = address.indexOf("::");
31984
+ let normalizedAddress = address;
31985
+ if (address.includes(".")) {
31986
+ const lastColonIndex = address.lastIndexOf(":");
31987
+ const ipv4Part = address.slice(lastColonIndex + 1);
31988
+ if (net3.isIPv4(ipv4Part)) {
31989
+ const octets = ipv4Part.split(".").map(Number);
31990
+ const high = (octets[0] << 8 | octets[1]).toString(16);
31991
+ const low = (octets[2] << 8 | octets[3]).toString(16);
31992
+ normalizedAddress = `${address.slice(0, lastColonIndex)}:${high}:${low}`;
31993
+ }
31994
+ }
31995
+ const doubleColonIndex = normalizedAddress.indexOf("::");
31778
31996
  if (doubleColonIndex !== -1) {
31779
- const nonEmptyParts = parts.filter((p) => p.length > 0).length;
31780
- const skipParts = 8 - nonEmptyParts;
31781
- for (let i = 0; i < parts.length; i++) {
31782
- if (parts[i] === "" && i === doubleColonIndex / 3) {
31783
- bufferIndex += skipParts * 2;
31784
- } else if (parts[i] !== "") {
31785
- const value = parseInt(parts[i], 16);
31786
- buffer.writeUInt16BE(value, bufferIndex);
31787
- bufferIndex += 2;
31788
- }
31997
+ const before = normalizedAddress.slice(0, doubleColonIndex);
31998
+ const after = normalizedAddress.slice(doubleColonIndex + 2);
31999
+ const beforeParts = before === "" ? [] : before.split(":");
32000
+ const afterParts = after === "" ? [] : after.split(":");
32001
+ let bufferIndex = 0;
32002
+ for (const part of beforeParts) {
32003
+ buffer.writeUInt16BE(parseInt(part, 16), bufferIndex);
32004
+ bufferIndex += 2;
32005
+ }
32006
+ bufferIndex = 16 - afterParts.length * 2;
32007
+ for (const part of afterParts) {
32008
+ buffer.writeUInt16BE(parseInt(part, 16), bufferIndex);
32009
+ bufferIndex += 2;
31789
32010
  }
31790
32011
  } else {
31791
- for (const part of parts) {
31792
- if (part === "") continue;
31793
- const value = parseInt(part, 16);
31794
- buffer.writeUInt16BE(value, partIndex * 2);
31795
- partIndex++;
32012
+ const parts = normalizedAddress.split(":");
32013
+ for (let i = 0; i < parts.length; i++) {
32014
+ buffer.writeUInt16BE(parseInt(parts[i], 16), i * 2);
31796
32015
  }
31797
32016
  }
31798
32017
  return buffer;
@@ -31898,6 +32117,7 @@ var require_socks5_client = __commonJS({
31898
32117
  var { debuglog } = require("util");
31899
32118
  var { parseAddress } = require_socks5_utils();
31900
32119
  var debug = debuglog("undici:socks5");
32120
+ var EMPTY_BUFFER = Buffer2.alloc(0);
31901
32121
  var SOCKS_VERSION = 5;
31902
32122
  var AUTH_METHODS = {
31903
32123
  NO_AUTH: 0,
@@ -31930,6 +32150,7 @@ var require_socks5_client = __commonJS({
31930
32150
  INITIAL: "initial",
31931
32151
  HANDSHAKING: "handshaking",
31932
32152
  AUTHENTICATING: "authenticating",
32153
+ AUTHENTICATED: "authenticated",
31933
32154
  CONNECTING: "connecting",
31934
32155
  CONNECTED: "connected",
31935
32156
  ERROR: "error",
@@ -31944,15 +32165,18 @@ var require_socks5_client = __commonJS({
31944
32165
  this.socket = socket;
31945
32166
  this.options = options;
31946
32167
  this.state = STATES.INITIAL;
31947
- this.buffer = Buffer2.alloc(0);
32168
+ this.buffer = EMPTY_BUFFER;
32169
+ this.onSocketData = this.onData.bind(this);
32170
+ this.onSocketError = this.onError.bind(this);
32171
+ this.onSocketClose = this.onClose.bind(this);
31948
32172
  this.authMethods = [];
31949
32173
  if (options.username && options.password) {
31950
32174
  this.authMethods.push(AUTH_METHODS.USERNAME_PASSWORD);
31951
32175
  }
31952
32176
  this.authMethods.push(AUTH_METHODS.NO_AUTH);
31953
- this.socket.on("data", this.onData.bind(this));
31954
- this.socket.on("error", this.onError.bind(this));
31955
- this.socket.on("close", this.onClose.bind(this));
32177
+ this.socket.on("data", this.onSocketData);
32178
+ this.socket.on("error", this.onSocketError);
32179
+ this.socket.on("close", this.onSocketClose);
31956
32180
  }
31957
32181
  /**
31958
32182
  * Handle incoming data from the socket
@@ -32001,6 +32225,10 @@ var require_socks5_client = __commonJS({
32001
32225
  this.socket.destroy();
32002
32226
  }
32003
32227
  }
32228
+ markAuthenticated() {
32229
+ this.state = STATES.AUTHENTICATED;
32230
+ this.emit("authenticated");
32231
+ }
32004
32232
  /**
32005
32233
  * Start the SOCKS5 handshake
32006
32234
  */
@@ -32036,7 +32264,7 @@ var require_socks5_client = __commonJS({
32036
32264
  this.buffer = this.buffer.subarray(2);
32037
32265
  debug("server selected auth method", method);
32038
32266
  if (method === AUTH_METHODS.NO_AUTH) {
32039
- this.emit("authenticated");
32267
+ this.markAuthenticated();
32040
32268
  } else if (method === AUTH_METHODS.USERNAME_PASSWORD) {
32041
32269
  this.state = STATES.AUTHENTICATING;
32042
32270
  this.sendAuthRequest();
@@ -32083,7 +32311,7 @@ var require_socks5_client = __commonJS({
32083
32311
  }
32084
32312
  this.buffer = this.buffer.subarray(2);
32085
32313
  debug("authentication successful");
32086
- this.emit("authenticated");
32314
+ this.markAuthenticated();
32087
32315
  }
32088
32316
  /**
32089
32317
  * Send CONNECT command
@@ -32091,8 +32319,11 @@ var require_socks5_client = __commonJS({
32091
32319
  * @param {number} port - Target port
32092
32320
  */
32093
32321
  connect(address, port) {
32094
- if (this.state === STATES.CONNECTED) {
32095
- throw new InvalidArgumentError("Already connected");
32322
+ if (this.state === STATES.CONNECTING || this.state === STATES.CONNECTED) {
32323
+ throw new InvalidArgumentError("Connection already in progress");
32324
+ }
32325
+ if (this.state !== STATES.AUTHENTICATED) {
32326
+ throw new InvalidArgumentError("Client must be authenticated before CONNECT");
32096
32327
  }
32097
32328
  debug("connecting to", address, port);
32098
32329
  this.state = STATES.CONNECTING;
@@ -32166,8 +32397,9 @@ var require_socks5_client = __commonJS({
32166
32397
  offset += 16;
32167
32398
  }
32168
32399
  const boundPort = this.buffer.readUInt16BE(offset);
32169
- this.buffer = this.buffer.subarray(responseLength);
32400
+ this.buffer = EMPTY_BUFFER;
32170
32401
  this.state = STATES.CONNECTED;
32402
+ this.socket.removeListener("data", this.onSocketData);
32171
32403
  debug("connected, bound address:", boundAddress, "port:", boundPort);
32172
32404
  this.emit("connected", { address: boundAddress, port: boundPort });
32173
32405
  }
@@ -32212,12 +32444,11 @@ var require_socks5_client = __commonJS({
32212
32444
  var require_socks5_proxy_agent = __commonJS({
32213
32445
  "node_modules/undici/lib/dispatcher/socks5-proxy-agent.js"(exports2, module2) {
32214
32446
  "use strict";
32215
- var net3 = require("net");
32216
32447
  var { URL: URL6 } = require("url");
32217
32448
  var tls;
32218
32449
  var DispatcherBase = require_dispatcher_base();
32219
32450
  var { InvalidArgumentError } = require_errors();
32220
- var { Socks5Client } = require_socks5_client();
32451
+ var { Socks5Client, STATES } = require_socks5_client();
32221
32452
  var { kDispatch, kClose, kDestroy } = require_symbols();
32222
32453
  var Pool = require_pool();
32223
32454
  var buildConnector = require_connect();
@@ -32226,8 +32457,10 @@ var require_socks5_proxy_agent = __commonJS({
32226
32457
  var kProxyUrl = /* @__PURE__ */ Symbol("proxy url");
32227
32458
  var kProxyHeaders = /* @__PURE__ */ Symbol("proxy headers");
32228
32459
  var kProxyAuth = /* @__PURE__ */ Symbol("proxy auth");
32229
- var kPool = /* @__PURE__ */ Symbol("pool");
32460
+ var kProxyProtocol = /* @__PURE__ */ Symbol("proxy protocol");
32461
+ var kPools = /* @__PURE__ */ Symbol("pools");
32230
32462
  var kConnector = /* @__PURE__ */ Symbol("connector");
32463
+ var kRequestTls = /* @__PURE__ */ Symbol("request tls settings");
32231
32464
  var experimentalWarningEmitted = false;
32232
32465
  var Socks5ProxyAgent = class extends DispatcherBase {
32233
32466
  constructor(proxyUrl, options = {}) {
@@ -32248,6 +32481,8 @@ var require_socks5_proxy_agent = __commonJS({
32248
32481
  }
32249
32482
  this[kProxyUrl] = url;
32250
32483
  this[kProxyHeaders] = options.headers || {};
32484
+ this[kProxyProtocol] = options.proxyTls ? "https:" : "http:";
32485
+ this[kRequestTls] = options.requestTls;
32251
32486
  this[kProxyAuth] = {
32252
32487
  username: options.username || (url.username ? decodeURIComponent(url.username) : null),
32253
32488
  password: options.password || (url.password ? decodeURIComponent(url.password) : null)
@@ -32256,7 +32491,7 @@ var require_socks5_proxy_agent = __commonJS({
32256
32491
  ...options.proxyTls,
32257
32492
  servername: options.proxyTls?.servername || url.hostname
32258
32493
  });
32259
- this[kPool] = null;
32494
+ this[kPools] = /* @__PURE__ */ new Map();
32260
32495
  }
32261
32496
  /**
32262
32497
  * Create a SOCKS5 connection to the proxy
@@ -32266,20 +32501,18 @@ var require_socks5_proxy_agent = __commonJS({
32266
32501
  const proxyPort = parseInt(this[kProxyUrl].port) || 1080;
32267
32502
  debug("creating SOCKS5 connection to", proxyHost, proxyPort);
32268
32503
  const socket = await new Promise((resolve2, reject) => {
32269
- const onConnect = () => {
32270
- socket2.removeListener("error", onError);
32271
- resolve2(socket2);
32272
- };
32273
- const onError = (err2) => {
32274
- socket2.removeListener("connect", onConnect);
32275
- reject(err2);
32276
- };
32277
- const socket2 = net3.connect({
32504
+ this[kConnector]({
32505
+ hostname: proxyHost,
32278
32506
  host: proxyHost,
32279
- port: proxyPort
32507
+ port: proxyPort,
32508
+ protocol: this[kProxyProtocol]
32509
+ }, (err2, socket2) => {
32510
+ if (err2) {
32511
+ reject(err2);
32512
+ } else {
32513
+ resolve2(socket2);
32514
+ }
32280
32515
  });
32281
- socket2.once("connect", onConnect);
32282
- socket2.once("error", onError);
32283
32516
  });
32284
32517
  const socks5Client = new Socks5Client(socket, this[kProxyAuth]);
32285
32518
  socks5Client.on("error", (err2) => {
@@ -32301,7 +32534,7 @@ var require_socks5_proxy_agent = __commonJS({
32301
32534
  socks5Client.removeListener("authenticated", onAuthenticated);
32302
32535
  reject(err2);
32303
32536
  };
32304
- if (socks5Client.state === "authenticated") {
32537
+ if (socks5Client.state === STATES.AUTHENTICATED) {
32305
32538
  clearTimeout(timeout);
32306
32539
  resolve2();
32307
32540
  } else {
@@ -32333,12 +32566,14 @@ var require_socks5_proxy_agent = __commonJS({
32333
32566
  /**
32334
32567
  * Dispatch a request through the SOCKS5 proxy
32335
32568
  */
32336
- async [kDispatch](opts, handler) {
32569
+ [kDispatch](opts, handler) {
32337
32570
  const { origin } = opts;
32338
32571
  debug("dispatching request to", origin, "via SOCKS5");
32339
32572
  try {
32340
- if (!this[kPool] || this[kPool].destroyed || this[kPool].closed) {
32341
- this[kPool] = new Pool(origin, {
32573
+ const originKey = String(origin);
32574
+ let pool = this[kPools].get(originKey);
32575
+ if (!pool || pool.destroyed || pool.closed) {
32576
+ pool = new Pool(origin, {
32342
32577
  pipelining: opts.pipelining,
32343
32578
  connections: opts.connections,
32344
32579
  connect: async (connectOpts, callback) => {
@@ -32355,9 +32590,9 @@ var require_socks5_proxy_agent = __commonJS({
32355
32590
  }
32356
32591
  debug("upgrading to TLS");
32357
32592
  finalSocket = tls.connect({
32593
+ ...this[kRequestTls],
32358
32594
  socket,
32359
- servername: targetHost,
32360
- ...connectOpts.tls || {}
32595
+ servername: this[kRequestTls]?.servername || targetHost
32361
32596
  });
32362
32597
  await new Promise((resolve2, reject) => {
32363
32598
  finalSocket.once("secureConnect", resolve2);
@@ -32371,26 +32606,37 @@ var require_socks5_proxy_agent = __commonJS({
32371
32606
  }
32372
32607
  }
32373
32608
  });
32609
+ this[kPools].set(originKey, pool);
32374
32610
  }
32375
- return this[kPool][kDispatch](opts, handler);
32611
+ return pool[kDispatch](opts, handler);
32376
32612
  } catch (err2) {
32377
32613
  debug("dispatch error:", err2);
32378
- if (typeof handler.onError === "function") {
32614
+ if (typeof handler.onResponseError === "function") {
32615
+ handler.onResponseError(null, err2);
32616
+ return false;
32617
+ } else if (typeof handler.onError === "function") {
32379
32618
  handler.onError(err2);
32619
+ return false;
32380
32620
  } else {
32381
32621
  throw err2;
32382
32622
  }
32383
32623
  }
32384
32624
  }
32385
32625
  async [kClose]() {
32386
- if (this[kPool]) {
32387
- await this[kPool].close();
32626
+ const closePromises = [];
32627
+ for (const pool of this[kPools].values()) {
32628
+ closePromises.push(pool.close());
32388
32629
  }
32630
+ this[kPools].clear();
32631
+ await Promise.all(closePromises);
32389
32632
  }
32390
32633
  async [kDestroy](err2) {
32391
- if (this[kPool]) {
32392
- await this[kPool].destroy(err2);
32634
+ const destroyPromises = [];
32635
+ for (const pool of this[kPools].values()) {
32636
+ destroyPromises.push(pool.destroy(err2));
32393
32637
  }
32638
+ this[kPools].clear();
32639
+ await Promise.all(destroyPromises);
32394
32640
  }
32395
32641
  };
32396
32642
  module2.exports = Socks5ProxyAgent;
@@ -32515,7 +32761,8 @@ var require_proxy_agent = __commonJS({
32515
32761
  factory: agentFactory,
32516
32762
  username: opts.username || username,
32517
32763
  password: opts.password || password,
32518
- proxyTls: opts.proxyTls
32764
+ proxyTls: opts.proxyTls,
32765
+ requestTls: opts.requestTls
32519
32766
  });
32520
32767
  }
32521
32768
  if (!this[kTunnelProxy] && protocol2 === "http:" && this[kProxy].protocol === "http:") {
@@ -32793,6 +33040,23 @@ var require_retry_handler = __commonJS({
32793
33040
  const retryTime = new Date(retryAfter).getTime();
32794
33041
  return isNaN(retryTime) ? 0 : retryTime - Date.now();
32795
33042
  }
33043
+ function validatePartialResponseContentLength(headers, range, statusCode, retryCount) {
33044
+ const contentLength = headers["content-length"];
33045
+ if (contentLength == null) {
33046
+ return;
33047
+ }
33048
+ if (!Number.isFinite(range.start) || !Number.isFinite(range.end)) {
33049
+ return;
33050
+ }
33051
+ const length = Number(contentLength);
33052
+ const expectedLength = range.end - range.start + 1;
33053
+ if (!Number.isFinite(length) || length !== expectedLength) {
33054
+ throw new RequestRetryError("Content-Length mismatch", statusCode, {
33055
+ headers,
33056
+ data: { count: retryCount }
33057
+ });
33058
+ }
33059
+ }
32796
33060
  var RetryHandler = class _RetryHandler {
32797
33061
  constructor(opts, { dispatch, handler }) {
32798
33062
  const { retryOptions, ...dispatchOpts } = opts;
@@ -32851,8 +33115,13 @@ var require_retry_handler = __commonJS({
32851
33115
  onResponseStartWithRetry(controller, statusCode, headers, statusMessage, err2) {
32852
33116
  if (this.retryOpts.throwOnError) {
32853
33117
  if (this.retryOpts.statusCodes.includes(statusCode) === false) {
32854
- this.headersSent = true;
32855
- this.handler.onResponseStart?.(controller, statusCode, headers, statusMessage);
33118
+ if (this.headersSent) {
33119
+ this.handler.onResponseError?.(controller, err2);
33120
+ } else {
33121
+ this.headersSent = true;
33122
+ this.checkpointResponseEnd(headers);
33123
+ this.handler.onResponseStart?.(controller, statusCode, headers, statusMessage);
33124
+ }
32856
33125
  } else {
32857
33126
  this.error = err2;
32858
33127
  }
@@ -32860,13 +33129,19 @@ var require_retry_handler = __commonJS({
32860
33129
  }
32861
33130
  if (isDisturbed(this.opts.body)) {
32862
33131
  this.headersSent = true;
33132
+ this.checkpointResponseEnd(headers);
32863
33133
  this.handler.onResponseStart?.(controller, statusCode, headers, statusMessage);
32864
33134
  return;
32865
33135
  }
32866
33136
  function shouldRetry(passedErr) {
32867
33137
  if (passedErr) {
32868
- this.headersSent = true;
32869
- this.handler.onResponseStart?.(controller, statusCode, headers, statusMessage);
33138
+ if (this.headersSent) {
33139
+ this.handler.onResponseError?.(controller, passedErr);
33140
+ } else {
33141
+ this.headersSent = true;
33142
+ this.checkpointResponseEnd(headers);
33143
+ this.handler.onResponseStart?.(controller, statusCode, headers, statusMessage);
33144
+ }
32870
33145
  controller.resume();
32871
33146
  return;
32872
33147
  }
@@ -32883,6 +33158,17 @@ var require_retry_handler = __commonJS({
32883
33158
  shouldRetry.bind(this)
32884
33159
  );
32885
33160
  }
33161
+ checkpointResponseEnd(headers) {
33162
+ if (this.end == null && this.opts.method !== "HEAD") {
33163
+ const contentLength = headers["content-length"];
33164
+ this.end = contentLength != null ? Number(contentLength) - 1 : null;
33165
+ assert(
33166
+ this.end == null || Number.isFinite(this.end),
33167
+ "invalid content-length"
33168
+ );
33169
+ this.resume = this.end != null;
33170
+ }
33171
+ }
32886
33172
  onRequestStart(controller, context) {
32887
33173
  if (!this.headersSent) {
32888
33174
  this.handler.onRequestStart?.(controller, context);
@@ -32961,9 +33247,14 @@ var require_retry_handler = __commonJS({
32961
33247
  data: { count: this.retryCount }
32962
33248
  });
32963
33249
  }
33250
+ validatePartialResponseContentLength(headers, contentRange, statusCode, this.retryCount);
32964
33251
  const { start, size, end = size ? size - 1 : null } = contentRange;
32965
- assert(this.start === start, "content-range mismatch");
32966
- assert(this.end == null || this.end === end, "content-range mismatch");
33252
+ if (this.start !== start || this.end != null && this.end !== end) {
33253
+ throw new RequestRetryError("Content-Range mismatch", statusCode, {
33254
+ headers,
33255
+ data: { count: this.retryCount }
33256
+ });
33257
+ }
32967
33258
  return;
32968
33259
  }
32969
33260
  if (this.end == null) {
@@ -32979,6 +33270,7 @@ var require_retry_handler = __commonJS({
32979
33270
  );
32980
33271
  return;
32981
33272
  }
33273
+ validatePartialResponseContentLength(headers, range, statusCode, this.retryCount);
32982
33274
  const { start, size, end = size ? size - 1 : null } = range;
32983
33275
  assert(
32984
33276
  start != null && Number.isFinite(start),
@@ -33055,7 +33347,7 @@ var require_retry_handler = __commonJS({
33055
33347
  }
33056
33348
  }
33057
33349
  onResponseError(controller, err2) {
33058
- if (controller?.aborted || isDisturbed(this.opts.body)) {
33350
+ if (controller?.aborted || isDisturbed(this.opts.body) || this.headersSent && !this.resume) {
33059
33351
  this.handler.onResponseError?.(controller, err2);
33060
33352
  return;
33061
33353
  }
@@ -33136,7 +33428,7 @@ var require_h2c_client = __commonJS({
33136
33428
  "h2c-client: Only h2c protocol is supported"
33137
33429
  );
33138
33430
  }
33139
- const { connect, maxConcurrentStreams, pipelining, ...opts } = clientOpts ?? {};
33431
+ const { maxConcurrentStreams, pipelining, ...opts } = clientOpts ?? {};
33140
33432
  let defaultMaxConcurrentStreams = 100;
33141
33433
  let defaultPipelining = 100;
33142
33434
  if (maxConcurrentStreams != null && Number.isInteger(maxConcurrentStreams) && maxConcurrentStreams > 0) {
@@ -33586,7 +33878,7 @@ var require_api_request = __commonJS({
33586
33878
  if (typeof callback !== "function") {
33587
33879
  throw new InvalidArgumentError("invalid callback");
33588
33880
  }
33589
- if (highWaterMark && (typeof highWaterMark !== "number" || highWaterMark < 0)) {
33881
+ if (highWaterMark != null && (!Number.isFinite(highWaterMark) || highWaterMark < 0)) {
33590
33882
  throw new InvalidArgumentError("invalid highWaterMark");
33591
33883
  }
33592
33884
  if (signal && typeof signal.on !== "function" && typeof signal.addEventListener !== "function") {
@@ -35025,13 +35317,13 @@ var require_mock_call_history = __commonJS({
35025
35317
  "use strict";
35026
35318
  var { kMockCallHistoryAddLog } = require_mock_symbols();
35027
35319
  var { InvalidArgumentError } = require_errors();
35028
- function handleFilterCallsWithOptions(criteria, options, handler, store) {
35320
+ function handleFilterCallsWithOptions(criteria, options, handler, store, allLogs) {
35029
35321
  switch (options.operator) {
35030
35322
  case "OR":
35031
- store.push(...handler(criteria));
35323
+ store.push(...handler(criteria, allLogs));
35032
35324
  return store;
35033
35325
  case "AND":
35034
- return handler.call({ logs: store }, criteria);
35326
+ return handler(criteria, store);
35035
35327
  default:
35036
35328
  throw new InvalidArgumentError("options.operator must to be a case insensitive string equal to 'OR' or 'AND'");
35037
35329
  }
@@ -35050,14 +35342,14 @@ var require_mock_call_history = __commonJS({
35050
35342
  return finalOptions;
35051
35343
  }
35052
35344
  function makeFilterCalls(parameterName) {
35053
- return (parameterValue) => {
35345
+ return (parameterValue, logs) => {
35054
35346
  if (typeof parameterValue === "string" || parameterValue == null) {
35055
- return this.logs.filter((log) => {
35347
+ return logs.filter((log) => {
35056
35348
  return log[parameterName] === parameterValue;
35057
35349
  });
35058
35350
  }
35059
35351
  if (parameterValue instanceof RegExp) {
35060
- return this.logs.filter((log) => {
35352
+ return logs.filter((log) => {
35061
35353
  return parameterValue.test(log[parameterName]);
35062
35354
  });
35063
35355
  }
@@ -35162,30 +35454,30 @@ var require_mock_call_history = __commonJS({
35162
35454
  return this.logs;
35163
35455
  }
35164
35456
  const finalOptions = { operator: "OR", ...buildAndValidateFilterCallsOptions(options) };
35165
- let maybeDuplicatedLogsFiltered = [];
35457
+ let maybeDuplicatedLogsFiltered = finalOptions.operator === "AND" ? this.logs : [];
35166
35458
  if ("protocol" in criteria) {
35167
- maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.protocol, finalOptions, this.filterCallsByProtocol, maybeDuplicatedLogsFiltered);
35459
+ maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.protocol, finalOptions, this.filterCallsByProtocol, maybeDuplicatedLogsFiltered, this.logs);
35168
35460
  }
35169
35461
  if ("host" in criteria) {
35170
- maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.host, finalOptions, this.filterCallsByHost, maybeDuplicatedLogsFiltered);
35462
+ maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.host, finalOptions, this.filterCallsByHost, maybeDuplicatedLogsFiltered, this.logs);
35171
35463
  }
35172
35464
  if ("port" in criteria) {
35173
- maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.port, finalOptions, this.filterCallsByPort, maybeDuplicatedLogsFiltered);
35465
+ maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.port, finalOptions, this.filterCallsByPort, maybeDuplicatedLogsFiltered, this.logs);
35174
35466
  }
35175
35467
  if ("origin" in criteria) {
35176
- maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.origin, finalOptions, this.filterCallsByOrigin, maybeDuplicatedLogsFiltered);
35468
+ maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.origin, finalOptions, this.filterCallsByOrigin, maybeDuplicatedLogsFiltered, this.logs);
35177
35469
  }
35178
35470
  if ("path" in criteria) {
35179
- maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.path, finalOptions, this.filterCallsByPath, maybeDuplicatedLogsFiltered);
35471
+ maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.path, finalOptions, this.filterCallsByPath, maybeDuplicatedLogsFiltered, this.logs);
35180
35472
  }
35181
35473
  if ("hash" in criteria) {
35182
- maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.hash, finalOptions, this.filterCallsByHash, maybeDuplicatedLogsFiltered);
35474
+ maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.hash, finalOptions, this.filterCallsByHash, maybeDuplicatedLogsFiltered, this.logs);
35183
35475
  }
35184
35476
  if ("fullUrl" in criteria) {
35185
- maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.fullUrl, finalOptions, this.filterCallsByFullUrl, maybeDuplicatedLogsFiltered);
35477
+ maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.fullUrl, finalOptions, this.filterCallsByFullUrl, maybeDuplicatedLogsFiltered, this.logs);
35186
35478
  }
35187
35479
  if ("method" in criteria) {
35188
- maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.method, finalOptions, this.filterCallsByMethod, maybeDuplicatedLogsFiltered);
35480
+ maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.method, finalOptions, this.filterCallsByMethod, maybeDuplicatedLogsFiltered, this.logs);
35189
35481
  }
35190
35482
  const uniqLogsFiltered = [...new Set(maybeDuplicatedLogsFiltered)];
35191
35483
  return uniqLogsFiltered;
@@ -36258,7 +36550,8 @@ var require_snapshot_agent = __commonJS({
36258
36550
  var require_global2 = __commonJS({
36259
36551
  "node_modules/undici/lib/global.js"(exports2, module2) {
36260
36552
  "use strict";
36261
- var globalDispatcher = /* @__PURE__ */ Symbol.for("undici.globalDispatcher.1");
36553
+ var globalDispatcher = /* @__PURE__ */ Symbol.for("undici.globalDispatcher.2");
36554
+ var legacyGlobalDispatcher = /* @__PURE__ */ Symbol.for("undici.globalDispatcher.1");
36262
36555
  var { InvalidArgumentError } = require_errors();
36263
36556
  var Agent = require_agent();
36264
36557
  if (getGlobalDispatcher() === void 0) {
@@ -36274,9 +36567,15 @@ var require_global2 = __commonJS({
36274
36567
  enumerable: false,
36275
36568
  configurable: false
36276
36569
  });
36570
+ Object.defineProperty(globalThis, legacyGlobalDispatcher, {
36571
+ value: agent,
36572
+ writable: true,
36573
+ enumerable: false,
36574
+ configurable: false
36575
+ });
36277
36576
  }
36278
36577
  function getGlobalDispatcher() {
36279
- return globalThis[globalDispatcher];
36578
+ return globalThis[legacyGlobalDispatcher];
36280
36579
  }
36281
36580
  var installedExports = (
36282
36581
  /** @type {const} */
@@ -36655,7 +36954,6 @@ var require_dump = __commonJS({
36655
36954
  #maxSize = 1024 * 1024;
36656
36955
  #dumped = false;
36657
36956
  #size = 0;
36658
- #controller = null;
36659
36957
  aborted = false;
36660
36958
  reason = false;
36661
36959
  constructor({ maxSize, signal }, handler) {
@@ -36671,7 +36969,6 @@ var require_dump = __commonJS({
36671
36969
  }
36672
36970
  onRequestStart(controller, context) {
36673
36971
  controller.abort = this.#abort.bind(this);
36674
- this.#controller = controller;
36675
36972
  return super.onRequestStart(controller, context);
36676
36973
  }
36677
36974
  onResponseStart(controller, statusCode, headers, statusMessage) {
@@ -36687,33 +36984,26 @@ var require_dump = __commonJS({
36687
36984
  return super.onResponseStart(controller, statusCode, headers, statusMessage);
36688
36985
  }
36689
36986
  onResponseError(controller, err2) {
36690
- if (this.#dumped) {
36691
- return;
36692
- }
36693
- err2 = this.#controller?.reason ?? err2;
36694
- super.onResponseError(controller, err2);
36987
+ super.onResponseError(controller, this.aborted === true ? this.reason : err2);
36695
36988
  }
36696
36989
  onResponseData(controller, chunk2) {
36697
36990
  this.#size = this.#size + chunk2.length;
36698
- if (this.#size >= this.#maxSize) {
36991
+ if (this.#size > this.#maxSize) {
36992
+ throw new RequestAbortedError(
36993
+ `Response size (${this.#size}) larger than maxSize (${this.#maxSize})`
36994
+ );
36995
+ }
36996
+ if (this.#size === this.#maxSize) {
36699
36997
  this.#dumped = true;
36700
- if (this.aborted === true) {
36701
- super.onResponseError(controller, this.reason);
36702
- } else {
36703
- super.onResponseEnd(controller, {});
36704
- }
36705
36998
  }
36706
36999
  return true;
36707
37000
  }
36708
37001
  onResponseEnd(controller, trailers) {
36709
- if (this.#dumped) {
36710
- return;
36711
- }
36712
- if (this.#controller.aborted === true) {
37002
+ if (this.aborted === true) {
36713
37003
  super.onResponseError(controller, this.reason);
36714
37004
  return;
36715
37005
  }
36716
- super.onResponseEnd(controller, trailers);
37006
+ super.onResponseEnd(controller, this.#dumped ? {} : trailers);
36717
37007
  }
36718
37008
  };
36719
37009
  function createDumpInterceptor({ maxSize: defaultMaxSize } = {
@@ -37177,15 +37467,127 @@ var require_cache = __commonJS({
37177
37467
  var {
37178
37468
  safeHTTPMethods,
37179
37469
  pathHasQueryOrFragment,
37180
- hasSafeIterator
37470
+ hasSafeIterator,
37471
+ isValidHTTPToken
37181
37472
  } = require_util();
37182
37473
  var { serializePathWithQuery } = require_util();
37474
+ var MAX_DELTA_SECONDS = 2147483647;
37475
+ var RESTRICTIVE_DIRECTIVE_NAMES = ["no-store", "private", "no-cache"];
37476
+ var kInvalidCacheControlDirectives = /* @__PURE__ */ Symbol("invalid cache-control directives");
37477
+ function trimOWS(value) {
37478
+ return value.replace(/^[\t ]+|[\t ]+$/g, "");
37479
+ }
37480
+ function arrayIncludes(array, value) {
37481
+ for (let i = 0; i < array.length; i++) {
37482
+ if (array[i] === value) {
37483
+ return true;
37484
+ }
37485
+ }
37486
+ return false;
37487
+ }
37488
+ function trimOWSStart(value) {
37489
+ return value.replace(/^[\t ]+/, "");
37490
+ }
37491
+ function trimOWSEnd(value) {
37492
+ return value.replace(/[\t ]+$/, "");
37493
+ }
37494
+ function findUnescapedQuote(value, start) {
37495
+ let escaped = false;
37496
+ for (let i = start; i < value.length; i++) {
37497
+ if (escaped) {
37498
+ escaped = false;
37499
+ } else if (value[i] === "\\") {
37500
+ escaped = true;
37501
+ } else if (value[i] === '"') {
37502
+ return i;
37503
+ }
37504
+ }
37505
+ return -1;
37506
+ }
37507
+ function splitCacheControlHeaderValue(value) {
37508
+ const directives = [];
37509
+ let start = 0;
37510
+ let quoteStart = -1;
37511
+ let inQuote = false;
37512
+ let escaped = false;
37513
+ for (let i = 0; i < value.length; i++) {
37514
+ if (inQuote) {
37515
+ if (escaped) {
37516
+ escaped = false;
37517
+ } else if (value[i] === "\\") {
37518
+ escaped = true;
37519
+ } else if (value[i] === '"') {
37520
+ inQuote = false;
37521
+ quoteStart = -1;
37522
+ }
37523
+ } else if (value[i] === '"') {
37524
+ inQuote = true;
37525
+ quoteStart = i;
37526
+ } else if (value[i] === ",") {
37527
+ directives.push({ value: value.substring(start, i), fromMalformedQuote: false });
37528
+ start = i + 1;
37529
+ }
37530
+ }
37531
+ if (!inQuote) {
37532
+ directives.push({ value: value.substring(start), fromMalformedQuote: false });
37533
+ return directives;
37534
+ }
37535
+ const tail = value.substring(start);
37536
+ const quoteOffset = quoteStart - start;
37537
+ let tailStart = 0;
37538
+ for (let i = 0; i < tail.length; i++) {
37539
+ if (tail[i] === ",") {
37540
+ directives.push({
37541
+ value: tail.substring(tailStart, i),
37542
+ fromMalformedQuote: tailStart > quoteOffset
37543
+ });
37544
+ tailStart = i + 1;
37545
+ }
37546
+ }
37547
+ directives.push({
37548
+ value: tail.substring(tailStart),
37549
+ fromMalformedQuote: tailStart > quoteOffset
37550
+ });
37551
+ return directives;
37552
+ }
37553
+ function markInvalidCacheControlDirective(directives, key) {
37554
+ let invalidDirectives = directives[kInvalidCacheControlDirectives];
37555
+ if (invalidDirectives === void 0) {
37556
+ invalidDirectives = /* @__PURE__ */ new Set();
37557
+ Object.defineProperty(directives, kInvalidCacheControlDirectives, {
37558
+ value: invalidDirectives
37559
+ });
37560
+ }
37561
+ invalidDirectives.add(key);
37562
+ }
37563
+ function hasInvalidCacheControlDirective(directives, key) {
37564
+ return directives[kInvalidCacheControlDirectives]?.has(key) === true;
37565
+ }
37566
+ function getMalformedRestrictiveDirectiveName(key) {
37567
+ for (const directiveName of RESTRICTIVE_DIRECTIVE_NAMES) {
37568
+ if (key.startsWith(directiveName) && key.length > directiveName.length && !isValidHTTPToken(key[directiveName.length])) {
37569
+ return directiveName;
37570
+ }
37571
+ }
37572
+ let tokenOnlyKey = "";
37573
+ let hasInvalidTokenChar = false;
37574
+ for (let i = 0; i < key.length; i++) {
37575
+ if (isValidHTTPToken(key[i])) {
37576
+ tokenOnlyKey += key[i];
37577
+ } else {
37578
+ hasInvalidTokenChar = true;
37579
+ }
37580
+ }
37581
+ if (hasInvalidTokenChar && arrayIncludes(RESTRICTIVE_DIRECTIVE_NAMES, tokenOnlyKey)) {
37582
+ return tokenOnlyKey;
37583
+ }
37584
+ }
37183
37585
  function makeCacheKey(opts) {
37184
37586
  if (!opts.origin) {
37185
37587
  throw new Error("opts.origin is undefined");
37186
37588
  }
37187
37589
  let fullPath = opts.path || "/";
37188
- if (opts.query && !pathHasQueryOrFragment(opts.path)) {
37590
+ if (opts.query && !pathHasQueryOrFragment(fullPath)) {
37189
37591
  fullPath = serializePathWithQuery(fullPath, opts.query);
37190
37592
  }
37191
37593
  return {
@@ -37195,6 +37597,18 @@ var require_cache = __commonJS({
37195
37597
  headers: opts.headers
37196
37598
  };
37197
37599
  }
37600
+ function appendHeader(headers, key, val) {
37601
+ const headerName = key.toLowerCase();
37602
+ const current = headers[headerName];
37603
+ const values = Array.isArray(val) ? val : [val];
37604
+ if (current === void 0) {
37605
+ headers[headerName] = Array.isArray(val) ? val.slice() : val;
37606
+ } else if (Array.isArray(current)) {
37607
+ current.push(...values);
37608
+ } else {
37609
+ headers[headerName] = [current, ...values];
37610
+ }
37611
+ }
37198
37612
  function normalizeHeaders(opts) {
37199
37613
  let headers;
37200
37614
  if (opts.headers == null) {
@@ -37210,11 +37624,11 @@ var require_cache = __commonJS({
37210
37624
  if (typeof key !== "string" || typeof val !== "string") {
37211
37625
  throw new Error("opts.headers is not a valid header map");
37212
37626
  }
37213
- headers[key.toLowerCase()] = val;
37627
+ appendHeader(headers, key, val);
37214
37628
  }
37215
37629
  } else {
37216
37630
  for (const key of Object.keys(opts.headers)) {
37217
- headers[key.toLowerCase()] = opts.headers[key];
37631
+ appendHeader(headers, key, opts.headers[key]);
37218
37632
  }
37219
37633
  }
37220
37634
  } else {
@@ -37259,25 +37673,32 @@ var require_cache = __commonJS({
37259
37673
  }
37260
37674
  function parseCacheControlHeader(header) {
37261
37675
  const output = {};
37262
- let directives;
37263
- if (Array.isArray(header)) {
37264
- directives = [];
37265
- for (const directive of header) {
37266
- directives.push(...directive.split(","));
37267
- }
37268
- } else {
37269
- directives = header.split(",");
37270
- }
37676
+ const invalidNumericDirectives = /* @__PURE__ */ new Set();
37677
+ const invalidNoArgumentDirectives = /* @__PURE__ */ new Set();
37678
+ const directives = splitCacheControlHeaderValue(Array.isArray(header) ? header.join(",") : header);
37271
37679
  for (let i = 0; i < directives.length; i++) {
37272
- const directive = directives[i].toLowerCase();
37680
+ const directiveRecord = directives[i];
37681
+ const directive = directiveRecord.value.toLowerCase();
37682
+ const fromMalformedQuote = directiveRecord.fromMalformedQuote;
37273
37683
  const keyValueDelimiter = directive.indexOf("=");
37274
37684
  let key;
37275
37685
  let value;
37686
+ let keyHasTrailingWhitespace = false;
37687
+ let valueHasLeadingWhitespace = false;
37276
37688
  if (keyValueDelimiter !== -1) {
37277
- key = directive.substring(0, keyValueDelimiter).trimStart();
37278
- value = directive.substring(keyValueDelimiter + 1);
37689
+ const rawKey = directive.substring(0, keyValueDelimiter);
37690
+ const rawValue = directive.substring(keyValueDelimiter + 1);
37691
+ keyHasTrailingWhitespace = trimOWSEnd(rawKey) !== rawKey;
37692
+ valueHasLeadingWhitespace = trimOWSStart(rawValue) !== rawValue;
37693
+ key = trimOWS(rawKey);
37694
+ value = trimOWSStart(rawValue);
37279
37695
  } else {
37280
- key = directive.trim();
37696
+ key = trimOWS(directive);
37697
+ }
37698
+ const malformedRestrictiveDirectiveName = getMalformedRestrictiveDirectiveName(key);
37699
+ if (malformedRestrictiveDirectiveName !== void 0) {
37700
+ output[malformedRestrictiveDirectiveName] = true;
37701
+ continue;
37281
37702
  }
37282
37703
  switch (key) {
37283
37704
  case "min-fresh":
@@ -37286,45 +37707,85 @@ var require_cache = __commonJS({
37286
37707
  case "s-maxage":
37287
37708
  case "stale-while-revalidate":
37288
37709
  case "stale-if-error": {
37289
- if (value === void 0 || value[0] === " ") {
37710
+ if (fromMalformedQuote || invalidNumericDirectives.has(key)) {
37711
+ continue;
37712
+ }
37713
+ if (value === void 0 || keyHasTrailingWhitespace || valueHasLeadingWhitespace) {
37714
+ delete output[key];
37715
+ invalidNumericDirectives.add(key);
37716
+ markInvalidCacheControlDirective(output, key);
37290
37717
  continue;
37291
37718
  }
37292
37719
  if (value.length >= 2 && value[0] === '"' && value[value.length - 1] === '"') {
37293
37720
  value = value.substring(1, value.length - 1);
37294
37721
  }
37295
- const parsedValue = parseInt(value, 10);
37296
- if (parsedValue !== parsedValue) {
37722
+ if (!/^[0-9]+$/.test(value)) {
37723
+ delete output[key];
37724
+ invalidNumericDirectives.add(key);
37725
+ markInvalidCacheControlDirective(output, key);
37297
37726
  continue;
37298
37727
  }
37299
- if (key === "max-age" && key in output && output[key] >= parsedValue) {
37300
- continue;
37728
+ const parsedValue = Math.min(parseInt(value, 10), MAX_DELTA_SECONDS);
37729
+ if (key === "min-fresh") {
37730
+ if (!(key in output) || output[key] < parsedValue) {
37731
+ output[key] = parsedValue;
37732
+ }
37733
+ } else if (!(key in output) || output[key] > parsedValue) {
37734
+ output[key] = parsedValue;
37301
37735
  }
37302
- output[key] = parsedValue;
37303
37736
  break;
37304
37737
  }
37305
37738
  case "private":
37306
37739
  case "no-cache": {
37740
+ if (fromMalformedQuote) {
37741
+ output[key] = true;
37742
+ break;
37743
+ }
37744
+ if (value !== void 0 && value.length === 0) {
37745
+ output[key] = true;
37746
+ break;
37747
+ }
37307
37748
  if (value) {
37308
37749
  if (value[0] === '"') {
37309
- const headers = [value.substring(1)];
37310
- let foundEndingQuote = value[value.length - 1] === '"';
37311
- if (!foundEndingQuote) {
37750
+ value = trimOWSEnd(value);
37751
+ let fieldList = "";
37752
+ let lastQuotedPart = i;
37753
+ let foundEndingQuote = false;
37754
+ const closingQuote = findUnescapedQuote(value, 1);
37755
+ if (closingQuote !== -1) {
37756
+ fieldList = value.substring(1, closingQuote);
37757
+ foundEndingQuote = true;
37758
+ } else {
37759
+ const fieldListParts = [value.substring(1)];
37312
37760
  for (let j = i + 1; j < directives.length; j++) {
37313
- const nextPart = directives[j];
37314
- const nextPartLength = nextPart.length;
37315
- headers.push(nextPart.trim());
37316
- if (nextPartLength !== 0 && nextPart[nextPartLength - 1] === '"') {
37761
+ const nextPart = trimOWS(directives[j].value);
37762
+ const closingQuote2 = findUnescapedQuote(nextPart, 0);
37763
+ lastQuotedPart = j;
37764
+ if (closingQuote2 !== -1) {
37765
+ fieldListParts.push(nextPart.substring(0, closingQuote2));
37317
37766
  foundEndingQuote = true;
37318
37767
  break;
37319
37768
  }
37769
+ fieldListParts.push(nextPart);
37320
37770
  }
37771
+ fieldList = fieldListParts.join(",");
37772
+ }
37773
+ if (!foundEndingQuote) {
37774
+ output[key] = true;
37775
+ break;
37321
37776
  }
37322
- if (foundEndingQuote) {
37323
- let lastHeader = headers[headers.length - 1];
37324
- if (lastHeader[lastHeader.length - 1] === '"') {
37325
- lastHeader = lastHeader.substring(0, lastHeader.length - 1);
37326
- headers[headers.length - 1] = lastHeader;
37777
+ i = lastQuotedPart;
37778
+ const headers = fieldList.split(",");
37779
+ let validFieldNames = true;
37780
+ for (let j = 0; j < headers.length; j++) {
37781
+ headers[j] = trimOWS(headers[j]);
37782
+ if (!isValidHTTPToken(headers[j])) {
37783
+ validFieldNames = false;
37327
37784
  }
37785
+ }
37786
+ if (!validFieldNames) {
37787
+ output[key] = true;
37788
+ } else if (output[key] !== true) {
37328
37789
  if (key in output) {
37329
37790
  output[key] = output[key].concat(headers);
37330
37791
  } else {
@@ -37332,10 +37793,15 @@ var require_cache = __commonJS({
37332
37793
  }
37333
37794
  }
37334
37795
  } else {
37335
- if (key in output) {
37336
- output[key] = output[key].concat(value);
37337
- } else {
37338
- output[key] = [value];
37796
+ const fieldName = trimOWS(value);
37797
+ if (!isValidHTTPToken(fieldName)) {
37798
+ output[key] = true;
37799
+ } else if (output[key] !== true) {
37800
+ if (key in output) {
37801
+ output[key] = output[key].concat(fieldName);
37802
+ } else {
37803
+ output[key] = [fieldName];
37804
+ }
37339
37805
  }
37340
37806
  }
37341
37807
  break;
@@ -37343,39 +37809,76 @@ var require_cache = __commonJS({
37343
37809
  }
37344
37810
  // eslint-disable-next-line no-fallthrough
37345
37811
  case "public":
37346
- case "no-store":
37347
37812
  case "must-revalidate":
37348
37813
  case "proxy-revalidate":
37349
37814
  case "immutable":
37350
37815
  case "no-transform":
37351
37816
  case "must-understand":
37352
37817
  case "only-if-cached":
37353
- if (value) {
37818
+ if (fromMalformedQuote || invalidNoArgumentDirectives.has(key)) {
37819
+ continue;
37820
+ }
37821
+ if (value !== void 0) {
37822
+ delete output[key];
37823
+ invalidNoArgumentDirectives.add(key);
37354
37824
  continue;
37355
37825
  }
37356
37826
  output[key] = true;
37357
37827
  break;
37828
+ case "no-store":
37829
+ output[key] = true;
37830
+ break;
37358
37831
  default:
37359
37832
  continue;
37360
37833
  }
37361
37834
  }
37362
37835
  return output;
37363
37836
  }
37837
+ function splitVaryHeader(varyHeader) {
37838
+ const values = Array.isArray(varyHeader) ? varyHeader : [varyHeader];
37839
+ const output = [];
37840
+ for (let i = 0; i < values.length; i++) {
37841
+ const parts = values[i].split(",");
37842
+ for (let j = 0; j < parts.length; j++) {
37843
+ output.push(parts[j]);
37844
+ }
37845
+ }
37846
+ return output;
37847
+ }
37848
+ function hasVaryStar(varyHeader) {
37849
+ const values = splitVaryHeader(varyHeader);
37850
+ for (let i = 0; i < values.length; i++) {
37851
+ if (trimOWS(values[i]).indexOf("*") !== -1) {
37852
+ return true;
37853
+ }
37854
+ }
37855
+ return false;
37856
+ }
37364
37857
  function parseVaryHeader(varyHeader, headers) {
37365
- if (typeof varyHeader === "string" && varyHeader.includes("*")) {
37858
+ if (hasVaryStar(varyHeader)) {
37366
37859
  return headers;
37367
37860
  }
37368
37861
  const output = (
37369
37862
  /** @type {Record<string, string | string[] | null>} */
37370
37863
  {}
37371
37864
  );
37372
- const varyingHeaders = typeof varyHeader === "string" ? varyHeader.split(",") : varyHeader;
37865
+ const varyingHeaders = splitVaryHeader(varyHeader);
37373
37866
  for (const header of varyingHeaders) {
37374
- const trimmedHeader = header.trim().toLowerCase();
37375
- output[trimmedHeader] = headers[trimmedHeader] ?? null;
37867
+ const trimmedHeader = trimOWS(header).toLowerCase();
37868
+ if (trimmedHeader.length === 0) {
37869
+ continue;
37870
+ }
37871
+ if (!isValidHTTPToken(trimmedHeader)) {
37872
+ return void 0;
37873
+ }
37874
+ const headerValue = headers[trimmedHeader];
37875
+ output[trimmedHeader] = Array.isArray(headerValue) ? headerValue.slice() : headerValue ?? null;
37376
37876
  }
37377
37877
  return output;
37378
37878
  }
37879
+ function isInvalidOrWildcardVaryHeader(varyHeader) {
37880
+ return hasVaryStar(varyHeader) || parseVaryHeader(varyHeader, {}) === void 0;
37881
+ }
37379
37882
  function isEtagUsable(etag) {
37380
37883
  if (etag.length <= 2) {
37381
37884
  return false;
@@ -37406,24 +37909,23 @@ var require_cache = __commonJS({
37406
37909
  throw new TypeError(`${name} needs to have at least one method`);
37407
37910
  }
37408
37911
  for (const method of methods) {
37409
- if (!safeHTTPMethods.includes(method)) {
37912
+ if (!arrayIncludes(safeHTTPMethods, method)) {
37410
37913
  throw new TypeError(`element of ${name}-array needs to be one of following values: ${safeHTTPMethods.join(", ")}, got ${method}`);
37411
37914
  }
37412
37915
  }
37413
37916
  }
37414
37917
  function makeDeduplicationKey(cacheKey, excludeHeaders) {
37415
- let key = `${cacheKey.origin}:${cacheKey.method}:${cacheKey.path}`;
37918
+ const headers = {};
37416
37919
  if (cacheKey.headers) {
37417
37920
  const sortedHeaders = Object.keys(cacheKey.headers).sort();
37418
37921
  for (const header of sortedHeaders) {
37419
37922
  if (excludeHeaders?.has(header.toLowerCase())) {
37420
37923
  continue;
37421
37924
  }
37422
- const value = cacheKey.headers[header];
37423
- key += `:${header}=${Array.isArray(value) ? value.join(",") : value}`;
37925
+ headers[header] = cacheKey.headers[header];
37424
37926
  }
37425
37927
  }
37426
- return key;
37928
+ return JSON.stringify([cacheKey.origin, cacheKey.method, cacheKey.path, headers]);
37427
37929
  }
37428
37930
  module2.exports = {
37429
37931
  makeCacheKey,
@@ -37431,7 +37933,10 @@ var require_cache = __commonJS({
37431
37933
  assertCacheKey,
37432
37934
  assertCacheValue,
37433
37935
  parseCacheControlHeader,
37936
+ hasInvalidCacheControlDirective,
37434
37937
  parseVaryHeader,
37938
+ hasVaryStar,
37939
+ isInvalidOrWildcardVaryHeader,
37435
37940
  isEtagUsable,
37436
37941
  assertCacheMethods,
37437
37942
  assertCacheStore,
@@ -37454,6 +37959,13 @@ var require_date = __commonJS({
37454
37959
  return parseRfc850Date(date);
37455
37960
  }
37456
37961
  }
37962
+ function makeDate(year, monthIdx, day, hour, minute, second, weekday) {
37963
+ const result = new Date(Date.UTC(year, monthIdx, day, hour, minute, second));
37964
+ if (year >= 0 && year <= 99) {
37965
+ result.setUTCFullYear(year);
37966
+ }
37967
+ 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;
37968
+ }
37457
37969
  function parseImfDate(date) {
37458
37970
  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") {
37459
37971
  return void 0;
@@ -37614,8 +38126,7 @@ var require_date = __commonJS({
37614
38126
  }
37615
38127
  second = (code1 - 48) * 10 + (code2 - 48);
37616
38128
  }
37617
- const result = new Date(Date.UTC(year, monthIdx, day, hour, minute, second));
37618
- return result.getUTCDay() === weekday ? result : void 0;
38129
+ return makeDate(year, monthIdx, day, hour, minute, second, weekday);
37619
38130
  }
37620
38131
  function parseAscTimeDate(date) {
37621
38132
  if (date.length !== 24 || date[7] !== " " || date[10] !== " " || date[19] !== " ") {
@@ -37777,8 +38288,7 @@ var require_date = __commonJS({
37777
38288
  return void 0;
37778
38289
  }
37779
38290
  const year = (yearDigit1 - 48) * 1e3 + (yearDigit2 - 48) * 100 + (yearDigit3 - 48) * 10 + (yearDigit4 - 48);
37780
- const result = new Date(Date.UTC(year, monthIdx, day, hour, minute, second));
37781
- return result.getUTCDay() === weekday ? result : void 0;
38291
+ return makeDate(year, monthIdx, day, hour, minute, second, weekday);
37782
38292
  }
37783
38293
  function parseRfc850Date(date) {
37784
38294
  let commaIndex = -1;
@@ -37927,8 +38437,7 @@ var require_date = __commonJS({
37927
38437
  }
37928
38438
  second = (code1 - 48) * 10 + (code2 - 48);
37929
38439
  }
37930
- const result = new Date(Date.UTC(year, monthIdx, day, hour, minute, second));
37931
- return result.getUTCDay() === weekday ? result : void 0;
38440
+ return makeDate(year, monthIdx, day, hour, minute, second, weekday);
37932
38441
  }
37933
38442
  module2.exports = {
37934
38443
  parseHttpDate
@@ -37943,7 +38452,10 @@ var require_cache_handler = __commonJS({
37943
38452
  var util = require_util();
37944
38453
  var {
37945
38454
  parseCacheControlHeader,
38455
+ hasInvalidCacheControlDirective,
37946
38456
  parseVaryHeader,
38457
+ hasVaryStar,
38458
+ isInvalidOrWildcardVaryHeader,
37947
38459
  isEtagUsable
37948
38460
  } = require_cache();
37949
38461
  var { parseHttpDate } = require_date();
@@ -37967,6 +38479,78 @@ var require_cache_handler = __commonJS({
37967
38479
  206
37968
38480
  ];
37969
38481
  var MAX_RESPONSE_AGE = 2147483647e3;
38482
+ function trimOWS(value) {
38483
+ return value.replace(/^[\t ]+|[\t ]+$/g, "");
38484
+ }
38485
+ function arrayIncludes(array, value) {
38486
+ for (let i = 0; i < array.length; i++) {
38487
+ if (array[i] === value) {
38488
+ return true;
38489
+ }
38490
+ }
38491
+ return false;
38492
+ }
38493
+ function appendConnectionHeaderTokens(headersToRemove, connectionHeader) {
38494
+ const values = Array.isArray(connectionHeader) ? connectionHeader : [connectionHeader];
38495
+ for (let i = 0; i < values.length; i++) {
38496
+ const tokens = values[i].split(",");
38497
+ for (let j = 0; j < tokens.length; j++) {
38498
+ headersToRemove.push(trimOWS(tokens[j]).toLowerCase());
38499
+ }
38500
+ }
38501
+ }
38502
+ function getSameOriginPath(cacheKey, location) {
38503
+ if (typeof location !== "string") {
38504
+ return void 0;
38505
+ }
38506
+ let originUrl;
38507
+ let requestUrl;
38508
+ let locationUrl;
38509
+ try {
38510
+ originUrl = new URL(cacheKey.origin);
38511
+ requestUrl = new URL(cacheKey.path, originUrl);
38512
+ locationUrl = new URL(location, requestUrl);
38513
+ } catch {
38514
+ return void 0;
38515
+ }
38516
+ if (locationUrl.origin !== originUrl.origin) {
38517
+ return void 0;
38518
+ }
38519
+ return locationUrl.pathname + locationUrl.search;
38520
+ }
38521
+ function deleteCachedUri(store, cacheKey, path74) {
38522
+ deleteCachedValue(store, {
38523
+ ...cacheKey,
38524
+ path: path74
38525
+ });
38526
+ for (let i = 0; i < util.safeHTTPMethods.length; i++) {
38527
+ const method = util.safeHTTPMethods[i];
38528
+ if (method !== cacheKey.method) {
38529
+ deleteCachedValue(store, {
38530
+ ...cacheKey,
38531
+ method,
38532
+ path: path74
38533
+ });
38534
+ }
38535
+ }
38536
+ }
38537
+ function deleteLocationTargets(store, cacheKey, headerValue) {
38538
+ if (headerValue === void 0) {
38539
+ return;
38540
+ }
38541
+ const values = Array.isArray(headerValue) ? headerValue : [headerValue];
38542
+ for (let i = 0; i < values.length; i++) {
38543
+ const path74 = getSameOriginPath(cacheKey, values[i]);
38544
+ if (path74 !== void 0) {
38545
+ deleteCachedUri(store, cacheKey, path74);
38546
+ }
38547
+ }
38548
+ }
38549
+ function invalidateUnsafeRequest(store, cacheKey, resHeaders) {
38550
+ deleteCachedUri(store, cacheKey, cacheKey.path);
38551
+ deleteLocationTargets(store, cacheKey, resHeaders.location);
38552
+ deleteLocationTargets(store, cacheKey, resHeaders["content-location"]);
38553
+ }
37970
38554
  var CacheHandler = class {
37971
38555
  /**
37972
38556
  * @type {import('../../types/cache-interceptor.d.ts').default.CacheKey}
@@ -38026,35 +38610,53 @@ var require_cache_handler = __commonJS({
38026
38610
  statusMessage
38027
38611
  );
38028
38612
  const handler = this;
38029
- if (!util.safeHTTPMethods.includes(this.#cacheKey.method) && statusCode >= 200 && statusCode <= 399) {
38030
- try {
38031
- this.#store.delete(this.#cacheKey)?.catch?.(noop);
38032
- } catch {
38033
- }
38613
+ if (!arrayIncludes(util.safeHTTPMethods, this.#cacheKey.method) && statusCode >= 200 && statusCode <= 399) {
38614
+ invalidateUnsafeRequest(this.#store, this.#cacheKey, resHeaders);
38034
38615
  return downstreamOnHeaders();
38035
38616
  }
38036
38617
  const cacheControlHeader = resHeaders["cache-control"];
38037
- const heuristicallyCacheable = resHeaders["last-modified"] && HEURISTICALLY_CACHEABLE_STATUS_CODES.includes(statusCode);
38618
+ const cacheControlDirectives = cacheControlHeader ? parseCacheControlHeader(cacheControlHeader) : {};
38619
+ if (revalidationResponseDisallowsCachedReuse(this.#cacheType, resHeaders, cacheControlDirectives)) {
38620
+ deleteCachedValue(this.#store, this.#cacheKey);
38621
+ return downstreamOnHeaders();
38622
+ }
38623
+ const heuristicallyCacheable = resHeaders["last-modified"] && arrayIncludes(HEURISTICALLY_CACHEABLE_STATUS_CODES, statusCode);
38038
38624
  if (!cacheControlHeader && !resHeaders["expires"] && !heuristicallyCacheable && !this.#cacheByDefault) {
38625
+ if (statusCode === 304 && resHeaders.vary && isInvalidOrWildcardVaryHeader(resHeaders.vary)) {
38626
+ deleteCachedValue(this.#store, this.#cacheKey);
38627
+ }
38039
38628
  return downstreamOnHeaders();
38040
38629
  }
38041
- const cacheControlDirectives = cacheControlHeader ? parseCacheControlHeader(cacheControlHeader) : {};
38042
- if (!canCacheResponse(this.#cacheType, statusCode, resHeaders, cacheControlDirectives, this.#cacheKey.headers)) {
38630
+ if (!canCacheResponse(this.#cacheType, this.#cacheKey.method, statusCode, resHeaders, cacheControlDirectives, this.#cacheKey.headers)) {
38631
+ if (statusCode === 304 && (cacheControlHeader || revalidationResponseDisallowsCachedReuse(this.#cacheType, resHeaders, cacheControlDirectives))) {
38632
+ deleteCachedValue(this.#store, this.#cacheKey);
38633
+ }
38043
38634
  return downstreamOnHeaders();
38044
38635
  }
38045
38636
  const now = Date.now();
38046
- const resAge = resHeaders.age ? getAge(resHeaders.age) : void 0;
38047
- if (resAge && resAge >= MAX_RESPONSE_AGE) {
38637
+ const resAge = Object.hasOwn(resHeaders, "age") ? getAge(resHeaders.age) : void 0;
38638
+ if (resAge !== void 0 && resAge >= MAX_RESPONSE_AGE) {
38639
+ deleteCachedValueIfNotModified(statusCode, this.#store, this.#cacheKey);
38640
+ return downstreamOnHeaders();
38641
+ }
38642
+ const resDate = Object.hasOwn(resHeaders, "date") ? getDate(resHeaders.date) : void 0;
38643
+ if (resDate === null) {
38644
+ deleteCachedValueIfNotModified(statusCode, this.#store, this.#cacheKey);
38048
38645
  return downstreamOnHeaders();
38049
38646
  }
38050
- const resDate = typeof resHeaders.date === "string" ? parseHttpDate(resHeaders.date) : void 0;
38647
+ const apparentAge = resDate ? Math.max(0, now - resDate.getTime()) : 0;
38648
+ const currentAge = Math.max(apparentAge, resAge ?? 0);
38051
38649
  const staleAt = determineStaleAt(this.#cacheType, now, resAge, resHeaders, resDate, cacheControlDirectives) ?? this.#cacheByDefault;
38052
- if (staleAt === void 0 || resAge && resAge > staleAt) {
38650
+ if (staleAt === void 0 || currentAge >= staleAt) {
38651
+ if (cacheControlHeader || staleAt !== void 0) {
38652
+ deleteCachedValueIfNotModified(statusCode, this.#store, this.#cacheKey);
38653
+ }
38053
38654
  return downstreamOnHeaders();
38054
38655
  }
38055
- const baseTime = resDate ? resDate.getTime() : now;
38656
+ const baseTime = now - currentAge;
38056
38657
  const absoluteStaleAt = staleAt + baseTime;
38057
38658
  if (now >= absoluteStaleAt) {
38659
+ deleteCachedValueIfNotModified(statusCode, this.#store, this.#cacheKey);
38058
38660
  return downstreamOnHeaders();
38059
38661
  }
38060
38662
  let varyDirectives;
@@ -38064,7 +38666,8 @@ var require_cache_handler = __commonJS({
38064
38666
  return downstreamOnHeaders();
38065
38667
  }
38066
38668
  }
38067
- const deleteAt = determineDeleteAt(baseTime, cacheControlDirectives, absoluteStaleAt);
38669
+ const cachedAt = baseTime;
38670
+ const deleteAt = determineDeleteAt(baseTime, now, cacheControlDirectives, absoluteStaleAt);
38068
38671
  const strippedHeaders = stripNecessaryHeaders(resHeaders, cacheControlDirectives);
38069
38672
  const value = {
38070
38673
  statusCode,
@@ -38072,7 +38675,7 @@ var require_cache_handler = __commonJS({
38072
38675
  headers: strippedHeaders,
38073
38676
  vary: varyDirectives,
38074
38677
  cacheControlDirectives,
38075
- cachedAt: resAge ? now - resAge : now,
38678
+ cachedAt,
38076
38679
  staleAt: absoluteStaleAt,
38077
38680
  deleteAt
38078
38681
  };
@@ -38084,6 +38687,7 @@ var require_cache_handler = __commonJS({
38084
38687
  value.statusCode = cachedValue.statusCode;
38085
38688
  value.statusMessage = cachedValue.statusMessage;
38086
38689
  value.etag = cachedValue.etag;
38690
+ value.vary = varyDirectives ?? cachedValue.vary;
38087
38691
  value.headers = { ...cachedValue.headers, ...strippedHeaders };
38088
38692
  downstreamOnHeaders();
38089
38693
  this.#writeStream = this.#store.createWriteStream(this.#cacheKey, value);
@@ -38174,74 +38778,129 @@ var require_cache_handler = __commonJS({
38174
38778
  this.#handler.onResponseError?.(controller, err2);
38175
38779
  }
38176
38780
  };
38177
- function canCacheResponse(cacheType, statusCode, resHeaders, cacheControlDirectives, reqHeaders) {
38178
- if (statusCode < 200 || NOT_UNDERSTOOD_STATUS_CODES.includes(statusCode)) {
38781
+ function deleteCachedValue(store, cacheKey) {
38782
+ try {
38783
+ store.delete(cacheKey)?.catch?.(noop);
38784
+ } catch {
38785
+ }
38786
+ }
38787
+ function deleteCachedValueIfNotModified(statusCode, store, cacheKey) {
38788
+ if (statusCode === 304) {
38789
+ deleteCachedValue(store, cacheKey);
38790
+ }
38791
+ }
38792
+ function revalidationResponseDisallowsCachedReuse(cacheType, resHeaders, cacheControlDirectives) {
38793
+ return cacheControlDirectives["no-store"] === true || cacheType === "shared" && (cacheControlDirectives.private === true || Object.hasOwn(resHeaders, "set-cookie")) || (resHeaders.vary ? isInvalidOrWildcardVaryHeader(resHeaders.vary) : false);
38794
+ }
38795
+ function canCacheResponse(cacheType, method, statusCode, resHeaders, cacheControlDirectives, reqHeaders) {
38796
+ if (!arrayIncludes(util.safeHTTPMethods, method)) {
38797
+ return false;
38798
+ }
38799
+ if (statusCode < 200 || arrayIncludes(NOT_UNDERSTOOD_STATUS_CODES, statusCode)) {
38179
38800
  return false;
38180
38801
  }
38181
- 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
38802
+ 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
38182
38803
  !(cacheControlDirectives.private && cacheType === "private") && !(cacheControlDirectives["s-maxage"] !== void 0 && cacheType === "shared")) {
38183
38804
  return false;
38184
38805
  }
38185
38806
  if (cacheControlDirectives["no-store"]) {
38186
38807
  return false;
38187
38808
  }
38188
- if (cacheType === "shared" && cacheControlDirectives.private === true) {
38809
+ if (cacheType === "shared" && (cacheControlDirectives.private === true || Object.hasOwn(resHeaders, "set-cookie"))) {
38189
38810
  return false;
38190
38811
  }
38191
- if (resHeaders.vary?.includes("*")) {
38812
+ if (resHeaders.vary && hasVaryStar(resHeaders.vary)) {
38192
38813
  return false;
38193
38814
  }
38194
- if (reqHeaders?.authorization) {
38815
+ if (reqHeaders != null && Object.hasOwn(reqHeaders, "authorization")) {
38195
38816
  if (!cacheControlDirectives.public && !cacheControlDirectives["s-maxage"] && !cacheControlDirectives["must-revalidate"]) {
38196
38817
  return false;
38197
38818
  }
38198
38819
  if (typeof reqHeaders.authorization !== "string") {
38199
38820
  return false;
38200
38821
  }
38201
- if (Array.isArray(cacheControlDirectives["no-cache"]) && cacheControlDirectives["no-cache"].includes("authorization")) {
38822
+ if (Array.isArray(cacheControlDirectives["no-cache"]) && arrayIncludes(cacheControlDirectives["no-cache"], "authorization")) {
38202
38823
  return false;
38203
38824
  }
38204
- if (Array.isArray(cacheControlDirectives["private"]) && cacheControlDirectives["private"].includes("authorization")) {
38825
+ if (Array.isArray(cacheControlDirectives["private"]) && arrayIncludes(cacheControlDirectives["private"], "authorization")) {
38205
38826
  return false;
38206
38827
  }
38207
38828
  }
38208
38829
  return true;
38209
38830
  }
38831
+ function getDate(dateHeader) {
38832
+ let dateValue = dateHeader;
38833
+ if (Array.isArray(dateValue)) {
38834
+ if (dateValue.length !== 1) {
38835
+ return null;
38836
+ }
38837
+ dateValue = dateValue[0];
38838
+ }
38839
+ if (typeof dateValue !== "string") {
38840
+ return null;
38841
+ }
38842
+ return parseHttpDate(dateValue);
38843
+ }
38210
38844
  function getAge(ageHeader) {
38211
- const age = parseInt(Array.isArray(ageHeader) ? ageHeader[0] : ageHeader);
38212
- return isNaN(age) ? void 0 : age * 1e3;
38845
+ let ageValue = ageHeader;
38846
+ if (Array.isArray(ageValue)) {
38847
+ if (ageValue.length !== 1) {
38848
+ return MAX_RESPONSE_AGE;
38849
+ }
38850
+ ageValue = ageValue[0];
38851
+ }
38852
+ if (typeof ageValue !== "string" || !/^[\t ]*[0-9]+[\t ]*$/.test(ageValue)) {
38853
+ return MAX_RESPONSE_AGE;
38854
+ }
38855
+ const age = BigInt(ageValue.replace(/^[\t ]+|[\t ]+$/g, ""));
38856
+ if (age >= BigInt(MAX_RESPONSE_AGE / 1e3)) {
38857
+ return MAX_RESPONSE_AGE;
38858
+ }
38859
+ return Number(age) * 1e3;
38213
38860
  }
38214
38861
  function determineStaleAt(cacheType, now, age, resHeaders, responseDate, cacheControlDirectives) {
38215
38862
  if (cacheType === "shared") {
38863
+ if (hasInvalidCacheControlDirective(cacheControlDirectives, "s-maxage")) {
38864
+ return 0;
38865
+ }
38216
38866
  const sMaxAge = cacheControlDirectives["s-maxage"];
38217
38867
  if (sMaxAge !== void 0) {
38218
- return sMaxAge > 0 ? sMaxAge * 1e3 : void 0;
38868
+ return sMaxAge * 1e3;
38219
38869
  }
38220
38870
  }
38871
+ if (hasInvalidCacheControlDirective(cacheControlDirectives, "max-age")) {
38872
+ return 0;
38873
+ }
38221
38874
  const maxAge = cacheControlDirectives["max-age"];
38222
38875
  if (maxAge !== void 0) {
38223
- return maxAge > 0 ? maxAge * 1e3 : void 0;
38876
+ return maxAge * 1e3;
38224
38877
  }
38225
- if (typeof resHeaders.expires === "string") {
38878
+ if (Object.hasOwn(resHeaders, "expires")) {
38879
+ if (typeof resHeaders.expires !== "string") {
38880
+ return 0;
38881
+ }
38226
38882
  const expiresDate = parseHttpDate(resHeaders.expires);
38227
- if (expiresDate) {
38228
- if (now >= expiresDate.getTime()) {
38229
- return void 0;
38883
+ if (!expiresDate) {
38884
+ return 0;
38885
+ }
38886
+ if (now >= expiresDate.getTime()) {
38887
+ return 0;
38888
+ }
38889
+ if (responseDate) {
38890
+ if (responseDate >= expiresDate) {
38891
+ return 0;
38230
38892
  }
38231
- if (responseDate) {
38232
- if (responseDate >= expiresDate) {
38233
- return void 0;
38234
- }
38235
- if (age !== void 0 && age > expiresDate - responseDate) {
38236
- return void 0;
38237
- }
38893
+ const freshnessLifetime = expiresDate.getTime() - responseDate.getTime();
38894
+ if (age !== void 0 && age >= freshnessLifetime) {
38895
+ return 0;
38238
38896
  }
38239
- return expiresDate.getTime() - now;
38897
+ return freshnessLifetime;
38240
38898
  }
38899
+ return expiresDate.getTime() - now;
38241
38900
  }
38242
38901
  if (typeof resHeaders["last-modified"] === "string") {
38243
- const lastModified = new Date(resHeaders["last-modified"]);
38244
- if (isValidDate(lastModified)) {
38902
+ const lastModified = parseHttpDate(resHeaders["last-modified"]);
38903
+ if (lastModified) {
38245
38904
  if (lastModified.getTime() >= now) {
38246
38905
  return void 0;
38247
38906
  }
@@ -38250,11 +38909,11 @@ var require_cache_handler = __commonJS({
38250
38909
  }
38251
38910
  }
38252
38911
  if (cacheControlDirectives.immutable) {
38253
- return 31536e3;
38912
+ return 31536e6;
38254
38913
  }
38255
38914
  return void 0;
38256
38915
  }
38257
- function determineDeleteAt(now, cacheControlDirectives, staleAt) {
38916
+ function determineDeleteAt(baseTime, cachedAt, cacheControlDirectives, staleAt) {
38258
38917
  let staleWhileRevalidate = -Infinity;
38259
38918
  let staleIfError = -Infinity;
38260
38919
  let immutable = -Infinity;
@@ -38265,11 +38924,12 @@ var require_cache_handler = __commonJS({
38265
38924
  staleIfError = staleAt + cacheControlDirectives["stale-if-error"] * 1e3;
38266
38925
  }
38267
38926
  if (cacheControlDirectives.immutable && staleWhileRevalidate === -Infinity && staleIfError === -Infinity) {
38268
- immutable = now + 31536e6;
38927
+ immutable = cachedAt + 31536e6;
38269
38928
  }
38270
38929
  if (staleWhileRevalidate === -Infinity && staleIfError === -Infinity && immutable === -Infinity) {
38271
- const freshnessLifetime = staleAt - now;
38272
- return staleAt + freshnessLifetime;
38930
+ const freshnessLifetime = staleAt - baseTime;
38931
+ const datePrecisionPadding = Math.min(Math.max(cachedAt - baseTime, 0), 1e3);
38932
+ return staleAt + freshnessLifetime + datePrecisionPadding;
38273
38933
  }
38274
38934
  return Math.max(staleAt, staleWhileRevalidate, staleIfError, immutable);
38275
38935
  }
@@ -38287,11 +38947,7 @@ var require_cache_handler = __commonJS({
38287
38947
  "age"
38288
38948
  ];
38289
38949
  if (resHeaders["connection"]) {
38290
- if (Array.isArray(resHeaders["connection"])) {
38291
- headersToRemove.push(...resHeaders["connection"].map((header) => header.trim()));
38292
- } else {
38293
- headersToRemove.push(...resHeaders["connection"].split(",").map((header) => header.trim()));
38294
- }
38950
+ appendConnectionHeaderTokens(headersToRemove, resHeaders["connection"]);
38295
38951
  }
38296
38952
  if (Array.isArray(cacheControlDirectives["no-cache"])) {
38297
38953
  headersToRemove.push(...cacheControlDirectives["no-cache"]);
@@ -38301,16 +38957,13 @@ var require_cache_handler = __commonJS({
38301
38957
  }
38302
38958
  let strippedHeaders;
38303
38959
  for (const headerName of headersToRemove) {
38304
- if (resHeaders[headerName]) {
38960
+ if (Object.hasOwn(resHeaders, headerName)) {
38305
38961
  strippedHeaders ??= { ...resHeaders };
38306
38962
  delete strippedHeaders[headerName];
38307
38963
  }
38308
38964
  }
38309
38965
  return strippedHeaders ?? resHeaders;
38310
38966
  }
38311
- function isValidDate(date) {
38312
- return date instanceof Date && Number.isFinite(date.valueOf());
38313
- }
38314
38967
  module2.exports = CacheHandler;
38315
38968
  }
38316
38969
  });
@@ -38481,12 +39134,43 @@ var require_memory_cache_store = __commonJS({
38481
39134
  }
38482
39135
  };
38483
39136
  function findEntry(key, entries, now) {
38484
- return entries.find((entry) => entry.deleteAt > now && entry.method === key.method && (entry.vary == null || Object.keys(entry.vary).every((headerName) => {
38485
- if (entry.vary[headerName] === null) {
38486
- return key.headers[headerName] === void 0;
39137
+ for (let i = 0; i < entries.length; i++) {
39138
+ const entry = entries[i];
39139
+ if (entry.deleteAt > now && entry.method === key.method && varyMatches(key, entry)) {
39140
+ return entry;
38487
39141
  }
38488
- return entry.vary[headerName] === key.headers[headerName];
38489
- })));
39142
+ }
39143
+ }
39144
+ function varyMatches(key, entry) {
39145
+ if (entry.vary == null) {
39146
+ return true;
39147
+ }
39148
+ for (const headerName in entry.vary) {
39149
+ if (Object.hasOwn(entry.vary, headerName) && !headerValueEquals(key.headers?.[headerName], entry.vary[headerName])) {
39150
+ return false;
39151
+ }
39152
+ }
39153
+ return true;
39154
+ }
39155
+ function headerValueEquals(lhs, rhs) {
39156
+ if (lhs == null && rhs == null) {
39157
+ return true;
39158
+ }
39159
+ if (lhs == null && rhs != null || lhs != null && rhs == null) {
39160
+ return false;
39161
+ }
39162
+ if (Array.isArray(lhs) && Array.isArray(rhs)) {
39163
+ if (lhs.length !== rhs.length) {
39164
+ return false;
39165
+ }
39166
+ for (let i = 0; i < lhs.length; i++) {
39167
+ if (lhs[i] !== rhs[i]) {
39168
+ return false;
39169
+ }
39170
+ }
39171
+ return true;
39172
+ }
39173
+ return lhs === rhs;
38490
39174
  }
38491
39175
  module2.exports = MemoryCacheStore;
38492
39176
  }
@@ -38500,7 +39184,7 @@ var require_cache_revalidation_handler = __commonJS({
38500
39184
  var CacheRevalidationHandler = class {
38501
39185
  #successful = false;
38502
39186
  /**
38503
- * @type {((boolean, any) => void) | null}
39187
+ * @type {((success: boolean, context?: any, statusCode?: number, headers?: import('../../types/header.d.ts').IncomingHttpHeaders) => void) | null}
38504
39188
  */
38505
39189
  #callback;
38506
39190
  /**
@@ -38513,7 +39197,7 @@ var require_cache_revalidation_handler = __commonJS({
38513
39197
  */
38514
39198
  #allowErrorStatusCodes;
38515
39199
  /**
38516
- * @param {(boolean) => void} callback Function to call if the cached value is valid
39200
+ * @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
38517
39201
  * @param {import('../../types/dispatcher.d.ts').default.DispatchHandlers} handler
38518
39202
  * @param {boolean} allowErrorStatusCodes
38519
39203
  */
@@ -38535,7 +39219,7 @@ var require_cache_revalidation_handler = __commonJS({
38535
39219
  onResponseStart(controller, statusCode, headers, statusMessage) {
38536
39220
  assert(this.#callback != null);
38537
39221
  this.#successful = statusCode === 304 || this.#allowErrorStatusCodes && statusCode >= 500 && statusCode <= 504;
38538
- this.#callback(this.#successful, this.#context);
39222
+ this.#callback(this.#successful, this.#context, statusCode, headers);
38539
39223
  this.#callback = null;
38540
39224
  if (this.#successful) {
38541
39225
  return true;
@@ -38589,8 +39273,9 @@ var require_cache2 = __commonJS({
38589
39273
  var CacheHandler = require_cache_handler();
38590
39274
  var MemoryCacheStore = require_memory_cache_store();
38591
39275
  var CacheRevalidationHandler = require_cache_revalidation_handler();
38592
- var { assertCacheStore, assertCacheMethods, makeCacheKey, normalizeHeaders, parseCacheControlHeader } = require_cache();
39276
+ var { assertCacheStore, assertCacheMethods, makeCacheKey, normalizeHeaders, parseCacheControlHeader, isInvalidOrWildcardVaryHeader } = require_cache();
38593
39277
  var { AbortError } = require_errors();
39278
+ var { parseHttpDate } = require_date();
38594
39279
  function assertCacheOrigins(origins, name) {
38595
39280
  if (origins === void 0) return;
38596
39281
  if (!Array.isArray(origins)) {
@@ -38605,6 +39290,37 @@ var require_cache2 = __commonJS({
38605
39290
  }
38606
39291
  var nop = () => {
38607
39292
  };
39293
+ function trimOWS(value) {
39294
+ return value.replace(/^[\t ]+|[\t ]+$/g, "");
39295
+ }
39296
+ function arrayIncludes(array, value) {
39297
+ for (let i = 0; i < array.length; i++) {
39298
+ if (array[i] === value) {
39299
+ return true;
39300
+ }
39301
+ }
39302
+ return false;
39303
+ }
39304
+ function hasPragmaNoCache(headers) {
39305
+ const pragma = headers?.pragma;
39306
+ if (!pragma) {
39307
+ return false;
39308
+ }
39309
+ const values = Array.isArray(pragma) ? pragma : [pragma];
39310
+ for (let i = 0; i < values.length; i++) {
39311
+ const value = values[i];
39312
+ if (typeof value !== "string") {
39313
+ continue;
39314
+ }
39315
+ const directives = value.split(",");
39316
+ for (let j = 0; j < directives.length; j++) {
39317
+ if (trimOWS(directives[j]).toLowerCase() === "no-cache") {
39318
+ return true;
39319
+ }
39320
+ }
39321
+ }
39322
+ return false;
39323
+ }
38608
39324
  function needsRevalidation(result, cacheControlDirectives, { headers = {} }) {
38609
39325
  if (cacheControlDirectives?.["no-cache"]) {
38610
39326
  return true;
@@ -38617,10 +39333,58 @@ var require_cache2 = __commonJS({
38617
39333
  }
38618
39334
  return false;
38619
39335
  }
38620
- function isStale(result, cacheControlDirectives) {
39336
+ function staleResponseRequiresRevalidation(result, cacheType) {
39337
+ 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
39338
+ // s-maxage implies proxy-revalidate for shared caches.
39339
+ result.cacheControlDirectives?.["s-maxage"] !== void 0);
39340
+ }
39341
+ function revalidationResponseDisallowsCachedReuse(cacheType, headers) {
39342
+ if (headers.vary && isInvalidOrWildcardVaryHeader(headers.vary) || cacheType === "shared" && Object.hasOwn(headers, "set-cookie")) {
39343
+ return true;
39344
+ }
39345
+ const cacheControl = headers["cache-control"];
39346
+ if (!cacheControl) {
39347
+ return false;
39348
+ }
39349
+ const cacheControlDirectives = parseCacheControlHeader(cacheControl);
39350
+ return cacheControlDirectives["no-store"] === true || cacheType === "shared" && cacheControlDirectives.private === true;
39351
+ }
39352
+ function revalidationResponseUpdatesCacheControl(headers) {
39353
+ return headers["cache-control"] !== void 0;
39354
+ }
39355
+ function deleteCachedValue(store, cacheKey) {
39356
+ try {
39357
+ store.delete(cacheKey)?.catch?.(nop);
39358
+ } catch {
39359
+ }
39360
+ }
39361
+ function getUsableLastModified(headers) {
39362
+ const lastModified = headers?.["last-modified"];
39363
+ if (typeof lastModified === "string" && parseHttpDate(lastModified)) {
39364
+ return lastModified;
39365
+ }
39366
+ }
39367
+ function makeRevalidationHeaders(opts, result) {
39368
+ const headers = {
39369
+ ...opts.headers,
39370
+ "if-modified-since": getUsableLastModified(result.headers) ?? new Date(result.cachedAt).toUTCString()
39371
+ };
39372
+ if (result.etag) {
39373
+ headers["if-none-match"] = result.etag;
39374
+ }
39375
+ if (result.vary) {
39376
+ for (const key in result.vary) {
39377
+ if (result.vary[key] != null) {
39378
+ headers[key] = result.vary[key];
39379
+ }
39380
+ }
39381
+ }
39382
+ return headers;
39383
+ }
39384
+ function isStale(result, cacheControlDirectives, cacheType) {
38621
39385
  const now = Date.now();
38622
39386
  if (now > result.staleAt) {
38623
- if (cacheControlDirectives?.["max-stale"]) {
39387
+ if (!staleResponseRequiresRevalidation(result, cacheType) && cacheControlDirectives?.["max-stale"]) {
38624
39388
  const gracePeriod = result.staleAt + cacheControlDirectives["max-stale"] * 1e3;
38625
39389
  return now > gracePeriod;
38626
39390
  }
@@ -38633,9 +39397,9 @@ var require_cache2 = __commonJS({
38633
39397
  }
38634
39398
  return false;
38635
39399
  }
38636
- function withinStaleWhileRevalidateWindow(result) {
39400
+ function withinStaleWhileRevalidateWindow(result, cacheType) {
38637
39401
  const staleWhileRevalidate = result.cacheControlDirectives?.["stale-while-revalidate"];
38638
- if (!staleWhileRevalidate) {
39402
+ if (!staleWhileRevalidate || staleResponseRequiresRevalidation(result, cacheType)) {
38639
39403
  return false;
38640
39404
  }
38641
39405
  const now = Date.now();
@@ -38730,37 +39494,29 @@ var require_cache2 = __commonJS({
38730
39494
  if (!result) {
38731
39495
  return handleUncachedResponse(dispatch, globalOpts, cacheKey, handler, opts, reqCacheControl);
38732
39496
  }
39497
+ if (globalOpts.type === "shared" && Object.hasOwn(result.headers, "set-cookie")) {
39498
+ if (util.isStream(result.body)) {
39499
+ result.body.on("error", nop).destroy();
39500
+ }
39501
+ deleteCachedValue(globalOpts.store, cacheKey);
39502
+ return handleUncachedResponse(dispatch, globalOpts, cacheKey, handler, opts, reqCacheControl);
39503
+ }
38733
39504
  const now = Date.now();
38734
39505
  if (now > result.deleteAt) {
38735
39506
  return dispatch(opts, new CacheHandler(globalOpts, cacheKey, handler));
38736
39507
  }
38737
39508
  const age = Math.round((now - result.cachedAt) / 1e3);
38738
- if (reqCacheControl?.["max-age"] && age >= reqCacheControl["max-age"]) {
38739
- return dispatch(opts, handler);
38740
- }
38741
- const stale = isStale(result, reqCacheControl);
38742
- const revalidate = needsRevalidation(result, reqCacheControl, opts);
39509
+ const requestMaxAgeExpired = reqCacheControl?.["max-age"] !== void 0 && age >= reqCacheControl["max-age"];
39510
+ const stale = requestMaxAgeExpired || isStale(result, reqCacheControl, globalOpts.type);
39511
+ const revalidate = requestMaxAgeExpired || needsRevalidation(result, reqCacheControl, opts);
38743
39512
  if (stale || revalidate) {
38744
39513
  if (util.isStream(opts.body) && util.bodyLength(opts.body) !== 0) {
38745
39514
  return dispatch(opts, new CacheHandler(globalOpts, cacheKey, handler));
38746
39515
  }
38747
- if (!revalidate && withinStaleWhileRevalidateWindow(result)) {
39516
+ if (!revalidate && withinStaleWhileRevalidateWindow(result, globalOpts.type)) {
38748
39517
  sendCachedValue(handler, opts, result, age, null, true);
38749
39518
  queueMicrotask(() => {
38750
- const headers2 = {
38751
- ...opts.headers,
38752
- "if-modified-since": new Date(result.cachedAt).toUTCString()
38753
- };
38754
- if (result.etag) {
38755
- headers2["if-none-match"] = result.etag;
38756
- }
38757
- if (result.vary) {
38758
- for (const key in result.vary) {
38759
- if (result.vary[key] != null) {
38760
- headers2[key] = result.vary[key];
38761
- }
38762
- }
38763
- }
39519
+ const headers2 = makeRevalidationHeaders(opts, result);
38764
39520
  dispatch(
38765
39521
  {
38766
39522
  ...opts,
@@ -38786,32 +39542,33 @@ var require_cache2 = __commonJS({
38786
39542
  return true;
38787
39543
  }
38788
39544
  let withinStaleIfErrorThreshold = false;
38789
- const staleIfErrorExpiry = result.cacheControlDirectives["stale-if-error"] ?? reqCacheControl?.["stale-if-error"];
38790
- if (staleIfErrorExpiry) {
38791
- withinStaleIfErrorThreshold = now < result.staleAt + staleIfErrorExpiry * 1e3;
38792
- }
38793
- const headers = {
38794
- ...opts.headers,
38795
- "if-modified-since": new Date(result.cachedAt).toUTCString()
38796
- };
38797
- if (result.etag) {
38798
- headers["if-none-match"] = result.etag;
38799
- }
38800
- if (result.vary) {
38801
- for (const key in result.vary) {
38802
- if (result.vary[key] != null) {
38803
- headers[key] = result.vary[key];
38804
- }
39545
+ if (!staleResponseRequiresRevalidation(result, globalOpts.type)) {
39546
+ const staleIfErrorExpiry = result.cacheControlDirectives["stale-if-error"] ?? reqCacheControl?.["stale-if-error"];
39547
+ if (staleIfErrorExpiry) {
39548
+ withinStaleIfErrorThreshold = now < result.staleAt + staleIfErrorExpiry * 1e3;
38805
39549
  }
38806
39550
  }
39551
+ const headers = makeRevalidationHeaders(opts, result);
38807
39552
  return dispatch(
38808
39553
  {
38809
39554
  ...opts,
38810
39555
  headers
38811
39556
  },
38812
39557
  new CacheRevalidationHandler(
38813
- (success, context) => {
39558
+ (success, context, statusCode, headers2) => {
38814
39559
  if (success) {
39560
+ if (statusCode === 304) {
39561
+ if (revalidationResponseDisallowsCachedReuse(globalOpts.type, headers2)) {
39562
+ if (util.isStream(result.body)) {
39563
+ result.body.on("error", nop).destroy();
39564
+ }
39565
+ deleteCachedValue(globalOpts.store, cacheKey);
39566
+ return dispatch(opts, new CacheHandler(globalOpts, cacheKey, handler));
39567
+ }
39568
+ if (revalidationResponseUpdatesCacheControl(headers2)) {
39569
+ deleteCachedValue(globalOpts.store, cacheKey);
39570
+ }
39571
+ }
38815
39572
  sendCachedValue(handler, opts, result, age, context, stale);
38816
39573
  } else if (util.isStream(result.body)) {
38817
39574
  result.body.on("error", nop).destroy();
@@ -38853,10 +39610,16 @@ var require_cache2 = __commonJS({
38853
39610
  cacheByDefault,
38854
39611
  type
38855
39612
  };
38856
- const safeMethodsToNotCache = util.safeHTTPMethods.filter((method) => methods.includes(method) === false);
39613
+ const safeMethodsToNotCache = [];
39614
+ for (let i = 0; i < util.safeHTTPMethods.length; i++) {
39615
+ const method = util.safeHTTPMethods[i];
39616
+ if (!arrayIncludes(methods, method)) {
39617
+ safeMethodsToNotCache.push(method);
39618
+ }
39619
+ }
38857
39620
  return (dispatch) => {
38858
39621
  return (opts2, handler) => {
38859
- if (!opts2.origin || safeMethodsToNotCache.includes(opts2.method)) {
39622
+ if (!opts2.origin || arrayIncludes(safeMethodsToNotCache, opts2.method)) {
38860
39623
  return dispatch(opts2, handler);
38861
39624
  }
38862
39625
  if (origins !== void 0) {
@@ -38882,11 +39645,14 @@ var require_cache2 = __commonJS({
38882
39645
  ...opts2,
38883
39646
  headers: normalizeHeaders(opts2)
38884
39647
  };
38885
- const reqCacheControl = opts2.headers?.["cache-control"] ? parseCacheControlHeader(opts2.headers["cache-control"]) : void 0;
39648
+ const reqCacheControl = opts2.headers?.["cache-control"] ? parseCacheControlHeader(opts2.headers["cache-control"]) : hasPragmaNoCache(opts2.headers) ? { "no-cache": true } : void 0;
38886
39649
  if (reqCacheControl?.["no-store"]) {
38887
39650
  return dispatch(opts2, handler);
38888
39651
  }
38889
39652
  const cacheKey = makeCacheKey(opts2);
39653
+ if (!arrayIncludes(util.safeHTTPMethods, opts2.method)) {
39654
+ return dispatch(opts2, new CacheHandler(globalOpts, cacheKey, handler));
39655
+ }
38890
39656
  const result = store.get(cacheKey);
38891
39657
  if (result && typeof result.then === "function") {
38892
39658
  return result.then((result2) => handleResult(
@@ -38920,7 +39686,8 @@ var require_decompress = __commonJS({
38920
39686
  "node_modules/undici/lib/interceptor/decompress.js"(exports2, module2) {
38921
39687
  "use strict";
38922
39688
  var { createInflate, createGunzip, createBrotliDecompress, createZstdDecompress } = require("zlib");
38923
- var { pipeline } = require("stream");
39689
+ var { pipeline, Transform: TransformStream2 } = require("stream");
39690
+ var { InvalidArgumentError, ResponseExceededMaxSizeError } = require_errors();
38924
39691
  var DecoratorHandler = require_decorator_handler();
38925
39692
  var { runtimeFeatures } = require_runtime_features();
38926
39693
  var supportedEncodings = {
@@ -38936,6 +39703,23 @@ var require_decompress = __commonJS({
38936
39703
  /** @type {const} */
38937
39704
  [204, 304]
38938
39705
  );
39706
+ var defaultMaxSize = 64 * 1024 * 1024;
39707
+ function createMaxSizeLimiter(maxSize) {
39708
+ let size = 0;
39709
+ return new TransformStream2({
39710
+ transform(chunk2, _encoding, callback) {
39711
+ const decompressedSize = size + chunk2.length;
39712
+ if (decompressedSize > maxSize) {
39713
+ callback(new ResponseExceededMaxSizeError(
39714
+ `Decompressed response size (${decompressedSize}) exceeded maxSize (${maxSize})`
39715
+ ));
39716
+ return;
39717
+ }
39718
+ size = decompressedSize;
39719
+ callback(null, chunk2);
39720
+ }
39721
+ });
39722
+ }
38939
39723
  var warningEmitted = (
38940
39724
  /** @type {boolean} */
38941
39725
  false
@@ -38943,14 +39727,28 @@ var require_decompress = __commonJS({
38943
39727
  var DecompressHandler = class extends DecoratorHandler {
38944
39728
  /** @type {Transform[]} */
38945
39729
  #decompressors = [];
39730
+ /** @type {Record<string, string | string[]> | undefined} */
39731
+ #trailers;
38946
39732
  /** @type {Readonly<number[]>} */
38947
39733
  #skipStatusCodes;
38948
39734
  /** @type {boolean} */
38949
39735
  #skipErrorResponses;
38950
- constructor(handler, { skipStatusCodes = defaultSkipStatusCodes, skipErrorResponses = true } = {}) {
39736
+ /** @type {number} */
39737
+ #maxSize;
39738
+ /** @type {number} */
39739
+ #decompressedSize = 0;
39740
+ /** @type {boolean} */
39741
+ #terminated = false;
39742
+ /** @type {boolean} */
39743
+ #inputEnded = false;
39744
+ constructor(handler, { skipStatusCodes = defaultSkipStatusCodes, skipErrorResponses = true, maxSize = defaultMaxSize } = {}) {
39745
+ if (!Number.isSafeInteger(maxSize) || maxSize < 1) {
39746
+ throw new InvalidArgumentError("maxSize must be a positive integer");
39747
+ }
38951
39748
  super(handler);
38952
39749
  this.#skipStatusCodes = skipStatusCodes;
38953
39750
  this.#skipErrorResponses = skipErrorResponses;
39751
+ this.#maxSize = maxSize;
38954
39752
  }
38955
39753
  /**
38956
39754
  * Determines if decompression should be skipped based on encoding and status code
@@ -38968,7 +39766,7 @@ var require_decompress = __commonJS({
38968
39766
  * Creates a chain of decompressors for multiple content encodings
38969
39767
  *
38970
39768
  * @param {string} encodings - Comma-separated list of content encodings
38971
- * @returns {Array<DecompressorStream>} - Array of decompressor streams
39769
+ * @returns {Array<Transform>} - Array of decompressor and limiting streams
38972
39770
  * @throws {Error} - If the number of content-encodings exceeds the maximum allowed
38973
39771
  */
38974
39772
  #createDecompressionChain(encodings) {
@@ -38987,7 +39785,33 @@ var require_decompress = __commonJS({
38987
39785
  }
38988
39786
  decompressors.push(supportedEncodings[encoding]());
38989
39787
  }
38990
- return decompressors;
39788
+ if (decompressors.length < 2) {
39789
+ return decompressors;
39790
+ }
39791
+ const streams = [];
39792
+ for (let i = 0; i < decompressors.length; i++) {
39793
+ streams.push(decompressors[i]);
39794
+ if (i < decompressors.length - 1) {
39795
+ streams.push(createMaxSizeLimiter(this.#maxSize));
39796
+ }
39797
+ }
39798
+ return streams;
39799
+ }
39800
+ /**
39801
+ * Stops decompression and reports an error.
39802
+ * @param {Controller} controller - The controller to coordinate with
39803
+ * @param {Error} error - The decompression error
39804
+ * @returns {void}
39805
+ */
39806
+ #fail(controller, error) {
39807
+ if (this.#terminated) {
39808
+ return;
39809
+ }
39810
+ if (this.#inputEnded) {
39811
+ this.onResponseError(controller, error);
39812
+ } else {
39813
+ controller.abort(error);
39814
+ }
38991
39815
  }
38992
39816
  /**
38993
39817
  * Sets up event handlers for a decompressor stream using readable events
@@ -38997,8 +39821,19 @@ var require_decompress = __commonJS({
38997
39821
  */
38998
39822
  #setupDecompressorEvents(decompressor, controller) {
38999
39823
  decompressor.on("readable", () => {
39824
+ if (this.#terminated) {
39825
+ return;
39826
+ }
39000
39827
  let chunk2;
39001
39828
  while ((chunk2 = decompressor.read()) !== null) {
39829
+ const decompressedSize = this.#decompressedSize + chunk2.length;
39830
+ if (decompressedSize > this.#maxSize) {
39831
+ this.#fail(controller, new ResponseExceededMaxSizeError(
39832
+ `Decompressed response size (${decompressedSize}) exceeded maxSize (${this.#maxSize})`
39833
+ ));
39834
+ return;
39835
+ }
39836
+ this.#decompressedSize = decompressedSize;
39002
39837
  const result = super.onResponseData(controller, chunk2);
39003
39838
  if (result === false) {
39004
39839
  break;
@@ -39006,7 +39841,7 @@ var require_decompress = __commonJS({
39006
39841
  }
39007
39842
  });
39008
39843
  decompressor.on("error", (error) => {
39009
- super.onResponseError(controller, error);
39844
+ this.#fail(controller, error);
39010
39845
  });
39011
39846
  }
39012
39847
  /**
@@ -39018,7 +39853,12 @@ var require_decompress = __commonJS({
39018
39853
  const decompressor = this.#decompressors[0];
39019
39854
  this.#setupDecompressorEvents(decompressor, controller);
39020
39855
  decompressor.on("end", () => {
39021
- super.onResponseEnd(controller, {});
39856
+ if (this.#terminated) {
39857
+ return;
39858
+ }
39859
+ this.#terminated = true;
39860
+ this.#cleanupDecompressors();
39861
+ super.onResponseEnd(controller, this.#trailers);
39022
39862
  });
39023
39863
  }
39024
39864
  /**
@@ -39030,11 +39870,16 @@ var require_decompress = __commonJS({
39030
39870
  const lastDecompressor = this.#decompressors[this.#decompressors.length - 1];
39031
39871
  this.#setupDecompressorEvents(lastDecompressor, controller);
39032
39872
  pipeline(this.#decompressors, (err2) => {
39873
+ if (this.#terminated) {
39874
+ return;
39875
+ }
39033
39876
  if (err2) {
39034
- super.onResponseError(controller, err2);
39877
+ this.#fail(controller, err2);
39035
39878
  return;
39036
39879
  }
39037
- super.onResponseEnd(controller, {});
39880
+ this.#terminated = true;
39881
+ this.#cleanupDecompressors();
39882
+ super.onResponseEnd(controller, this.#trailers);
39038
39883
  });
39039
39884
  }
39040
39885
  /**
@@ -39063,6 +39908,29 @@ var require_decompress = __commonJS({
39063
39908
  }
39064
39909
  this.#decompressors = decompressors;
39065
39910
  const { "content-encoding": _, "content-length": __, ...newHeaders } = headers;
39911
+ if (controller?.rawHeaders) {
39912
+ const rawHeaders = controller.rawHeaders;
39913
+ if (Array.isArray(rawHeaders)) {
39914
+ const filteredHeaders = [];
39915
+ for (let i = 0; i < rawHeaders.length; i += 2) {
39916
+ const headerName = rawHeaders[i];
39917
+ const name = Buffer.isBuffer(headerName) ? headerName.toString("latin1") : `${headerName}`;
39918
+ const lowerName = name.toLowerCase();
39919
+ if (lowerName === "content-encoding" || lowerName === "content-length") {
39920
+ continue;
39921
+ }
39922
+ filteredHeaders.push(rawHeaders[i], rawHeaders[i + 1]);
39923
+ }
39924
+ rawHeaders.splice(0, rawHeaders.length, ...filteredHeaders);
39925
+ } else if (typeof rawHeaders === "object") {
39926
+ for (const name of Object.keys(rawHeaders)) {
39927
+ const lowerName = name.toLowerCase();
39928
+ if (lowerName === "content-encoding" || lowerName === "content-length") {
39929
+ delete rawHeaders[name];
39930
+ }
39931
+ }
39932
+ }
39933
+ }
39066
39934
  if (this.#decompressors.length === 1) {
39067
39935
  this.#setupSingleDecompressor(controller);
39068
39936
  } else {
@@ -39089,8 +39957,9 @@ var require_decompress = __commonJS({
39089
39957
  */
39090
39958
  onResponseEnd(controller, trailers) {
39091
39959
  if (this.#decompressors.length > 0) {
39960
+ this.#inputEnded = true;
39961
+ this.#trailers = trailers;
39092
39962
  this.#decompressors[0].end();
39093
- this.#cleanupDecompressors();
39094
39963
  return;
39095
39964
  }
39096
39965
  super.onResponseEnd(controller, trailers);
@@ -39101,12 +39970,14 @@ var require_decompress = __commonJS({
39101
39970
  * @returns {void}
39102
39971
  */
39103
39972
  onResponseError(controller, err2) {
39104
- if (this.#decompressors.length > 0) {
39105
- for (const decompressor of this.#decompressors) {
39106
- decompressor.destroy(err2);
39107
- }
39108
- this.#cleanupDecompressors();
39973
+ if (this.#terminated) {
39974
+ return;
39109
39975
  }
39976
+ this.#terminated = true;
39977
+ for (const decompressor of this.#decompressors) {
39978
+ decompressor.destroy();
39979
+ }
39980
+ this.#cleanupDecompressors();
39110
39981
  super.onResponseError(controller, err2);
39111
39982
  }
39112
39983
  };
@@ -39738,7 +40609,7 @@ var require_sqlite_cache_store = __commonJS({
39738
40609
  SELECT
39739
40610
  id
39740
40611
  FROM cacheInterceptorV${VERSION}
39741
- ORDER BY cachedAt DESC
40612
+ ORDER BY cachedAt ASC
39742
40613
  LIMIT ?
39743
40614
  )
39744
40615
  `);
@@ -39793,7 +40664,6 @@ var require_sqlite_cache_store = __commonJS({
39793
40664
  existingValue.id
39794
40665
  );
39795
40666
  } else {
39796
- this.#prune();
39797
40667
  this.#insertValueQuery.run(
39798
40668
  url,
39799
40669
  key.method,
@@ -39808,6 +40678,7 @@ var require_sqlite_cache_store = __commonJS({
39808
40678
  value.cachedAt,
39809
40679
  value.staleAt
39810
40680
  );
40681
+ this.#prune();
39811
40682
  }
39812
40683
  }
39813
40684
  /**
@@ -39895,7 +40766,7 @@ var require_sqlite_cache_store = __commonJS({
39895
40766
  const now = Date.now();
39896
40767
  for (const value of values) {
39897
40768
  if (now >= value.deleteAt && !canBeExpired) {
39898
- return void 0;
40769
+ continue;
39899
40770
  }
39900
40771
  let matches = true;
39901
40772
  if (value.vary) {
@@ -39925,7 +40796,12 @@ var require_sqlite_cache_store = __commonJS({
39925
40796
  if (lhs.length !== rhs.length) {
39926
40797
  return false;
39927
40798
  }
39928
- return lhs.every((x, i) => x === rhs[i]);
40799
+ for (let i = 0; i < lhs.length; i++) {
40800
+ if (lhs[i] !== rhs[i]) {
40801
+ return false;
40802
+ }
40803
+ }
40804
+ return true;
39929
40805
  }
39930
40806
  return lhs === rhs;
39931
40807
  }
@@ -42214,7 +43090,7 @@ var require_fetch = __commonJS({
42214
43090
  cacheState = "";
42215
43091
  }
42216
43092
  let responseStatus = 0;
42217
- if (fetchParams.request.mode !== "navigator" || !response.hasCrossOriginRedirects) {
43093
+ if (fetchParams.request.mode !== "navigate" || !response.hasCrossOriginRedirects) {
42218
43094
  responseStatus = response.status;
42219
43095
  const mimeType = extractMimeType(response.headersList);
42220
43096
  if (mimeType !== "failure") {
@@ -42378,7 +43254,7 @@ var require_fetch = __commonJS({
42378
43254
  if (contentLength != null) {
42379
43255
  contentLengthHeaderValue = isomorphicEncode(`${contentLength}`);
42380
43256
  }
42381
- if (contentLengthHeaderValue != null) {
43257
+ if (contentLengthHeaderValue != null && !httpRequest.headersList.contains("content-length", true)) {
42382
43258
  httpRequest.headersList.append("content-length", contentLengthHeaderValue, true);
42383
43259
  }
42384
43260
  if (contentLength != null && httpRequest.keepalive) {
@@ -42456,10 +43332,10 @@ var require_fetch = __commonJS({
42456
43332
  response.rangeRequested = true;
42457
43333
  }
42458
43334
  response.requestIncludesCredentials = includeCredentials;
42459
- if (response.status === 401 && httpRequest.responseTainting !== "cors" && includeCredentials && isTraversableNavigable(request2.traversableForUserPrompts)) {
43335
+ if (response.status === 401 && httpRequest.responseTainting !== "cors" && includeCredentials && (request2.useURLCredentials !== void 0 || isTraversableNavigable(request2.traversableForUserPrompts))) {
42460
43336
  if (request2.body != null) {
42461
43337
  if (request2.body.source == null) {
42462
- return makeNetworkError("expected non-null body source");
43338
+ return response;
42463
43339
  }
42464
43340
  request2.body = safelyExtractBody(request2.body.source)[0];
42465
43341
  }
@@ -42701,7 +43577,15 @@ var require_fetch = __commonJS({
42701
43577
  }
42702
43578
  const headersList = new HeadersList();
42703
43579
  for (let i = 0; i < rawHeaders.length; i += 2) {
42704
- headersList.append(bufferToLowerCasedHeaderName(rawHeaders[i]), rawHeaders[i + 1].toString("latin1"), true);
43580
+ const nameStr = bufferToLowerCasedHeaderName(rawHeaders[i]);
43581
+ const value = rawHeaders[i + 1];
43582
+ if (Array.isArray(value) && !Buffer.isBuffer(rawHeaders[i + 1])) {
43583
+ for (const val of value) {
43584
+ headersList.append(nameStr, val.toString("latin1"), true);
43585
+ }
43586
+ } else {
43587
+ headersList.append(nameStr, value.toString("latin1"), true);
43588
+ }
42705
43589
  }
42706
43590
  const location = headersList.get("location", true);
42707
43591
  this.body = new Readable({ read: resume });
@@ -42815,7 +43699,15 @@ var require_fetch = __commonJS({
42815
43699
  }
42816
43700
  const headersList = new HeadersList();
42817
43701
  for (let i = 0; i < rawHeaders.length; i += 2) {
42818
- headersList.append(bufferToLowerCasedHeaderName(rawHeaders[i]), rawHeaders[i + 1].toString("latin1"), true);
43702
+ const nameStr = bufferToLowerCasedHeaderName(rawHeaders[i]);
43703
+ const value = rawHeaders[i + 1];
43704
+ if (Array.isArray(value) && !Buffer.isBuffer(rawHeaders[i + 1])) {
43705
+ for (const val of value) {
43706
+ headersList.append(nameStr, val.toString("latin1"), true);
43707
+ }
43708
+ } else {
43709
+ headersList.append(nameStr, value.toString("latin1"), true);
43710
+ }
42819
43711
  }
42820
43712
  resolve2({
42821
43713
  status,
@@ -43605,14 +44497,48 @@ var require_util4 = __commonJS({
43605
44497
  for (let i = 0; i < path74.length; ++i) {
43606
44498
  const code = path74.charCodeAt(i);
43607
44499
  if (code < 32 || // exclude CTLs (0-31)
43608
- code === 127 || // DEL
44500
+ code > 126 || // exclude DEL and non-ascii
43609
44501
  code === 59) {
43610
44502
  throw new Error("Invalid cookie path");
43611
44503
  }
43612
44504
  }
43613
44505
  }
44506
+ function isLetterOrDigit(code) {
44507
+ return code >= 48 && code <= 57 || // 0-9
44508
+ code >= 65 && code <= 90 || // A-Z
44509
+ code >= 97 && code <= 122;
44510
+ }
43614
44511
  function validateCookieDomain(domain) {
43615
- if (domain.startsWith("-") || domain.endsWith(".") || domain.endsWith("-")) {
44512
+ if (domain === " ") {
44513
+ return;
44514
+ }
44515
+ if (domain.length > 255) {
44516
+ throw new Error("Invalid cookie domain");
44517
+ }
44518
+ let labelLength = 0;
44519
+ for (let i = 0; i < domain.length; ++i) {
44520
+ const code = domain.charCodeAt(i);
44521
+ if (code === 46) {
44522
+ if (labelLength === 0) {
44523
+ throw new Error("Invalid cookie domain");
44524
+ }
44525
+ if (domain.charCodeAt(i - 1) === 45) {
44526
+ throw new Error("Invalid cookie domain");
44527
+ }
44528
+ labelLength = 0;
44529
+ continue;
44530
+ }
44531
+ if (labelLength === 0 && !isLetterOrDigit(code)) {
44532
+ throw new Error("Invalid cookie domain");
44533
+ }
44534
+ if (!isLetterOrDigit(code) && code !== 45) {
44535
+ throw new Error("Invalid cookie domain");
44536
+ }
44537
+ if (++labelLength > 63) {
44538
+ throw new Error("Invalid cookie domain");
44539
+ }
44540
+ }
44541
+ if (labelLength === 0 || domain.charCodeAt(domain.length - 1) === 45) {
43616
44542
  throw new Error("Invalid cookie domain");
43617
44543
  }
43618
44544
  }
@@ -43695,7 +44621,11 @@ var require_util4 = __commonJS({
43695
44621
  throw new Error("Invalid unparsed");
43696
44622
  }
43697
44623
  const [key, ...value] = part.split("=");
43698
- out.push(`${key.trim()}=${value.join("=")}`);
44624
+ const trimmedKey = key.trim();
44625
+ const joinedValue = value.join("=");
44626
+ validateCookieName(trimmedKey);
44627
+ validateCookieValue(joinedValue);
44628
+ out.push(`${trimmedKey}=${joinedValue}`);
43699
44629
  }
43700
44630
  return out.join("; ");
43701
44631
  }
@@ -43718,7 +44648,6 @@ var require_parse = __commonJS({
43718
44648
  var { maxNameValuePairSize, maxAttributeValueSize } = require_constants4();
43719
44649
  var { isCTLExcludingHtab } = require_util4();
43720
44650
  var assert = require("assert");
43721
- var { unescape: qsUnescape } = require("querystring");
43722
44651
  function parseSetCookie(header) {
43723
44652
  if (isCTLExcludingHtab(header)) {
43724
44653
  return null;
@@ -43752,7 +44681,7 @@ var require_parse = __commonJS({
43752
44681
  }
43753
44682
  return {
43754
44683
  name,
43755
- value: qsUnescape(value),
44684
+ value,
43756
44685
  ...parseUnparsedAttributes(unparsedAttributes)
43757
44686
  };
43758
44687
  }
@@ -43826,18 +44755,14 @@ var require_parse = __commonJS({
43826
44755
  } else if (attributeNameLowercase === "httponly") {
43827
44756
  cookieAttributeList.httpOnly = true;
43828
44757
  } else if (attributeNameLowercase === "samesite") {
43829
- let enforcement = "Default";
43830
44758
  const attributeValueLowercase = attributeValue.toLowerCase();
43831
- if (attributeValueLowercase.includes("none")) {
43832
- enforcement = "None";
43833
- }
43834
- if (attributeValueLowercase.includes("strict")) {
43835
- enforcement = "Strict";
43836
- }
43837
- if (attributeValueLowercase.includes("lax")) {
43838
- enforcement = "Lax";
44759
+ if (attributeValueLowercase === "none") {
44760
+ cookieAttributeList.sameSite = "None";
44761
+ } else if (attributeValueLowercase === "strict") {
44762
+ cookieAttributeList.sameSite = "Strict";
44763
+ } else if (attributeValueLowercase === "lax") {
44764
+ cookieAttributeList.sameSite = "Lax";
43839
44765
  }
43840
- cookieAttributeList.sameSite = enforcement;
43841
44766
  } else {
43842
44767
  cookieAttributeList.unparsed ??= [];
43843
44768
  cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`);
@@ -44682,7 +45607,7 @@ var require_connection = __commonJS({
44682
45607
  const secProtocol = response.headersList.get("Sec-WebSocket-Protocol");
44683
45608
  if (secProtocol !== null) {
44684
45609
  const requestProtocols = getDecodeSplit("sec-websocket-protocol", request2.headersList);
44685
- if (!requestProtocols.includes(secProtocol)) {
45610
+ if (requestProtocols === null || !requestProtocols.includes(secProtocol)) {
44686
45611
  failWebsocketConnection(handler, 1002, "Protocol was not set in the opening handshake.");
44687
45612
  return;
44688
45613
  }
@@ -44758,27 +45683,26 @@ var require_permessage_deflate = __commonJS({
44758
45683
  var tail = Buffer.from([0, 0, 255, 255]);
44759
45684
  var kBuffer = /* @__PURE__ */ Symbol("kBuffer");
44760
45685
  var kLength = /* @__PURE__ */ Symbol("kLength");
44761
- var kDefaultMaxDecompressedSize = 4 * 1024 * 1024;
44762
45686
  var PerMessageDeflate = class {
44763
45687
  /** @type {import('node:zlib').InflateRaw} */
44764
45688
  #inflate;
44765
45689
  #options = {};
44766
- /** @type {boolean} */
44767
- #aborted = false;
44768
- /** @type {Function|null} */
44769
- #currentCallback = null;
45690
+ #maxPayloadSize = 0;
44770
45691
  /**
44771
45692
  * @param {Map<string, string>} extensions
44772
45693
  */
44773
- constructor(extensions) {
45694
+ constructor(extensions, options) {
44774
45695
  this.#options.serverNoContextTakeover = extensions.has("server_no_context_takeover");
44775
45696
  this.#options.serverMaxWindowBits = extensions.get("server_max_window_bits");
45697
+ this.#maxPayloadSize = options.maxPayloadSize;
44776
45698
  }
45699
+ /**
45700
+ * Decompress a compressed payload.
45701
+ * @param {Buffer} chunk Compressed data
45702
+ * @param {boolean} fin Final fragment flag
45703
+ * @param {Function} callback Callback function
45704
+ */
44777
45705
  decompress(chunk2, fin, callback) {
44778
- if (this.#aborted) {
44779
- callback(new MessageSizeExceededError());
44780
- return;
44781
- }
44782
45706
  if (!this.#inflate) {
44783
45707
  let windowBits = Z_DEFAULT_WINDOWBITS;
44784
45708
  if (this.#options.serverMaxWindowBits) {
@@ -44797,20 +45721,12 @@ var require_permessage_deflate = __commonJS({
44797
45721
  this.#inflate[kBuffer] = [];
44798
45722
  this.#inflate[kLength] = 0;
44799
45723
  this.#inflate.on("data", (data) => {
44800
- if (this.#aborted) {
44801
- return;
44802
- }
44803
45724
  this.#inflate[kLength] += data.length;
44804
- if (this.#inflate[kLength] > kDefaultMaxDecompressedSize) {
44805
- this.#aborted = true;
45725
+ if (this.#maxPayloadSize > 0 && this.#inflate[kLength] > this.#maxPayloadSize) {
45726
+ callback(new MessageSizeExceededError());
44806
45727
  this.#inflate.removeAllListeners();
44807
45728
  this.#inflate.destroy();
44808
45729
  this.#inflate = null;
44809
- if (this.#currentCallback) {
44810
- const cb = this.#currentCallback;
44811
- this.#currentCallback = null;
44812
- cb(new MessageSizeExceededError());
44813
- }
44814
45730
  return;
44815
45731
  }
44816
45732
  this.#inflate[kBuffer].push(data);
@@ -44820,19 +45736,17 @@ var require_permessage_deflate = __commonJS({
44820
45736
  callback(err2);
44821
45737
  });
44822
45738
  }
44823
- this.#currentCallback = callback;
44824
45739
  this.#inflate.write(chunk2);
44825
45740
  if (fin) {
44826
45741
  this.#inflate.write(tail);
44827
45742
  }
44828
45743
  this.#inflate.flush(() => {
44829
- if (this.#aborted || !this.#inflate) {
45744
+ if (!this.#inflate) {
44830
45745
  return;
44831
45746
  }
44832
45747
  const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]);
44833
45748
  this.#inflate[kBuffer].length = 0;
44834
45749
  this.#inflate[kLength] = 0;
44835
- this.#currentCallback = null;
44836
45750
  callback(null, full);
44837
45751
  });
44838
45752
  }
@@ -44873,16 +45787,23 @@ var require_receiver = __commonJS({
44873
45787
  #extensions;
44874
45788
  /** @type {import('./websocket').Handler} */
44875
45789
  #handler;
45790
+ /** @type {number} */
45791
+ #maxFragments;
45792
+ /** @type {number} */
45793
+ #maxPayloadSize;
44876
45794
  /**
44877
45795
  * @param {import('./websocket').Handler} handler
44878
45796
  * @param {Map<string, string>|null} extensions
45797
+ * @param {{ maxFragments?: number, maxPayloadSize?: number }} [options]
44879
45798
  */
44880
- constructor(handler, extensions) {
45799
+ constructor(handler, extensions, options = {}) {
44881
45800
  super();
44882
45801
  this.#handler = handler;
44883
45802
  this.#extensions = extensions == null ? /* @__PURE__ */ new Map() : extensions;
45803
+ this.#maxFragments = options.maxFragments ?? 0;
45804
+ this.#maxPayloadSize = options.maxPayloadSize ?? 0;
44884
45805
  if (this.#extensions.has("permessage-deflate")) {
44885
- this.#extensions.set("permessage-deflate", new PerMessageDeflate(extensions));
45806
+ this.#extensions.set("permessage-deflate", new PerMessageDeflate(extensions, options));
44886
45807
  }
44887
45808
  }
44888
45809
  /**
@@ -44895,6 +45816,13 @@ var require_receiver = __commonJS({
44895
45816
  this.#loop = true;
44896
45817
  this.run(callback);
44897
45818
  }
45819
+ #validatePayloadLength() {
45820
+ if (this.#maxPayloadSize > 0 && !isControlFrame(this.#info.opcode) && this.#info.payloadLength + this.#fragmentsBytes > this.#maxPayloadSize) {
45821
+ failWebsocketConnection(this.#handler, 1009, "Payload size exceeds maximum allowed size");
45822
+ return false;
45823
+ }
45824
+ return true;
45825
+ }
44898
45826
  /**
44899
45827
  * Runs whenever a new chunk is received.
44900
45828
  * Callback is called whenever there are no more chunks buffering,
@@ -44954,6 +45882,9 @@ var require_receiver = __commonJS({
44954
45882
  if (payloadLength <= 125) {
44955
45883
  this.#info.payloadLength = payloadLength;
44956
45884
  this.#state = parserStates.READ_DATA;
45885
+ if (!this.#validatePayloadLength()) {
45886
+ return;
45887
+ }
44957
45888
  } else if (payloadLength === 126) {
44958
45889
  this.#state = parserStates.PAYLOADLENGTH_16;
44959
45890
  } else if (payloadLength === 127) {
@@ -44974,6 +45905,9 @@ var require_receiver = __commonJS({
44974
45905
  const buffer = this.consume(2);
44975
45906
  this.#info.payloadLength = buffer.readUInt16BE(0);
44976
45907
  this.#state = parserStates.READ_DATA;
45908
+ if (!this.#validatePayloadLength()) {
45909
+ return;
45910
+ }
44977
45911
  } else if (this.#state === parserStates.PAYLOADLENGTH_64) {
44978
45912
  if (this.#byteOffset < 8) {
44979
45913
  return callback();
@@ -44987,6 +45921,9 @@ var require_receiver = __commonJS({
44987
45921
  }
44988
45922
  this.#info.payloadLength = lower;
44989
45923
  this.#state = parserStates.READ_DATA;
45924
+ if (!this.#validatePayloadLength()) {
45925
+ return;
45926
+ }
44990
45927
  } else if (this.#state === parserStates.READ_DATA) {
44991
45928
  if (this.#byteOffset < this.#info.payloadLength) {
44992
45929
  return callback();
@@ -44997,30 +45934,43 @@ var require_receiver = __commonJS({
44997
45934
  this.#state = parserStates.INFO;
44998
45935
  } else {
44999
45936
  if (!this.#info.compressed) {
45000
- this.writeFragments(body);
45937
+ if (!this.writeFragments(body)) {
45938
+ return;
45939
+ }
45001
45940
  if (!this.#info.fragmented && this.#info.fin) {
45002
45941
  websocketMessageReceived(this.#handler, this.#info.binaryType, this.consumeFragments());
45003
45942
  }
45004
45943
  this.#state = parserStates.INFO;
45005
45944
  } else {
45006
- this.#extensions.get("permessage-deflate").decompress(body, this.#info.fin, (error, data) => {
45007
- if (error) {
45008
- const code = error instanceof MessageSizeExceededError ? 1009 : 1007;
45009
- failWebsocketConnection(this.#handler, code, error.message);
45010
- return;
45011
- }
45012
- this.writeFragments(data);
45013
- if (!this.#info.fin) {
45014
- this.#state = parserStates.INFO;
45945
+ this.#extensions.get("permessage-deflate").decompress(
45946
+ body,
45947
+ this.#info.fin,
45948
+ (error, data) => {
45949
+ if (error) {
45950
+ const code = error instanceof MessageSizeExceededError ? 1009 : 1007;
45951
+ failWebsocketConnection(this.#handler, code, error.message);
45952
+ return;
45953
+ }
45954
+ if (!this.writeFragments(data)) {
45955
+ return;
45956
+ }
45957
+ if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) {
45958
+ failWebsocketConnection(this.#handler, 1009, new MessageSizeExceededError().message);
45959
+ return;
45960
+ }
45961
+ if (!this.#info.fin) {
45962
+ this.#state = parserStates.INFO;
45963
+ this.#loop = true;
45964
+ this.run(callback);
45965
+ return;
45966
+ }
45967
+ websocketMessageReceived(this.#handler, this.#info.binaryType, this.consumeFragments());
45015
45968
  this.#loop = true;
45969
+ this.#state = parserStates.INFO;
45016
45970
  this.run(callback);
45017
- return;
45018
- }
45019
- websocketMessageReceived(this.#handler, this.#info.binaryType, this.consumeFragments());
45020
- this.#loop = true;
45021
- this.#state = parserStates.INFO;
45022
- this.run(callback);
45023
- });
45971
+ },
45972
+ this.#fragmentsBytes
45973
+ );
45024
45974
  this.#loop = false;
45025
45975
  break;
45026
45976
  }
@@ -45068,8 +46018,13 @@ var require_receiver = __commonJS({
45068
46018
  }
45069
46019
  }
45070
46020
  writeFragments(fragment) {
46021
+ if (this.#maxFragments > 0 && this.#fragments.length === this.#maxFragments) {
46022
+ failWebsocketConnection(this.#handler, 1008, "Too many message fragments");
46023
+ return false;
46024
+ }
45071
46025
  this.#fragmentsBytes += fragment.length;
45072
46026
  this.#fragments.push(fragment);
46027
+ return true;
45073
46028
  }
45074
46029
  consumeFragments() {
45075
46030
  const fragments = this.#fragments;
@@ -45536,7 +46491,13 @@ var require_websocket = __commonJS({
45536
46491
  */
45537
46492
  #onConnectionEstablished(response, parsedExtensions) {
45538
46493
  this.#handler.socket = response.socket;
45539
- const parser = new ByteParser(this.#handler, parsedExtensions);
46494
+ const webSocketOptions = this.#handler.controller.dispatcher?.webSocketOptions;
46495
+ const maxFragments = webSocketOptions?.maxFragments;
46496
+ const maxPayloadSize = webSocketOptions?.maxPayloadSize;
46497
+ const parser = new ByteParser(this.#handler, parsedExtensions, {
46498
+ maxFragments,
46499
+ maxPayloadSize
46500
+ });
45540
46501
  parser.on("drain", () => this.#handler.onParserDrain());
45541
46502
  parser.on("error", (err2) => this.#handler.onParserError(err2));
45542
46503
  this.#parser = parser;
@@ -45842,9 +46803,9 @@ var require_websocketstream = __commonJS({
45842
46803
  #readableStream;
45843
46804
  /** @type {ReadableStreamDefaultController} */
45844
46805
  #readableStreamController;
45845
- // Each WebSocketStream object has an associated writable stream , which is a WritableStream .
45846
- /** @type {WritableStream} */
45847
- #writableStream;
46806
+ // Retain the controller so the writable stream can be errored while locked.
46807
+ /** @type {WritableStreamDefaultController} */
46808
+ #writableStreamController;
45848
46809
  // Each WebSocketStream object has an associated boolean handshake aborted , which is initially false.
45849
46810
  #handshakeAborted = false;
45850
46811
  /** @type {import('../websocket').Handler} */
@@ -45980,7 +46941,12 @@ var require_websocketstream = __commonJS({
45980
46941
  /** @type {import('../websocket').Handler['onConnectionEstablished']} */
45981
46942
  #onConnectionEstablished(response, parsedExtensions) {
45982
46943
  this.#handler.socket = response.socket;
45983
- const parser = new ByteParser(this.#handler, parsedExtensions);
46944
+ const maxFragments = this.#handler.controller.dispatcher?.webSocketOptions?.maxFragments;
46945
+ const maxPayloadSize = this.#handler.controller.dispatcher?.webSocketOptions?.maxPayloadSize;
46946
+ const parser = new ByteParser(this.#handler, parsedExtensions, {
46947
+ maxFragments,
46948
+ maxPayloadSize
46949
+ });
45984
46950
  parser.on("drain", () => this.#handler.onParserDrain());
45985
46951
  parser.on("error", (err2) => this.#handler.onParserError(err2));
45986
46952
  this.#parser = parser;
@@ -45991,21 +46957,17 @@ var require_websocketstream = __commonJS({
45991
46957
  start: (controller) => {
45992
46958
  this.#readableStreamController = controller;
45993
46959
  },
45994
- pull(controller) {
45995
- let chunk2;
45996
- while (controller.desiredSize > 0 && (chunk2 = response.socket.read()) !== null) {
45997
- controller.enqueue(chunk2);
45998
- }
45999
- },
46000
46960
  cancel: (reason) => this.#cancel(reason)
46001
46961
  });
46002
46962
  const writable = new WritableStream({
46963
+ start: (controller) => {
46964
+ this.#writableStreamController = controller;
46965
+ },
46003
46966
  write: (chunk2) => this.#write(chunk2),
46004
46967
  close: () => closeWebSocketConnection(this.#handler, null, null),
46005
46968
  abort: (reason) => this.#closeUsingReason(reason)
46006
46969
  });
46007
46970
  this.#readableStream = readable;
46008
- this.#writableStream = writable;
46009
46971
  this.#openedPromise.resolve({
46010
46972
  extensions,
46011
46973
  protocol,
@@ -46023,7 +46985,7 @@ var require_websocketstream = __commonJS({
46023
46985
  try {
46024
46986
  chunk2 = utf8Decode(data);
46025
46987
  } catch {
46026
- failWebsocketConnection(this.#handler, "Received invalid UTF-8 in text frame.");
46988
+ failWebsocketConnection(this.#handler, 1007, "Received invalid UTF-8 in text frame.");
46027
46989
  return;
46028
46990
  }
46029
46991
  } else if (type === opcodes.BINARY) {
@@ -46049,9 +47011,7 @@ var require_websocketstream = __commonJS({
46049
47011
  const reason = result?.reason == null ? "" : utf8DecodeBytes(Buffer.from(result.reason));
46050
47012
  if (wasClean) {
46051
47013
  this.#readableStreamController.close();
46052
- if (!this.#writableStream.locked) {
46053
- this.#writableStream.abort(new DOMException("A closed WebSocketStream cannot be written to", "InvalidStateError"));
46054
- }
47014
+ this.#writableStreamController.error(new DOMException("A closed WebSocketStream cannot be written to", "InvalidStateError"));
46055
47015
  this.#closedPromise.resolve({
46056
47016
  closeCode: code,
46057
47017
  reason
@@ -46059,7 +47019,7 @@ var require_websocketstream = __commonJS({
46059
47019
  } else {
46060
47020
  const error = createUnvalidatedWebSocketError("unclean close", code, reason);
46061
47021
  this.#readableStreamController?.error(error);
46062
- this.#writableStream?.abort(error);
47022
+ this.#writableStreamController?.error(error);
46063
47023
  this.#closedPromise.reject(error);
46064
47024
  }
46065
47025
  }
@@ -46154,6 +47114,40 @@ var require_eventsource_stream = __commonJS({
46154
47114
  var CR = 13;
46155
47115
  var COLON = 58;
46156
47116
  var SPACE = 32;
47117
+ var DATA = Buffer.from("data");
47118
+ var EVENT = Buffer.from("event");
47119
+ var ID = Buffer.from("id");
47120
+ var RETRY = Buffer.from("retry");
47121
+ function isASCIINumberBytes(buffer, start) {
47122
+ if (start >= buffer.length) {
47123
+ return false;
47124
+ }
47125
+ for (let i = start; i < buffer.length; i++) {
47126
+ if (buffer[i] < 48 || buffer[i] > 57) {
47127
+ return false;
47128
+ }
47129
+ }
47130
+ return true;
47131
+ }
47132
+ function isValidLastEventIdBytes(buffer, start) {
47133
+ for (let i = start; i < buffer.length; i++) {
47134
+ if (buffer[i] === 0) {
47135
+ return false;
47136
+ }
47137
+ }
47138
+ return true;
47139
+ }
47140
+ function isFieldName(line, length, field) {
47141
+ if (length !== field.length) {
47142
+ return false;
47143
+ }
47144
+ for (let i = 0; i < length; i++) {
47145
+ if (line[i] !== field[i]) {
47146
+ return false;
47147
+ }
47148
+ }
47149
+ return true;
47150
+ }
46157
47151
  var EventSourceStream = class extends Transform {
46158
47152
  /**
46159
47153
  * @type {eventSourceSettings}
@@ -46173,10 +47167,13 @@ var require_eventsource_stream = __commonJS({
46173
47167
  */
46174
47168
  eventEndCheck = false;
46175
47169
  /**
46176
- * @type {Buffer|null}
47170
+ * @type {Buffer[]}
46177
47171
  */
46178
- buffer = null;
47172
+ chunks = [];
47173
+ chunkIndex = 0;
46179
47174
  pos = 0;
47175
+ lineChunkIndex = 0;
47176
+ linePos = 0;
46180
47177
  event = {
46181
47178
  data: void 0,
46182
47179
  event: void 0,
@@ -46208,63 +47205,30 @@ var require_eventsource_stream = __commonJS({
46208
47205
  callback();
46209
47206
  return;
46210
47207
  }
46211
- if (this.buffer) {
46212
- this.buffer = Buffer.concat([this.buffer, chunk2]);
46213
- } else {
46214
- this.buffer = chunk2;
46215
- }
47208
+ this.chunks.push(chunk2);
46216
47209
  if (this.checkBOM) {
46217
- switch (this.buffer.length) {
46218
- case 1:
46219
- if (this.buffer[0] === BOM[0]) {
46220
- callback();
46221
- return;
46222
- }
46223
- this.checkBOM = false;
46224
- callback();
46225
- return;
46226
- case 2:
46227
- if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1]) {
46228
- callback();
46229
- return;
46230
- }
46231
- this.checkBOM = false;
46232
- break;
46233
- case 3:
46234
- if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) {
46235
- this.buffer = Buffer.alloc(0);
46236
- this.checkBOM = false;
46237
- callback();
46238
- return;
46239
- }
46240
- this.checkBOM = false;
46241
- break;
46242
- default:
46243
- if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) {
46244
- this.buffer = this.buffer.subarray(3);
46245
- }
46246
- this.checkBOM = false;
46247
- break;
47210
+ if (this.handleBOM()) {
47211
+ callback();
47212
+ return;
46248
47213
  }
46249
47214
  }
46250
- while (this.pos < this.buffer.length) {
47215
+ while (this.hasCurrentByte()) {
47216
+ const byte = this.currentByte();
46251
47217
  if (this.eventEndCheck) {
46252
47218
  if (this.crlfCheck) {
46253
- if (this.buffer[this.pos] === LF) {
46254
- this.buffer = this.buffer.subarray(this.pos + 1);
46255
- this.pos = 0;
47219
+ if (byte === LF) {
46256
47220
  this.crlfCheck = false;
47221
+ this.consumeCurrentByte();
46257
47222
  continue;
46258
47223
  }
46259
47224
  this.crlfCheck = false;
46260
47225
  }
46261
- if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) {
46262
- if (this.buffer[this.pos] === CR) {
47226
+ if (byte === LF || byte === CR) {
47227
+ if (byte === CR) {
46263
47228
  this.crlfCheck = true;
46264
47229
  }
46265
- this.buffer = this.buffer.subarray(this.pos + 1);
46266
- this.pos = 0;
46267
- if (this.event.data !== void 0 || this.event.event || this.event.id !== void 0 || this.event.retry) {
47230
+ this.consumeCurrentByte();
47231
+ if (this.hasPendingEvent()) {
46268
47232
  this.processEvent(this.event);
46269
47233
  }
46270
47234
  this.clearEvent();
@@ -46273,17 +47237,16 @@ var require_eventsource_stream = __commonJS({
46273
47237
  this.eventEndCheck = false;
46274
47238
  continue;
46275
47239
  }
46276
- if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) {
46277
- if (this.buffer[this.pos] === CR) {
47240
+ if (byte === LF || byte === CR) {
47241
+ if (byte === CR) {
46278
47242
  this.crlfCheck = true;
46279
47243
  }
46280
- this.parseLine(this.buffer.subarray(0, this.pos), this.event);
46281
- this.buffer = this.buffer.subarray(this.pos + 1);
46282
- this.pos = 0;
47244
+ this.parseLine(this.readLine(), this.event);
47245
+ this.consumeCurrentByte();
46283
47246
  this.eventEndCheck = true;
46284
47247
  continue;
46285
47248
  }
46286
- this.pos++;
47249
+ this.advanceCursor();
46287
47250
  }
46288
47251
  callback();
46289
47252
  }
@@ -46299,43 +47262,42 @@ var require_eventsource_stream = __commonJS({
46299
47262
  if (colonPosition === 0) {
46300
47263
  return;
46301
47264
  }
46302
- let field = "";
46303
- let value = "";
47265
+ let fieldLength = line.length;
47266
+ let valueStart = line.length;
46304
47267
  if (colonPosition !== -1) {
46305
- field = line.subarray(0, colonPosition).toString("utf8");
46306
- let valueStart = colonPosition + 1;
47268
+ fieldLength = colonPosition;
47269
+ valueStart = colonPosition + 1;
46307
47270
  if (line[valueStart] === SPACE) {
46308
47271
  ++valueStart;
46309
47272
  }
46310
- value = line.subarray(valueStart).toString("utf8");
46311
- } else {
46312
- field = line.toString("utf8");
46313
- value = "";
46314
47273
  }
46315
- switch (field) {
46316
- case "data":
46317
- if (event[field] === void 0) {
46318
- event[field] = value;
46319
- } else {
46320
- event[field] += `
47274
+ if (isFieldName(line, fieldLength, DATA)) {
47275
+ const value = line.toString("utf8", valueStart);
47276
+ if (event.data === void 0) {
47277
+ event.data = value;
47278
+ } else {
47279
+ event.data += `
46321
47280
  ${value}`;
46322
- }
46323
- break;
46324
- case "retry":
46325
- if (isASCIINumber(value)) {
46326
- event[field] = value;
46327
- }
46328
- break;
46329
- case "id":
46330
- if (isValidLastEventId(value)) {
46331
- event[field] = value;
46332
- }
46333
- break;
46334
- case "event":
46335
- if (value.length > 0) {
46336
- event[field] = value;
46337
- }
46338
- break;
47281
+ }
47282
+ return;
47283
+ }
47284
+ if (isFieldName(line, fieldLength, RETRY)) {
47285
+ if (isASCIINumberBytes(line, valueStart)) {
47286
+ event.retry = line.toString("utf8", valueStart);
47287
+ }
47288
+ return;
47289
+ }
47290
+ if (isFieldName(line, fieldLength, ID)) {
47291
+ if (isValidLastEventIdBytes(line, valueStart)) {
47292
+ event.id = line.toString("utf8", valueStart);
47293
+ }
47294
+ return;
47295
+ }
47296
+ if (isFieldName(line, fieldLength, EVENT)) {
47297
+ const value = line.toString("utf8", valueStart);
47298
+ if (value.length > 0) {
47299
+ event.event = value;
47300
+ }
46339
47301
  }
46340
47302
  }
46341
47303
  /**
@@ -46360,12 +47322,120 @@ ${value}`;
46360
47322
  }
46361
47323
  }
46362
47324
  clearEvent() {
46363
- this.event = {
46364
- data: void 0,
46365
- event: void 0,
46366
- id: void 0,
46367
- retry: void 0
46368
- };
47325
+ this.event.data = void 0;
47326
+ this.event.event = void 0;
47327
+ this.event.id = void 0;
47328
+ this.event.retry = void 0;
47329
+ }
47330
+ hasPendingEvent() {
47331
+ return this.event.data !== void 0 || this.event.event !== void 0 || this.event.id !== void 0 || this.event.retry !== void 0;
47332
+ }
47333
+ hasCurrentByte() {
47334
+ return this.chunkIndex < this.chunks.length && this.pos < this.chunks[this.chunkIndex].length;
47335
+ }
47336
+ currentByte() {
47337
+ return this.chunks[this.chunkIndex][this.pos];
47338
+ }
47339
+ consumeCurrentByte() {
47340
+ this.advanceCursor();
47341
+ this.syncLineStartToCursor();
47342
+ }
47343
+ advanceCursor() {
47344
+ this.pos++;
47345
+ while (this.chunkIndex < this.chunks.length && this.pos >= this.chunks[this.chunkIndex].length) {
47346
+ this.chunkIndex++;
47347
+ this.pos = 0;
47348
+ }
47349
+ }
47350
+ syncLineStartToCursor() {
47351
+ this.lineChunkIndex = this.chunkIndex;
47352
+ this.linePos = this.pos;
47353
+ this.dropConsumedChunks();
47354
+ }
47355
+ dropConsumedChunks() {
47356
+ while (this.lineChunkIndex > 0) {
47357
+ this.chunks.shift();
47358
+ this.lineChunkIndex--;
47359
+ this.chunkIndex--;
47360
+ }
47361
+ if (this.chunkIndex === this.chunks.length) {
47362
+ this.chunks.length = 0;
47363
+ this.chunkIndex = 0;
47364
+ this.pos = 0;
47365
+ this.lineChunkIndex = 0;
47366
+ this.linePos = 0;
47367
+ }
47368
+ }
47369
+ readLine() {
47370
+ if (this.lineChunkIndex === this.chunkIndex) {
47371
+ return this.chunks[this.chunkIndex].subarray(this.linePos, this.pos);
47372
+ }
47373
+ const chunks = [];
47374
+ let length = 0;
47375
+ for (let i = this.lineChunkIndex; i <= this.chunkIndex; i++) {
47376
+ const chunk2 = this.chunks[i];
47377
+ const start = i === this.lineChunkIndex ? this.linePos : 0;
47378
+ const end = i === this.chunkIndex ? this.pos : chunk2.length;
47379
+ const slice = chunk2.subarray(start, end);
47380
+ length += slice.length;
47381
+ chunks.push(slice);
47382
+ }
47383
+ return Buffer.concat(chunks, length);
47384
+ }
47385
+ peekBufferedByte(offset) {
47386
+ let chunkIndex = this.lineChunkIndex;
47387
+ let pos = this.linePos;
47388
+ while (chunkIndex < this.chunks.length) {
47389
+ const chunk2 = this.chunks[chunkIndex];
47390
+ const remaining = chunk2.length - pos;
47391
+ if (offset < remaining) {
47392
+ return chunk2[pos + offset];
47393
+ }
47394
+ offset -= remaining;
47395
+ chunkIndex++;
47396
+ pos = 0;
47397
+ }
47398
+ }
47399
+ discardLeadingBytes(count) {
47400
+ while (count > 0 && this.lineChunkIndex < this.chunks.length) {
47401
+ const chunk2 = this.chunks[this.lineChunkIndex];
47402
+ const remaining = chunk2.length - this.linePos;
47403
+ if (count < remaining) {
47404
+ this.linePos += count;
47405
+ count = 0;
47406
+ } else {
47407
+ count -= remaining;
47408
+ this.lineChunkIndex++;
47409
+ this.linePos = 0;
47410
+ }
47411
+ }
47412
+ this.chunkIndex = this.lineChunkIndex;
47413
+ this.pos = this.linePos;
47414
+ this.dropConsumedChunks();
47415
+ }
47416
+ handleBOM() {
47417
+ const first = this.peekBufferedByte(0);
47418
+ const second = this.peekBufferedByte(1);
47419
+ const third = this.peekBufferedByte(2);
47420
+ if (second === void 0) {
47421
+ if (first === BOM[0]) {
47422
+ return true;
47423
+ }
47424
+ this.checkBOM = false;
47425
+ return true;
47426
+ }
47427
+ if (third === void 0) {
47428
+ if (first === BOM[0] && second === BOM[1]) {
47429
+ return true;
47430
+ }
47431
+ this.checkBOM = false;
47432
+ return false;
47433
+ }
47434
+ if (first === BOM[0] && second === BOM[1] && third === BOM[2]) {
47435
+ this.discardLeadingBytes(3);
47436
+ }
47437
+ this.checkBOM = false;
47438
+ return !this.hasCurrentByte();
46369
47439
  }
46370
47440
  };
46371
47441
  module2.exports = {