@modelcontextprotocol/inspector 2.2.0 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -654,6 +654,22 @@ var require_errors = __commonJS({
654
654
  return true;
655
655
  }
656
656
  };
657
+ var kProxyConnectionError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_PRX_CONN");
658
+ var ProxyConnectionError = class extends UndiciError {
659
+ constructor(cause, message, options = {}) {
660
+ super(message, { cause, ...options });
661
+ this.name = "ProxyConnectionError";
662
+ this.message = message || "Proxy Connection failed";
663
+ this.code = "UND_ERR_PRX_CONN";
664
+ this.cause = cause;
665
+ }
666
+ static [Symbol.hasInstance](instance) {
667
+ return instance && instance[kProxyConnectionError] === true;
668
+ }
669
+ get [kProxyConnectionError]() {
670
+ return true;
671
+ }
672
+ };
657
673
  var kMaxOriginsReachedError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_MAX_ORIGINS_REACHED");
658
674
  var MaxOriginsReachedError = class extends UndiciError {
659
675
  constructor(message) {
@@ -715,6 +731,7 @@ var require_errors = __commonJS({
715
731
  RequestRetryError,
716
732
  ResponseError,
717
733
  SecureProxyConnectionError,
734
+ ProxyConnectionError,
718
735
  MaxOriginsReachedError,
719
736
  Socks5ProxyError,
720
737
  MessageSizeExceededError
@@ -1172,7 +1189,10 @@ var require_util = __commonJS({
1172
1189
  if (Object.getPrototypeOf(stream2).constructor === IncomingMessage) {
1173
1190
  stream2.socket = null;
1174
1191
  }
1175
- stream2.destroy(err);
1192
+ try {
1193
+ stream2.destroy(err);
1194
+ } catch {
1195
+ }
1176
1196
  } else if (err) {
1177
1197
  queueMicrotask(() => {
1178
1198
  stream2.emit("error", err);
@@ -1740,7 +1760,18 @@ var require_util = __commonJS({
1740
1760
  message += ` timeout: ${opts.timeout}ms)`;
1741
1761
  destroy(socket, new ConnectTimeoutError(message));
1742
1762
  }
1763
+ var lastUrlString = null;
1764
+ var lastProtocol = null;
1743
1765
  function getProtocolFromUrlString(urlString) {
1766
+ if (urlString === lastUrlString) {
1767
+ return lastProtocol;
1768
+ }
1769
+ const protocol = getProtocolFromUrlStringSlow(urlString);
1770
+ lastUrlString = urlString;
1771
+ lastProtocol = protocol;
1772
+ return protocol;
1773
+ }
1774
+ function getProtocolFromUrlStringSlow(urlString) {
1744
1775
  if (urlString[0] === "h" && urlString[1] === "t" && urlString[2] === "t" && urlString[3] === "p") {
1745
1776
  switch (urlString[4]) {
1746
1777
  case ":":
@@ -1769,7 +1800,9 @@ var require_util = __commonJS({
1769
1800
  post: "POST",
1770
1801
  POST: "POST",
1771
1802
  put: "PUT",
1772
- PUT: "PUT"
1803
+ PUT: "PUT",
1804
+ query: "QUERY",
1805
+ QUERY: "QUERY"
1773
1806
  };
1774
1807
  var normalizedMethodRecords = {
1775
1808
  ...normalizedMethodRecordsBase,
@@ -2220,7 +2253,7 @@ var require_request = __commonJS({
2220
2253
  this.headersTimeout = headersTimeout;
2221
2254
  this.bodyTimeout = bodyTimeout;
2222
2255
  this.method = method;
2223
- this.typeOfService = typeOfService ?? 0;
2256
+ this.typeOfService = typeOfService;
2224
2257
  this.abort = null;
2225
2258
  if (body == null) {
2226
2259
  this.body = null;
@@ -2260,7 +2293,7 @@ var require_request = __commonJS({
2260
2293
  this.path = query ? serializePathWithQuery(path, query) : path;
2261
2294
  this.origin = origin;
2262
2295
  this.protocol = getProtocolFromUrlString(origin);
2263
- this.idempotent = idempotent == null ? method === "HEAD" || method === "GET" : idempotent;
2296
+ this.idempotent = idempotent == null ? method === "HEAD" || method === "GET" || method === "QUERY" : idempotent;
2264
2297
  this.blocking = blocking ?? this.method !== "HEAD";
2265
2298
  this.reset = reset == null ? null : reset;
2266
2299
  this.host = null;
@@ -2454,7 +2487,11 @@ var require_request = __commonJS({
2454
2487
  } else if (typeof val[i] === "object") {
2455
2488
  throw new InvalidArgumentError(`invalid ${key} header`);
2456
2489
  } else {
2457
- arr.push(`${val[i]}`);
2490
+ const str = `${val[i]}`;
2491
+ if (!isValidHeaderValue(str)) {
2492
+ throw new InvalidArgumentError(`invalid ${key} header`);
2493
+ }
2494
+ arr.push(str);
2458
2495
  }
2459
2496
  }
2460
2497
  val = arr;
@@ -2466,6 +2503,9 @@ var require_request = __commonJS({
2466
2503
  val = "";
2467
2504
  } else {
2468
2505
  val = `${val}`;
2506
+ if (!isValidHeaderValue(val)) {
2507
+ throw new InvalidArgumentError(`invalid ${key} header`);
2508
+ }
2469
2509
  }
2470
2510
  if (headerName === "host") {
2471
2511
  if (request.host !== null) {
@@ -3647,7 +3687,7 @@ var require_constants3 = __commonJS({
3647
3687
  );
3648
3688
  var safeMethods = (
3649
3689
  /** @type {const} */
3650
- ["GET", "HEAD", "OPTIONS", "TRACE"]
3690
+ ["GET", "HEAD", "OPTIONS", "TRACE", "QUERY"]
3651
3691
  );
3652
3692
  var safeMethodsSet = new Set(safeMethods);
3653
3693
  var requestMode = (
@@ -5369,7 +5409,7 @@ var require_util2 = __commonJS({
5369
5409
  if (rangeEndValue === null && rangeStartValue === null) {
5370
5410
  return "failure";
5371
5411
  }
5372
- if (rangeStartValue > rangeEndValue) {
5412
+ if (rangeStartValue !== null && rangeEndValue !== null && rangeStartValue > rangeEndValue) {
5373
5413
  return "failure";
5374
5414
  }
5375
5415
  return { rangeStartValue, rangeEndValue };
@@ -6155,6 +6195,7 @@ var require_body = __commonJS({
6155
6195
  var { multipartFormDataParser } = require_formdata_parser();
6156
6196
  var { parseJSONFromBytes } = require_infra();
6157
6197
  var { utf8DecodeBytes } = require_encoding();
6198
+ var { ReadableStreamTee } = __require("stream/web");
6158
6199
  var textEncoder = new TextEncoder();
6159
6200
  function noop() {
6160
6201
  }
@@ -6297,7 +6338,7 @@ Content-Type: ${value.type || "application/octet-stream"}\r
6297
6338
  return extractBody(object, keepalive);
6298
6339
  }
6299
6340
  function cloneBody(body) {
6300
- const { 0: out1, 1: out2 } = body.stream.tee();
6341
+ const { 0: out1, 1: out2 } = ReadableStreamTee?.(body.stream, true) ?? body.stream.tee();
6301
6342
  body.stream = out1;
6302
6343
  return {
6303
6344
  stream: out2,
@@ -6450,6 +6491,7 @@ var require_client_h1 = __commonJS({
6450
6491
  RequestContentLengthMismatchError,
6451
6492
  ResponseContentLengthMismatchError,
6452
6493
  RequestAbortedError,
6494
+ InvalidArgumentError,
6453
6495
  HeadersTimeoutError,
6454
6496
  HeadersOverflowError,
6455
6497
  SocketError,
@@ -6499,6 +6541,7 @@ var require_client_h1 = __commonJS({
6499
6541
  var kIdleSocketValidation = /* @__PURE__ */ Symbol("kIdleSocketValidation");
6500
6542
  var kIdleSocketValidationTimeout = /* @__PURE__ */ Symbol("kIdleSocketValidationTimeout");
6501
6543
  var kSocketUsed = /* @__PURE__ */ Symbol("kSocketUsed");
6544
+ var kTypeOfService = /* @__PURE__ */ Symbol("kTypeOfService");
6502
6545
  var extractBody;
6503
6546
  function lazyllhttp() {
6504
6547
  const llhttpWasmData = process.env.JEST_WORKER_ID ? require_llhttp_wasm() : void 0;
@@ -6740,6 +6783,19 @@ var require_client_h1 = __commonJS({
6740
6783
  assert(currentParser === null);
6741
6784
  assert(this.ptr != null);
6742
6785
  const { llhttp } = this;
6786
+ if (this.paused) {
6787
+ let data;
6788
+ do {
6789
+ llhttp.llhttp_resume(this.ptr);
6790
+ this.paused = false;
6791
+ data = this.socket.read() || EMPTY_BUF;
6792
+ this.execute(data);
6793
+ } while (this.paused && data.length > 0);
6794
+ if (this.paused) {
6795
+ llhttp.llhttp_resume(this.ptr);
6796
+ this.paused = false;
6797
+ }
6798
+ }
6743
6799
  let ret;
6744
6800
  try {
6745
6801
  currentParser = this;
@@ -7222,20 +7278,20 @@ var require_client_h1 = __commonJS({
7222
7278
  }
7223
7279
  function clearIdleSocketValidation(socket) {
7224
7280
  if (socket[kIdleSocketValidationTimeout]) {
7225
- clearTimeout(socket[kIdleSocketValidationTimeout]);
7281
+ clearImmediate(socket[kIdleSocketValidationTimeout]);
7226
7282
  socket[kIdleSocketValidationTimeout] = null;
7227
7283
  }
7228
7284
  socket[kIdleSocketValidation] = 0;
7229
7285
  }
7230
7286
  function scheduleIdleSocketValidation(client, socket) {
7231
7287
  socket[kIdleSocketValidation] = 1;
7232
- socket[kIdleSocketValidationTimeout] = setTimeout(() => {
7288
+ socket[kIdleSocketValidationTimeout] = setImmediate(() => {
7233
7289
  socket[kIdleSocketValidationTimeout] = null;
7234
7290
  socket[kIdleSocketValidation] = 2;
7235
7291
  if (client[kSocket] === socket && !socket.destroyed) {
7236
7292
  client[kResume]();
7237
7293
  }
7238
- }, 0);
7294
+ });
7239
7295
  socket[kIdleSocketValidationTimeout].unref?.();
7240
7296
  }
7241
7297
  function resumeH1(client) {
@@ -7289,6 +7345,24 @@ var require_client_h1 = __commonJS({
7289
7345
  function shouldSendContentLength(method) {
7290
7346
  return method !== "GET" && method !== "HEAD" && method !== "OPTIONS" && method !== "TRACE" && method !== "CONNECT";
7291
7347
  }
7348
+ function setTypeOfService(socket, request) {
7349
+ if (typeof socket.setTypeOfService !== "function") {
7350
+ return;
7351
+ }
7352
+ const typeOfService = request.typeOfService;
7353
+ if (typeOfService === void 0) {
7354
+ return;
7355
+ }
7356
+ const currentTypeOfService = socket[kTypeOfService];
7357
+ if (currentTypeOfService === typeOfService) {
7358
+ return;
7359
+ }
7360
+ try {
7361
+ socket.setTypeOfService(typeOfService);
7362
+ socket[kTypeOfService] = typeOfService;
7363
+ } catch {
7364
+ }
7365
+ }
7292
7366
  function writeH1(client, request) {
7293
7367
  const { method, path, host, upgrade, blocking, reset } = request;
7294
7368
  let { body, headers, contentLength } = request;
@@ -7303,8 +7377,16 @@ var require_client_h1 = __commonJS({
7303
7377
  }
7304
7378
  body = bodyStream.stream;
7305
7379
  contentLength = bodyStream.length;
7306
- } else if (util.isBlobLike(body) && request.contentType == null && body.type) {
7307
- headers.push("content-type", body.type);
7380
+ } else if (util.isBlobLike(body) && request.contentType == null) {
7381
+ const contentType = body.type;
7382
+ if (contentType) {
7383
+ const contentTypeValue = `${contentType}`;
7384
+ if (!util.isValidHeaderValue(contentTypeValue)) {
7385
+ util.errorRequest(client, request, new InvalidArgumentError("invalid content-type header"));
7386
+ return false;
7387
+ }
7388
+ headers.push("content-type", contentTypeValue);
7389
+ }
7308
7390
  }
7309
7391
  if (body && typeof body.read === "function") {
7310
7392
  body.read(0);
@@ -7357,9 +7439,7 @@ var require_client_h1 = __commonJS({
7357
7439
  if (blocking) {
7358
7440
  socket[kBlocking] = true;
7359
7441
  }
7360
- if (socket.setTypeOfService) {
7361
- socket.setTypeOfService(request.typeOfService);
7362
- }
7442
+ setTypeOfService(socket, request);
7363
7443
  let header = `${method} ${path} HTTP/1.1\r
7364
7444
  `;
7365
7445
  if (typeof host === "string") {
@@ -7839,11 +7919,18 @@ var require_client_h2 = __commonJS({
7839
7919
  client[kQueue].splice(client[kPendingIdx] + 1, 0, request);
7840
7920
  }
7841
7921
  function completeRequest(client, request, resetPendingIdx = false) {
7842
- const index = client[kQueue].indexOf(request, client[kRunningIdx]);
7922
+ const queue = client[kQueue];
7923
+ const runningIdx = client[kRunningIdx];
7924
+ if (runningIdx < client[kPendingIdx] && queue[runningIdx] === request) {
7925
+ queue[runningIdx] = null;
7926
+ client[kRunningIdx] = runningIdx + 1;
7927
+ return;
7928
+ }
7929
+ const index = queue.indexOf(request, runningIdx);
7843
7930
  if (index === -1 || index >= client[kPendingIdx]) {
7844
7931
  return;
7845
7932
  }
7846
- client[kQueue].splice(index, 1);
7933
+ queue.splice(index, 1);
7847
7934
  client[kPendingIdx]--;
7848
7935
  if (resetPendingIdx && client[kPendingIdx] < client[kRunningIdx]) {
7849
7936
  client[kPendingIdx] = client[kRunningIdx];
@@ -7853,9 +7940,7 @@ var require_client_h2 = __commonJS({
7853
7940
  const { body } = request;
7854
7941
  return body == null || util.isBuffer(body) || util.isBlobLike(body);
7855
7942
  }
7856
- function closeRequestStream(request, code = NGHTTP2_REFUSED_STREAM) {
7857
- const stream = request[kRequestStream];
7858
- clearRequestStream(request);
7943
+ function closeStream(stream, code = NGHTTP2_REFUSED_STREAM) {
7859
7944
  if (stream != null && !stream.destroyed && !stream.closed) {
7860
7945
  try {
7861
7946
  stream.close(code);
@@ -7863,6 +7948,11 @@ var require_client_h2 = __commonJS({
7863
7948
  }
7864
7949
  }
7865
7950
  }
7951
+ function detachRequestStreamForClose(request) {
7952
+ const stream = request[kRequestStream];
7953
+ clearRequestStream(request);
7954
+ return stream;
7955
+ }
7866
7956
  function connectH2(client, socket) {
7867
7957
  client[kSocket] = socket;
7868
7958
  const http2InitialWindowSize = client[kHTTP2InitialWindowSize];
@@ -7882,6 +7972,11 @@ var require_client_h2 = __commonJS({
7882
7972
  session[kSocket] = socket;
7883
7973
  session[kHTTP2SessionState] = {
7884
7974
  idleTimeout: null,
7975
+ // Sockets start out ref'd. Session ref/unref proxies to the socket, so a
7976
+ // single cached flag lets us skip redundant uv ref/unref calls, provided
7977
+ // every ref/unref of the session or its socket goes through
7978
+ // refH2Session/unrefH2Session.
7979
+ refed: true,
7885
7980
  ping: {
7886
7981
  interval: client[kPingInterval] === 0 ? null : setInterval(onHttp2SendPing, client[kPingInterval], session).unref()
7887
7982
  }
@@ -7894,11 +7989,10 @@ var require_client_h2 = __commonJS({
7894
7989
  }
7895
7990
  util.addListener(session, "error", onHttp2SessionError);
7896
7991
  util.addListener(session, "frameError", onHttp2FrameError);
7897
- util.addListener(session, "end", onHttp2SessionEnd);
7898
7992
  util.addListener(session, "goaway", onHttp2SessionGoAway);
7899
7993
  util.addListener(session, "close", onHttp2SessionClose);
7900
7994
  util.addListener(session, "remoteSettings", onHttp2RemoteSettings);
7901
- session.unref();
7995
+ unrefH2Session(session);
7902
7996
  client[kHTTP2Session] = session;
7903
7997
  socket[kHTTP2Session] = session;
7904
7998
  util.addListener(socket, "error", onHttp2SocketError);
@@ -7953,7 +8047,6 @@ var require_client_h2 = __commonJS({
7953
8047
  if (request != null) {
7954
8048
  if (client[kRunning] > 0) {
7955
8049
  if ((request.upgrade === "websocket" || request.method === "CONNECT") && session[kRemoteSettings] === false) return true;
7956
- if (util.bodyLength(request.body) !== 0 && (util.isStream(request.body) || util.isAsyncIterable(request.body) || util.isFormDataLike(request.body))) return true;
7957
8050
  } else {
7958
8051
  return (request.upgrade === "websocket" || request.method === "CONNECT") && session[kRemoteSettings] === false;
7959
8052
  }
@@ -7962,16 +8055,28 @@ var require_client_h2 = __commonJS({
7962
8055
  }
7963
8056
  };
7964
8057
  }
8058
+ function refH2Session(session) {
8059
+ const state = session[kHTTP2SessionState];
8060
+ if (state.refed === false) {
8061
+ state.refed = true;
8062
+ session.ref();
8063
+ }
8064
+ }
8065
+ function unrefH2Session(session) {
8066
+ const state = session[kHTTP2SessionState];
8067
+ if (state.refed === true) {
8068
+ state.refed = false;
8069
+ session.unref();
8070
+ }
8071
+ }
7965
8072
  function resumeH2(client) {
7966
8073
  const socket = client[kSocket];
7967
8074
  const session = client[kHTTP2Session];
7968
8075
  if (socket?.destroyed === false) {
7969
8076
  if (client[kSize] === 0 || client[kMaxConcurrentStreams] === 0) {
7970
- socket.unref();
7971
- session.unref();
8077
+ unrefH2Session(session);
7972
8078
  } else {
7973
- socket.ref();
7974
- session.ref();
8079
+ refH2Session(session);
7975
8080
  }
7976
8081
  if (client[kSize] === 0 && session[kOpenStreams] === 0) {
7977
8082
  setHttp2IdleTimeout(session);
@@ -8056,20 +8161,21 @@ var require_client_h2 = __commonJS({
8056
8161
  function onHttp2SessionError(err) {
8057
8162
  assert(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID");
8058
8163
  this[kSocket][kError] = err;
8164
+ if (this[kReceivedGoAway]) {
8165
+ return;
8166
+ }
8059
8167
  this[kClient][kOnError](err);
8060
8168
  }
8061
8169
  function onHttp2FrameError(type, code, id) {
8062
8170
  if (id === 0) {
8171
+ if (this[kReceivedGoAway]) {
8172
+ return;
8173
+ }
8063
8174
  const err = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`);
8064
8175
  this[kSocket][kError] = err;
8065
8176
  this[kClient][kOnError](err);
8066
8177
  }
8067
8178
  }
8068
- function onHttp2SessionEnd() {
8069
- const err = new SocketError("other side closed", util.getSocketInfo(this[kSocket]));
8070
- this.destroy(err);
8071
- util.destroy(this[kSocket], err);
8072
- }
8073
8179
  function onHttp2SessionGoAway(errorCode, lastStreamID) {
8074
8180
  if (this[kReceivedGoAway]) {
8075
8181
  return;
@@ -8080,10 +8186,11 @@ var require_client_h2 = __commonJS({
8080
8186
  const previousPendingIdx = client[kPendingIdx];
8081
8187
  const pendingIdx = getGoAwayPendingIdx(client, lastStreamID);
8082
8188
  const retriableRequests = [];
8189
+ const streamsToClose = [];
8083
8190
  for (let i = pendingIdx; i < previousPendingIdx; i++) {
8084
8191
  const request = client[kQueue][i];
8085
8192
  if (request != null) {
8086
- closeRequestStream(request);
8193
+ streamsToClose.push(detachRequestStreamForClose(request));
8087
8194
  if (canRetryRequestAfterGoAway(request)) {
8088
8195
  retriableRequests.push(request);
8089
8196
  } else {
@@ -8091,6 +8198,9 @@ var require_client_h2 = __commonJS({
8091
8198
  }
8092
8199
  }
8093
8200
  }
8201
+ for (let i = 0; i < streamsToClose.length; i++) {
8202
+ closeStream(streamsToClose[i]);
8203
+ }
8094
8204
  if (pendingIdx !== previousPendingIdx) {
8095
8205
  const remainingPendingRequests = client[kQueue].slice(previousPendingIdx);
8096
8206
  client[kQueue].length = pendingIdx;
@@ -8156,7 +8266,10 @@ var require_client_h2 = __commonJS({
8156
8266
  function onHttp2SocketError(err) {
8157
8267
  assert(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID");
8158
8268
  this[kError] = err;
8159
- this[kClient][kOnError](err);
8269
+ if (this[kHTTP2Session]?.[kReceivedGoAway]) {
8270
+ return;
8271
+ }
8272
+ this[kHTTP2Session]?.[kClient]?.[kOnError](err);
8160
8273
  }
8161
8274
  function onHttp2SocketEnd() {
8162
8275
  util.destroy(this, new SocketError("other side closed", util.getSocketInfo(this)));
@@ -8171,7 +8284,7 @@ var require_client_h2 = __commonJS({
8171
8284
  stream[kHTTP2Session] = null;
8172
8285
  session[kOpenStreams] -= 1;
8173
8286
  if (session[kOpenStreams] === 0) {
8174
- session.unref();
8287
+ unrefH2Session(session);
8175
8288
  setHttp2IdleTimeout(session);
8176
8289
  }
8177
8290
  }
@@ -8182,17 +8295,16 @@ var require_client_h2 = __commonJS({
8182
8295
  failUpgradeStream(state, new InformationalError("HTTP/2: stream closed before response headers"));
8183
8296
  closeStreamSession(this);
8184
8297
  }
8185
- function onRequestStreamClose() {
8298
+ function completeRequestStream() {
8186
8299
  const state = this[kRequestStreamState];
8187
- if (state) {
8188
- releaseRequestStream(this);
8189
- if (state.pendingEnd && !state.request.aborted && !state.request.completed) {
8190
- state.request.onResponseEnd(state.trailers || {});
8191
- state.finalizeRequest();
8192
- }
8300
+ if (state == null) {
8301
+ return;
8193
8302
  }
8194
- this.off("data", onData);
8195
- this.off("error", noop);
8303
+ releaseRequestStream(this);
8304
+ if (state.pendingEnd && !state.request.aborted && !state.request.completed) {
8305
+ state.request.onResponseEnd(state.trailers || {});
8306
+ }
8307
+ finalizeRequest(state);
8196
8308
  closeStreamSession(this);
8197
8309
  this[kRequestStreamState] = null;
8198
8310
  }
@@ -8286,7 +8398,7 @@ var require_client_h2 = __commonJS({
8286
8398
  }
8287
8399
  removeUpgradeStreamListeners(stream);
8288
8400
  detachRequestFromStream(request);
8289
- state.finalizeRequest();
8401
+ finalizeRequest(state);
8290
8402
  }
8291
8403
  function setupUpgradeStream(stream, state) {
8292
8404
  const { request, headersTimeout, session } = state;
@@ -8304,28 +8416,63 @@ var require_client_h2 = __commonJS({
8304
8416
  ++session[kOpenStreams];
8305
8417
  stream.setTimeout(headersTimeout);
8306
8418
  }
8419
+ function finalizeRequest(state, resetPendingIdx = false) {
8420
+ if (state.requestFinalized) {
8421
+ return;
8422
+ }
8423
+ state.requestFinalized = true;
8424
+ completeRequest(state.client, state.request, resetPendingIdx);
8425
+ state.client[kResume]();
8426
+ }
8427
+ function openStream(client, request, session, abort, headers, options) {
8428
+ try {
8429
+ return session.request(headers, options);
8430
+ } catch (err) {
8431
+ if (err?.code === "ERR_HTTP2_INVALID_SESSION" || err?.code === "ERR_HTTP2_GOAWAY_SESSION") {
8432
+ const wrappedErr2 = new SocketError(err.message, util.getSocketInfo(session[kSocket]));
8433
+ wrappedErr2.cause = err;
8434
+ session[kError] = wrappedErr2;
8435
+ resetHttp2Session(session, wrappedErr2);
8436
+ requeueUnsentRequest(client, request);
8437
+ return null;
8438
+ }
8439
+ const wrappedErr = new InformationalError(err.message, { cause: err });
8440
+ session[kError] = wrappedErr;
8441
+ session[kSocket][kError] = wrappedErr;
8442
+ session.destroy(wrappedErr);
8443
+ util.destroy(session[kSocket], wrappedErr);
8444
+ abort(wrappedErr);
8445
+ return null;
8446
+ }
8447
+ }
8307
8448
  function writeH2(client, request) {
8308
8449
  const headersTimeout = request.headersTimeout ?? client[kHeadersTimeout];
8309
8450
  const bodyTimeout = request.bodyTimeout ?? client[kBodyTimeout];
8310
8451
  const session = client[kHTTP2Session];
8311
8452
  const { method, path, host, upgrade, expectContinue, signal, protocol, headers: reqHeaders } = request;
8312
- let { body } = request;
8313
8453
  if (upgrade != null && upgrade !== "websocket") {
8314
8454
  util.errorRequest(client, request, new InvalidArgumentError(`Custom upgrade "${upgrade}" not supported over HTTP/2`));
8315
8455
  return false;
8316
8456
  }
8317
8457
  const headers = buildRequestHeaders(reqHeaders);
8318
- let stream = null;
8319
8458
  headers[HTTP2_HEADER_AUTHORITY] = host || client[kHostAuthority];
8320
8459
  headers[HTTP2_HEADER_METHOD] = method;
8321
- let requestFinalized = false;
8322
- const finalizeRequest = (resetPendingIdx = false) => {
8323
- if (requestFinalized) {
8324
- return;
8325
- }
8326
- requestFinalized = true;
8327
- completeRequest(client, request, resetPendingIdx);
8328
- client[kResume]();
8460
+ const state = {
8461
+ abort: null,
8462
+ body: request.body,
8463
+ client,
8464
+ contentLength: null,
8465
+ expectsPayload: false,
8466
+ request,
8467
+ headersTimeout,
8468
+ bodyTimeout,
8469
+ requestFinalized: false,
8470
+ responseReceived: false,
8471
+ bodySent: false,
8472
+ pendingEnd: false,
8473
+ trailers: null,
8474
+ session,
8475
+ stream: null
8329
8476
  };
8330
8477
  const abort = (err, resetPendingIdx = false) => {
8331
8478
  if (request.aborted || request.completed) {
@@ -8333,35 +8480,20 @@ var require_client_h2 = __commonJS({
8333
8480
  }
8334
8481
  err = err || new RequestAbortedError();
8335
8482
  util.errorRequest(client, request, err);
8336
- if (stream != null) {
8483
+ if (state.stream != null) {
8337
8484
  clearRequestStream(request);
8338
- stream.close();
8485
+ const stream2 = state.stream;
8486
+ stream2.close();
8487
+ if (!stream2.destroyed) {
8488
+ util.destroy(stream2);
8489
+ }
8339
8490
  client[kOnError](err);
8340
- finalizeRequest(resetPendingIdx);
8341
- }
8342
- util.destroy(body, err);
8343
- };
8344
- const requestStream = (headers2, options) => {
8345
- try {
8346
- return session.request(headers2, options);
8347
- } catch (err) {
8348
- if (err?.code === "ERR_HTTP2_INVALID_SESSION") {
8349
- const wrappedErr2 = new SocketError(err.message, util.getSocketInfo(session[kSocket]));
8350
- wrappedErr2.cause = err;
8351
- session[kError] = wrappedErr2;
8352
- resetHttp2Session(session, wrappedErr2);
8353
- requeueUnsentRequest(client, request);
8354
- return null;
8355
- }
8356
- const wrappedErr = new InformationalError(err.message, { cause: err });
8357
- session[kError] = wrappedErr;
8358
- session[kSocket][kError] = wrappedErr;
8359
- session.destroy(wrappedErr);
8360
- util.destroy(session[kSocket], wrappedErr);
8361
- abort(wrappedErr);
8362
- return null;
8491
+ finalizeRequest(state, resetPendingIdx);
8363
8492
  }
8493
+ util.destroy(state.body, err);
8364
8494
  };
8495
+ state.abort = abort;
8496
+ let stream = null;
8365
8497
  try {
8366
8498
  request.onRequestStart(abort, null);
8367
8499
  } catch (err) {
@@ -8371,21 +8503,11 @@ var require_client_h2 = __commonJS({
8371
8503
  return false;
8372
8504
  }
8373
8505
  if (upgrade || method === "CONNECT") {
8374
- session.ref();
8375
- const upgradeState = {
8376
- abort,
8377
- finalizeRequest,
8378
- request,
8379
- headersTimeout,
8380
- bodyTimeout,
8381
- responseReceived: false,
8382
- session,
8383
- stream: null
8384
- };
8506
+ refH2Session(session);
8385
8507
  if (upgrade === "websocket") {
8386
8508
  if (session[kEnableConnectProtocol] === false) {
8387
8509
  util.errorRequest(client, request, new InformationalError("HTTP/2: Extended CONNECT protocol not supported by server"));
8388
- session.unref();
8510
+ unrefH2Session(session);
8389
8511
  return false;
8390
8512
  }
8391
8513
  headers[HTTP2_HEADER_METHOD] = "CONNECT";
@@ -8396,25 +8518,26 @@ var require_client_h2 = __commonJS({
8396
8518
  } else {
8397
8519
  headers[HTTP2_HEADER_SCHEME] = protocol === "http:" ? "http" : "https";
8398
8520
  }
8399
- stream = requestStream(headers, { endStream: false, signal });
8521
+ stream = openStream(client, request, session, abort, headers, { endStream: false, signal });
8400
8522
  if (stream == null) {
8401
- session.unref();
8523
+ unrefH2Session(session);
8402
8524
  return false;
8403
8525
  }
8404
- setupUpgradeStream(stream, upgradeState);
8526
+ setupUpgradeStream(stream, state);
8405
8527
  return true;
8406
8528
  }
8407
- stream = requestStream(headers, { endStream: false, signal });
8529
+ stream = openStream(client, request, session, abort, headers, { endStream: false, signal });
8408
8530
  if (stream == null) {
8409
- session.unref();
8531
+ unrefH2Session(session);
8410
8532
  return false;
8411
8533
  }
8412
- setupUpgradeStream(stream, upgradeState);
8534
+ setupUpgradeStream(stream, state);
8413
8535
  return true;
8414
8536
  }
8415
8537
  headers[HTTP2_HEADER_PATH] = path;
8416
8538
  headers[HTTP2_HEADER_SCHEME] = protocol === "http:" ? "http" : "https";
8417
8539
  const expectsPayload = method === "PUT" || method === "POST" || method === "PATCH" || method === "QUERY" || method === "PROPFIND" || method === "PROPPATCH";
8540
+ let body = state.body;
8418
8541
  if (body && typeof body.read === "function") {
8419
8542
  body.read(0);
8420
8543
  }
@@ -8443,7 +8566,7 @@ var require_client_h2 = __commonJS({
8443
8566
  assert(body || contentLength === 0, "no body must not have content length");
8444
8567
  headers[HTTP2_HEADER_CONTENT_LENGTH] = `${contentLength}`;
8445
8568
  }
8446
- session.ref();
8569
+ refH2Session(session);
8447
8570
  if (channels.sendHeaders.hasSubscribers) {
8448
8571
  let header = "";
8449
8572
  for (const key in headers) {
@@ -8453,24 +8576,13 @@ var require_client_h2 = __commonJS({
8453
8576
  channels.sendHeaders.publish({ request, headers: header, socket: session[kSocket] });
8454
8577
  }
8455
8578
  const shouldEndStream = body === null || contentLength === 0;
8456
- const state = {
8457
- abort,
8458
- body,
8459
- client,
8460
- contentLength,
8461
- expectsPayload,
8462
- finalizeRequest,
8463
- request,
8464
- headersTimeout,
8465
- bodyTimeout,
8466
- responseReceived: false,
8467
- session,
8468
- stream: null
8469
- };
8579
+ state.body = body;
8580
+ state.contentLength = contentLength;
8581
+ state.expectsPayload = expectsPayload;
8470
8582
  if (expectContinue) {
8471
8583
  headers[HTTP2_HEADER_EXPECT] = "100-continue";
8472
8584
  }
8473
- stream = requestStream(headers, { endStream: shouldEndStream, signal });
8585
+ stream = openStream(client, request, session, abort, headers, { endStream: shouldEndStream, signal });
8474
8586
  if (stream == null) {
8475
8587
  return false;
8476
8588
  }
@@ -8479,20 +8591,24 @@ var require_client_h2 = __commonJS({
8479
8591
  state.stream = stream;
8480
8592
  clearHttp2IdleTimeout(session);
8481
8593
  ++session[kOpenStreams];
8482
- stream.setTimeout(headersTimeout);
8594
+ if (headersTimeout) {
8595
+ stream.setTimeout(headersTimeout);
8596
+ }
8483
8597
  stream[kHTTP2Session] = session;
8484
- stream.once("close", onRequestStreamClose);
8598
+ stream.on("close", completeRequestStream);
8485
8599
  bindRequestToStream(request, stream, releaseRequestStream);
8486
8600
  if (expectContinue) {
8487
8601
  stream.once("continue", writeBodyH2);
8488
8602
  }
8489
- stream.once("response", onResponse);
8490
- stream.once("end", onEnd);
8491
- stream.once("error", onError);
8492
- stream.once("frameError", onFrameError);
8603
+ stream.on("response", onResponse);
8604
+ stream.on("end", onEnd);
8605
+ stream.on("error", onError);
8606
+ stream.on("frameError", onFrameError);
8493
8607
  stream.on("aborted", onAborted);
8494
- stream.on("timeout", onTimeout);
8495
- stream.once("trailers", onTrailers);
8608
+ if (headersTimeout || bodyTimeout) {
8609
+ stream.on("timeout", onTimeout);
8610
+ }
8611
+ stream.on("trailers", onTrailers);
8496
8612
  if (!expectContinue) {
8497
8613
  writeBodyH2.call(stream);
8498
8614
  }
@@ -8522,14 +8638,18 @@ var require_client_h2 = __commonJS({
8522
8638
  if (request[kRequestStream] === stream) {
8523
8639
  detachRequestFromStream(request);
8524
8640
  }
8525
- removeRequestStreamListeners(stream);
8526
8641
  if (!stream.destroyed && !stream.closed) {
8642
+ removeRequestStreamListeners(stream);
8527
8643
  stream.once("error", noop);
8528
8644
  }
8529
8645
  }
8530
8646
  function onData(chunk) {
8531
8647
  const stream = this;
8532
- const { request } = stream[kRequestStreamState];
8648
+ const state = stream[kRequestStreamState];
8649
+ if (state == null) {
8650
+ return;
8651
+ }
8652
+ const { request } = state;
8533
8653
  if (request.aborted || request.completed) {
8534
8654
  return;
8535
8655
  }
@@ -8540,14 +8660,23 @@ var require_client_h2 = __commonJS({
8540
8660
  function onResponse(headers) {
8541
8661
  const stream = this;
8542
8662
  const state = stream[kRequestStreamState];
8663
+ if (state == null) {
8664
+ return;
8665
+ }
8543
8666
  const { request } = state;
8544
8667
  stream.off("response", onResponse);
8668
+ if (state.body != null && !state.bodySent && !stream.writableEnded) {
8669
+ stream.removeListener("continue", writeBodyH2);
8670
+ stream.end();
8671
+ }
8545
8672
  const statusCode = headers[HTTP2_HEADER_STATUS];
8546
8673
  delete headers[HTTP2_HEADER_STATUS];
8547
8674
  request.onResponseStarted();
8548
8675
  state.responseReceived = true;
8549
- stream.setTimeout(state.bodyTimeout);
8550
- if (request.aborted) {
8676
+ if (state.headersTimeout || state.bodyTimeout) {
8677
+ stream.setTimeout(state.bodyTimeout);
8678
+ }
8679
+ if (request.aborted || request.completed) {
8551
8680
  releaseRequestStream(stream);
8552
8681
  return;
8553
8682
  }
@@ -8559,11 +8688,15 @@ var require_client_h2 = __commonJS({
8559
8688
  function onEnd() {
8560
8689
  const stream = this;
8561
8690
  const state = stream[kRequestStreamState];
8691
+ if (state == null) {
8692
+ return;
8693
+ }
8562
8694
  const { request } = state;
8563
8695
  stream.off("end", onEnd);
8564
8696
  if (state.responseReceived) {
8565
8697
  if (!request.aborted && !request.completed) {
8566
8698
  state.pendingEnd = true;
8699
+ completeRequestStream.call(stream);
8567
8700
  }
8568
8701
  } else {
8569
8702
  state.abort(new InformationalError("HTTP/2: stream half-closed (remote)"), true);
@@ -8572,12 +8705,18 @@ var require_client_h2 = __commonJS({
8572
8705
  function onError(err) {
8573
8706
  const stream = this;
8574
8707
  const state = stream[kRequestStreamState];
8708
+ if (state == null) {
8709
+ return;
8710
+ }
8575
8711
  stream.off("error", onError);
8576
8712
  state.abort(err);
8577
8713
  }
8578
8714
  function onFrameError(type, code) {
8579
8715
  const stream = this;
8580
8716
  const state = stream[kRequestStreamState];
8717
+ if (state == null) {
8718
+ return;
8719
+ }
8581
8720
  stream.off("frameError", onFrameError);
8582
8721
  state.abort(new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`));
8583
8722
  }
@@ -8587,6 +8726,9 @@ var require_client_h2 = __commonJS({
8587
8726
  function onTimeout() {
8588
8727
  const stream = this;
8589
8728
  const state = stream[kRequestStreamState];
8729
+ if (state == null) {
8730
+ return;
8731
+ }
8590
8732
  stream.off("timeout", onTimeout);
8591
8733
  const err = state.responseReceived ? new BodyTimeoutError(`HTTP/2: "stream timeout after ${state.bodyTimeout}"`) : new HeadersTimeoutError(`HTTP/2: "headers timeout after ${state.headersTimeout}"`);
8592
8734
  state.abort(err);
@@ -8594,6 +8736,9 @@ var require_client_h2 = __commonJS({
8594
8736
  function onTrailers(trailers) {
8595
8737
  const stream = this;
8596
8738
  const state = stream[kRequestStreamState];
8739
+ if (state == null) {
8740
+ return;
8741
+ }
8597
8742
  const { request } = state;
8598
8743
  stream.off("trailers", onTrailers);
8599
8744
  stream.off("data", onData);
@@ -8605,6 +8750,7 @@ var require_client_h2 = __commonJS({
8605
8750
  function writeBodyH2() {
8606
8751
  const stream = this;
8607
8752
  const state = stream[kRequestStreamState];
8753
+ state.bodySent = true;
8608
8754
  const { abort, body, client, contentLength, expectsPayload, request } = state;
8609
8755
  if (!body || contentLength === 0) {
8610
8756
  writeBuffer(
@@ -10081,14 +10227,14 @@ var require_agent = __commonJS({
10081
10227
  dispatcher.close();
10082
10228
  }
10083
10229
  let hasOrigin = false;
10084
- for (const client of this[kClients].values()) {
10085
- if (client[kUrl].origin === dispatcher[kUrl].origin) {
10230
+ for (const k of this[kClients].keys()) {
10231
+ if (k === origin || k === `${origin}#http1-only`) {
10086
10232
  hasOrigin = true;
10087
10233
  break;
10088
10234
  }
10089
10235
  }
10090
10236
  if (!hasOrigin) {
10091
- this[kOrigins].delete(dispatcher[kUrl].origin);
10237
+ this[kOrigins].delete(origin);
10092
10238
  }
10093
10239
  };
10094
10240
  dispatcher.on("drain", this[kOnDrain]).on("connect", this[kOnConnect]).on("disconnect", (origin2, targets, err) => {
@@ -10923,7 +11069,7 @@ var require_proxy_agent = __commonJS({
10923
11069
  var Agent = require_agent();
10924
11070
  var Pool = require_pool();
10925
11071
  var DispatcherBase = require_dispatcher_base();
10926
- var { InvalidArgumentError, RequestAbortedError, SecureProxyConnectionError } = require_errors();
11072
+ var { InvalidArgumentError, RequestAbortedError, SecureProxyConnectionError, ProxyConnectionError } = require_errors();
10927
11073
  var buildConnector = require_connect();
10928
11074
  var Client = require_client();
10929
11075
  var { channels } = require_diagnostics();
@@ -10951,14 +11097,19 @@ var require_proxy_agent = __commonJS({
10951
11097
  }
10952
11098
  return new Pool(origin, opts);
10953
11099
  }
11100
+ function shouldProxyTunnel(requestProtocol, proxyTunnel) {
11101
+ return proxyTunnel === true || requestProtocol !== "http:";
11102
+ }
10954
11103
  var Http1ProxyWrapper = class extends DispatcherBase {
10955
11104
  #client;
10956
- constructor(proxyUrl, { headers = {}, connect, factory }) {
11105
+ #proxyServername;
11106
+ constructor(proxyUrl, { headers = {}, connect, factory, proxyServername }) {
10957
11107
  if (!proxyUrl) {
10958
11108
  throw new InvalidArgumentError("Proxy URL is mandatory");
10959
11109
  }
10960
11110
  super();
10961
11111
  this[kProxyHeaders] = headers;
11112
+ this.#proxyServername = proxyServername;
10962
11113
  if (factory) {
10963
11114
  this.#client = factory(proxyUrl, { connect });
10964
11115
  } else {
@@ -10987,6 +11138,9 @@ var require_proxy_agent = __commonJS({
10987
11138
  headers.host = host;
10988
11139
  }
10989
11140
  opts.headers = { ...this[kProxyHeaders], ...headers };
11141
+ if (this.#proxyServername != null) {
11142
+ opts.servername = this.#proxyServername;
11143
+ }
10990
11144
  return this.#client[kDispatch](opts, handler);
10991
11145
  }
10992
11146
  [kClose]() {
@@ -11005,7 +11159,7 @@ var require_proxy_agent = __commonJS({
11005
11159
  if (typeof clientFactory !== "function") {
11006
11160
  throw new InvalidArgumentError("Proxy opts.clientFactory must be a function.");
11007
11161
  }
11008
- const { proxyTunnel = true, connectTimeout } = opts;
11162
+ const { proxyTunnel, connectTimeout } = opts;
11009
11163
  super();
11010
11164
  const url = this.#getUrl(opts);
11011
11165
  const { href, origin, port, protocol, username, password, hostname: proxyHostname } = url;
@@ -11026,6 +11180,7 @@ var require_proxy_agent = __commonJS({
11026
11180
  this[kProxyHeaders]["proxy-authorization"] = `Basic ${Buffer.from(`${decodeURIComponent(username)}:`).toString("base64")}`;
11027
11181
  }
11028
11182
  const connect = buildConnector({ timeout: connectTimeout, ...opts.proxyTls });
11183
+ const connectHTTP1 = buildConnector({ timeout: connectTimeout, ...opts.proxyTls, allowH2: false });
11029
11184
  this[kConnectEndpoint] = buildConnector({ timeout: connectTimeout, ...opts.requestTls });
11030
11185
  this[kConnectEndpointHTTP1] = buildConnector({ timeout: connectTimeout, ...opts.requestTls, allowH2: false });
11031
11186
  const agentFactory = opts.factory || defaultAgentFactory;
@@ -11042,11 +11197,19 @@ var require_proxy_agent = __commonJS({
11042
11197
  requestTls: opts.requestTls
11043
11198
  });
11044
11199
  }
11045
- if (!this[kTunnelProxy] && protocol2 === "http:" && this[kProxy].protocol === "http:") {
11200
+ if (!shouldProxyTunnel(protocol2, this[kTunnelProxy])) {
11201
+ const forwardConnect = this[kProxy].protocol === "https:" ? (opts2, cb) => connectHTTP1(opts2, (err, socket) => {
11202
+ if (err && err.code === "ERR_TLS_CERT_ALTNAME_INVALID") {
11203
+ cb(new SecureProxyConnectionError(err));
11204
+ } else {
11205
+ cb(err, socket);
11206
+ }
11207
+ }) : connectHTTP1;
11046
11208
  return new Http1ProxyWrapper(this[kProxy].uri, {
11047
11209
  headers: this[kProxyHeaders],
11048
- connect,
11049
- factory: agentFactory
11210
+ connect: forwardConnect,
11211
+ factory: agentFactory,
11212
+ proxyServername: this[kProxy].protocol === "https:" ? this[kProxyTls]?.servername || proxyHostname : void 0
11050
11213
  });
11051
11214
  }
11052
11215
  return agentFactory(origin2, options);
@@ -11108,6 +11271,8 @@ var require_proxy_agent = __commonJS({
11108
11271
  } catch (err) {
11109
11272
  if (err.code === "ERR_TLS_CERT_ALTNAME_INVALID") {
11110
11273
  callback(new SecureProxyConnectionError(err));
11274
+ } else if (err.code === "UND_ERR_SOCKET") {
11275
+ callback(new ProxyConnectionError(err));
11111
11276
  } else {
11112
11277
  callback(err);
11113
11278
  }
@@ -11325,8 +11490,54 @@ var require_retry_handler = __commonJS({
11325
11490
  } = require_util();
11326
11491
  function calculateRetryAfterHeader(retryAfter) {
11327
11492
  const retryTime = new Date(retryAfter).getTime();
11328
- return isNaN(retryTime) ? 0 : retryTime - Date.now();
11493
+ return isNaN(retryTime) ? null : retryTime - Date.now();
11494
+ }
11495
+ function validatePartialResponseContentLength(headers, range, statusCode, retryCount) {
11496
+ const contentLength = headers["content-length"];
11497
+ if (contentLength == null) {
11498
+ return;
11499
+ }
11500
+ if (!Number.isFinite(range.start) || !Number.isFinite(range.end)) {
11501
+ return;
11502
+ }
11503
+ const length = Number(contentLength);
11504
+ const expectedLength = range.end - range.start + 1;
11505
+ if (!Number.isFinite(length) || length !== expectedLength) {
11506
+ throw new RequestRetryError("Content-Length mismatch", statusCode, {
11507
+ headers,
11508
+ data: { count: retryCount }
11509
+ });
11510
+ }
11329
11511
  }
11512
+ var RetryController = class {
11513
+ constructor() {
11514
+ this.target = null;
11515
+ }
11516
+ pause() {
11517
+ this.target?.pause();
11518
+ }
11519
+ resume() {
11520
+ this.target?.resume();
11521
+ }
11522
+ abort(reason) {
11523
+ this.target?.abort(reason);
11524
+ }
11525
+ get paused() {
11526
+ return this.target?.paused ?? false;
11527
+ }
11528
+ get aborted() {
11529
+ return this.target?.aborted ?? false;
11530
+ }
11531
+ get reason() {
11532
+ return this.target?.reason ?? null;
11533
+ }
11534
+ get rawHeaders() {
11535
+ return this.target?.rawHeaders ?? null;
11536
+ }
11537
+ get rawTrailers() {
11538
+ return this.target?.rawTrailers ?? null;
11539
+ }
11540
+ };
11330
11541
  var RetryHandler = class _RetryHandler {
11331
11542
  constructor(opts, { dispatch, handler }) {
11332
11543
  const { retryOptions, ...dispatchOpts } = opts;
@@ -11359,7 +11570,7 @@ var require_retry_handler = __commonJS({
11359
11570
  timeoutFactor: timeoutFactor ?? 2,
11360
11571
  maxRetries: maxRetries ?? 5,
11361
11572
  // What errors we should retry
11362
- methods: methods ?? ["GET", "HEAD", "OPTIONS", "PUT", "DELETE", "TRACE"],
11573
+ methods: methods ?? ["GET", "HEAD", "OPTIONS", "PUT", "DELETE", "TRACE", "QUERY"],
11363
11574
  // Indicates which errors to retry
11364
11575
  statusCodes: statusCodes ?? [500, 502, 503, 504, 429],
11365
11576
  // List of errors to retry
@@ -11383,12 +11594,13 @@ var require_retry_handler = __commonJS({
11383
11594
  this.etag = null;
11384
11595
  this.statusCode = null;
11385
11596
  this.headers = null;
11597
+ this.controllerProxy = new RetryController();
11386
11598
  }
11387
11599
  onResponseStartWithRetry(controller, statusCode, headers, statusMessage, err) {
11388
11600
  if (this.retryOpts.throwOnError) {
11389
11601
  if (this.retryOpts.statusCodes.includes(statusCode) === false) {
11390
11602
  this.headersSent = true;
11391
- this.handler.onResponseStart?.(controller, statusCode, headers, statusMessage);
11603
+ this.handler.onResponseStart?.(this.controllerProxy, statusCode, headers, statusMessage);
11392
11604
  } else {
11393
11605
  this.error = err;
11394
11606
  }
@@ -11396,13 +11608,13 @@ var require_retry_handler = __commonJS({
11396
11608
  }
11397
11609
  if (isDisturbed(this.opts.body)) {
11398
11610
  this.headersSent = true;
11399
- this.handler.onResponseStart?.(controller, statusCode, headers, statusMessage);
11611
+ this.handler.onResponseStart?.(this.controllerProxy, statusCode, headers, statusMessage);
11400
11612
  return;
11401
11613
  }
11402
11614
  function shouldRetry(passedErr) {
11403
11615
  if (passedErr) {
11404
11616
  this.headersSent = true;
11405
- this.handler.onResponseStart?.(controller, statusCode, headers, statusMessage);
11617
+ this.handler.onResponseStart?.(this.controllerProxy, statusCode, headers, statusMessage);
11406
11618
  controller.resume();
11407
11619
  return;
11408
11620
  }
@@ -11420,12 +11632,13 @@ var require_retry_handler = __commonJS({
11420
11632
  );
11421
11633
  }
11422
11634
  onRequestStart(controller, context) {
11635
+ this.controllerProxy.target = controller;
11423
11636
  if (!this.headersSent) {
11424
- this.handler.onRequestStart?.(controller, context);
11637
+ this.handler.onRequestStart?.(this.controllerProxy, context);
11425
11638
  }
11426
11639
  }
11427
- onRequestUpgrade(controller, statusCode, headers, socket) {
11428
- this.handler.onRequestUpgrade?.(controller, statusCode, headers, socket);
11640
+ onRequestUpgrade(_controller, statusCode, headers, socket) {
11641
+ this.handler.onRequestUpgrade?.(this.controllerProxy, statusCode, headers, socket);
11429
11642
  }
11430
11643
  static [kRetryHandlerDefaultRetry](err, { state, opts }, cb) {
11431
11644
  const { statusCode, code, headers } = err;
@@ -11461,7 +11674,7 @@ var require_retry_handler = __commonJS({
11461
11674
  retryAfterHeader = Number(retryAfterHeader);
11462
11675
  retryAfterHeader = Number.isNaN(retryAfterHeader) ? calculateRetryAfterHeader(headers["retry-after"]) : retryAfterHeader * 1e3;
11463
11676
  }
11464
- const retryTimeout = retryAfterHeader > 0 ? Math.min(retryAfterHeader, maxTimeout) : Math.min(minTimeout * timeoutFactor ** (counter - 1), maxTimeout);
11677
+ const retryTimeout = retryAfterHeader === 0 ? 0 : retryAfterHeader > 0 ? Math.min(retryAfterHeader, maxTimeout) : Math.min(minTimeout * timeoutFactor ** (counter - 1), maxTimeout);
11465
11678
  setTimeout(() => cb(null), retryTimeout);
11466
11679
  }
11467
11680
  onResponseStart(controller, statusCode, headers, statusMessage) {
@@ -11499,6 +11712,7 @@ var require_retry_handler = __commonJS({
11499
11712
  data: { count: this.retryCount }
11500
11713
  });
11501
11714
  }
11715
+ validatePartialResponseContentLength(headers, contentRange, statusCode, this.retryCount);
11502
11716
  const { start, size, end = size ? size - 1 : null } = contentRange;
11503
11717
  assert(this.start === start, "content-range mismatch");
11504
11718
  assert(this.end == null || this.end === end, "content-range mismatch");
@@ -11510,13 +11724,14 @@ var require_retry_handler = __commonJS({
11510
11724
  if (range == null) {
11511
11725
  this.headersSent = true;
11512
11726
  this.handler.onResponseStart?.(
11513
- controller,
11727
+ this.controllerProxy,
11514
11728
  statusCode,
11515
11729
  headers,
11516
11730
  statusMessage
11517
11731
  );
11518
11732
  return;
11519
11733
  }
11734
+ validatePartialResponseContentLength(headers, range, statusCode, this.retryCount);
11520
11735
  const { start, size, end = size ? size - 1 : null } = range;
11521
11736
  assert(
11522
11737
  start != null && Number.isFinite(start),
@@ -11542,7 +11757,7 @@ var require_retry_handler = __commonJS({
11542
11757
  }
11543
11758
  this.headersSent = true;
11544
11759
  this.handler.onResponseStart?.(
11545
- controller,
11760
+ this.controllerProxy,
11546
11761
  statusCode,
11547
11762
  headers,
11548
11763
  statusMessage
@@ -11554,14 +11769,14 @@ var require_retry_handler = __commonJS({
11554
11769
  });
11555
11770
  }
11556
11771
  }
11557
- onResponseData(controller, chunk) {
11772
+ onResponseData(_controller, chunk) {
11558
11773
  if (this.error) {
11559
11774
  return;
11560
11775
  }
11561
11776
  this.start += chunk.length;
11562
- this.handler.onResponseData?.(controller, chunk);
11777
+ this.handler.onResponseData?.(this.controllerProxy, chunk);
11563
11778
  }
11564
- onResponseEnd(controller, trailers) {
11779
+ onResponseEnd(_controller, trailers) {
11565
11780
  if (this.error && this.retryOpts.throwOnError) {
11566
11781
  throw this.error;
11567
11782
  }
@@ -11575,11 +11790,11 @@ var require_retry_handler = __commonJS({
11575
11790
  }
11576
11791
  }
11577
11792
  this.retryCount = 0;
11578
- return this.handler.onResponseEnd?.(controller, trailers);
11793
+ return this.handler.onResponseEnd?.(this.controllerProxy, trailers);
11579
11794
  }
11580
- this.retry(controller);
11795
+ this.retry();
11581
11796
  }
11582
- retry(controller) {
11797
+ retry() {
11583
11798
  if (this.start !== 0) {
11584
11799
  const headers = { range: `bytes=${this.start}-${this.end ?? ""}` };
11585
11800
  if (this.etag != null) {
@@ -11597,20 +11812,20 @@ var require_retry_handler = __commonJS({
11597
11812
  this.retryCountCheckpoint = this.retryCount;
11598
11813
  this.dispatch(this.opts, this);
11599
11814
  } catch (err) {
11600
- this.handler.onResponseError?.(controller, err);
11815
+ this.handler.onResponseError?.(this.controllerProxy, err);
11601
11816
  }
11602
11817
  }
11603
11818
  onResponseError(controller, err) {
11604
11819
  if (controller?.aborted || isDisturbed(this.opts.body)) {
11605
- this.handler.onResponseError?.(controller, err);
11820
+ this.handler.onResponseError?.(this.controllerProxy, err);
11606
11821
  return;
11607
11822
  }
11608
11823
  function shouldRetry(returnedErr) {
11609
11824
  if (!returnedErr) {
11610
- this.retry(controller);
11825
+ this.retry();
11611
11826
  return;
11612
11827
  }
11613
- this.handler?.onResponseError?.(controller, returnedErr);
11828
+ this.handler?.onResponseError?.(this.controllerProxy, returnedErr);
11614
11829
  }
11615
11830
  if (this.retryCount - this.retryCountCheckpoint > 0) {
11616
11831
  this.retryCount = this.retryCountCheckpoint + (this.retryCount - this.retryCountCheckpoint);
@@ -11727,6 +11942,7 @@ var require_readable = __commonJS({
11727
11942
  var kContentLength = /* @__PURE__ */ Symbol("kContentLength");
11728
11943
  var kUsed = /* @__PURE__ */ Symbol("kUsed");
11729
11944
  var kBytesRead = /* @__PURE__ */ Symbol("kBytesRead");
11945
+ var kPreservedBuffer = /* @__PURE__ */ Symbol("kPreservedBuffer");
11730
11946
  var noop = () => {
11731
11947
  };
11732
11948
  var BodyReadable = class extends Readable {
@@ -11965,7 +12181,22 @@ var require_readable = __commonJS({
11965
12181
  */
11966
12182
  setEncoding(encoding) {
11967
12183
  if (Buffer.isEncoding(encoding)) {
11968
- this._readableState.encoding = encoding;
12184
+ const state = this._readableState;
12185
+ const buffer = state.buffer;
12186
+ if (buffer && state.length > 0) {
12187
+ const bufferIndex = state.bufferIndex ?? 0;
12188
+ const preserved = [];
12189
+ const source = typeof buffer.slice === "function" ? buffer.slice(bufferIndex) : buffer;
12190
+ for (const data of source) {
12191
+ if (Buffer.isBuffer(data)) {
12192
+ preserved.push(data);
12193
+ }
12194
+ }
12195
+ if (preserved.length > 0) {
12196
+ this[kPreservedBuffer] = (this[kPreservedBuffer] || []).concat(preserved);
12197
+ }
12198
+ }
12199
+ super.setEncoding(encoding);
11969
12200
  }
11970
12201
  return this;
11971
12202
  }
@@ -12015,7 +12246,13 @@ var require_readable = __commonJS({
12015
12246
  return;
12016
12247
  }
12017
12248
  const { _readableState: state } = consume2.stream;
12018
- if (state.bufferIndex) {
12249
+ const preserved = consume2.stream[kPreservedBuffer];
12250
+ if (preserved && preserved.length > 0) {
12251
+ for (const chunk of preserved) {
12252
+ consumePush(consume2, chunk);
12253
+ }
12254
+ consume2.stream[kPreservedBuffer] = null;
12255
+ } else if (state.bufferIndex) {
12019
12256
  const start = state.bufferIndex;
12020
12257
  const end = state.buffer.length;
12021
12258
  for (let n = start; n < end; n++) {
@@ -12086,6 +12323,9 @@ var require_readable = __commonJS({
12086
12323
  }
12087
12324
  }
12088
12325
  function consumePush(consume2, chunk) {
12326
+ if (consume2.body === null) {
12327
+ return;
12328
+ }
12089
12329
  consume2.length += chunk.length;
12090
12330
  consume2.body.push(chunk);
12091
12331
  }
@@ -12172,7 +12412,9 @@ var require_api_request = __commonJS({
12172
12412
  this.removeAbortListener = util.addAbortListener(signal, () => {
12173
12413
  this.reason = signal.reason ?? new RequestAbortedError();
12174
12414
  if (this.res) {
12175
- util.destroy(this.res.on("error", noop), this.reason);
12415
+ const res = this.res;
12416
+ this.res = null;
12417
+ util.destroy(res.on("error", noop), this.reason);
12176
12418
  } else if (this.abort) {
12177
12419
  this.abort(this.reason);
12178
12420
  }
@@ -13281,16 +13523,34 @@ var require_mock_utils = __commonJS({
13281
13523
  function mockDispatch(opts, handler) {
13282
13524
  const key = buildKey(opts);
13283
13525
  const mockDispatch2 = getMockDispatch(this[kDispatches], key);
13526
+ const mockDispatches = this[kDispatches];
13284
13527
  mockDispatch2.timesInvoked++;
13285
- if (mockDispatch2.data.callback) {
13286
- mockDispatch2.data = { ...mockDispatch2.data, ...mockDispatch2.data.callback(opts) };
13287
- }
13288
- const { data: { statusCode, data, headers, trailers, error }, delay, persist } = mockDispatch2;
13289
13528
  const { timesInvoked, times } = mockDispatch2;
13290
- mockDispatch2.consumed = !persist && timesInvoked >= times;
13529
+ mockDispatch2.consumed = !mockDispatch2.persist && timesInvoked >= times;
13291
13530
  mockDispatch2.pending = timesInvoked < times;
13531
+ if (mockDispatch2.data.callback) {
13532
+ const callbackResult = mockDispatch2.data.callback(opts);
13533
+ if (isPromise(callbackResult)) {
13534
+ callbackResult.then(
13535
+ (resolvedData) => {
13536
+ mockDispatch2.data = { ...mockDispatch2.data, ...resolvedData };
13537
+ dispatchMockReply(mockDispatches, mockDispatch2, key, opts, handler);
13538
+ },
13539
+ (error) => {
13540
+ deleteMockDispatch(mockDispatches, key);
13541
+ handler.onResponseError(null, error);
13542
+ }
13543
+ );
13544
+ return true;
13545
+ }
13546
+ mockDispatch2.data = { ...mockDispatch2.data, ...callbackResult };
13547
+ }
13548
+ return dispatchMockReply(mockDispatches, mockDispatch2, key, opts, handler);
13549
+ }
13550
+ function dispatchMockReply(mockDispatches, mockDispatch2, key, opts, handler) {
13551
+ const { data: { statusCode, data, headers, trailers, error }, delay } = mockDispatch2;
13292
13552
  if (error !== null) {
13293
- deleteMockDispatch(this[kDispatches], key);
13553
+ deleteMockDispatch(mockDispatches, key);
13294
13554
  handler.onResponseError(null, error);
13295
13555
  return true;
13296
13556
  }
@@ -13322,19 +13582,19 @@ var require_mock_utils = __commonJS({
13322
13582
  if (typeof delay === "number" && delay > 0) {
13323
13583
  timer = setTimeout(() => {
13324
13584
  timer = null;
13325
- handleReply(this[kDispatches]);
13585
+ handleReply(mockDispatches);
13326
13586
  }, delay);
13327
13587
  } else {
13328
- handleReply(this[kDispatches]);
13588
+ handleReply(mockDispatches);
13329
13589
  }
13330
- function handleReply(mockDispatches, _data = data) {
13590
+ function handleReply(mockDispatches2, _data = data) {
13331
13591
  if (aborted) {
13332
13592
  return;
13333
13593
  }
13334
13594
  const optsHeaders = Array.isArray(opts.headers) ? buildHeadersFromArray(opts.headers) : opts.headers;
13335
13595
  const body = typeof _data === "function" ? _data({ ...opts, headers: optsHeaders }) : _data;
13336
13596
  if (isPromise(body)) {
13337
- return body.then((newData) => handleReply(mockDispatches, newData));
13597
+ return body.then((newData) => handleReply(mockDispatches2, newData));
13338
13598
  }
13339
13599
  if (aborted) {
13340
13600
  return;
@@ -13347,7 +13607,7 @@ var require_mock_utils = __commonJS({
13347
13607
  handler.onResponseStart?.(controller, statusCode, parseHeaders(responseHeaders), getStatusText(statusCode));
13348
13608
  handler.onResponseData?.(controller, Buffer.from(responseData));
13349
13609
  handler.onResponseEnd?.(controller, parseHeaders(responseTrailers));
13350
- deleteMockDispatch(mockDispatches, key);
13610
+ deleteMockDispatch(mockDispatches2, key);
13351
13611
  }
13352
13612
  return true;
13353
13613
  }
@@ -13451,6 +13711,11 @@ var require_mock_interceptor = __commonJS({
13451
13711
  } = require_mock_symbols();
13452
13712
  var { InvalidArgumentError } = require_errors();
13453
13713
  var { serializePathWithQuery } = require_util();
13714
+ var {
13715
+ types: {
13716
+ isPromise
13717
+ }
13718
+ } = __require("util");
13454
13719
  var MockScope = class {
13455
13720
  constructor(mockDispatch) {
13456
13721
  this[kMockDispatch] = mockDispatch;
@@ -13532,8 +13797,7 @@ var require_mock_interceptor = __commonJS({
13532
13797
  */
13533
13798
  reply(replyOptionsCallbackOrStatusCode) {
13534
13799
  if (typeof replyOptionsCallbackOrStatusCode === "function") {
13535
- const wrappedDefaultsCallback = (opts) => {
13536
- const resolvedData = replyOptionsCallbackOrStatusCode(opts);
13800
+ const resolveReplyCallbackData = (resolvedData) => {
13537
13801
  if (typeof resolvedData !== "object" || resolvedData === null) {
13538
13802
  throw new InvalidArgumentError("reply options callback must return an object");
13539
13803
  }
@@ -13543,6 +13807,13 @@ var require_mock_interceptor = __commonJS({
13543
13807
  ...this.createMockScopeDispatchData(replyParameters2)
13544
13808
  };
13545
13809
  };
13810
+ const wrappedDefaultsCallback = (opts) => {
13811
+ const resolvedData = replyOptionsCallbackOrStatusCode(opts);
13812
+ if (isPromise(resolvedData)) {
13813
+ return resolvedData.then(resolveReplyCallbackData);
13814
+ }
13815
+ return resolveReplyCallbackData(resolvedData);
13816
+ };
13546
13817
  const newMockDispatch2 = addMockDispatch(this[kDispatches], this[kDispatchKey], wrappedDefaultsCallback, { ignoreTrailingSlash: this[kIgnoreTrailingSlash] });
13547
13818
  return new MockScope(newMockDispatch2);
13548
13819
  }
@@ -14931,6 +15202,7 @@ var require_global2 = __commonJS({
14931
15202
  var { InvalidArgumentError } = require_errors();
14932
15203
  var Agent = require_agent();
14933
15204
  var Dispatcher1Wrapper = require_dispatcher1_wrapper();
15205
+ var fallbackDispatcher;
14934
15206
  if (getGlobalDispatcher() === void 0) {
14935
15207
  setGlobalDispatcher(new Agent());
14936
15208
  }
@@ -14938,22 +15210,36 @@ var require_global2 = __commonJS({
14938
15210
  if (!agent || typeof agent.dispatch !== "function") {
14939
15211
  throw new InvalidArgumentError("Argument agent must implement Agent");
14940
15212
  }
14941
- Object.defineProperty(globalThis, globalDispatcher, {
14942
- value: agent,
14943
- writable: true,
14944
- enumerable: false,
14945
- configurable: false
14946
- });
14947
- const legacyAgent = agent instanceof Dispatcher1Wrapper ? agent : new Dispatcher1Wrapper(agent);
14948
- Object.defineProperty(globalThis, legacyGlobalDispatcher, {
14949
- value: legacyAgent,
14950
- writable: true,
14951
- enumerable: false,
14952
- configurable: false
14953
- });
15213
+ try {
15214
+ Object.defineProperty(globalThis, globalDispatcher, {
15215
+ value: agent,
15216
+ writable: true,
15217
+ enumerable: false,
15218
+ configurable: false
15219
+ });
15220
+ } catch (err) {
15221
+ if (err instanceof TypeError) {
15222
+ fallbackDispatcher = agent;
15223
+ return;
15224
+ }
15225
+ throw err;
15226
+ }
15227
+ try {
15228
+ const legacyAgent = agent instanceof Dispatcher1Wrapper ? agent : new Dispatcher1Wrapper(agent);
15229
+ Object.defineProperty(globalThis, legacyGlobalDispatcher, {
15230
+ value: legacyAgent,
15231
+ writable: true,
15232
+ enumerable: false,
15233
+ configurable: false
15234
+ });
15235
+ } catch (err) {
15236
+ if (!(err instanceof TypeError)) {
15237
+ throw err;
15238
+ }
15239
+ }
14954
15240
  }
14955
15241
  function getGlobalDispatcher() {
14956
- return globalThis[globalDispatcher];
15242
+ return globalThis[globalDispatcher] ?? fallbackDispatcher;
14957
15243
  }
14958
15244
  var installedExports = (
14959
15245
  /** @type {const} */
@@ -15079,12 +15365,14 @@ var require_redirect_handler = __commonJS({
15079
15365
  if (this.opts.throwOnMaxRedirect && this.history.length >= this.maxRedirections) {
15080
15366
  throw new Error("max redirects");
15081
15367
  }
15368
+ let removeContentHeaders = statusCode === 303;
15082
15369
  if ((statusCode === 301 || statusCode === 302) && this.opts.method === "POST") {
15083
15370
  this.opts.method = "GET";
15084
15371
  if (util.isStream(this.opts.body)) {
15085
15372
  util.destroy(this.opts.body.on("error", noop));
15086
15373
  }
15087
15374
  this.opts.body = null;
15375
+ removeContentHeaders = true;
15088
15376
  }
15089
15377
  if (statusCode === 303 && this.opts.method !== "HEAD") {
15090
15378
  this.opts.method = "GET";
@@ -15109,7 +15397,7 @@ var require_redirect_handler = __commonJS({
15109
15397
  throw new InvalidArgumentError(`Redirect loop detected. Cannot redirect to ${origin}. This typically happens when using a Client or Pool with cross-origin redirects. Use an Agent for cross-origin redirects.`);
15110
15398
  }
15111
15399
  }
15112
- this.opts.headers = cleanRequestHeaders(this.opts.headers, statusCode === 303, this.opts.origin !== origin, this.stripHeadersOnRedirect, this.stripHeadersOnCrossOriginRedirect);
15400
+ this.opts.headers = cleanRequestHeaders(this.opts.headers, removeContentHeaders, this.opts.origin !== origin, this.stripHeadersOnRedirect, this.stripHeadersOnCrossOriginRedirect);
15113
15401
  this.opts.path = path;
15114
15402
  this.opts.origin = origin;
15115
15403
  this.opts.query = null;
@@ -15850,16 +16138,128 @@ var require_cache = __commonJS({
15850
16138
  var {
15851
16139
  safeHTTPMethods,
15852
16140
  pathHasQueryOrFragment,
15853
- hasSafeIterator
16141
+ hasSafeIterator,
16142
+ isValidHTTPToken
15854
16143
  } = require_util();
15855
16144
  var { serializePathWithQuery } = require_util();
15856
- function makeCacheKey(opts) {
15857
- if (!opts.origin) {
15858
- throw new Error("opts.origin is undefined");
16145
+ var MAX_DELTA_SECONDS = 2147483647;
16146
+ var RESTRICTIVE_DIRECTIVE_NAMES = ["no-store", "private", "no-cache"];
16147
+ var kInvalidCacheControlDirectives = /* @__PURE__ */ Symbol("invalid cache-control directives");
16148
+ function trimOWS(value) {
16149
+ return value.replace(/^[\t ]+|[\t ]+$/g, "");
16150
+ }
16151
+ function arrayIncludes(array, value) {
16152
+ for (let i = 0; i < array.length; i++) {
16153
+ if (array[i] === value) {
16154
+ return true;
16155
+ }
15859
16156
  }
15860
- let fullPath = opts.path || "/";
15861
- if (opts.query && !pathHasQueryOrFragment(fullPath)) {
15862
- fullPath = serializePathWithQuery(fullPath, opts.query);
16157
+ return false;
16158
+ }
16159
+ function trimOWSStart(value) {
16160
+ return value.replace(/^[\t ]+/, "");
16161
+ }
16162
+ function trimOWSEnd(value) {
16163
+ return value.replace(/[\t ]+$/, "");
16164
+ }
16165
+ function findUnescapedQuote(value, start) {
16166
+ let escaped = false;
16167
+ for (let i = start; i < value.length; i++) {
16168
+ if (escaped) {
16169
+ escaped = false;
16170
+ } else if (value[i] === "\\") {
16171
+ escaped = true;
16172
+ } else if (value[i] === '"') {
16173
+ return i;
16174
+ }
16175
+ }
16176
+ return -1;
16177
+ }
16178
+ function splitCacheControlHeaderValue(value) {
16179
+ const directives = [];
16180
+ let start = 0;
16181
+ let quoteStart = -1;
16182
+ let inQuote = false;
16183
+ let escaped = false;
16184
+ for (let i = 0; i < value.length; i++) {
16185
+ if (inQuote) {
16186
+ if (escaped) {
16187
+ escaped = false;
16188
+ } else if (value[i] === "\\") {
16189
+ escaped = true;
16190
+ } else if (value[i] === '"') {
16191
+ inQuote = false;
16192
+ quoteStart = -1;
16193
+ }
16194
+ } else if (value[i] === '"') {
16195
+ inQuote = true;
16196
+ quoteStart = i;
16197
+ } else if (value[i] === ",") {
16198
+ directives.push({ value: value.substring(start, i), fromMalformedQuote: false });
16199
+ start = i + 1;
16200
+ }
16201
+ }
16202
+ if (!inQuote) {
16203
+ directives.push({ value: value.substring(start), fromMalformedQuote: false });
16204
+ return directives;
16205
+ }
16206
+ const tail = value.substring(start);
16207
+ const quoteOffset = quoteStart - start;
16208
+ let tailStart = 0;
16209
+ for (let i = 0; i < tail.length; i++) {
16210
+ if (tail[i] === ",") {
16211
+ directives.push({
16212
+ value: tail.substring(tailStart, i),
16213
+ fromMalformedQuote: tailStart > quoteOffset
16214
+ });
16215
+ tailStart = i + 1;
16216
+ }
16217
+ }
16218
+ directives.push({
16219
+ value: tail.substring(tailStart),
16220
+ fromMalformedQuote: tailStart > quoteOffset
16221
+ });
16222
+ return directives;
16223
+ }
16224
+ function markInvalidCacheControlDirective(directives, key) {
16225
+ let invalidDirectives = directives[kInvalidCacheControlDirectives];
16226
+ if (invalidDirectives === void 0) {
16227
+ invalidDirectives = /* @__PURE__ */ new Set();
16228
+ Object.defineProperty(directives, kInvalidCacheControlDirectives, {
16229
+ value: invalidDirectives
16230
+ });
16231
+ }
16232
+ invalidDirectives.add(key);
16233
+ }
16234
+ function hasInvalidCacheControlDirective(directives, key) {
16235
+ return directives[kInvalidCacheControlDirectives]?.has(key) === true;
16236
+ }
16237
+ function getMalformedRestrictiveDirectiveName(key) {
16238
+ for (const directiveName of RESTRICTIVE_DIRECTIVE_NAMES) {
16239
+ if (key.startsWith(directiveName) && key.length > directiveName.length && !isValidHTTPToken(key[directiveName.length])) {
16240
+ return directiveName;
16241
+ }
16242
+ }
16243
+ let tokenOnlyKey = "";
16244
+ let hasInvalidTokenChar = false;
16245
+ for (let i = 0; i < key.length; i++) {
16246
+ if (isValidHTTPToken(key[i])) {
16247
+ tokenOnlyKey += key[i];
16248
+ } else {
16249
+ hasInvalidTokenChar = true;
16250
+ }
16251
+ }
16252
+ if (hasInvalidTokenChar && arrayIncludes(RESTRICTIVE_DIRECTIVE_NAMES, tokenOnlyKey)) {
16253
+ return tokenOnlyKey;
16254
+ }
16255
+ }
16256
+ function makeCacheKey(opts) {
16257
+ if (!opts.origin) {
16258
+ throw new Error("opts.origin is undefined");
16259
+ }
16260
+ let fullPath = opts.path || "/";
16261
+ if (opts.query && !pathHasQueryOrFragment(fullPath)) {
16262
+ fullPath = serializePathWithQuery(fullPath, opts.query);
15863
16263
  }
15864
16264
  return {
15865
16265
  origin: opts.origin.toString(),
@@ -15868,6 +16268,18 @@ var require_cache = __commonJS({
15868
16268
  headers: opts.headers
15869
16269
  };
15870
16270
  }
16271
+ function appendHeader(headers, key, val) {
16272
+ const headerName = key.toLowerCase();
16273
+ const current = headers[headerName];
16274
+ const values = Array.isArray(val) ? val : [val];
16275
+ if (current === void 0) {
16276
+ headers[headerName] = Array.isArray(val) ? val.slice() : val;
16277
+ } else if (Array.isArray(current)) {
16278
+ current.push(...values);
16279
+ } else {
16280
+ headers[headerName] = [current, ...values];
16281
+ }
16282
+ }
15871
16283
  function normalizeHeaders(opts) {
15872
16284
  let headers;
15873
16285
  if (opts.headers == null) {
@@ -15875,19 +16287,57 @@ var require_cache = __commonJS({
15875
16287
  } else if (typeof opts.headers === "object") {
15876
16288
  headers = {};
15877
16289
  if (hasSafeIterator(opts.headers)) {
15878
- for (const x of opts.headers) {
15879
- if (!Array.isArray(x)) {
15880
- throw new Error("opts.headers is not a valid header map");
16290
+ if (Array.isArray(opts.headers)) {
16291
+ const first = opts.headers[0];
16292
+ if (Array.isArray(first)) {
16293
+ for (const x of opts.headers) {
16294
+ if (!Array.isArray(x)) {
16295
+ throw new Error("opts.headers is not a valid header map");
16296
+ }
16297
+ const [key, val] = x;
16298
+ if (typeof key !== "string" || typeof val !== "string") {
16299
+ throw new Error("opts.headers is not a valid header map");
16300
+ }
16301
+ appendHeader(headers, key, val);
16302
+ }
16303
+ } else {
16304
+ const len = opts.headers.length;
16305
+ if (len % 2 !== 0) {
16306
+ throw new Error("opts.headers is not a valid header map");
16307
+ }
16308
+ for (let i = 0; i < len; i += 2) {
16309
+ const key = opts.headers[i];
16310
+ const val = opts.headers[i + 1];
16311
+ if (typeof key !== "string" || typeof val !== "string" && !Array.isArray(val)) {
16312
+ throw new Error("opts.headers is not a valid header map");
16313
+ }
16314
+ if (typeof val === "string") {
16315
+ appendHeader(headers, key, val);
16316
+ } else {
16317
+ const mapped = [];
16318
+ for (let j = 0; j < val.length; j++) {
16319
+ const v = val[j];
16320
+ mapped.push(typeof v === "string" ? v : v.toString("latin1"));
16321
+ }
16322
+ appendHeader(headers, key, mapped);
16323
+ }
16324
+ }
15881
16325
  }
15882
- const [key, val] = x;
15883
- if (typeof key !== "string" || typeof val !== "string") {
15884
- throw new Error("opts.headers is not a valid header map");
16326
+ } else {
16327
+ for (const x of opts.headers) {
16328
+ if (!Array.isArray(x)) {
16329
+ throw new Error("opts.headers is not a valid header map");
16330
+ }
16331
+ const [key, val] = x;
16332
+ if (typeof key !== "string" || typeof val !== "string") {
16333
+ throw new Error("opts.headers is not a valid header map");
16334
+ }
16335
+ appendHeader(headers, key, val);
15885
16336
  }
15886
- headers[key.toLowerCase()] = val;
15887
16337
  }
15888
16338
  } else {
15889
16339
  for (const key of Object.keys(opts.headers)) {
15890
- headers[key.toLowerCase()] = opts.headers[key];
16340
+ appendHeader(headers, key, opts.headers[key]);
15891
16341
  }
15892
16342
  }
15893
16343
  } else {
@@ -15932,25 +16382,32 @@ var require_cache = __commonJS({
15932
16382
  }
15933
16383
  function parseCacheControlHeader(header) {
15934
16384
  const output = {};
15935
- let directives;
15936
- if (Array.isArray(header)) {
15937
- directives = [];
15938
- for (const directive of header) {
15939
- directives.push(...directive.split(","));
15940
- }
15941
- } else {
15942
- directives = header.split(",");
15943
- }
16385
+ const invalidNumericDirectives = /* @__PURE__ */ new Set();
16386
+ const invalidNoArgumentDirectives = /* @__PURE__ */ new Set();
16387
+ const directives = splitCacheControlHeaderValue(Array.isArray(header) ? header.join(",") : header);
15944
16388
  for (let i = 0; i < directives.length; i++) {
15945
- const directive = directives[i].toLowerCase();
16389
+ const directiveRecord = directives[i];
16390
+ const directive = directiveRecord.value.toLowerCase();
16391
+ const fromMalformedQuote = directiveRecord.fromMalformedQuote;
15946
16392
  const keyValueDelimiter = directive.indexOf("=");
15947
16393
  let key;
15948
16394
  let value;
16395
+ let keyHasTrailingWhitespace = false;
16396
+ let valueHasLeadingWhitespace = false;
15949
16397
  if (keyValueDelimiter !== -1) {
15950
- key = directive.substring(0, keyValueDelimiter).trimStart();
15951
- value = directive.substring(keyValueDelimiter + 1);
16398
+ const rawKey = directive.substring(0, keyValueDelimiter);
16399
+ const rawValue = directive.substring(keyValueDelimiter + 1);
16400
+ keyHasTrailingWhitespace = trimOWSEnd(rawKey) !== rawKey;
16401
+ valueHasLeadingWhitespace = trimOWSStart(rawValue) !== rawValue;
16402
+ key = trimOWS(rawKey);
16403
+ value = trimOWSStart(rawValue);
15952
16404
  } else {
15953
- key = directive.trim();
16405
+ key = trimOWS(directive);
16406
+ }
16407
+ const malformedRestrictiveDirectiveName = getMalformedRestrictiveDirectiveName(key);
16408
+ if (malformedRestrictiveDirectiveName !== void 0) {
16409
+ output[malformedRestrictiveDirectiveName] = true;
16410
+ continue;
15954
16411
  }
15955
16412
  switch (key) {
15956
16413
  case "min-fresh":
@@ -15959,48 +16416,85 @@ var require_cache = __commonJS({
15959
16416
  case "s-maxage":
15960
16417
  case "stale-while-revalidate":
15961
16418
  case "stale-if-error": {
15962
- if (value === void 0 || value[0] === " ") {
16419
+ if (fromMalformedQuote || invalidNumericDirectives.has(key)) {
16420
+ continue;
16421
+ }
16422
+ if (value === void 0 || keyHasTrailingWhitespace || valueHasLeadingWhitespace) {
16423
+ delete output[key];
16424
+ invalidNumericDirectives.add(key);
16425
+ markInvalidCacheControlDirective(output, key);
15963
16426
  continue;
15964
16427
  }
15965
16428
  if (value.length >= 2 && value[0] === '"' && value[value.length - 1] === '"') {
15966
16429
  value = value.substring(1, value.length - 1);
15967
16430
  }
15968
- const parsedValue = parseInt(value, 10);
15969
- if (parsedValue !== parsedValue) {
16431
+ if (!/^[0-9]+$/.test(value)) {
16432
+ delete output[key];
16433
+ invalidNumericDirectives.add(key);
16434
+ markInvalidCacheControlDirective(output, key);
15970
16435
  continue;
15971
16436
  }
15972
- if (key === "max-age" && key in output && output[key] >= parsedValue) {
15973
- continue;
16437
+ const parsedValue = Math.min(parseInt(value, 10), MAX_DELTA_SECONDS);
16438
+ if (key === "min-fresh") {
16439
+ if (!(key in output) || output[key] < parsedValue) {
16440
+ output[key] = parsedValue;
16441
+ }
16442
+ } else if (!(key in output) || output[key] > parsedValue) {
16443
+ output[key] = parsedValue;
15974
16444
  }
15975
- output[key] = parsedValue;
15976
16445
  break;
15977
16446
  }
15978
16447
  case "private":
15979
16448
  case "no-cache": {
16449
+ if (fromMalformedQuote) {
16450
+ output[key] = true;
16451
+ break;
16452
+ }
16453
+ if (value !== void 0 && value.length === 0) {
16454
+ output[key] = true;
16455
+ break;
16456
+ }
15980
16457
  if (value) {
15981
16458
  if (value[0] === '"') {
15982
- const headers = [value.substring(1)];
15983
- let foundEndingQuote = value[value.length - 1] === '"';
15984
- if (!foundEndingQuote) {
16459
+ value = trimOWSEnd(value);
16460
+ let fieldList = "";
16461
+ let lastQuotedPart = i;
16462
+ let foundEndingQuote = false;
16463
+ const closingQuote = findUnescapedQuote(value, 1);
16464
+ if (closingQuote !== -1) {
16465
+ fieldList = value.substring(1, closingQuote);
16466
+ foundEndingQuote = true;
16467
+ } else {
16468
+ const fieldListParts = [value.substring(1)];
15985
16469
  for (let j = i + 1; j < directives.length; j++) {
15986
- const nextPart = directives[j];
15987
- const nextPartLength = nextPart.length;
15988
- headers.push(nextPart.trim());
15989
- if (nextPartLength !== 0 && nextPart[nextPartLength - 1] === '"') {
16470
+ const nextPart = trimOWS(directives[j].value);
16471
+ const closingQuote2 = findUnescapedQuote(nextPart, 0);
16472
+ lastQuotedPart = j;
16473
+ if (closingQuote2 !== -1) {
16474
+ fieldListParts.push(nextPart.substring(0, closingQuote2));
15990
16475
  foundEndingQuote = true;
15991
16476
  break;
15992
16477
  }
16478
+ fieldListParts.push(nextPart);
15993
16479
  }
16480
+ fieldList = fieldListParts.join(",");
15994
16481
  }
15995
- if (foundEndingQuote) {
15996
- let lastHeader = headers[headers.length - 1];
15997
- if (lastHeader[lastHeader.length - 1] === '"') {
15998
- lastHeader = lastHeader.substring(0, lastHeader.length - 1);
15999
- headers[headers.length - 1] = lastHeader;
16000
- }
16001
- for (let j = 0; j < headers.length; j++) {
16002
- headers[j] = headers[j].trim();
16482
+ if (!foundEndingQuote) {
16483
+ output[key] = true;
16484
+ break;
16485
+ }
16486
+ i = lastQuotedPart;
16487
+ const headers = fieldList.split(",");
16488
+ let validFieldNames = true;
16489
+ for (let j = 0; j < headers.length; j++) {
16490
+ headers[j] = trimOWS(headers[j]);
16491
+ if (!isValidHTTPToken(headers[j])) {
16492
+ validFieldNames = false;
16003
16493
  }
16494
+ }
16495
+ if (!validFieldNames) {
16496
+ output[key] = true;
16497
+ } else if (output[key] !== true) {
16004
16498
  if (key in output) {
16005
16499
  output[key] = output[key].concat(headers);
16006
16500
  } else {
@@ -16008,11 +16502,15 @@ var require_cache = __commonJS({
16008
16502
  }
16009
16503
  }
16010
16504
  } else {
16011
- const fieldName = value.trim();
16012
- if (key in output) {
16013
- output[key] = output[key].concat(fieldName);
16014
- } else {
16015
- output[key] = [fieldName];
16505
+ const fieldName = trimOWS(value);
16506
+ if (!isValidHTTPToken(fieldName)) {
16507
+ output[key] = true;
16508
+ } else if (output[key] !== true) {
16509
+ if (key in output) {
16510
+ output[key] = output[key].concat(fieldName);
16511
+ } else {
16512
+ output[key] = [fieldName];
16513
+ }
16016
16514
  }
16017
16515
  }
16018
16516
  break;
@@ -16020,39 +16518,76 @@ var require_cache = __commonJS({
16020
16518
  }
16021
16519
  // eslint-disable-next-line no-fallthrough
16022
16520
  case "public":
16023
- case "no-store":
16024
16521
  case "must-revalidate":
16025
16522
  case "proxy-revalidate":
16026
16523
  case "immutable":
16027
16524
  case "no-transform":
16028
16525
  case "must-understand":
16029
16526
  case "only-if-cached":
16030
- if (value) {
16527
+ if (fromMalformedQuote || invalidNoArgumentDirectives.has(key)) {
16528
+ continue;
16529
+ }
16530
+ if (value !== void 0) {
16531
+ delete output[key];
16532
+ invalidNoArgumentDirectives.add(key);
16031
16533
  continue;
16032
16534
  }
16033
16535
  output[key] = true;
16034
16536
  break;
16537
+ case "no-store":
16538
+ output[key] = true;
16539
+ break;
16035
16540
  default:
16036
16541
  continue;
16037
16542
  }
16038
16543
  }
16039
16544
  return output;
16040
16545
  }
16546
+ function splitVaryHeader(varyHeader) {
16547
+ const values = Array.isArray(varyHeader) ? varyHeader : [varyHeader];
16548
+ const output = [];
16549
+ for (let i = 0; i < values.length; i++) {
16550
+ const parts = values[i].split(",");
16551
+ for (let j = 0; j < parts.length; j++) {
16552
+ output.push(parts[j]);
16553
+ }
16554
+ }
16555
+ return output;
16556
+ }
16557
+ function hasVaryStar(varyHeader) {
16558
+ const values = splitVaryHeader(varyHeader);
16559
+ for (let i = 0; i < values.length; i++) {
16560
+ if (trimOWS(values[i]).indexOf("*") !== -1) {
16561
+ return true;
16562
+ }
16563
+ }
16564
+ return false;
16565
+ }
16041
16566
  function parseVaryHeader(varyHeader, headers) {
16042
- if (typeof varyHeader === "string" && varyHeader.includes("*")) {
16567
+ if (hasVaryStar(varyHeader)) {
16043
16568
  return headers;
16044
16569
  }
16045
16570
  const output = (
16046
16571
  /** @type {Record<string, string | string[] | null>} */
16047
16572
  {}
16048
16573
  );
16049
- const varyingHeaders = typeof varyHeader === "string" ? varyHeader.split(",") : varyHeader;
16574
+ const varyingHeaders = splitVaryHeader(varyHeader);
16050
16575
  for (const header of varyingHeaders) {
16051
- const trimmedHeader = header.trim().toLowerCase();
16052
- output[trimmedHeader] = headers[trimmedHeader] ?? null;
16576
+ const trimmedHeader = trimOWS(header).toLowerCase();
16577
+ if (trimmedHeader.length === 0) {
16578
+ continue;
16579
+ }
16580
+ if (!isValidHTTPToken(trimmedHeader)) {
16581
+ return void 0;
16582
+ }
16583
+ const headerValue = headers[trimmedHeader];
16584
+ output[trimmedHeader] = Array.isArray(headerValue) ? headerValue.slice() : headerValue ?? null;
16053
16585
  }
16054
16586
  return output;
16055
16587
  }
16588
+ function isInvalidOrWildcardVaryHeader(varyHeader) {
16589
+ return hasVaryStar(varyHeader) || parseVaryHeader(varyHeader, {}) === void 0;
16590
+ }
16056
16591
  function isEtagUsable(etag) {
16057
16592
  if (etag.length <= 2) {
16058
16593
  return false;
@@ -16083,7 +16618,7 @@ var require_cache = __commonJS({
16083
16618
  throw new TypeError(`${name} needs to have at least one method`);
16084
16619
  }
16085
16620
  for (const method of methods) {
16086
- if (!safeHTTPMethods.includes(method)) {
16621
+ if (!arrayIncludes(safeHTTPMethods, method)) {
16087
16622
  throw new TypeError(`element of ${name}-array needs to be one of following values: ${safeHTTPMethods.join(", ")}, got ${method}`);
16088
16623
  }
16089
16624
  }
@@ -16107,7 +16642,10 @@ var require_cache = __commonJS({
16107
16642
  assertCacheKey,
16108
16643
  assertCacheValue,
16109
16644
  parseCacheControlHeader,
16645
+ hasInvalidCacheControlDirective,
16110
16646
  parseVaryHeader,
16647
+ hasVaryStar,
16648
+ isInvalidOrWildcardVaryHeader,
16111
16649
  isEtagUsable,
16112
16650
  assertCacheMethods,
16113
16651
  assertCacheStore,
@@ -16130,6 +16668,13 @@ var require_date = __commonJS({
16130
16668
  return parseRfc850Date(date);
16131
16669
  }
16132
16670
  }
16671
+ function makeDate(year, monthIdx, day, hour, minute, second, weekday) {
16672
+ const result = new Date(Date.UTC(year, monthIdx, day, hour, minute, second));
16673
+ if (year >= 0 && year <= 99) {
16674
+ result.setUTCFullYear(year);
16675
+ }
16676
+ 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;
16677
+ }
16133
16678
  function parseImfDate(date) {
16134
16679
  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") {
16135
16680
  return void 0;
@@ -16290,8 +16835,7 @@ var require_date = __commonJS({
16290
16835
  }
16291
16836
  second = (code1 - 48) * 10 + (code2 - 48);
16292
16837
  }
16293
- const result = new Date(Date.UTC(year, monthIdx, day, hour, minute, second));
16294
- return result.getUTCDay() === weekday ? result : void 0;
16838
+ return makeDate(year, monthIdx, day, hour, minute, second, weekday);
16295
16839
  }
16296
16840
  function parseAscTimeDate(date) {
16297
16841
  if (date.length !== 24 || date[7] !== " " || date[10] !== " " || date[19] !== " ") {
@@ -16453,8 +16997,7 @@ var require_date = __commonJS({
16453
16997
  return void 0;
16454
16998
  }
16455
16999
  const year = (yearDigit1 - 48) * 1e3 + (yearDigit2 - 48) * 100 + (yearDigit3 - 48) * 10 + (yearDigit4 - 48);
16456
- const result = new Date(Date.UTC(year, monthIdx, day, hour, minute, second));
16457
- return result.getUTCDay() === weekday ? result : void 0;
17000
+ return makeDate(year, monthIdx, day, hour, minute, second, weekday);
16458
17001
  }
16459
17002
  function parseRfc850Date(date) {
16460
17003
  let commaIndex = -1;
@@ -16603,8 +17146,7 @@ var require_date = __commonJS({
16603
17146
  }
16604
17147
  second = (code1 - 48) * 10 + (code2 - 48);
16605
17148
  }
16606
- const result = new Date(Date.UTC(year, monthIdx, day, hour, minute, second));
16607
- return result.getUTCDay() === weekday ? result : void 0;
17149
+ return makeDate(year, monthIdx, day, hour, minute, second, weekday);
16608
17150
  }
16609
17151
  module.exports = {
16610
17152
  parseHttpDate
@@ -16619,7 +17161,10 @@ var require_cache_handler = __commonJS({
16619
17161
  var util = require_util();
16620
17162
  var {
16621
17163
  parseCacheControlHeader,
17164
+ hasInvalidCacheControlDirective,
16622
17165
  parseVaryHeader,
17166
+ hasVaryStar,
17167
+ isInvalidOrWildcardVaryHeader,
16623
17168
  isEtagUsable
16624
17169
  } = require_cache();
16625
17170
  var { parseHttpDate } = require_date();
@@ -16643,6 +17188,79 @@ var require_cache_handler = __commonJS({
16643
17188
  206
16644
17189
  ];
16645
17190
  var MAX_RESPONSE_AGE = 2147483647e3;
17191
+ var REVALIDATION_ONLY_RETENTION = 864e5;
17192
+ function trimOWS(value) {
17193
+ return value.replace(/^[\t ]+|[\t ]+$/g, "");
17194
+ }
17195
+ function arrayIncludes(array, value) {
17196
+ for (let i = 0; i < array.length; i++) {
17197
+ if (array[i] === value) {
17198
+ return true;
17199
+ }
17200
+ }
17201
+ return false;
17202
+ }
17203
+ function appendConnectionHeaderTokens(headersToRemove, connectionHeader) {
17204
+ const values = Array.isArray(connectionHeader) ? connectionHeader : [connectionHeader];
17205
+ for (let i = 0; i < values.length; i++) {
17206
+ const tokens = values[i].split(",");
17207
+ for (let j = 0; j < tokens.length; j++) {
17208
+ headersToRemove.push(trimOWS(tokens[j]).toLowerCase());
17209
+ }
17210
+ }
17211
+ }
17212
+ function getSameOriginPath(cacheKey, location) {
17213
+ if (typeof location !== "string") {
17214
+ return void 0;
17215
+ }
17216
+ let originUrl;
17217
+ let requestUrl;
17218
+ let locationUrl;
17219
+ try {
17220
+ originUrl = new URL(cacheKey.origin);
17221
+ requestUrl = new URL(cacheKey.path, originUrl);
17222
+ locationUrl = new URL(location, requestUrl);
17223
+ } catch {
17224
+ return void 0;
17225
+ }
17226
+ if (locationUrl.origin !== originUrl.origin) {
17227
+ return void 0;
17228
+ }
17229
+ return locationUrl.pathname + locationUrl.search;
17230
+ }
17231
+ function deleteCachedUri(store, cacheKey, path) {
17232
+ deleteCachedValue(store, {
17233
+ ...cacheKey,
17234
+ path
17235
+ });
17236
+ for (let i = 0; i < util.safeHTTPMethods.length; i++) {
17237
+ const method = util.safeHTTPMethods[i];
17238
+ if (method !== cacheKey.method) {
17239
+ deleteCachedValue(store, {
17240
+ ...cacheKey,
17241
+ method,
17242
+ path
17243
+ });
17244
+ }
17245
+ }
17246
+ }
17247
+ function deleteLocationTargets(store, cacheKey, headerValue) {
17248
+ if (headerValue === void 0) {
17249
+ return;
17250
+ }
17251
+ const values = Array.isArray(headerValue) ? headerValue : [headerValue];
17252
+ for (let i = 0; i < values.length; i++) {
17253
+ const path = getSameOriginPath(cacheKey, values[i]);
17254
+ if (path !== void 0) {
17255
+ deleteCachedUri(store, cacheKey, path);
17256
+ }
17257
+ }
17258
+ }
17259
+ function invalidateUnsafeRequest(store, cacheKey, resHeaders) {
17260
+ deleteCachedUri(store, cacheKey, cacheKey.path);
17261
+ deleteLocationTargets(store, cacheKey, resHeaders.location);
17262
+ deleteLocationTargets(store, cacheKey, resHeaders["content-location"]);
17263
+ }
16646
17264
  var CacheHandler = class {
16647
17265
  /**
16648
17266
  * @type {import('../../types/cache-interceptor.d.ts').default.CacheKey}
@@ -16702,35 +17320,51 @@ var require_cache_handler = __commonJS({
16702
17320
  statusMessage
16703
17321
  );
16704
17322
  const handler = this;
16705
- if (!util.safeHTTPMethods.includes(this.#cacheKey.method) && statusCode >= 200 && statusCode <= 399) {
16706
- try {
16707
- this.#store.delete(this.#cacheKey)?.catch?.(noop);
16708
- } catch {
16709
- }
17323
+ if (!arrayIncludes(util.safeHTTPMethods, this.#cacheKey.method) && statusCode >= 200 && statusCode <= 399) {
17324
+ invalidateUnsafeRequest(this.#store, this.#cacheKey, resHeaders);
16710
17325
  return downstreamOnHeaders();
16711
17326
  }
16712
17327
  const cacheControlHeader = resHeaders["cache-control"];
16713
- const heuristicallyCacheable = resHeaders["last-modified"] && HEURISTICALLY_CACHEABLE_STATUS_CODES.includes(statusCode);
17328
+ const heuristicallyCacheable = resHeaders["last-modified"] && arrayIncludes(HEURISTICALLY_CACHEABLE_STATUS_CODES, statusCode);
16714
17329
  if (!cacheControlHeader && !resHeaders["expires"] && !heuristicallyCacheable && !this.#cacheByDefault) {
17330
+ if (statusCode === 304 && resHeaders.vary && isInvalidOrWildcardVaryHeader(resHeaders.vary)) {
17331
+ deleteCachedValue(this.#store, this.#cacheKey);
17332
+ }
16715
17333
  return downstreamOnHeaders();
16716
17334
  }
16717
17335
  const cacheControlDirectives = cacheControlHeader ? parseCacheControlHeader(cacheControlHeader) : {};
16718
17336
  if (!canCacheResponse(this.#cacheType, statusCode, resHeaders, cacheControlDirectives, this.#cacheKey.headers)) {
17337
+ if (statusCode === 304 && (cacheControlHeader || revalidationResponseDisallowsCachedReuse(this.#cacheType, resHeaders, cacheControlDirectives))) {
17338
+ deleteCachedValue(this.#store, this.#cacheKey);
17339
+ }
16719
17340
  return downstreamOnHeaders();
16720
17341
  }
16721
17342
  const now = Date.now();
16722
- const resAge = resHeaders.age ? getAge(resHeaders.age) : void 0;
16723
- if (resAge && resAge >= MAX_RESPONSE_AGE) {
17343
+ const resAge = Object.hasOwn(resHeaders, "age") ? getAge(resHeaders.age) : void 0;
17344
+ if (resAge !== void 0 && resAge >= MAX_RESPONSE_AGE) {
17345
+ deleteCachedValueIfNotModified(statusCode, this.#store, this.#cacheKey);
16724
17346
  return downstreamOnHeaders();
16725
17347
  }
16726
- const resDate = typeof resHeaders.date === "string" ? parseHttpDate(resHeaders.date) : void 0;
16727
- const staleAt = determineStaleAt(this.#cacheType, now, resAge, resHeaders, resDate, cacheControlDirectives) ?? this.#cacheByDefault;
16728
- if (staleAt === void 0 || resAge && resAge > staleAt) {
17348
+ const resDate = Object.hasOwn(resHeaders, "date") ? getDate(resHeaders.date) : void 0;
17349
+ if (resDate === null) {
17350
+ deleteCachedValueIfNotModified(statusCode, this.#store, this.#cacheKey);
16729
17351
  return downstreamOnHeaders();
16730
17352
  }
16731
- const baseTime = resDate ? resDate.getTime() : now;
17353
+ const apparentAge = resDate ? Math.max(0, now - resDate.getTime()) : 0;
17354
+ const currentAge = Math.max(apparentAge, resAge ?? 0);
17355
+ const hasValidator = typeof resHeaders.etag === "string" && isEtagUsable(resHeaders.etag) || typeof resHeaders["last-modified"] === "string";
17356
+ const staleAt = determineStaleAt(this.#cacheType, now, resAge, resHeaders, resDate, cacheControlDirectives, hasValidator) ?? this.#cacheByDefault;
17357
+ const revalidationOnly = staleAt === 0 && hasValidator;
17358
+ if (staleAt === void 0 || currentAge >= staleAt && !revalidationOnly) {
17359
+ if (cacheControlHeader || staleAt !== void 0) {
17360
+ deleteCachedValueIfNotModified(statusCode, this.#store, this.#cacheKey);
17361
+ }
17362
+ return downstreamOnHeaders();
17363
+ }
17364
+ const baseTime = now - currentAge;
16732
17365
  const absoluteStaleAt = staleAt + baseTime;
16733
- if (now >= absoluteStaleAt) {
17366
+ if (now >= absoluteStaleAt && !revalidationOnly) {
17367
+ deleteCachedValueIfNotModified(statusCode, this.#store, this.#cacheKey);
16734
17368
  return downstreamOnHeaders();
16735
17369
  }
16736
17370
  let varyDirectives;
@@ -16740,8 +17374,8 @@ var require_cache_handler = __commonJS({
16740
17374
  return downstreamOnHeaders();
16741
17375
  }
16742
17376
  }
16743
- const cachedAt = resAge ? now - resAge : now;
16744
- const deleteAt = determineDeleteAt(baseTime, cachedAt, cacheControlDirectives, absoluteStaleAt);
17377
+ const cachedAt = baseTime;
17378
+ const deleteAt = determineDeleteAt(baseTime, now, cacheControlDirectives, absoluteStaleAt);
16745
17379
  const strippedHeaders = stripNecessaryHeaders(resHeaders, cacheControlDirectives);
16746
17380
  const value = {
16747
17381
  statusCode,
@@ -16761,6 +17395,7 @@ var require_cache_handler = __commonJS({
16761
17395
  value.statusCode = cachedValue.statusCode;
16762
17396
  value.statusMessage = cachedValue.statusMessage;
16763
17397
  value.etag = cachedValue.etag;
17398
+ value.vary = varyDirectives ?? cachedValue.vary;
16764
17399
  value.headers = { ...cachedValue.headers, ...strippedHeaders };
16765
17400
  downstreamOnHeaders();
16766
17401
  this.#writeStream = this.#store.createWriteStream(this.#cacheKey, value);
@@ -16851,11 +17486,25 @@ var require_cache_handler = __commonJS({
16851
17486
  this.#handler.onResponseError?.(controller, err);
16852
17487
  }
16853
17488
  };
17489
+ function deleteCachedValue(store, cacheKey) {
17490
+ try {
17491
+ store.delete(cacheKey)?.catch?.(noop);
17492
+ } catch {
17493
+ }
17494
+ }
17495
+ function deleteCachedValueIfNotModified(statusCode, store, cacheKey) {
17496
+ if (statusCode === 304) {
17497
+ deleteCachedValue(store, cacheKey);
17498
+ }
17499
+ }
17500
+ function revalidationResponseDisallowsCachedReuse(cacheType, resHeaders, cacheControlDirectives) {
17501
+ return cacheControlDirectives["no-store"] === true || cacheType === "shared" && cacheControlDirectives.private === true || (resHeaders.vary ? isInvalidOrWildcardVaryHeader(resHeaders.vary) : false);
17502
+ }
16854
17503
  function canCacheResponse(cacheType, statusCode, resHeaders, cacheControlDirectives, reqHeaders) {
16855
- if (statusCode < 200 || NOT_UNDERSTOOD_STATUS_CODES.includes(statusCode)) {
17504
+ if (statusCode < 200 || arrayIncludes(NOT_UNDERSTOOD_STATUS_CODES, statusCode)) {
16856
17505
  return false;
16857
17506
  }
16858
- 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
17507
+ 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
16859
17508
  !(cacheControlDirectives.private && cacheType === "private") && !(cacheControlDirectives["s-maxage"] !== void 0 && cacheType === "shared")) {
16860
17509
  return false;
16861
17510
  }
@@ -16865,60 +17514,104 @@ var require_cache_handler = __commonJS({
16865
17514
  if (cacheType === "shared" && cacheControlDirectives.private === true) {
16866
17515
  return false;
16867
17516
  }
16868
- if (resHeaders.vary?.includes("*")) {
17517
+ if (resHeaders.vary && hasVaryStar(resHeaders.vary)) {
16869
17518
  return false;
16870
17519
  }
16871
- if (reqHeaders?.authorization) {
17520
+ if (reqHeaders != null && Object.hasOwn(reqHeaders, "authorization")) {
16872
17521
  if (!cacheControlDirectives.public && !cacheControlDirectives["s-maxage"] && !cacheControlDirectives["must-revalidate"]) {
16873
17522
  return false;
16874
17523
  }
16875
17524
  if (typeof reqHeaders.authorization !== "string") {
16876
17525
  return false;
16877
17526
  }
16878
- if (Array.isArray(cacheControlDirectives["no-cache"]) && cacheControlDirectives["no-cache"].includes("authorization")) {
17527
+ if (Array.isArray(cacheControlDirectives["no-cache"]) && arrayIncludes(cacheControlDirectives["no-cache"], "authorization")) {
16879
17528
  return false;
16880
17529
  }
16881
- if (Array.isArray(cacheControlDirectives["private"]) && cacheControlDirectives["private"].includes("authorization")) {
17530
+ if (Array.isArray(cacheControlDirectives["private"]) && arrayIncludes(cacheControlDirectives["private"], "authorization")) {
16882
17531
  return false;
16883
17532
  }
16884
17533
  }
16885
17534
  return true;
16886
17535
  }
17536
+ function getDate(dateHeader) {
17537
+ let dateValue = dateHeader;
17538
+ if (Array.isArray(dateValue)) {
17539
+ if (dateValue.length !== 1) {
17540
+ return null;
17541
+ }
17542
+ dateValue = dateValue[0];
17543
+ }
17544
+ if (typeof dateValue !== "string") {
17545
+ return null;
17546
+ }
17547
+ return parseHttpDate(dateValue);
17548
+ }
16887
17549
  function getAge(ageHeader) {
16888
- const age = parseInt(Array.isArray(ageHeader) ? ageHeader[0] : ageHeader);
16889
- return isNaN(age) ? void 0 : age * 1e3;
17550
+ let ageValue = ageHeader;
17551
+ if (Array.isArray(ageValue)) {
17552
+ if (ageValue.length !== 1) {
17553
+ return MAX_RESPONSE_AGE;
17554
+ }
17555
+ ageValue = ageValue[0];
17556
+ }
17557
+ if (typeof ageValue !== "string" || !/^[\t ]*[0-9]+[\t ]*$/.test(ageValue)) {
17558
+ return MAX_RESPONSE_AGE;
17559
+ }
17560
+ const age = BigInt(ageValue.replace(/^[\t ]+|[\t ]+$/g, ""));
17561
+ if (age >= BigInt(MAX_RESPONSE_AGE / 1e3)) {
17562
+ return MAX_RESPONSE_AGE;
17563
+ }
17564
+ return Number(age) * 1e3;
16890
17565
  }
16891
- function determineStaleAt(cacheType, now, age, resHeaders, responseDate, cacheControlDirectives) {
17566
+ function determineStaleAt(cacheType, now, age, resHeaders, responseDate, cacheControlDirectives, hasValidator) {
16892
17567
  if (cacheType === "shared") {
17568
+ if (hasInvalidCacheControlDirective(cacheControlDirectives, "s-maxage")) {
17569
+ return 0;
17570
+ }
16893
17571
  const sMaxAge = cacheControlDirectives["s-maxage"];
16894
17572
  if (sMaxAge !== void 0) {
16895
- return sMaxAge > 0 ? sMaxAge * 1e3 : void 0;
17573
+ if (sMaxAge > 0) {
17574
+ return sMaxAge * 1e3;
17575
+ }
17576
+ return 0;
16896
17577
  }
16897
17578
  }
17579
+ if (hasInvalidCacheControlDirective(cacheControlDirectives, "max-age")) {
17580
+ return 0;
17581
+ }
16898
17582
  const maxAge = cacheControlDirectives["max-age"];
16899
17583
  if (maxAge !== void 0) {
16900
- return maxAge > 0 ? maxAge * 1e3 : void 0;
17584
+ if (maxAge > 0) {
17585
+ return maxAge * 1e3;
17586
+ }
17587
+ return 0;
16901
17588
  }
16902
- if (typeof resHeaders.expires === "string") {
17589
+ if (Object.hasOwn(resHeaders, "expires")) {
17590
+ if (typeof resHeaders.expires !== "string") {
17591
+ return 0;
17592
+ }
16903
17593
  const expiresDate = parseHttpDate(resHeaders.expires);
16904
- if (expiresDate) {
16905
- if (now >= expiresDate.getTime()) {
16906
- return void 0;
17594
+ if (!expiresDate) {
17595
+ return 0;
17596
+ }
17597
+ if (now >= expiresDate.getTime()) {
17598
+ return 0;
17599
+ }
17600
+ if (responseDate) {
17601
+ if (responseDate >= expiresDate) {
17602
+ return 0;
16907
17603
  }
16908
- if (responseDate) {
16909
- if (responseDate >= expiresDate) {
16910
- return void 0;
16911
- }
16912
- if (age !== void 0 && age > expiresDate - responseDate) {
16913
- return void 0;
16914
- }
17604
+ const freshnessLifetime = expiresDate.getTime() - responseDate.getTime();
17605
+ if (age !== void 0 && age >= freshnessLifetime) {
17606
+ return 0;
16915
17607
  }
16916
- return expiresDate.getTime() - now;
17608
+ return freshnessLifetime;
16917
17609
  }
17610
+ return expiresDate.getTime() - now;
16918
17611
  }
16919
17612
  if (typeof resHeaders["last-modified"] === "string") {
16920
- const lastModified = new Date(resHeaders["last-modified"]);
16921
- if (isValidDate(lastModified)) {
17613
+ const lastModified = parseHttpDate(resHeaders["last-modified"]);
17614
+ if (lastModified) {
16922
17615
  if (lastModified.getTime() >= now) {
16923
17616
  return void 0;
16924
17617
  }
@@ -16929,6 +17622,9 @@ var require_cache_handler = __commonJS({
16929
17622
  if (cacheControlDirectives.immutable) {
16930
17623
  return 31536e6;
16931
17624
  }
17625
+ if (cacheControlDirectives["no-cache"] === true && hasValidator) {
17626
+ return 0;
17627
+ }
16932
17628
  return void 0;
16933
17629
  }
16934
17630
  function determineDeleteAt(baseTime, cachedAt, cacheControlDirectives, staleAt) {
@@ -16946,6 +17642,9 @@ var require_cache_handler = __commonJS({
16946
17642
  }
16947
17643
  if (staleWhileRevalidate === -Infinity && staleIfError === -Infinity && immutable === -Infinity) {
16948
17644
  const freshnessLifetime = staleAt - baseTime;
17645
+ if (freshnessLifetime <= 0) {
17646
+ return cachedAt + REVALIDATION_ONLY_RETENTION;
17647
+ }
16949
17648
  const datePrecisionPadding = Math.min(Math.max(cachedAt - baseTime, 0), 1e3);
16950
17649
  return staleAt + freshnessLifetime + datePrecisionPadding;
16951
17650
  }
@@ -16965,11 +17664,7 @@ var require_cache_handler = __commonJS({
16965
17664
  "age"
16966
17665
  ];
16967
17666
  if (resHeaders["connection"]) {
16968
- if (Array.isArray(resHeaders["connection"])) {
16969
- headersToRemove.push(...resHeaders["connection"].map((header) => header.trim()));
16970
- } else {
16971
- headersToRemove.push(...resHeaders["connection"].split(",").map((header) => header.trim()));
16972
- }
17667
+ appendConnectionHeaderTokens(headersToRemove, resHeaders["connection"]);
16973
17668
  }
16974
17669
  if (Array.isArray(cacheControlDirectives["no-cache"])) {
16975
17670
  headersToRemove.push(...cacheControlDirectives["no-cache"]);
@@ -16979,16 +17674,13 @@ var require_cache_handler = __commonJS({
16979
17674
  }
16980
17675
  let strippedHeaders;
16981
17676
  for (const headerName of headersToRemove) {
16982
- if (resHeaders[headerName]) {
17677
+ if (Object.hasOwn(resHeaders, headerName)) {
16983
17678
  strippedHeaders ??= { ...resHeaders };
16984
17679
  delete strippedHeaders[headerName];
16985
17680
  }
16986
17681
  }
16987
17682
  return strippedHeaders ?? resHeaders;
16988
17683
  }
16989
- function isValidDate(date) {
16990
- return date instanceof Date && Number.isFinite(date.valueOf());
16991
- }
16992
17684
  module.exports = CacheHandler;
16993
17685
  }
16994
17686
  });
@@ -17159,12 +17851,43 @@ var require_memory_cache_store = __commonJS({
17159
17851
  }
17160
17852
  };
17161
17853
  function findEntry(key, entries, now) {
17162
- return entries.find((entry) => entry.deleteAt > now && entry.method === key.method && (entry.vary == null || Object.keys(entry.vary).every((headerName) => {
17163
- if (entry.vary[headerName] === null) {
17164
- return key.headers[headerName] === void 0;
17854
+ for (let i = 0; i < entries.length; i++) {
17855
+ const entry = entries[i];
17856
+ if (entry.deleteAt > now && entry.method === key.method && varyMatches(key, entry)) {
17857
+ return entry;
17165
17858
  }
17166
- return entry.vary[headerName] === key.headers[headerName];
17167
- })));
17859
+ }
17860
+ }
17861
+ function varyMatches(key, entry) {
17862
+ if (entry.vary == null) {
17863
+ return true;
17864
+ }
17865
+ for (const headerName in entry.vary) {
17866
+ if (Object.hasOwn(entry.vary, headerName) && !headerValueEquals(key.headers?.[headerName], entry.vary[headerName])) {
17867
+ return false;
17868
+ }
17869
+ }
17870
+ return true;
17871
+ }
17872
+ function headerValueEquals(lhs, rhs) {
17873
+ if (lhs == null && rhs == null) {
17874
+ return true;
17875
+ }
17876
+ if (lhs == null && rhs != null || lhs != null && rhs == null) {
17877
+ return false;
17878
+ }
17879
+ if (Array.isArray(lhs) && Array.isArray(rhs)) {
17880
+ if (lhs.length !== rhs.length) {
17881
+ return false;
17882
+ }
17883
+ for (let i = 0; i < lhs.length; i++) {
17884
+ if (lhs[i] !== rhs[i]) {
17885
+ return false;
17886
+ }
17887
+ }
17888
+ return true;
17889
+ }
17890
+ return lhs === rhs;
17168
17891
  }
17169
17892
  module.exports = MemoryCacheStore;
17170
17893
  }
@@ -17178,7 +17901,7 @@ var require_cache_revalidation_handler = __commonJS({
17178
17901
  var CacheRevalidationHandler = class {
17179
17902
  #successful = false;
17180
17903
  /**
17181
- * @type {((boolean, any) => void) | null}
17904
+ * @type {((success: boolean, context?: any, statusCode?: number, headers?: import('../../types/header.d.ts').IncomingHttpHeaders) => void) | null}
17182
17905
  */
17183
17906
  #callback;
17184
17907
  /**
@@ -17191,7 +17914,7 @@ var require_cache_revalidation_handler = __commonJS({
17191
17914
  */
17192
17915
  #allowErrorStatusCodes;
17193
17916
  /**
17194
- * @param {(boolean) => void} callback Function to call if the cached value is valid
17917
+ * @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
17195
17918
  * @param {import('../../types/dispatcher.d.ts').default.DispatchHandlers} handler
17196
17919
  * @param {boolean} allowErrorStatusCodes
17197
17920
  */
@@ -17213,7 +17936,7 @@ var require_cache_revalidation_handler = __commonJS({
17213
17936
  onResponseStart(controller, statusCode, headers, statusMessage) {
17214
17937
  assert(this.#callback != null);
17215
17938
  this.#successful = statusCode === 304 || this.#allowErrorStatusCodes && statusCode >= 500 && statusCode <= 504;
17216
- this.#callback(this.#successful, this.#context);
17939
+ this.#callback(this.#successful, this.#context, statusCode, headers);
17217
17940
  this.#callback = null;
17218
17941
  if (this.#successful) {
17219
17942
  return true;
@@ -17243,6 +17966,12 @@ var require_cache_revalidation_handler = __commonJS({
17243
17966
  return;
17244
17967
  }
17245
17968
  if (this.#callback) {
17969
+ if (this.#allowErrorStatusCodes) {
17970
+ this.#successful = true;
17971
+ this.#callback(true, this.#context);
17972
+ this.#callback = null;
17973
+ return;
17974
+ }
17246
17975
  this.#callback(false);
17247
17976
  this.#callback = null;
17248
17977
  }
@@ -17267,8 +17996,9 @@ var require_cache2 = __commonJS({
17267
17996
  var CacheHandler = require_cache_handler();
17268
17997
  var MemoryCacheStore = require_memory_cache_store();
17269
17998
  var CacheRevalidationHandler = require_cache_revalidation_handler();
17270
- var { assertCacheStore, assertCacheMethods, makeCacheKey, normalizeHeaders, parseCacheControlHeader } = require_cache();
17999
+ var { assertCacheStore, assertCacheMethods, makeCacheKey, normalizeHeaders, parseCacheControlHeader, isInvalidOrWildcardVaryHeader } = require_cache();
17271
18000
  var { AbortError } = require_errors();
18001
+ var { parseHttpDate } = require_date();
17272
18002
  function assertCacheOrigins(origins, name) {
17273
18003
  if (origins === void 0) return;
17274
18004
  if (!Array.isArray(origins)) {
@@ -17283,6 +18013,37 @@ var require_cache2 = __commonJS({
17283
18013
  }
17284
18014
  var nop = () => {
17285
18015
  };
18016
+ function trimOWS(value) {
18017
+ return value.replace(/^[\t ]+|[\t ]+$/g, "");
18018
+ }
18019
+ function arrayIncludes(array, value) {
18020
+ for (let i = 0; i < array.length; i++) {
18021
+ if (array[i] === value) {
18022
+ return true;
18023
+ }
18024
+ }
18025
+ return false;
18026
+ }
18027
+ function hasPragmaNoCache(headers) {
18028
+ const pragma = headers?.pragma;
18029
+ if (!pragma) {
18030
+ return false;
18031
+ }
18032
+ const values = Array.isArray(pragma) ? pragma : [pragma];
18033
+ for (let i = 0; i < values.length; i++) {
18034
+ const value = values[i];
18035
+ if (typeof value !== "string") {
18036
+ continue;
18037
+ }
18038
+ const directives = value.split(",");
18039
+ for (let j = 0; j < directives.length; j++) {
18040
+ if (trimOWS(directives[j]).toLowerCase() === "no-cache") {
18041
+ return true;
18042
+ }
18043
+ }
18044
+ }
18045
+ return false;
18046
+ }
17286
18047
  function needsRevalidation(result, cacheControlDirectives, { headers = {} }) {
17287
18048
  if (cacheControlDirectives?.["no-cache"]) {
17288
18049
  return true;
@@ -17295,10 +18056,58 @@ var require_cache2 = __commonJS({
17295
18056
  }
17296
18057
  return false;
17297
18058
  }
17298
- function isStale(result, cacheControlDirectives) {
18059
+ function staleResponseRequiresRevalidation(result, cacheType) {
18060
+ 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
18061
+ // s-maxage implies proxy-revalidate for shared caches.
18062
+ result.cacheControlDirectives?.["s-maxage"] !== void 0);
18063
+ }
18064
+ function revalidationResponseDisallowsCachedReuse(cacheType, headers) {
18065
+ if (headers.vary && isInvalidOrWildcardVaryHeader(headers.vary)) {
18066
+ return true;
18067
+ }
18068
+ const cacheControl = headers["cache-control"];
18069
+ if (!cacheControl) {
18070
+ return false;
18071
+ }
18072
+ const cacheControlDirectives = parseCacheControlHeader(cacheControl);
18073
+ return cacheControlDirectives["no-store"] === true || cacheType === "shared" && cacheControlDirectives.private === true;
18074
+ }
18075
+ function revalidationResponseUpdatesCacheControl(headers) {
18076
+ return headers["cache-control"] !== void 0;
18077
+ }
18078
+ function deleteCachedValue(store, cacheKey) {
18079
+ try {
18080
+ store.delete(cacheKey)?.catch?.(nop);
18081
+ } catch {
18082
+ }
18083
+ }
18084
+ function getUsableLastModified(headers) {
18085
+ const lastModified = headers?.["last-modified"];
18086
+ if (typeof lastModified === "string" && parseHttpDate(lastModified)) {
18087
+ return lastModified;
18088
+ }
18089
+ }
18090
+ function makeRevalidationHeaders(opts, result) {
18091
+ const headers = {
18092
+ ...opts.headers,
18093
+ "if-modified-since": getUsableLastModified(result.headers) ?? new Date(result.cachedAt).toUTCString()
18094
+ };
18095
+ if (result.etag) {
18096
+ headers["if-none-match"] = result.etag;
18097
+ }
18098
+ if (result.vary) {
18099
+ for (const key in result.vary) {
18100
+ if (result.vary[key] != null) {
18101
+ headers[key] = result.vary[key];
18102
+ }
18103
+ }
18104
+ }
18105
+ return headers;
18106
+ }
18107
+ function isStale(result, cacheControlDirectives, cacheType) {
17299
18108
  const now = Date.now();
17300
18109
  if (now > result.staleAt) {
17301
- if (cacheControlDirectives?.["max-stale"]) {
18110
+ if (!staleResponseRequiresRevalidation(result, cacheType) && cacheControlDirectives?.["max-stale"]) {
17302
18111
  const gracePeriod = result.staleAt + cacheControlDirectives["max-stale"] * 1e3;
17303
18112
  return now > gracePeriod;
17304
18113
  }
@@ -17311,9 +18120,9 @@ var require_cache2 = __commonJS({
17311
18120
  }
17312
18121
  return false;
17313
18122
  }
17314
- function withinStaleWhileRevalidateWindow(result) {
18123
+ function withinStaleWhileRevalidateWindow(result, cacheType) {
17315
18124
  const staleWhileRevalidate = result.cacheControlDirectives?.["stale-while-revalidate"];
17316
- if (!staleWhileRevalidate) {
18125
+ if (!staleWhileRevalidate || staleResponseRequiresRevalidation(result, cacheType)) {
17317
18126
  return false;
17318
18127
  }
17319
18128
  const now = Date.now();
@@ -17423,32 +18232,17 @@ var require_cache2 = __commonJS({
17423
18232
  return dispatch(opts, new CacheHandler(globalOpts, cacheKey, handler));
17424
18233
  }
17425
18234
  const age = Math.round((now - result.cachedAt) / 1e3);
17426
- if (reqCacheControl?.["max-age"] && age >= reqCacheControl["max-age"]) {
17427
- return dispatch(opts, handler);
17428
- }
17429
- const stale = isStale(result, reqCacheControl);
17430
- const revalidate = needsRevalidation(result, reqCacheControl, opts);
18235
+ const requestMaxAgeExpired = reqCacheControl?.["max-age"] !== void 0 && age >= reqCacheControl["max-age"];
18236
+ const stale = requestMaxAgeExpired || isStale(result, reqCacheControl, globalOpts.type);
18237
+ const revalidate = requestMaxAgeExpired || needsRevalidation(result, reqCacheControl, opts);
17431
18238
  if (stale || revalidate) {
17432
18239
  if (util.isStream(opts.body) && util.bodyLength(opts.body) !== 0) {
17433
18240
  return dispatch(opts, new CacheHandler(globalOpts, cacheKey, handler));
17434
18241
  }
17435
- if (!revalidate && withinStaleWhileRevalidateWindow(result)) {
18242
+ if (!revalidate && withinStaleWhileRevalidateWindow(result, globalOpts.type)) {
17436
18243
  sendCachedValue(handler, opts, result, age, null, true);
17437
18244
  queueMicrotask(() => {
17438
- const headers2 = {
17439
- ...opts.headers,
17440
- "if-modified-since": new Date(result.cachedAt).toUTCString()
17441
- };
17442
- if (result.etag) {
17443
- headers2["if-none-match"] = result.etag;
17444
- }
17445
- if (result.vary) {
17446
- for (const key in result.vary) {
17447
- if (result.vary[key] != null) {
17448
- headers2[key] = result.vary[key];
17449
- }
17450
- }
17451
- }
18245
+ const headers2 = makeRevalidationHeaders(opts, result);
17452
18246
  dispatch(
17453
18247
  {
17454
18248
  ...opts,
@@ -17474,32 +18268,33 @@ var require_cache2 = __commonJS({
17474
18268
  return true;
17475
18269
  }
17476
18270
  let withinStaleIfErrorThreshold = false;
17477
- const staleIfErrorExpiry = result.cacheControlDirectives["stale-if-error"] ?? reqCacheControl?.["stale-if-error"];
17478
- if (staleIfErrorExpiry) {
17479
- withinStaleIfErrorThreshold = now < result.staleAt + staleIfErrorExpiry * 1e3;
17480
- }
17481
- const headers = {
17482
- ...opts.headers,
17483
- "if-modified-since": new Date(result.cachedAt).toUTCString()
17484
- };
17485
- if (result.etag) {
17486
- headers["if-none-match"] = result.etag;
17487
- }
17488
- if (result.vary) {
17489
- for (const key in result.vary) {
17490
- if (result.vary[key] != null) {
17491
- headers[key] = result.vary[key];
17492
- }
18271
+ if (!staleResponseRequiresRevalidation(result, globalOpts.type)) {
18272
+ const staleIfErrorExpiry = result.cacheControlDirectives["stale-if-error"] ?? reqCacheControl?.["stale-if-error"];
18273
+ if (staleIfErrorExpiry) {
18274
+ withinStaleIfErrorThreshold = now < result.staleAt + staleIfErrorExpiry * 1e3;
17493
18275
  }
17494
18276
  }
18277
+ const headers = makeRevalidationHeaders(opts, result);
17495
18278
  return dispatch(
17496
18279
  {
17497
18280
  ...opts,
17498
18281
  headers
17499
18282
  },
17500
18283
  new CacheRevalidationHandler(
17501
- (success, context) => {
18284
+ (success, context, statusCode, headers2) => {
17502
18285
  if (success) {
18286
+ if (statusCode === 304) {
18287
+ if (revalidationResponseDisallowsCachedReuse(globalOpts.type, headers2)) {
18288
+ if (util.isStream(result.body)) {
18289
+ result.body.on("error", nop).destroy();
18290
+ }
18291
+ deleteCachedValue(globalOpts.store, cacheKey);
18292
+ return dispatch(opts, new CacheHandler(globalOpts, cacheKey, handler));
18293
+ }
18294
+ if (revalidationResponseUpdatesCacheControl(headers2)) {
18295
+ deleteCachedValue(globalOpts.store, cacheKey);
18296
+ }
18297
+ }
17503
18298
  sendCachedValue(handler, opts, result, age, context, stale);
17504
18299
  } else if (util.isStream(result.body)) {
17505
18300
  result.body.on("error", nop).destroy();
@@ -17541,10 +18336,16 @@ var require_cache2 = __commonJS({
17541
18336
  cacheByDefault,
17542
18337
  type
17543
18338
  };
17544
- const safeMethodsToNotCache = util.safeHTTPMethods.filter((method) => methods.includes(method) === false);
18339
+ const safeMethodsToNotCache = [];
18340
+ for (let i = 0; i < util.safeHTTPMethods.length; i++) {
18341
+ const method = util.safeHTTPMethods[i];
18342
+ if (!arrayIncludes(methods, method)) {
18343
+ safeMethodsToNotCache.push(method);
18344
+ }
18345
+ }
17545
18346
  return (dispatch) => {
17546
18347
  return (opts2, handler) => {
17547
- if (!opts2.origin || safeMethodsToNotCache.includes(opts2.method)) {
18348
+ if (!opts2.origin || arrayIncludes(safeMethodsToNotCache, opts2.method)) {
17548
18349
  return dispatch(opts2, handler);
17549
18350
  }
17550
18351
  if (origins !== void 0) {
@@ -17570,7 +18371,7 @@ var require_cache2 = __commonJS({
17570
18371
  ...opts2,
17571
18372
  headers: normalizeHeaders(opts2)
17572
18373
  };
17573
- const reqCacheControl = opts2.headers?.["cache-control"] ? parseCacheControlHeader(opts2.headers["cache-control"]) : void 0;
18374
+ const reqCacheControl = opts2.headers?.["cache-control"] ? parseCacheControlHeader(opts2.headers["cache-control"]) : hasPragmaNoCache(opts2.headers) ? { "no-cache": true } : void 0;
17574
18375
  if (reqCacheControl?.["no-store"]) {
17575
18376
  return dispatch(opts2, handler);
17576
18377
  }
@@ -17630,6 +18431,8 @@ var require_decompress = __commonJS({
17630
18431
  var DecompressHandler = class extends DecoratorHandler {
17631
18432
  /** @type {Transform[]} */
17632
18433
  #decompressors = [];
18434
+ /** @type {Record<string, string | string[]> | undefined} */
18435
+ #trailers;
17633
18436
  /** @type {Readonly<number[]>} */
17634
18437
  #skipStatusCodes;
17635
18438
  /** @type {boolean} */
@@ -17705,7 +18508,7 @@ var require_decompress = __commonJS({
17705
18508
  const decompressor = this.#decompressors[0];
17706
18509
  this.#setupDecompressorEvents(decompressor, controller);
17707
18510
  decompressor.on("end", () => {
17708
- super.onResponseEnd(controller, {});
18511
+ super.onResponseEnd(controller, this.#trailers);
17709
18512
  });
17710
18513
  }
17711
18514
  /**
@@ -17721,7 +18524,7 @@ var require_decompress = __commonJS({
17721
18524
  super.onResponseError(controller, err);
17722
18525
  return;
17723
18526
  }
17724
- super.onResponseEnd(controller, {});
18527
+ super.onResponseEnd(controller, this.#trailers);
17725
18528
  });
17726
18529
  }
17727
18530
  /**
@@ -17799,6 +18602,7 @@ var require_decompress = __commonJS({
17799
18602
  */
17800
18603
  onResponseEnd(controller, trailers) {
17801
18604
  if (this.#decompressors.length > 0) {
18605
+ this.#trailers = trailers;
17802
18606
  this.#decompressors[0].end();
17803
18607
  this.#cleanupDecompressors();
17804
18608
  return;
@@ -17830,6 +18634,9 @@ var require_decompress = __commonJS({
17830
18634
  }
17831
18635
  return (dispatch) => {
17832
18636
  return (opts, handler) => {
18637
+ if (opts.method === "HEAD") {
18638
+ return dispatch(opts, handler);
18639
+ }
17833
18640
  const decompressHandler = new DecompressHandler(handler, options);
17834
18641
  return dispatch(opts, decompressHandler);
17835
18642
  };
@@ -18637,7 +19444,12 @@ var require_sqlite_cache_store = __commonJS({
18637
19444
  if (lhs.length !== rhs.length) {
18638
19445
  return false;
18639
19446
  }
18640
- return lhs.every((x, i) => x === rhs[i]);
19447
+ for (let i = 0; i < lhs.length; i++) {
19448
+ if (lhs[i] !== rhs[i]) {
19449
+ return false;
19450
+ }
19451
+ }
19452
+ return true;
18641
19453
  }
18642
19454
  return lhs === rhs;
18643
19455
  }
@@ -19143,9 +19955,7 @@ var require_response = __commonJS({
19143
19955
  // https://fetch.spec.whatwg.org/#dom-response-json
19144
19956
  static json(data, init = void 0) {
19145
19957
  webidl.argumentLengthCheck(arguments, 1, "Response.json");
19146
- if (init !== null) {
19147
- init = webidl.converters.ResponseInit(init);
19148
- }
19958
+ init = webidl.converters.ResponseInit(init);
19149
19959
  const bytes = textEncoder.encode(
19150
19960
  serializeJavascriptValueToJSONString(data)
19151
19961
  );
@@ -21130,7 +21940,12 @@ var require_fetch = __commonJS({
21130
21940
  httpFetchParams = fetchParams;
21131
21941
  httpRequest = request;
21132
21942
  } else {
21133
- httpRequest = cloneRequest(request);
21943
+ if (request.body?.source != null) {
21944
+ httpRequest = cloneRequest(request);
21945
+ } else {
21946
+ httpRequest = cloneRequest({ ...request, body: null });
21947
+ httpRequest.body = request.body;
21948
+ }
21134
21949
  httpFetchParams = { ...fetchParams };
21135
21950
  httpFetchParams.request = httpRequest;
21136
21951
  }
@@ -21175,7 +21990,7 @@ var require_fetch = __commonJS({
21175
21990
  }
21176
21991
  if (!httpRequest.headersList.contains("accept-encoding", true)) {
21177
21992
  if (urlHasHttpsScheme(requestCurrentURL(httpRequest))) {
21178
- httpRequest.headersList.append("accept-encoding", "br, gzip, deflate", true);
21993
+ httpRequest.headersList.append("accept-encoding", "br, gzip, deflate, zstd", true);
21179
21994
  } else {
21180
21995
  httpRequest.headersList.append("accept-encoding", "gzip, deflate", true);
21181
21996
  }
@@ -22353,14 +23168,48 @@ var require_util4 = __commonJS({
22353
23168
  for (let i = 0; i < path.length; ++i) {
22354
23169
  const code = path.charCodeAt(i);
22355
23170
  if (code < 32 || // exclude CTLs (0-31)
22356
- code === 127 || // DEL
23171
+ code > 126 || // exclude non-ascii and DEL
22357
23172
  code === 59) {
22358
23173
  throw new Error("Invalid cookie path");
22359
23174
  }
22360
23175
  }
22361
23176
  }
23177
+ function isLetterOrDigit(code) {
23178
+ return code >= 48 && code <= 57 || // 0-9
23179
+ code >= 65 && code <= 90 || // A-Z
23180
+ code >= 97 && code <= 122;
23181
+ }
22362
23182
  function validateCookieDomain(domain) {
22363
- if (domain.startsWith("-") || domain.endsWith(".") || domain.endsWith("-")) {
23183
+ if (domain === " ") {
23184
+ return;
23185
+ }
23186
+ if (domain.length > 255) {
23187
+ throw new Error("Invalid cookie domain");
23188
+ }
23189
+ let labelLength = 0;
23190
+ for (let i = 0; i < domain.length; ++i) {
23191
+ const code = domain.charCodeAt(i);
23192
+ if (code === 46) {
23193
+ if (labelLength === 0) {
23194
+ throw new Error("Invalid cookie domain");
23195
+ }
23196
+ if (domain.charCodeAt(i - 1) === 45) {
23197
+ throw new Error("Invalid cookie domain");
23198
+ }
23199
+ labelLength = 0;
23200
+ continue;
23201
+ }
23202
+ if (labelLength === 0 && !isLetterOrDigit(code)) {
23203
+ throw new Error("Invalid cookie domain");
23204
+ }
23205
+ if (!isLetterOrDigit(code) && code !== 45) {
23206
+ throw new Error("Invalid cookie domain");
23207
+ }
23208
+ if (++labelLength > 63) {
23209
+ throw new Error("Invalid cookie domain");
23210
+ }
23211
+ }
23212
+ if (labelLength === 0 || domain.charCodeAt(domain.length - 1) === 45) {
22364
23213
  throw new Error("Invalid cookie domain");
22365
23214
  }
22366
23215
  }
@@ -22443,7 +23292,11 @@ var require_util4 = __commonJS({
22443
23292
  throw new Error("Invalid unparsed");
22444
23293
  }
22445
23294
  const [key, ...value] = part.split("=");
22446
- out.push(`${key.trim()}=${value.join("=")}`);
23295
+ const trimmedKey = key.trim();
23296
+ const joinedValue = value.join("=");
23297
+ validateCookieName(trimmedKey);
23298
+ validateCookieValue(joinedValue);
23299
+ out.push(`${trimmedKey}=${joinedValue}`);
22447
23300
  }
22448
23301
  return out.join("; ");
22449
23302
  }
@@ -22542,7 +23395,9 @@ var require_parse = __commonJS({
22542
23395
  const attributeNameLowercase = attributeName.toLowerCase();
22543
23396
  if (attributeNameLowercase === "expires") {
22544
23397
  const expiryTime = new Date(attributeValue);
22545
- cookieAttributeList.expires = expiryTime;
23398
+ if (!Number.isNaN(expiryTime.getTime())) {
23399
+ cookieAttributeList.expires = expiryTime;
23400
+ }
22546
23401
  } else if (attributeNameLowercase === "max-age") {
22547
23402
  const charCode = attributeValue.charCodeAt(0);
22548
23403
  if ((charCode < 48 || charCode > 57) && attributeValue[0] !== "-") {
@@ -24922,7 +25777,7 @@ var require_util6 = __commonJS({
24922
25777
  destination,
24923
25778
  mode,
24924
25779
  credentials: credentialsMode,
24925
- useCredentials: true
25780
+ useURLCredentials: true
24926
25781
  });
24927
25782
  }
24928
25783
  module.exports = {