@chrischall/warapp-mcp 0.18.0 → 0.19.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.
package/dist/bundle.js CHANGED
@@ -27332,6 +27332,7 @@ var require_symbols = __commonJS({
27332
27332
  kMaxResponseSize: /* @__PURE__ */ Symbol("max response size"),
27333
27333
  kHTTP2Session: /* @__PURE__ */ Symbol("http2Session"),
27334
27334
  kHTTP2Options: /* @__PURE__ */ Symbol("http2 options"),
27335
+ kQueuedAbort: /* @__PURE__ */ Symbol("queued abort"),
27335
27336
  kHTTP2SessionState: /* @__PURE__ */ Symbol("http2Session state"),
27336
27337
  kRetryHandlerDefaultRetry: /* @__PURE__ */ Symbol("retry agent default retry"),
27337
27338
  kConstruct: /* @__PURE__ */ Symbol("constructable"),
@@ -27349,7 +27350,8 @@ var require_symbols = __commonJS({
27349
27350
  kNoProxyAgent: /* @__PURE__ */ Symbol("no proxy agent"),
27350
27351
  kHttpProxyAgent: /* @__PURE__ */ Symbol("http proxy agent"),
27351
27352
  kHttpsProxyAgent: /* @__PURE__ */ Symbol("https proxy agent"),
27352
- kSocks5ProxyAgent: /* @__PURE__ */ Symbol("socks5 proxy agent")
27353
+ kSocks5ProxyAgent: /* @__PURE__ */ Symbol("socks5 proxy agent"),
27354
+ kInterceptorKind: /* @__PURE__ */ Symbol("interceptor kind")
27353
27355
  };
27354
27356
  }
27355
27357
  });
@@ -30939,7 +30941,7 @@ var require_util4 = __commonJS({
30939
30941
  }
30940
30942
  return url4;
30941
30943
  }
30942
- var isPotentialleTrustworthyIPv4 = RegExp.prototype.test.bind(/^127\.(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)\.){2}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)$/);
30944
+ var isPotentiallyTrustworthyIPv4 = RegExp.prototype.test.bind(/^127\.(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)\.){2}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)$/);
30943
30945
  var isPotentiallyTrustworthyIPv6 = RegExp.prototype.test.bind(/^(?:(?:0{1,4}:){7}|(?:0{1,4}:){1,6}:|::)0{0,3}1$/);
30944
30946
  function isOriginIPPotentiallyTrustworthy(origin) {
30945
30947
  if (origin.includes(":")) {
@@ -30948,7 +30950,7 @@ var require_util4 = __commonJS({
30948
30950
  }
30949
30951
  return isPotentiallyTrustworthyIPv6(origin);
30950
30952
  }
30951
- return isPotentialleTrustworthyIPv4(origin);
30953
+ return isPotentiallyTrustworthyIPv4(origin);
30952
30954
  }
30953
30955
  function isOriginPotentiallyTrustworthy(origin) {
30954
30956
  if (origin == null || origin === "null") {
@@ -31610,18 +31612,10 @@ var require_formdata = __commonJS({
31610
31612
  }
31611
31613
  }
31612
31614
  [nodeUtil.inspect.custom](depth, options) {
31613
- const state = this.#state.reduce((a, b) => {
31614
- if (a[b.name]) {
31615
- if (Array.isArray(a[b.name])) {
31616
- a[b.name].push(b.value);
31617
- } else {
31618
- a[b.name] = [a[b.name], b.value];
31619
- }
31620
- } else {
31621
- a[b.name] = b.value;
31622
- }
31623
- return a;
31624
- }, { __proto__: null });
31615
+ const state = Object.groupBy(this.#state, ({ name }) => name);
31616
+ for (const [name, entries2] of Object.entries(state)) {
31617
+ state[name] = entries2.length === 1 ? entries2[0].value : entries2.map(({ value }) => value);
31618
+ }
31625
31619
  options.depth ??= depth;
31626
31620
  options.colors ??= true;
31627
31621
  const output2 = nodeUtil.formatWithOptions(options, state);
@@ -31717,6 +31711,8 @@ var require_request = __commonJS({
31717
31711
  var kHandler = /* @__PURE__ */ Symbol("handler");
31718
31712
  var kController = /* @__PURE__ */ Symbol("controller");
31719
31713
  var kResume = /* @__PURE__ */ Symbol("resume");
31714
+ function noop() {
31715
+ }
31720
31716
  var RequestController = class {
31721
31717
  #paused = false;
31722
31718
  #reason = null;
@@ -32040,11 +32036,23 @@ var require_request = __commonJS({
32040
32036
  this.endHandler = null;
32041
32037
  }
32042
32038
  }
32039
+ // Fails a request that was aborted before it reached a connection. The
32040
+ // handler gets an aborted controller, so wrappers such as RetryHandler can
32041
+ // tell a caller abort apart from a retryable connection failure.
32042
+ onQueuedAbort(reason) {
32043
+ this[kController] = createAbortedController(reason);
32044
+ return this.onResponseError(reason);
32045
+ }
32043
32046
  addHeader(key, value) {
32044
32047
  processHeader(this, key, value);
32045
32048
  return this;
32046
32049
  }
32047
32050
  };
32051
+ function createAbortedController(reason) {
32052
+ const controller = new RequestController(noop);
32053
+ controller.abort(reason);
32054
+ return controller;
32055
+ }
32048
32056
  function processHeader(request, key, val) {
32049
32057
  if (val && (typeof val === "object" && !Array.isArray(val))) {
32050
32058
  throw new InvalidArgumentError(`invalid ${key} header`);
@@ -32141,6 +32149,7 @@ var require_request = __commonJS({
32141
32149
  return isFormData(body);
32142
32150
  }
32143
32151
  module.exports = Request;
32152
+ module.exports.createAbortedController = createAbortedController;
32144
32153
  }
32145
32154
  });
32146
32155
 
@@ -32149,7 +32158,8 @@ var require_dispatcher = __commonJS({
32149
32158
  "node_modules/undici/lib/dispatcher/dispatcher.js"(exports, module) {
32150
32159
  "use strict";
32151
32160
  var EventEmitter = __require("node:events");
32152
- var { kOriginless, kUrl } = require_symbols();
32161
+ var { InvalidArgumentError } = require_errors4();
32162
+ var { kOriginless, kUrl, kInterceptorKind } = require_symbols();
32153
32163
  var Dispatcher = class extends EventEmitter {
32154
32164
  dispatch() {
32155
32165
  throw new Error("not implemented");
@@ -32164,6 +32174,7 @@ var require_dispatcher = __commonJS({
32164
32174
  const interceptors = Array.isArray(args[0]) ? args[0] : args;
32165
32175
  const interceptorOrigin = this[kOriginless] === true ? null : this[kUrl]?.origin;
32166
32176
  let dispatch = this.dispatch.bind(this);
32177
+ const orderSensitiveKinds = [];
32167
32178
  for (const interceptor of interceptors) {
32168
32179
  if (interceptor == null) {
32169
32180
  continue;
@@ -32171,11 +32182,19 @@ var require_dispatcher = __commonJS({
32171
32182
  if (typeof interceptor !== "function") {
32172
32183
  throw new TypeError(`invalid interceptor, expected function received ${typeof interceptor}`);
32173
32184
  }
32185
+ if (interceptor[kInterceptorKind] != null) {
32186
+ orderSensitiveKinds.push(interceptor[kInterceptorKind]);
32187
+ }
32174
32188
  dispatch = interceptor(dispatch, interceptorOrigin);
32175
32189
  if (dispatch == null || typeof dispatch !== "function" || dispatch.length !== 2) {
32176
32190
  throw new TypeError("invalid interceptor");
32177
32191
  }
32178
32192
  }
32193
+ const cacheIndex2 = orderSensitiveKinds.indexOf("cache");
32194
+ const redirectIndex = orderSensitiveKinds.indexOf("redirect");
32195
+ if (cacheIndex2 !== -1 && redirectIndex !== -1 && cacheIndex2 < redirectIndex) {
32196
+ throw new InvalidArgumentError("the cache interceptor must be composed after the redirect interceptor; composing the cache before the redirect disables the cache's cross-origin and credential redirect guards (GHSA-75VM-9G8F-99J4, GHSA-MQG3-3V4R-CM32, GHSA-4W7W-5XRC-9H26, GHSA-7XG3-FPHP-28HG)");
32197
+ }
32179
32198
  const originalDispatch = dispatch;
32180
32199
  const self = this;
32181
32200
  dispatch = function(opts, handler) {
@@ -32349,7 +32368,7 @@ var require_dispatcher_base = __commonJS({
32349
32368
  throw err;
32350
32369
  }
32351
32370
  handler.onResponseError(null, err);
32352
- return false;
32371
+ return true;
32353
32372
  }
32354
32373
  }
32355
32374
  };
@@ -36596,6 +36615,7 @@ var require_client_h1 = __commonJS({
36596
36615
  var kIdleSocketValidation = /* @__PURE__ */ Symbol("kIdleSocketValidation");
36597
36616
  var kIdleSocketValidationTimeout = /* @__PURE__ */ Symbol("kIdleSocketValidationTimeout");
36598
36617
  var kSocketUsed = /* @__PURE__ */ Symbol("kSocketUsed");
36618
+ var kIdleSince = /* @__PURE__ */ Symbol("kIdleSince");
36599
36619
  var kTypeOfService = /* @__PURE__ */ Symbol("kTypeOfService");
36600
36620
  var extractBody;
36601
36621
  function lazyllhttp() {
@@ -37367,6 +37387,10 @@ var require_client_h1 = __commonJS({
37367
37387
  }
37368
37388
  });
37369
37389
  }
37390
+ function isIdleSocketExpired(socket) {
37391
+ const parser = socket[kParser];
37392
+ return parser.timeoutType === TIMEOUT_KEEP_ALIVE && parser.timeoutValue > 0 && performance.now() - socket[kIdleSince] >= parser.timeoutValue;
37393
+ }
37370
37394
  function resumeH1(client) {
37371
37395
  const socket = client[kSocket];
37372
37396
  if (socket && !socket.destroyed) {
@@ -37379,6 +37403,10 @@ var require_client_h1 = __commonJS({
37379
37403
  socket.ref();
37380
37404
  socket[kNoRef] = false;
37381
37405
  }
37406
+ if (client[kRunning] === 0 && client[kPending] > 0 && isIdleSocketExpired(socket)) {
37407
+ util.destroy(socket, new InformationalError("socket idle timeout"));
37408
+ return;
37409
+ }
37382
37410
  if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) {
37383
37411
  if (socket[kIdleSocketValidation] === 0) {
37384
37412
  scheduleIdleSocketValidation(client, socket);
@@ -37404,6 +37432,7 @@ var require_client_h1 = __commonJS({
37404
37432
  }
37405
37433
  if (client[kSize] === 0) {
37406
37434
  if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) {
37435
+ socket[kIdleSince] = performance.now();
37407
37436
  socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE);
37408
37437
  }
37409
37438
  } else if (client[kRunning] > 0 && socket[kParser].statusCode < 200) {
@@ -37955,6 +37984,7 @@ var require_client_h2 = __commonJS({
37955
37984
  HTTP2_HEADER_STATUS,
37956
37985
  HTTP2_HEADER_PROTOCOL,
37957
37986
  NGHTTP2_NO_ERROR,
37987
+ NGHTTP2_PROTOCOL_ERROR,
37958
37988
  NGHTTP2_REFUSED_STREAM
37959
37989
  }
37960
37990
  } = http2;
@@ -38106,7 +38136,9 @@ var require_client_h2 = __commonJS({
38106
38136
  // refH2Session/unrefH2Session.
38107
38137
  refed: true,
38108
38138
  ping: {
38109
- interval: client[kHTTP2Options].pingInterval === 0 ? null : setInterval(onHttp2SendPing, client[kHTTP2Options].pingInterval, session).unref()
38139
+ interval: client[kHTTP2Options].pingInterval === 0 ? null : setInterval(onHttp2SendPing, client[kHTTP2Options].pingInterval, session).unref(),
38140
+ // Set while a periodic PING waits for its ack.
38141
+ pending: false
38110
38142
  }
38111
38143
  };
38112
38144
  session[kReceivedGoAway] = false;
@@ -38287,6 +38319,9 @@ var require_client_h2 = __commonJS({
38287
38319
  if (session.closed || session.destroyed) {
38288
38320
  return;
38289
38321
  }
38322
+ resetUnresponsiveHttp2Session(session);
38323
+ }
38324
+ function resetUnresponsiveHttp2Session(session) {
38290
38325
  const err = new SocketError("HTTP/2: connection unresponsive", util.getSocketInfo(session[kSocket]));
38291
38326
  session[kError] = err;
38292
38327
  resetHttp2Session(session, err);
@@ -38354,13 +38389,19 @@ var require_client_h2 = __commonJS({
38354
38389
  state.ping.interval = null;
38355
38390
  return;
38356
38391
  }
38392
+ if (state.ping.pending) {
38393
+ resetUnresponsiveHttp2Session(session);
38394
+ return;
38395
+ }
38396
+ state.ping.pending = true;
38357
38397
  session.ping(onPing.bind(session));
38358
38398
  function onPing(err, duration3) {
38399
+ state.ping.pending = false;
38359
38400
  const client = this[kClient];
38360
38401
  const socket = this[kSocket];
38361
38402
  if (err != null) {
38362
38403
  const error62 = new InformationalError(`HTTP/2: "PING" errored - type ${err.message}`);
38363
- socket[kError] = error62;
38404
+ socket[kError] ??= error62;
38364
38405
  client[kOnError](error62);
38365
38406
  } else {
38366
38407
  client.emit("ping", duration3);
@@ -39012,8 +39053,10 @@ var require_client_h2 = __commonJS({
39012
39053
  }
39013
39054
  stream.off("error", onError);
39014
39055
  stream.on("error", noop);
39015
- if (state.responseContentLength != null && state.bytesRead !== state.responseContentLength) {
39016
- err = new ResponseContentLengthMismatchError();
39056
+ if ((err.code === "ERR_HTTP2_ERROR" || err.code === "ERR_HTTP2_STREAM_ERROR" && stream.rstCode === NGHTTP2_PROTOCOL_ERROR) && state.responseContentLength != null && state.bytesRead !== state.responseContentLength) {
39057
+ const mismatch = new ResponseContentLengthMismatchError();
39058
+ mismatch.cause = err;
39059
+ err = mismatch;
39017
39060
  }
39018
39061
  if (typeof stream.rstCode === "number" && stream.rstCode !== NGHTTP2_NO_ERROR) {
39019
39062
  err.http2ErrorCode = stream.rstCode;
@@ -39309,11 +39352,13 @@ var require_client = __commonJS({
39309
39352
  kHostAuthority,
39310
39353
  kResume,
39311
39354
  kHTTP2Options,
39312
- kUseMilo
39355
+ kUseMilo,
39356
+ kQueuedAbort
39313
39357
  } = require_symbols();
39314
39358
  var connectH1 = require_client_h1();
39315
39359
  var connectH2 = require_client_h2();
39316
39360
  var kClosedResolve = /* @__PURE__ */ Symbol("kClosedResolve");
39361
+ var kCancelConnect = /* @__PURE__ */ Symbol("kCancelConnect");
39317
39362
  var getDefaultNodeMaxHeaderSize = http && http.maxHeaderSize && Number.isInteger(http.maxHeaderSize) && http.maxHeaderSize > 0 ? () => http.maxHeaderSize : () => {
39318
39363
  throw new InvalidArgumentError("http module not available or http.maxHeaderSize invalid");
39319
39364
  };
@@ -39521,6 +39566,7 @@ var require_client = __commonJS({
39521
39566
  this[kClosedResolve] = null;
39522
39567
  this[kMaxResponseSize] = maxResponseSize > -1 ? maxResponseSize : -1;
39523
39568
  this[kHTTPContext] = null;
39569
+ this[kCancelConnect] = null;
39524
39570
  this[kHTTP2Options] = {
39525
39571
  pingInterval: h2Options?.pingInterval ?? pingInterval ?? 6e4,
39526
39572
  connectionWindowSize: h2Options?.connectionWindowSize ?? connectionWindowSize ?? 524288,
@@ -39573,6 +39619,7 @@ var require_client = __commonJS({
39573
39619
  }
39574
39620
  [kConnect](cb) {
39575
39621
  connect(this);
39622
+ this[kCancelConnect] = null;
39576
39623
  this.once("connect", cb);
39577
39624
  }
39578
39625
  [kDispatch](opts, handler) {
@@ -39585,6 +39632,12 @@ var require_client = __commonJS({
39585
39632
  } else {
39586
39633
  this[kResume](true);
39587
39634
  }
39635
+ if (request.abort === null && !request.aborted) {
39636
+ const onQueued = opts[kQueuedAbort];
39637
+ if (onQueued !== void 0) {
39638
+ onQueued((reason) => abortPendingRequest(this, request, reason));
39639
+ }
39640
+ }
39588
39641
  if (this[kResuming] && this[kNeedDrain] !== 2 && this[kBusy]) {
39589
39642
  this[kNeedDrain] = 2;
39590
39643
  }
@@ -39625,6 +39678,39 @@ var require_client = __commonJS({
39625
39678
  });
39626
39679
  }
39627
39680
  };
39681
+ function failQueuedRequest(client, request, reason) {
39682
+ try {
39683
+ request.onQueuedAbort(reason);
39684
+ assert2(request.aborted);
39685
+ } catch (err) {
39686
+ client.emit("error", err);
39687
+ }
39688
+ }
39689
+ function abortPendingRequest(client, request, reason) {
39690
+ if (request.aborted || request.abort !== null) {
39691
+ return;
39692
+ }
39693
+ const queue = client[kQueue];
39694
+ const idx = queue.indexOf(request, client[kPendingIdx]);
39695
+ if (idx === -1) {
39696
+ return;
39697
+ }
39698
+ if (idx === client[kPendingIdx] && client[kResuming] === 2) {
39699
+ return;
39700
+ }
39701
+ queue.splice(idx, 1);
39702
+ failQueuedRequest(client, request, reason);
39703
+ client[kResume](true);
39704
+ if (client[kCancelConnect] !== null && client[kSize] === 0) {
39705
+ queueMicrotask(() => cancelUnusedConnect(client));
39706
+ }
39707
+ }
39708
+ function cancelUnusedConnect(client) {
39709
+ const cancel = client[kCancelConnect];
39710
+ if (cancel !== null && client[kSize] === 0) {
39711
+ cancel(new InformationalError("no request waits for this connection"));
39712
+ }
39713
+ }
39628
39714
  function onError(client, err) {
39629
39715
  if (client[kRunning] === 0 && err.code !== "UND_ERR_INFO" && err.code !== "UND_ERR_SOCKET") {
39630
39716
  assert2(client[kPendingIdx] === client[kRunningIdx]);
@@ -39650,6 +39736,28 @@ var require_client = __commonJS({
39650
39736
  hostname3 = ip;
39651
39737
  }
39652
39738
  client[kConnecting] = true;
39739
+ const servername = client[kServerName];
39740
+ let calledBack = false;
39741
+ let cancelled = false;
39742
+ const abandon = (socket, err) => {
39743
+ client[kConnecting] = false;
39744
+ if (channels.connectError.hasSubscribers) {
39745
+ channels.connectError.publish({
39746
+ connectParams: {
39747
+ host,
39748
+ hostname: hostname3,
39749
+ protocol,
39750
+ port,
39751
+ version: client[kHTTPContext]?.version,
39752
+ servername,
39753
+ localAddress: client[kLocalAddress]
39754
+ },
39755
+ connector: client[kConnector],
39756
+ error: err
39757
+ });
39758
+ }
39759
+ util.destroy(socket.on("error", noop), err);
39760
+ };
39653
39761
  if (channels.beforeConnect.hasSubscribers) {
39654
39762
  channels.beforeConnect.publish({
39655
39763
  connectParams: {
@@ -39658,23 +39766,31 @@ var require_client = __commonJS({
39658
39766
  protocol,
39659
39767
  port,
39660
39768
  version: client[kHTTPContext]?.version,
39661
- servername: client[kServerName],
39769
+ servername,
39662
39770
  localAddress: client[kLocalAddress]
39663
39771
  },
39664
39772
  connector: client[kConnector]
39665
39773
  });
39666
39774
  }
39667
39775
  try {
39668
- client[kConnector]({
39776
+ const connecting = client[kConnector]({
39669
39777
  host,
39670
39778
  hostname: hostname3,
39671
39779
  protocol,
39672
39780
  port,
39673
- servername: client[kServerName],
39781
+ servername,
39674
39782
  localAddress: client[kLocalAddress]
39675
39783
  }, (err, socket) => {
39784
+ calledBack = true;
39785
+ if (cancelled) {
39786
+ if (socket) {
39787
+ util.destroy(socket.on("error", noop));
39788
+ }
39789
+ return;
39790
+ }
39791
+ client[kCancelConnect] = null;
39676
39792
  if (err) {
39677
- handleConnectError(client, err, { host, hostname: hostname3, protocol, port });
39793
+ handleConnectError(client, err, { host, hostname: hostname3, protocol, port, servername });
39678
39794
  client[kResume]();
39679
39795
  return;
39680
39796
  }
@@ -39684,11 +39800,16 @@ var require_client = __commonJS({
39684
39800
  return;
39685
39801
  }
39686
39802
  assert2(socket);
39803
+ if (client[kServerName] !== servername) {
39804
+ abandon(socket, new InformationalError("servername changed"));
39805
+ client[kResume]();
39806
+ return;
39807
+ }
39687
39808
  try {
39688
39809
  client[kHTTPContext] = socket.alpnProtocol === "h2" ? connectH2(client, socket) : connectH1(client, socket);
39689
39810
  } catch (err2) {
39690
39811
  socket.destroy().on("error", noop);
39691
- handleConnectError(client, err2, { host, hostname: hostname3, protocol, port });
39812
+ handleConnectError(client, err2, { host, hostname: hostname3, protocol, port, servername });
39692
39813
  client[kResume]();
39693
39814
  return;
39694
39815
  }
@@ -39705,7 +39826,7 @@ var require_client = __commonJS({
39705
39826
  protocol,
39706
39827
  port,
39707
39828
  version: client[kHTTPContext]?.version,
39708
- servername: client[kServerName],
39829
+ servername,
39709
39830
  localAddress: client[kLocalAddress]
39710
39831
  },
39711
39832
  connector: client[kConnector],
@@ -39715,12 +39836,19 @@ var require_client = __commonJS({
39715
39836
  client.emit("connect", client[kUrl], [client]);
39716
39837
  client[kResume]();
39717
39838
  });
39839
+ if (!calledBack && util.isStream(connecting)) {
39840
+ client[kCancelConnect] = (err) => {
39841
+ cancelled = true;
39842
+ client[kCancelConnect] = null;
39843
+ abandon(connecting, err);
39844
+ };
39845
+ }
39718
39846
  } catch (err) {
39719
- handleConnectError(client, err, { host, hostname: hostname3, protocol, port });
39847
+ handleConnectError(client, err, { host, hostname: hostname3, protocol, port, servername });
39720
39848
  client[kResume]();
39721
39849
  }
39722
39850
  }
39723
- function handleConnectError(client, err, { host, hostname: hostname3, protocol, port }) {
39851
+ function handleConnectError(client, err, { host, hostname: hostname3, protocol, port, servername }) {
39724
39852
  if (client.destroyed) {
39725
39853
  return;
39726
39854
  }
@@ -39733,7 +39861,7 @@ var require_client = __commonJS({
39733
39861
  protocol,
39734
39862
  port,
39735
39863
  version: client[kHTTPContext]?.version,
39736
- servername: client[kServerName],
39864
+ servername,
39737
39865
  localAddress: client[kLocalAddress]
39738
39866
  },
39739
39867
  connector: client[kConnector],
@@ -39746,7 +39874,7 @@ var require_client = __commonJS({
39746
39874
  for (let i2 = 0; i2 < running.length; i2++) {
39747
39875
  util.errorRequest(client, running[i2], err);
39748
39876
  }
39749
- while (client[kPending] > 0 && client[kQueue][client[kPendingIdx]].servername === client[kServerName]) {
39877
+ while (client[kPending] > 0 && client[kQueue][client[kPendingIdx]].servername === servername) {
39750
39878
  const request = client[kQueue].splice(client[kPendingIdx], 1)[0];
39751
39879
  util.errorRequest(client, request, err);
39752
39880
  }
@@ -39820,6 +39948,7 @@ var require_client = __commonJS({
39820
39948
  client[kHTTPContext] = null;
39821
39949
  resume(client);
39822
39950
  });
39951
+ client[kCancelConnect]?.(new InformationalError("servername changed"));
39823
39952
  }
39824
39953
  if (client[kConnecting]) {
39825
39954
  return;
@@ -39925,7 +40054,8 @@ var require_pool_base = __commonJS({
39925
40054
  var { PoolStats } = require_stats();
39926
40055
  var DispatcherBase = require_dispatcher_base();
39927
40056
  var FixedQueue = require_fixed_queue();
39928
- var { kConnected, kSize, kRunning, kPending, kQueued, kBusy, kFree, kUrl, kClose, kDestroy, kDispatch } = require_symbols();
40057
+ var { kConnected, kSize, kRunning, kPending, kQueued, kBusy, kFree, kUrl, kClose, kDestroy, kDispatch, kQueuedAbort } = require_symbols();
40058
+ var { createAbortedController } = require_request();
39929
40059
  var kClients = /* @__PURE__ */ Symbol("clients");
39930
40060
  var kNeedDrain = /* @__PURE__ */ Symbol("needDrain");
39931
40061
  var kQueue = /* @__PURE__ */ Symbol("queue");
@@ -39943,11 +40073,14 @@ var require_pool_base = __commonJS({
39943
40073
  var kRemoveClient = /* @__PURE__ */ Symbol("remove client");
39944
40074
  var kRetireClient = /* @__PURE__ */ Symbol("retire client");
39945
40075
  var kRetiring = /* @__PURE__ */ Symbol("retiring clients");
40076
+ var kShiftQueue = /* @__PURE__ */ Symbol("shift queue");
40077
+ var kAbortQueued = /* @__PURE__ */ Symbol("abort queued");
39946
40078
  var QueuedRequest = class extends AsyncResource {
39947
40079
  constructor(opts, handler) {
39948
40080
  super("UNDICI_POOL_QUEUED_REQUEST");
39949
40081
  this.opts = opts;
39950
40082
  this.handler = handler;
40083
+ this.queued = true;
39951
40084
  }
39952
40085
  dispatch(dispatcher) {
39953
40086
  return this.runInAsyncScope(dispatcher.dispatch, dispatcher, this.opts, this.handler);
@@ -39978,21 +40111,19 @@ var require_pool_base = __commonJS({
39978
40111
  if (client.closed || client.destroyed) {
39979
40112
  return;
39980
40113
  }
39981
- const queue = this[kQueue];
39982
40114
  let needDrain = false;
39983
40115
  this[kOnClientDrain](client);
39984
40116
  while (!needDrain) {
39985
- const item = queue.shift();
40117
+ const item = this[kShiftQueue]();
39986
40118
  if (!item) {
39987
40119
  break;
39988
40120
  }
39989
- this[kQueued]--;
39990
40121
  needDrain = !item.dispatch(client);
39991
40122
  }
39992
40123
  client[kNeedDrain] = needDrain;
39993
40124
  if (needDrain) {
39994
40125
  this[kOnClientBusy](client);
39995
- if (!queue.isEmpty()) {
40126
+ if (this[kQueued] > 0) {
39996
40127
  return this[kDrainQueue](origin, targets);
39997
40128
  }
39998
40129
  }
@@ -40000,7 +40131,7 @@ var require_pool_base = __commonJS({
40000
40131
  this[kNeedDrain] = false;
40001
40132
  this.emit("drain", origin, [this, ...targets]);
40002
40133
  }
40003
- if (this[kClosedResolve] && queue.isEmpty()) {
40134
+ if (this[kClosedResolve] && this[kQueued] === 0) {
40004
40135
  return closeClients(this).then(this[kClosedResolve]);
40005
40136
  }
40006
40137
  }
@@ -40009,20 +40140,26 @@ var require_pool_base = __commonJS({
40009
40140
  [kOnClientDrain]() {
40010
40141
  }
40011
40142
  [kDrainQueue](origin, targets) {
40012
- const queue = this[kQueue];
40013
40143
  let hasDispatcher = true;
40014
- while (!queue.isEmpty()) {
40015
- const dispatcher = this[kGetDispatcher]();
40144
+ while (this[kQueued] > 0) {
40145
+ let dispatcher;
40146
+ try {
40147
+ dispatcher = this[kGetDispatcher]();
40148
+ } catch (err) {
40149
+ const item2 = this[kShiftQueue]();
40150
+ item2.runInAsyncScope(item2.handler.onResponseError, item2.handler, null, err);
40151
+ hasDispatcher = !this.destroyed && this[kHasDispatcher](false);
40152
+ continue;
40153
+ }
40016
40154
  if (!dispatcher) {
40017
40155
  hasDispatcher = false;
40018
40156
  break;
40019
40157
  }
40020
- const item = queue.shift();
40021
- this[kQueued]--;
40158
+ const item = this[kShiftQueue]();
40022
40159
  if (!item.dispatch(dispatcher)) {
40023
40160
  dispatcher[kNeedDrain] = true;
40024
40161
  this[kOnClientBusy](dispatcher);
40025
- hasDispatcher = this[kHasDispatcher]();
40162
+ hasDispatcher = this[kHasDispatcher](false);
40026
40163
  if (!hasDispatcher) {
40027
40164
  break;
40028
40165
  }
@@ -40032,10 +40169,40 @@ var require_pool_base = __commonJS({
40032
40169
  this[kNeedDrain] = false;
40033
40170
  this.emit("drain", origin, [this, ...targets]);
40034
40171
  }
40035
- if (this[kClosedResolve] && queue.isEmpty()) {
40172
+ if (this[kClosedResolve] && this[kQueued] === 0) {
40036
40173
  return closeClients(this).then(this[kClosedResolve]);
40037
40174
  }
40038
40175
  }
40176
+ // Aborted requests stay in the queue as tombstones (queued === false) and
40177
+ // are skipped here; kQueued only counts the live ones.
40178
+ [kShiftQueue]() {
40179
+ const queue = this[kQueue];
40180
+ let item = queue.shift();
40181
+ while (item !== null && item.queued === false) {
40182
+ item = queue.shift();
40183
+ }
40184
+ if (item !== null) {
40185
+ this[kQueued]--;
40186
+ item.queued = false;
40187
+ }
40188
+ return item;
40189
+ }
40190
+ // Called through the handler's kQueuedAbort hook when a queued request is
40191
+ // aborted.
40192
+ [kAbortQueued](item, reason) {
40193
+ if (!item.queued) {
40194
+ return;
40195
+ }
40196
+ const { handler } = item;
40197
+ item.queued = false;
40198
+ item.opts = null;
40199
+ item.handler = null;
40200
+ this[kQueued]--;
40201
+ item.runInAsyncScope(handler.onResponseError, handler, createAbortedController(reason), reason);
40202
+ if (this[kClosedResolve] && this[kQueued] === 0) {
40203
+ closeClients(this).then(this[kClosedResolve]);
40204
+ }
40205
+ }
40039
40206
  [kOnConnect] = (origin, targets) => {
40040
40207
  this.emit("connect", origin, [this, ...targets]);
40041
40208
  };
@@ -40087,7 +40254,7 @@ var require_pool_base = __commonJS({
40087
40254
  return new PoolStats(this);
40088
40255
  }
40089
40256
  [kClose]() {
40090
- if (this[kQueue].isEmpty()) {
40257
+ if (this[kQueued] === 0) {
40091
40258
  return closeClients(this);
40092
40259
  } else {
40093
40260
  return new Promise((resolve6) => {
@@ -40097,7 +40264,7 @@ var require_pool_base = __commonJS({
40097
40264
  }
40098
40265
  [kDestroy](err) {
40099
40266
  while (true) {
40100
- const item = this[kQueue].shift();
40267
+ const item = this[kShiftQueue]();
40101
40268
  if (!item) {
40102
40269
  break;
40103
40270
  }
@@ -40115,9 +40282,14 @@ var require_pool_base = __commonJS({
40115
40282
  [kDispatch](opts, handler) {
40116
40283
  const dispatcher = this[kGetDispatcher]();
40117
40284
  if (!dispatcher) {
40285
+ const item = new QueuedRequest(opts, handler);
40118
40286
  this[kNeedDrain] = true;
40119
- this[kQueue].push(new QueuedRequest(opts, handler));
40287
+ this[kQueue].push(item);
40120
40288
  this[kQueued]++;
40289
+ const onQueued = opts[kQueuedAbort];
40290
+ if (onQueued !== void 0) {
40291
+ onQueued((reason) => this[kAbortQueued](item, reason));
40292
+ }
40121
40293
  } else if (!dispatcher.dispatch(opts, handler)) {
40122
40294
  dispatcher[kNeedDrain] = true;
40123
40295
  this[kOnClientBusy](dispatcher);
@@ -40215,7 +40387,7 @@ var require_pool = __commonJS({
40215
40387
  InvalidArgumentError
40216
40388
  } = require_errors4();
40217
40389
  var util = require_util3();
40218
- var { kConnecting, kHTTPContext, kUrl, kQueued } = require_symbols();
40390
+ var { kConnecting, kHTTPContext, kHTTP2Session, kRemoteSettings, kUrl, kQueued } = require_symbols();
40219
40391
  var buildConnector2 = require_connect();
40220
40392
  var kOptions = /* @__PURE__ */ Symbol("options");
40221
40393
  var kConnections = /* @__PURE__ */ Symbol("connections");
@@ -40291,9 +40463,19 @@ var require_pool = __commonJS({
40291
40463
  this[kProtocol] = client[kHTTPContext]?.version;
40292
40464
  }
40293
40465
  if (client === this[kProtocolProbe]) {
40294
- if (this[kProtocol] !== "h2") {
40295
- this[kProtocolProbe] = null;
40296
- this[kDrainQueue](origin2, targets.slice(1));
40466
+ const releaseProbe = () => {
40467
+ if (client === this[kProtocolProbe]) {
40468
+ this[kProtocolProbe] = null;
40469
+ if (!this.destroyed && (this[kQueued] > 0 || !this.closed && this[kHasDispatcher](false))) {
40470
+ this[kDrainQueue](origin2, targets.slice(1));
40471
+ }
40472
+ }
40473
+ };
40474
+ const session = client[kHTTP2Session];
40475
+ if (this[kProtocol] !== "h2" || session[kRemoteSettings]) {
40476
+ releaseProbe();
40477
+ } else {
40478
+ session.once("remoteSettings", releaseProbe);
40297
40479
  }
40298
40480
  }
40299
40481
  });
@@ -40347,7 +40529,7 @@ var require_pool = __commonJS({
40347
40529
  return createClient(this);
40348
40530
  }
40349
40531
  }
40350
- [kHasDispatcher]() {
40532
+ [kHasDispatcher](create = true) {
40351
40533
  const clientTtlOption = this[kOptions].clientTtl;
40352
40534
  for (let i2 = 0; i2 < this[kClients].length; i2++) {
40353
40535
  const client = this[kClients][i2];
@@ -40362,7 +40544,7 @@ var require_pool = __commonJS({
40362
40544
  return false;
40363
40545
  }
40364
40546
  if (!this[kConnections] || this[kClients].length < this[kConnections]) {
40365
- createClient(this);
40547
+ if (create) createClient(this);
40366
40548
  return true;
40367
40549
  }
40368
40550
  return false;
@@ -40738,11 +40920,19 @@ var require_agent = __commonJS({
40738
40920
  let dispatcher = this[kClients].get(key);
40739
40921
  if (!dispatcher) {
40740
40922
  dispatcher = this[kFactory](opts.origin, allowH2 === false ? { ...this[kOptions], allowH2: false } : this[kOptions]);
40741
- const closeClientIfUnused = () => {
40923
+ const closeClientIfUnused = (deferred = false) => {
40742
40924
  if (this[kClients].get(key) !== dispatcher) {
40743
40925
  return;
40744
40926
  }
40745
- if (dispatcher[kConnected] > 0 || dispatcher[kBusy] || dispatcher[kPending] > 0) {
40927
+ if (dispatcher[kConnected] > 0 || dispatcher[kBusy]) {
40928
+ return;
40929
+ }
40930
+ if (dispatcher[kPending] > 0) {
40931
+ if (!deferred) {
40932
+ queueMicrotask(() => {
40933
+ closeClientIfUnused(true);
40934
+ });
40935
+ }
40746
40936
  return;
40747
40937
  }
40748
40938
  this[kClients].delete(key);
@@ -41794,8 +41984,10 @@ var require_proxy_agent = __commonJS({
41794
41984
  headers: this[kProxyHeaders],
41795
41985
  connect,
41796
41986
  factory: agentFactory,
41797
- username: opts.username || username,
41798
- password: opts.password || password,
41987
+ // Socks5ProxyAgent decodes the credentials embedded in the URI;
41988
+ // the URL getters return them still percent-encoded.
41989
+ username: opts.username,
41990
+ password: opts.password,
41799
41991
  connectTimeout,
41800
41992
  proxyTls: opts.proxyTls,
41801
41993
  requestTls: opts.requestTls
@@ -42133,7 +42325,7 @@ var require_retry_handler = __commonJS({
42133
42325
  "node_modules/undici/lib/handler/retry-handler.js"(exports, module) {
42134
42326
  "use strict";
42135
42327
  var assert2 = __require("node:assert");
42136
- var { kRetryHandlerDefaultRetry } = require_symbols();
42328
+ var { kRetryHandlerDefaultRetry, kQueuedAbort } = require_symbols();
42137
42329
  var { RequestRetryError, RequestAbortedError } = require_errors4();
42138
42330
  var {
42139
42331
  hasSafeIterator,
@@ -42217,6 +42409,10 @@ var require_retry_handler = __commonJS({
42217
42409
  }
42218
42410
  };
42219
42411
  var RetryHandler = class _RetryHandler {
42412
+ // Takes the retry that waits for a connection out of its queue.
42413
+ #queuedCancel = null;
42414
+ // Whether retries are dispatched with a hook that sets #queuedCancel.
42415
+ #tracksQueuedRetry = false;
42220
42416
  constructor(opts, { dispatch, handler }) {
42221
42417
  const { retryOptions, ...dispatchOpts } = opts;
42222
42418
  const {
@@ -42557,6 +42753,14 @@ var require_retry_handler = __commonJS({
42557
42753
  headers: buildResumeHeaders(this.opts.headers, `bytes=${this.start}-${this.end ?? ""}`, this.etag)
42558
42754
  };
42559
42755
  }
42756
+ if (!this.#tracksQueuedRetry) {
42757
+ this.#tracksQueuedRetry = true;
42758
+ const onQueued = this.opts[kQueuedAbort];
42759
+ this.opts[kQueuedAbort] = (cancel) => {
42760
+ this.#queuedCancel = cancel;
42761
+ onQueued?.(cancel);
42762
+ };
42763
+ }
42560
42764
  try {
42561
42765
  this.retryCountCheckpoint = this.retryCount;
42562
42766
  this.dispatch(this.opts, this);
@@ -42600,6 +42804,11 @@ var require_retry_handler = __commonJS({
42600
42804
  ) ?? null;
42601
42805
  }
42602
42806
  #onAbort(reason) {
42807
+ const cancel = this.#queuedCancel;
42808
+ if (cancel !== null) {
42809
+ this.#queuedCancel = null;
42810
+ cancel(reason ?? new RequestAbortedError());
42811
+ }
42603
42812
  if (!this.retryPending) {
42604
42813
  return;
42605
42814
  }
@@ -43156,6 +43365,89 @@ var require_readable = __commonJS({
43156
43365
  }
43157
43366
  });
43158
43367
 
43368
+ // node_modules/undici/lib/api/abort-signal.js
43369
+ var require_abort_signal = __commonJS({
43370
+ "node_modules/undici/lib/api/abort-signal.js"(exports, module) {
43371
+ "use strict";
43372
+ var { addAbortListener } = require_util3();
43373
+ var { RequestAbortedError } = require_errors4();
43374
+ var { kQueuedAbort } = require_symbols();
43375
+ var kListener = /* @__PURE__ */ Symbol("kListener");
43376
+ var kSignal = /* @__PURE__ */ Symbol("kSignal");
43377
+ function abort(self) {
43378
+ self.reason = self[kSignal]?.reason ?? new RequestAbortedError();
43379
+ if (self.abort) {
43380
+ self.abort(self.reason);
43381
+ }
43382
+ removeSignal(self);
43383
+ }
43384
+ function addSignal(self, signal) {
43385
+ self.reason = null;
43386
+ self[kSignal] = null;
43387
+ self[kListener] = null;
43388
+ if (!signal) {
43389
+ return;
43390
+ }
43391
+ if (signal.aborted) {
43392
+ self.reason = signal.reason ?? new RequestAbortedError();
43393
+ return;
43394
+ }
43395
+ self[kSignal] = signal;
43396
+ self[kListener] = () => {
43397
+ abort(self);
43398
+ };
43399
+ addAbortListener(self[kSignal], self[kListener]);
43400
+ }
43401
+ function removeSignal(self) {
43402
+ if (!self[kSignal]) {
43403
+ return;
43404
+ }
43405
+ if ("removeEventListener" in self[kSignal]) {
43406
+ self[kSignal].removeEventListener("abort", self[kListener]);
43407
+ } else {
43408
+ self[kSignal].removeListener("abort", self[kListener]);
43409
+ }
43410
+ self[kSignal] = null;
43411
+ self[kListener] = null;
43412
+ }
43413
+ function queuedAbortHook(handler) {
43414
+ let started = null;
43415
+ let installed = null;
43416
+ return (cancel) => {
43417
+ if (handler.reason) {
43418
+ cancel(handler.reason);
43419
+ return;
43420
+ }
43421
+ if (handler.abort !== installed) {
43422
+ started = handler.abort;
43423
+ }
43424
+ if (started === null) {
43425
+ installed = cancel;
43426
+ } else {
43427
+ const abortStarted = started;
43428
+ installed = (reason) => {
43429
+ abortStarted(reason);
43430
+ cancel(reason);
43431
+ };
43432
+ }
43433
+ handler.abort = installed;
43434
+ };
43435
+ }
43436
+ function dispatchWithSignal(dispatcher, opts, handler) {
43437
+ if (handler.reason) {
43438
+ handler.onResponseError(null, handler.reason);
43439
+ return;
43440
+ }
43441
+ dispatcher.dispatch({ ...opts, [kQueuedAbort]: queuedAbortHook(handler) }, handler);
43442
+ }
43443
+ module.exports = {
43444
+ addSignal,
43445
+ removeSignal,
43446
+ dispatchWithSignal
43447
+ };
43448
+ }
43449
+ });
43450
+
43159
43451
  // node_modules/undici/lib/api/api-request.js
43160
43452
  var require_api_request = __commonJS({
43161
43453
  "node_modules/undici/lib/api/api-request.js"(exports, module) {
@@ -43165,6 +43457,7 @@ var require_api_request = __commonJS({
43165
43457
  var { Readable } = require_readable();
43166
43458
  var { InvalidArgumentError, RequestAbortedError } = require_errors4();
43167
43459
  var util = require_util3();
43460
+ var { dispatchWithSignal } = require_abort_signal();
43168
43461
  function noop() {
43169
43462
  }
43170
43463
  var RequestHandler = class extends AsyncResource {
@@ -43189,6 +43482,9 @@ var require_api_request = __commonJS({
43189
43482
  if (onInfo && typeof onInfo !== "function") {
43190
43483
  throw new InvalidArgumentError("invalid onInfo callback");
43191
43484
  }
43485
+ if (signal?.aborted) {
43486
+ throw signal.reason ?? new RequestAbortedError();
43487
+ }
43192
43488
  super("UNDICI_REQUEST");
43193
43489
  } catch (err) {
43194
43490
  if (util.isStream(body)) {
@@ -43210,9 +43506,7 @@ var require_api_request = __commonJS({
43210
43506
  this.highWaterMark = highWaterMark;
43211
43507
  this.reason = null;
43212
43508
  this.removeAbortListener = null;
43213
- if (signal?.aborted) {
43214
- this.reason = signal.reason ?? new RequestAbortedError();
43215
- } else if (signal) {
43509
+ if (signal) {
43216
43510
  this.removeAbortListener = util.addAbortListener(signal, () => {
43217
43511
  this.reason = signal.reason ?? new RequestAbortedError();
43218
43512
  if (this.res) {
@@ -43241,7 +43535,7 @@ var require_api_request = __commonJS({
43241
43535
  const responseHeaderData = responseHeaders === "raw" ? util.parseRawHeaders(rawHeaders) : headers;
43242
43536
  if (statusCode < 200) {
43243
43537
  if (this.onInfo) {
43244
- this.onInfo({ statusCode, headers: responseHeaderData });
43538
+ this.runInAsyncScope(this.onInfo, null, { statusCode, headers: responseHeaderData });
43245
43539
  }
43246
43540
  return;
43247
43541
  }
@@ -43343,7 +43637,11 @@ var require_api_request = __commonJS({
43343
43637
  }
43344
43638
  try {
43345
43639
  const handler = new RequestHandler(opts, callback2);
43346
- this.dispatch(opts, handler);
43640
+ if (opts.signal == null) {
43641
+ this.dispatch(opts, handler);
43642
+ } else {
43643
+ dispatchWithSignal(this, opts, handler);
43644
+ }
43347
43645
  } catch (err) {
43348
43646
  if (typeof callback2 !== "function") {
43349
43647
  throw err;
@@ -43357,58 +43655,6 @@ var require_api_request = __commonJS({
43357
43655
  }
43358
43656
  });
43359
43657
 
43360
- // node_modules/undici/lib/api/abort-signal.js
43361
- var require_abort_signal = __commonJS({
43362
- "node_modules/undici/lib/api/abort-signal.js"(exports, module) {
43363
- "use strict";
43364
- var { addAbortListener } = require_util3();
43365
- var { RequestAbortedError } = require_errors4();
43366
- var kListener = /* @__PURE__ */ Symbol("kListener");
43367
- var kSignal = /* @__PURE__ */ Symbol("kSignal");
43368
- function abort(self) {
43369
- if (self.abort) {
43370
- self.abort(self[kSignal]?.reason);
43371
- } else {
43372
- self.reason = self[kSignal]?.reason ?? new RequestAbortedError();
43373
- }
43374
- removeSignal(self);
43375
- }
43376
- function addSignal(self, signal) {
43377
- self.reason = null;
43378
- self[kSignal] = null;
43379
- self[kListener] = null;
43380
- if (!signal) {
43381
- return;
43382
- }
43383
- if (signal.aborted) {
43384
- abort(self);
43385
- return;
43386
- }
43387
- self[kSignal] = signal;
43388
- self[kListener] = () => {
43389
- abort(self);
43390
- };
43391
- addAbortListener(self[kSignal], self[kListener]);
43392
- }
43393
- function removeSignal(self) {
43394
- if (!self[kSignal]) {
43395
- return;
43396
- }
43397
- if ("removeEventListener" in self[kSignal]) {
43398
- self[kSignal].removeEventListener("abort", self[kListener]);
43399
- } else {
43400
- self[kSignal].removeListener("abort", self[kListener]);
43401
- }
43402
- self[kSignal] = null;
43403
- self[kListener] = null;
43404
- }
43405
- module.exports = {
43406
- addSignal,
43407
- removeSignal
43408
- };
43409
- }
43410
- });
43411
-
43412
43658
  // node_modules/undici/lib/api/api-stream.js
43413
43659
  var require_api_stream = __commonJS({
43414
43660
  "node_modules/undici/lib/api/api-stream.js"(exports, module) {
@@ -43417,7 +43663,7 @@ var require_api_stream = __commonJS({
43417
43663
  var { AsyncResource } = __require("node:async_hooks");
43418
43664
  var { InvalidArgumentError, InvalidReturnValueError } = require_errors4();
43419
43665
  var util = require_util3();
43420
- var { addSignal, removeSignal } = require_abort_signal();
43666
+ var { addSignal, removeSignal, dispatchWithSignal } = require_abort_signal();
43421
43667
  function noop() {
43422
43668
  }
43423
43669
  function getWritableError(stream2) {
@@ -43606,7 +43852,11 @@ var require_api_stream = __commonJS({
43606
43852
  }
43607
43853
  try {
43608
43854
  const handler = new StreamHandler(opts, factory, callback2);
43609
- this.dispatch(opts, handler);
43855
+ if (opts.signal == null) {
43856
+ this.dispatch(opts, handler);
43857
+ } else {
43858
+ dispatchWithSignal(this, opts, handler);
43859
+ }
43610
43860
  } catch (err) {
43611
43861
  if (typeof callback2 !== "function") {
43612
43862
  throw err;
@@ -43637,7 +43887,7 @@ var require_api_pipeline = __commonJS({
43637
43887
  } = require_errors4();
43638
43888
  var util = require_util3();
43639
43889
  var { kBodyUsed } = require_symbols();
43640
- var { addSignal, removeSignal } = require_abort_signal();
43890
+ var { addSignal, removeSignal, dispatchWithSignal } = require_abort_signal();
43641
43891
  function noop() {
43642
43892
  }
43643
43893
  var kResume = /* @__PURE__ */ Symbol("resume");
@@ -43722,7 +43972,7 @@ var require_api_pipeline = __commonJS({
43722
43972
  if (!err && !ret._readableState.endEmitted) {
43723
43973
  err = new RequestAbortedError();
43724
43974
  }
43725
- if (abort && err) {
43975
+ if (abort && (err || !res?.readableEnded)) {
43726
43976
  abort();
43727
43977
  }
43728
43978
  util.destroy(body, err);
@@ -43816,7 +44066,12 @@ var require_api_pipeline = __commonJS({
43816
44066
  function pipeline(opts, handler) {
43817
44067
  try {
43818
44068
  const pipelineHandler = new PipelineHandler(opts, handler);
43819
- this.dispatch({ ...opts, body: pipelineHandler.req }, pipelineHandler);
44069
+ const pipelineOpts = { ...opts, body: pipelineHandler.req };
44070
+ if (opts.signal == null) {
44071
+ this.dispatch(pipelineOpts, pipelineHandler);
44072
+ } else {
44073
+ dispatchWithSignal(this, pipelineOpts, pipelineHandler);
44074
+ }
43820
44075
  return pipelineHandler.ret;
43821
44076
  } catch (err) {
43822
44077
  return new PassThrough().destroy(err);
@@ -43835,7 +44090,7 @@ var require_api_upgrade = __commonJS({
43835
44090
  var assert2 = __require("node:assert");
43836
44091
  var util = require_util3();
43837
44092
  var { kHTTP2Stream } = require_symbols();
43838
- var { addSignal, removeSignal } = require_abort_signal();
44093
+ var { addSignal, removeSignal, dispatchWithSignal } = require_abort_signal();
43839
44094
  var UpgradeHandler = class extends AsyncResource {
43840
44095
  constructor(opts, callback2) {
43841
44096
  if (!opts || typeof opts !== "object") {
@@ -43913,7 +44168,11 @@ var require_api_upgrade = __commonJS({
43913
44168
  method: opts.method || "GET",
43914
44169
  upgrade: opts.protocol || "Websocket"
43915
44170
  };
43916
- this.dispatch(upgradeOpts, upgradeHandler);
44171
+ if (opts.signal == null) {
44172
+ this.dispatch(upgradeOpts, upgradeHandler);
44173
+ } else {
44174
+ dispatchWithSignal(this, upgradeOpts, upgradeHandler);
44175
+ }
43917
44176
  } catch (err) {
43918
44177
  if (typeof callback2 !== "function") {
43919
44178
  throw err;
@@ -43934,7 +44193,7 @@ var require_api_connect = __commonJS({
43934
44193
  var { AsyncResource } = __require("node:async_hooks");
43935
44194
  var { InvalidArgumentError, SocketError } = require_errors4();
43936
44195
  var util = require_util3();
43937
- var { addSignal, removeSignal } = require_abort_signal();
44196
+ var { addSignal, removeSignal, dispatchWithSignal } = require_abort_signal();
43938
44197
  var ConnectHandler = class extends AsyncResource {
43939
44198
  constructor(opts, callback2) {
43940
44199
  if (!opts || typeof opts !== "object") {
@@ -44005,7 +44264,11 @@ var require_api_connect = __commonJS({
44005
44264
  try {
44006
44265
  const connectHandler = new ConnectHandler(opts, callback2);
44007
44266
  const connectOptions = { ...opts, method: "CONNECT" };
44008
- this.dispatch(connectOptions, connectHandler);
44267
+ if (opts.signal == null) {
44268
+ this.dispatch(connectOptions, connectHandler);
44269
+ } else {
44270
+ dispatchWithSignal(this, connectOptions, connectHandler);
44271
+ }
44009
44272
  } catch (err) {
44010
44273
  if (typeof callback2 !== "function") {
44011
44274
  throw err;
@@ -46497,8 +46760,9 @@ var require_redirect = __commonJS({
46497
46760
  "node_modules/undici/lib/interceptor/redirect.js"(exports, module) {
46498
46761
  "use strict";
46499
46762
  var RedirectHandler = require_redirect_handler();
46763
+ var { kInterceptorKind } = require_symbols();
46500
46764
  function createRedirectInterceptor({ maxRedirections: defaultMaxRedirections, throwOnMaxRedirect: defaultThrowOnMaxRedirect, stripHeadersOnRedirect: defaultStripHeadersOnRedirect, stripHeadersOnCrossOriginRedirect: defaultStripHeadersOnCrossOriginRedirect } = {}) {
46501
- return (dispatch) => {
46765
+ const interceptor = (dispatch) => {
46502
46766
  return function Intercept(opts, handler) {
46503
46767
  const { maxRedirections = defaultMaxRedirections, throwOnMaxRedirect = defaultThrowOnMaxRedirect, stripHeadersOnRedirect = defaultStripHeadersOnRedirect, stripHeadersOnCrossOriginRedirect = defaultStripHeadersOnCrossOriginRedirect, ...rest } = opts;
46504
46768
  if (maxRedirections == null || maxRedirections === 0) {
@@ -46509,6 +46773,8 @@ var require_redirect = __commonJS({
46509
46773
  return dispatch(dispatchOpts, redirectHandler);
46510
46774
  };
46511
46775
  };
46776
+ interceptor[kInterceptorKind] = "redirect";
46777
+ return interceptor;
46512
46778
  }
46513
46779
  module.exports = createRedirectInterceptor;
46514
46780
  }
@@ -49370,7 +49636,9 @@ var require_cache2 = __commonJS({
49370
49636
  isEtagUsable
49371
49637
  } = require_cache();
49372
49638
  var { AbortError } = require_errors4();
49639
+ var { kQueuedAbort } = require_symbols();
49373
49640
  var { parseHttpDate } = require_date();
49641
+ var { kInterceptorKind } = require_symbols();
49374
49642
  function assertCacheOrigins(origins, name) {
49375
49643
  if (origins === void 0) return;
49376
49644
  if (!Array.isArray(origins)) {
@@ -49685,7 +49953,10 @@ var require_cache2 = __commonJS({
49685
49953
  dispatch(
49686
49954
  {
49687
49955
  ...opts,
49688
- headers: headers2
49956
+ headers: headers2,
49957
+ // The revalidation is not the caller's request: aborting the
49958
+ // caller must not cancel it while it waits for a connection.
49959
+ [kQueuedAbort]: void 0
49689
49960
  },
49690
49961
  new CacheHandler(globalOpts, cacheKey, {
49691
49962
  // Silent handler that just updates the cache
@@ -49787,7 +50058,7 @@ var require_cache2 = __commonJS({
49787
50058
  safeMethodsToNotCache.push(method);
49788
50059
  }
49789
50060
  }
49790
- return (dispatch, interceptorOrigin) => {
50061
+ const interceptor = (dispatch, interceptorOrigin) => {
49791
50062
  return (opts2, handler) => {
49792
50063
  const requestOrigin = getInterceptorOrigin(opts2, interceptorOrigin);
49793
50064
  if (!requestOrigin || arrayIncludes(safeMethodsToNotCache, opts2.method)) {
@@ -49872,6 +50143,8 @@ var require_cache2 = __commonJS({
49872
50143
  }
49873
50144
  };
49874
50145
  };
50146
+ interceptor[kInterceptorKind] = "cache";
50147
+ return interceptor;
49875
50148
  };
49876
50149
  }
49877
50150
  });
@@ -49969,10 +50242,6 @@ var require_decompress = __commonJS({
49969
50242
  }
49970
50243
  });
49971
50244
  }
49972
- var warningEmitted = (
49973
- /** @type {boolean} */
49974
- false
49975
- );
49976
50245
  var DecompressHandler = class extends DecoratorHandler {
49977
50246
  /** @type {Transform[]} */
49978
50247
  #decompressors = [];
@@ -50334,13 +50603,6 @@ var require_decompress = __commonJS({
50334
50603
  }
50335
50604
  };
50336
50605
  function createDecompressInterceptor(options = {}) {
50337
- if (!warningEmitted) {
50338
- process.emitWarning(
50339
- "DecompressInterceptor is experimental and subject to change",
50340
- "ExperimentalWarning"
50341
- );
50342
- warningEmitted = true;
50343
- }
50344
50606
  return (dispatch) => {
50345
50607
  return (opts, handler) => {
50346
50608
  if (opts.method === "HEAD") {
@@ -50780,6 +51042,7 @@ var require_deduplicate = __commonJS({
50780
51042
  var util = require_util3();
50781
51043
  var DeduplicationHandler = require_deduplication_handler();
50782
51044
  var { getInterceptorOrigin, normalizeHeaders, makeCacheKey, makeDeduplicationKey } = require_cache();
51045
+ var { kInterceptorKind } = require_symbols();
50783
51046
  var pendingRequestsChannel = diagnosticsChannel.channel("undici:request:pending-requests");
50784
51047
  module.exports = (opts = {}) => {
50785
51048
  const {
@@ -50811,7 +51074,7 @@ var require_deduplicate = __commonJS({
50811
51074
  const skipHeaderNamesSet = new Set(skipHeaderNames.map((name) => name.toLowerCase()));
50812
51075
  const excludeHeaderNamesSet = new Set(excludeHeaderNames.map((name) => name.toLowerCase()));
50813
51076
  const pendingRequests = /* @__PURE__ */ new Map();
50814
- return (dispatch, interceptorOrigin) => {
51077
+ const interceptor = (dispatch, interceptorOrigin) => {
50815
51078
  return (opts2, handler) => {
50816
51079
  const requestOrigin = getInterceptorOrigin(opts2, interceptorOrigin);
50817
51080
  if (!requestOrigin || opts2.upgrade || methods.includes(opts2.method) === false) {
@@ -50854,6 +51117,8 @@ var require_deduplicate = __commonJS({
50854
51117
  return dispatch(opts2, deduplicationHandler);
50855
51118
  };
50856
51119
  };
51120
+ interceptor[kInterceptorKind] = "deduplicate";
51121
+ return interceptor;
50857
51122
  };
50858
51123
  }
50859
51124
  });
@@ -53100,7 +53365,7 @@ var require_fetch = __commonJS({
53100
53365
  var EE = __require("node:events");
53101
53366
  var { Readable, pipeline, finished, isErrored, isReadable } = __require("node:stream");
53102
53367
  var { addAbortListener, bufferToLowerCasedHeaderName } = require_util3();
53103
- var { SocketError } = require_errors4();
53368
+ var { SocketError, InformationalError } = require_errors4();
53104
53369
  var { dataURLProcessor, serializeAMimeType, minimizeSupportedMimeType } = require_data_url();
53105
53370
  var { getGlobalDispatcher } = require_global2();
53106
53371
  var { webidl } = require_webidl();
@@ -54121,6 +54386,7 @@ var require_fetch = __commonJS({
54121
54386
  }
54122
54387
  }
54123
54388
  }
54389
+ this.nullBodyStatus = nullBodyStatus.includes(status);
54124
54390
  this.body = new Readable({ read: () => controller.resume() });
54125
54391
  const onError = (err) => this.onResponseError(controller, err);
54126
54392
  resolve6({
@@ -54135,6 +54401,10 @@ var require_fetch = __commonJS({
54135
54401
  });
54136
54402
  },
54137
54403
  onResponseData(controller, chunk2) {
54404
+ if (this.nullBodyStatus) {
54405
+ controller.abort(new InformationalError("response with null body status has content"));
54406
+ return;
54407
+ }
54138
54408
  if (fetchParams.controller.dump) {
54139
54409
  return;
54140
54410
  }
@@ -54155,6 +54425,10 @@ var require_fetch = __commonJS({
54155
54425
  if (this.abort) {
54156
54426
  fetchParams.controller.off("terminated", this.abort);
54157
54427
  }
54428
+ if (this.nullBodyStatus) {
54429
+ this.body?.destroy();
54430
+ return;
54431
+ }
54158
54432
  if (request.mode === "websocket" && allowH2 !== false && error62?.code === "UND_ERR_INFO" && error62?.message === "HTTP/2: Extended CONNECT protocol not supported by server") {
54159
54433
  resolve6(dispatchWithProtocolPreference(body2, false));
54160
54434
  return;
@@ -98698,6 +98972,68 @@ function siegeReport(s, g, captured, bonusName) {
98698
98972
  };
98699
98973
  }
98700
98974
 
98975
+ // src/analysis/plan/fogged-break.ts
98976
+ var ONE_SHORT_WEIGHT = 0.5;
98977
+ var OPENING_STRIKE_FIRST = 2;
98978
+ var OPENING_STRIKE_LAST = 4;
98979
+ function foggedBreakables(g, state, foe, mine3, known2, turn) {
98980
+ const opening = turn !== null && turn >= OPENING_STRIKE_FIRST && turn <= OPENING_STRIKE_LAST;
98981
+ const out = [];
98982
+ for (const b of [...g.map.bonuses].sort((x, y) => x.id - y.id)) {
98983
+ if (b.value <= 0 || known2.has(b.id)) continue;
98984
+ const ts = bonusTerritories(g, b.id);
98985
+ if (!ts.length) continue;
98986
+ const players = /* @__PURE__ */ new Set();
98987
+ const others = [];
98988
+ let fogged = 0;
98989
+ for (const t of ts) {
98990
+ const st = state.get(t);
98991
+ const shown2 = ownerShown(st);
98992
+ if (!shown2) {
98993
+ fogged++;
98994
+ continue;
98995
+ }
98996
+ if (shown2.owner.kind === "player" && foe(shown2.owner.playerId)) {
98997
+ players.add(shown2.owner.playerId);
98998
+ if (!visibleState(st)) fogged++;
98999
+ } else others.push(t);
99000
+ }
99001
+ if (players.size !== 1) continue;
99002
+ const player2 = [...players][0];
99003
+ const members2 = ts.filter((t) => {
99004
+ const st = visibleState(state.get(t));
99005
+ return st?.owner.kind === "player" && st.owner.playerId === player2 && neighborsOf(g, t).some((n) => mine3.has(n));
99006
+ }).sort((x, y) => x - y);
99007
+ if (!members2.length) continue;
99008
+ if (!others.length) {
99009
+ if (!fogged) continue;
99010
+ out.push({
99011
+ bonusId: b.id,
99012
+ value: b.value,
99013
+ player: player2,
99014
+ probable: `a member in view is its and its ${fogged} fogged member${fogged > 1 ? "s" : ""} could all be its, #593`,
99015
+ members: members2,
99016
+ fogged
99017
+ });
99018
+ continue;
99019
+ }
99020
+ if (!opening || others.length !== 1 || state.get(others[0])?.owner.kind !== "neutral") continue;
99021
+ out.push({
99022
+ bonusId: b.id,
99023
+ value: b.value,
99024
+ player: player2,
99025
+ probable: `one territory short of complete, ${others[0]} still neutral, #593`,
99026
+ members: members2,
99027
+ fogged,
99028
+ shortOf: others[0]
99029
+ });
99030
+ }
99031
+ return out;
99032
+ }
99033
+ function partialDeploy(estimate, fronts) {
99034
+ return Math.ceil(Math.max(0, estimate) / Math.max(1, fronts));
99035
+ }
99036
+
98701
99037
  // src/analysis/plan/bonus-attempts.ts
98702
99038
  var FAILED_ATTEMPTS = 2;
98703
99039
  var ALL_IN_VALUE_TURNS = 2;
@@ -101471,6 +101807,7 @@ function newPlanState() {
101471
101807
  captureOrder: [],
101472
101808
  captureUndo: /* @__PURE__ */ new Map(),
101473
101809
  doomedOut: /* @__PURE__ */ new Set(),
101810
+ expanded: /* @__PURE__ */ new Set(),
101474
101811
  staged: /* @__PURE__ */ new Map(),
101475
101812
  anchor: void 0,
101476
101813
  assumeGone: () => false,
@@ -102119,7 +102456,8 @@ function planEnemyEstimates(input2) {
102119
102456
  fog: ctx.fog,
102120
102457
  reinforcement: ctx.reinforcement,
102121
102458
  ...ctx.reinforcementPlays ? { plays: ctx.reinforcementPlays } : {},
102122
- ...previousBoard && input2.previousOrders ? { previousOrders: input2.previousOrders } : {}
102459
+ ...previousBoard && input2.previousOrders ? { previousOrders: input2.previousOrders } : {},
102460
+ ...ctx.trackCalibration ? { calibration: ctx.trackCalibration } : {}
102123
102461
  });
102124
102462
  const priced = applyKnown(
102125
102463
  applyArmyPrice(applySanctions(estimates, input2.sanctions ?? [], turn), input2.settings?.armyCostMultiplier ?? 0),
@@ -103353,6 +103691,27 @@ function deployBook(ctx, ps, previousBoard) {
103353
103691
  return out;
103354
103692
  };
103355
103693
  const opensCache = /* @__PURE__ */ new Map();
103694
+ const hubsAt = (t) => {
103695
+ const cached4 = hubCache.get(t);
103696
+ if (cached4) return cached4;
103697
+ const out = [];
103698
+ if (ps.holdings.has(t)) {
103699
+ const near2 = new Set(neighborsOf(g, t));
103700
+ for (const b of [...g.map.bonuses].sort((x, y) => x.id - y.id)) {
103701
+ if (b.value <= 0) continue;
103702
+ const ts = bonusTerritories(g, b.id);
103703
+ if (ts.length < HUB_MIN_MEMBERS || !ts.includes(t) || !ts.every((x) => ps.holdings.has(x))) continue;
103704
+ const others = ts.filter((x) => x !== t);
103705
+ const borders = others.filter((x) => near2.has(x)).length;
103706
+ if (borders < HUB_DEGREE * others.length) continue;
103707
+ out.push({ bonusId: b.id, value: b.value, borders, others: others.length, worth: Math.round(HUB_WEIGHT * b.value * 10) / 10 });
103708
+ }
103709
+ }
103710
+ hubCache.set(t, out);
103711
+ return out;
103712
+ };
103713
+ const hubCache = /* @__PURE__ */ new Map();
103714
+ const hubWorthOf = (bonusId, members2) => members2.map((m) => hubsAt(m).find((h) => h.bonusId === bonusId)?.worth ?? 0).reduce((a, b) => Math.max(a, b), 0);
103356
103715
  const protectedValue = (t) => {
103357
103716
  let v = (cutOff(t)?.income ?? 0) + (breachAt(t)?.worth ?? 0) + (opensAt(t)?.worth ?? 0);
103358
103717
  const mineWithout = (x) => x !== t && ps.holdings.has(x);
@@ -103365,7 +103724,7 @@ function deployBook(ctx, ps, previousBoard) {
103365
103724
  }
103366
103725
  if (b.value === 0) continue;
103367
103726
  if (ts.every((x) => ps.holdings.has(x))) {
103368
- v += b.value;
103727
+ v += b.value + (hubsAt(t).find((h) => h.bonusId === b.id)?.worth ?? 0);
103369
103728
  continue;
103370
103729
  }
103371
103730
  const access = (has) => ts.some((x) => has(x) || neighborsOf(g, x).some(has));
@@ -103418,6 +103777,9 @@ function deployBook(ctx, ps, previousBoard) {
103418
103777
  breachCache,
103419
103778
  opensAt,
103420
103779
  opensCache,
103780
+ hubsAt,
103781
+ hubCache,
103782
+ hubWorthOf,
103421
103783
  stakeAt
103422
103784
  };
103423
103785
  }
@@ -103650,7 +104012,7 @@ function withdrawals(pc, ps, book, threats, hb, prev) {
103650
104012
  function reconsiderAndGarrison(pc, ps, book, threats, hb, prev) {
103651
104013
  const { g, guarded, reserve, paybackTurns, label: label3, bonusName, mine: mine3, mineSet, unitsAt, toTake, myCommanders } = pc;
103652
104014
  const { warnings, rationale, deployed, locked, captured, moves } = ps;
103653
- const { orderOf, deploy, pools, valueCache, cutCache, breachCache, opensCache, valueOf } = book;
104015
+ const { orderOf, deploy, pools, valueCache, cutCache, breachCache, opensCache, hubCache, valueOf } = book;
103654
104016
  const local = pools !== null && pools.bonuses.length > 0;
103655
104017
  const { borders } = threats;
103656
104018
  const { conceded, kept, garrisoned } = hb;
@@ -103662,6 +104024,7 @@ function reconsiderAndGarrison(pc, ps, book, threats, hb, prev) {
103662
104024
  cutCache.clear();
103663
104025
  breachCache.clear();
103664
104026
  opensCache.clear();
104027
+ hubCache.clear();
103665
104028
  if (!conceded.size) return;
103666
104029
  for (const t of [...conceded].sort(byNum2)) {
103667
104030
  if (moves.some((m) => m.from === t && m.reason === "withdraws from a conceded border")) continue;
@@ -103798,7 +104161,7 @@ function holdBasics(pc, ps, book, threats) {
103798
104161
  }
103799
104162
  function soloLeaderHolds(pc, ps, book, threats, prev) {
103800
104163
  const { g, ffaLeader, paybackTurns, label: label3, bonusName, unitsAt, toTake, myCommanders } = pc;
103801
- const { valueOf, stakeAt, pools } = book;
104164
+ const { valueOf, stakeAt, pools, hubWorthOf } = book;
103802
104165
  const { borders, borderAt, safeAtStart } = threats;
103803
104166
  const { uneconomic, stayAt } = prev;
103804
104167
  if (!ffaLeader) return;
@@ -103859,7 +104222,7 @@ function soloLeaderHolds(pc, ps, book, threats, prev) {
103859
104222
  if (!members2.length) continue;
103860
104223
  let joint = 0;
103861
104224
  let single = 0;
103862
- let worth = bonus.value;
104225
+ let worth = bonus.value + hubWorthOf(bonus.id, members2);
103863
104226
  let recent = false;
103864
104227
  const lowered = [];
103865
104228
  for (const t of members2) {
@@ -104052,15 +104415,16 @@ function twoStepHolds(pc, ps, book, threats, hb, pass, prev) {
104052
104415
  return { twoStepCited, arrived, twoStepBound, twoStepHold, twoStepKeep, twoStepCite, twoStepNote };
104053
104416
  }
104054
104417
  function holdOrConcede(pc, ps, book, threats, hb, prev) {
104055
- const { goal, paybackTurns, label: label3, unitsAt, bombOn, toTake, myCommanders } = pc;
104418
+ const { goal, paybackTurns, label: label3, bonusName, unitsAt, bombOn, toTake, myCommanders } = pc;
104056
104419
  const { warnings, rationale, locked } = ps;
104057
- const { deploy, valueOf, stakeAt, cutOff, breachAt, opensAt } = book;
104420
+ const { deploy, valueOf, stakeAt, cutOff, breachAt, opensAt, hubsAt } = book;
104058
104421
  const { borders, recentlyTakenFrom } = threats;
104059
104422
  const { threatened: threatened2, conceded } = hb;
104060
104423
  const { stayAt } = prev;
104061
104424
  const cutNoted = /* @__PURE__ */ new Set();
104062
104425
  const breachNoted = /* @__PURE__ */ new Set();
104063
104426
  const opensNoted = /* @__PURE__ */ new Set();
104427
+ const hubNoted = /* @__PURE__ */ new Set();
104064
104428
  const threatWarnings = /* @__PURE__ */ new Map();
104065
104429
  const assessThreats = () => {
104066
104430
  for (const b of borders.values()) {
@@ -104101,6 +104465,13 @@ function holdOrConcede(pc, ps, book, threats, hb, prev) {
104101
104465
  `${label3(b.id)} is the only way in to ${named3}${more} (+${opens.income} income): losing it opens them to the enemy, so its value counts half of that (+${opens.worth}) (#291).`
104102
104466
  );
104103
104467
  }
104468
+ if (!hubNoted.has(b.id))
104469
+ for (const h of hubsAt(b.id)) {
104470
+ hubNoted.add(b.id);
104471
+ rationale.push(
104472
+ `${label3(b.id)} borders ${h.borders} of bonus ${bonusName(h.bonusId)}'s ${h.others} other members: its fall takes the rest, so its value counts ${HUB_WEIGHT * 100}% of the bonus more (+${h.worth}) (#593).`
104473
+ );
104474
+ }
104104
104475
  const from = recentlyTakenFrom(b.id);
104105
104476
  threatened2.push({
104106
104477
  id: b.id,
@@ -104162,7 +104533,7 @@ function holdOrConcede(pc, ps, book, threats, hb, prev) {
104162
104533
  function heldBonusUnits(pc, ps, book, threats, hb, prev) {
104163
104534
  const { g, paybackTurns, label: label3, bonusName, incomeAfter: incomeAfter2, toTake } = pc;
104164
104535
  const { warnings, rationale, locked } = ps;
104165
- const { deploy, undeploy, pools, roomAt, stakeAt } = book;
104536
+ const { deploy, undeploy, pools, roomAt, stakeAt, hubWorthOf, hubsAt } = book;
104166
104537
  const local = pools !== null && pools.bonuses.length > 0;
104167
104538
  const { expectedAt } = threats;
104168
104539
  const { threatened: threatened2, conceded, units } = hb;
@@ -104184,7 +104555,8 @@ function heldBonusUnits(pc, ps, book, threats, hb, prev) {
104184
104555
  if (!members2.length) continue;
104185
104556
  const paying = members2.filter((m) => !commanderHeld.has(m.id));
104186
104557
  const cost = paying.reduce((n, m) => n + m.holdCost, 0);
104187
- const worth = b.value + paying.reduce((n, m) => n + (m.have + stakeAt(m.id)) / paybackTurns, 0);
104558
+ const hub = hubWorthOf(b.id, paying.map((m) => m.id));
104559
+ const worth = b.value + hub + paying.reduce((n, m) => n + (m.have + stakeAt(m.id)) / paybackTurns, 0);
104188
104560
  const recent = members2.some((m) => m.recentFrom !== void 0);
104189
104561
  const pool = poolOf(b.id);
104190
104562
  const net = Math.max(0, cost - pool);
@@ -104199,13 +104571,14 @@ function heldBonusUnits(pc, ps, book, threats, hb, prev) {
104199
104571
  loss: net > paybackTurns * b.value ? "payback" : !recent && net > CONCEDE_FACTOR * worth ? "factor" : null,
104200
104572
  conceded: false,
104201
104573
  floored: false,
104202
- contested: false
104574
+ contested: false,
104575
+ ...hub > 0 && !recent && net <= paybackTurns * b.value && net <= CONCEDE_FACTOR * worth && net > CONCEDE_FACTOR * (worth - hub) ? { hubOnly: true } : {}
104203
104576
  });
104204
104577
  }
104205
104578
  };
104206
104579
  const inLiveUnit = (id) => units.some((u) => !u.conceded && u.members.some((m) => m.id === id));
104207
104580
  const residual = (t) => {
104208
- const lost = units.filter((u) => u.conceded && u.members.some((m) => m.id === t.id)).reduce((n, u) => n + u.value, 0);
104581
+ const lost = units.filter((u) => u.conceded && u.members.some((m) => m.id === t.id)).reduce((n, u) => n + u.value + (hubsAt(t.id).find((h) => h.bonusId === u.bonusId)?.worth ?? 0), 0);
104209
104582
  const value = Math.max(0, t.value - lost);
104210
104583
  return { ...t, value, worth: value + (t.have + stakeAt(t.id)) / paybackTurns };
104211
104584
  };
@@ -104718,7 +105091,7 @@ function floorTier(pc, ps, book, threats, hb, prev) {
104718
105091
  }
104719
105092
  };
104720
105093
  const losing = units.filter((u) => u.loss);
104721
- floorUnits(losing);
105094
+ floorUnits([...losing, ...units.filter((u) => !u.loss && u.hubOnly)]);
104722
105095
  for (const u of losing) contest(u);
104723
105096
  const items = [
104724
105097
  ...units.filter((u) => !u.conceded && !u.contested).map((unit) => ({ unit })),
@@ -105632,7 +106005,13 @@ function borderThreats(pc, ps, input2, src, forces) {
105632
106005
  const track = input2.tracks.find((t) => t.playerId === p);
105633
106006
  const used = track.turns.filter((x) => e.trackedTurns.includes(x.from));
105634
106007
  rationale.push(
105635
- `Tracked income for player ${p}: ~${e.tracked}/turn (${incomeBasis(track)}): ${used.map((x) => `turn ${x.from} +${x.observed}`).join(", ")}, each observed deploy a lower bound under fog${e.coverage ? `, read from ${coverageText(e.coverage)}` : ""}; at least its visible base + bonuses ${track.visibleIncome}; used in place of the single-turn observed figure (warapp_track_opponents has the details).`
106008
+ `Tracked income for player ${p}: ~${e.trackCalibration ? e.trackCalibration.raw : e.tracked}/turn (${incomeBasis(track)}): ${used.map((x) => `turn ${x.from} +${x.observed}`).join(", ")}, each observed deploy a lower bound under fog${e.coverage ? `, read from ${coverageText(e.coverage)}` : ""}; at least its visible base + bonuses ${track.visibleIncome}; used in place of the single-turn observed figure (warapp_track_opponents has the details).`
106009
+ );
106010
+ }
106011
+ if (e.trackCalibration) {
106012
+ const c = e.trackCalibration;
106013
+ warnings.push(
106014
+ `Player ${p}'s tracked income ~${c.raw} is raised to ~${c.figure} (#568, draft): past games' tracker read ${c.geoMean.toFixed(2)}\xD7 the true income at this frontier coverage (${c.band}, ${c.n} samples), divided by its square root (${c.factor.toFixed(2)}).`
105636
106015
  );
105637
106016
  }
105638
106017
  if (e.cardInTrack) {
@@ -105814,13 +106193,16 @@ function targetsPhase(pc, ps, input2, threats, hd) {
105814
106193
  threats.reinforcementAt,
105815
106194
  (t) => c4.targets.has(t) || c4.repulsed.has(t) || pc.truce.noTarget(t)
105816
106195
  );
105817
- return { ...c4, denials, emptyEnemies };
106196
+ const deadBonuses = input2.deadAdvance ?? /* @__PURE__ */ new Map();
106197
+ return { ...c4, denials, emptyEnemies, deadBonuses };
105818
106198
  }
105819
106199
  var RETAKE_VALUE_TURNS = 5;
105820
106200
  function breakTargets(pc, input2) {
105821
106201
  const { g, me, foe, balanced, territories: state, mineSet, unitsAt, costAt } = pc;
105822
106202
  const breakable = balanced ? breakableBonuses(g, state, foe, input2.tracks) : [];
105823
106203
  const breakMember = new Set(breakable.flatMap((b) => bonusTerritories(g, b.bonusId)));
106204
+ const foggedBreaks = balanced && pc.profile.format === "1v1" ? foggedBreakables(g, state, foe, mineSet, new Set(breakable.map((b) => b.bonusId)), pc.turnNow) : [];
106205
+ const foggedMember = new Set(foggedBreaks.flatMap((b) => b.members));
105824
106206
  const counterAt = /* @__PURE__ */ new Map();
105825
106207
  if (balanced && input2.previousBoard) {
105826
106208
  const before = new Map(input2.previousBoard.territories.map((t) => [t.territoryId, t]));
@@ -105854,7 +106236,7 @@ function breakTargets(pc, input2) {
105854
106236
  counterAt.set(id, { player: p, from: was.armies, to: st.armies, costNow, costThen });
105855
106237
  }
105856
106238
  }
105857
- return { breakable, breakMember, counterAt };
106239
+ return { breakable, breakMember, counterAt, foggedBreaks, foggedMember };
105858
106240
  }
105859
106241
  function captureTargets(pc, ps, input2, threats, prev) {
105860
106242
  const {
@@ -105879,7 +106261,7 @@ function captureTargets(pc, ps, input2, threats, prev) {
105879
106261
  } = pc;
105880
106262
  const { warnings, rationale } = ps;
105881
106263
  const { reinforcementAt, hiddenFoe, hiddenMovable, hiddenPool } = threats;
105882
- const { breakMember, counterAt } = prev;
106264
+ const { breakMember, counterAt, foggedMember } = prev;
105883
106265
  const targets = /* @__PURE__ */ new Map();
105884
106266
  const bonusDropped = input2.bonusPush?.dropped ?? /* @__PURE__ */ new Set();
105885
106267
  const droppedMembers = new Set([...bonusDropped].flatMap((id) => g.bonusById.has(id) ? bonusTerritories(g, id).filter((t) => !mineSet.has(t)) : []));
@@ -106020,7 +106402,7 @@ function captureTargets(pc, ps, input2, threats, prev) {
106020
106402
  continue;
106021
106403
  }
106022
106404
  const enemy = st.owner.kind === "player";
106023
- if (enemy && goal !== "complete-bonus" && !(balanced && (breakMember.has(t) || counterAt.has(t))) && !pileMembers.has(t) && !retakeMembers.has(t)) {
106405
+ if (enemy && goal !== "complete-bonus" && !(balanced && (breakMember.has(t) || counterAt.has(t) || foggedMember.has(t))) && !pileMembers.has(t) && !retakeMembers.has(t)) {
106024
106406
  if (!leadStepsOn || unitsAt(t) > 0 || droppedMembers.has(t) || !g.map.bonuses.some((b) => b.value > 0 && bonusTs.get(b.id).includes(t))) continue;
106025
106407
  const defenders2 = defenceAt(t);
106026
106408
  const extra = reinforcementAt(t);
@@ -106590,6 +106972,53 @@ function afterLeftoverCaptures(pc, ps, book, threats, hd, tgt, caps, before, ski
106590
106972
  return taken;
106591
106973
  }
106592
106974
 
106975
+ // src/analysis/plan/dead-advance.ts
106976
+ function deadAdvanceOf(pc, t, held, conceded, carried, completable2 = () => false) {
106977
+ if (pc.inFocus(t) || pc.vacated.has(t) || pc.mineSet.has(t)) return null;
106978
+ const bonuses = (pc.bonusesWith.get(t) ?? []).filter((id) => (pc.g.bonusById.get(id)?.value ?? 0) > 0);
106979
+ if (!bonuses.length) return null;
106980
+ const after = /* @__PURE__ */ new Set([...held, t]);
106981
+ const dead = [];
106982
+ for (const id of bonuses) {
106983
+ const ts = pc.bonusTs.get(id) ?? [];
106984
+ if (ts.every((x) => after.has(x))) return null;
106985
+ const now = ts.filter((x) => x !== t && pc.mineSet.has(x) && conceded.has(x));
106986
+ const was = carried.get(id)?.filter((x) => x !== t && pc.mineSet.has(x));
106987
+ if (was?.length) {
106988
+ dead.push({ bonusId: id, members: now.length ? now : [...was], carried: !now.length });
106989
+ continue;
106990
+ }
106991
+ if (completable2(id) || !now.length) return null;
106992
+ if (breaksForAttacker(pc, t, ts, now)) return null;
106993
+ dead.push({ bonusId: id, members: now, carried: false });
106994
+ }
106995
+ return dead;
106996
+ }
106997
+ function breaksForAttacker(pc, t, ts, now) {
106998
+ const ownerOf9 = (x) => {
106999
+ const o = pc.territories.get(x)?.owner;
107000
+ return o?.kind === "player" ? o.playerId : null;
107001
+ };
107002
+ const attackers = /* @__PURE__ */ new Set();
107003
+ for (const m of now)
107004
+ for (const n of pc.g.neighbors.get(m) ?? []) {
107005
+ const p = ownerOf9(n);
107006
+ const st = pc.territories.get(n);
107007
+ if (p !== null && pc.foe(p) && (st?.armies ?? 0) > 0) attackers.add(p);
107008
+ }
107009
+ if (!attackers.size) return false;
107010
+ const owner = ownerOf9(t);
107011
+ if (owner !== null) return attackers.has(owner);
107012
+ if (pc.territories.get(t)?.owner.kind !== "neutral") return false;
107013
+ const conceded = new Set(now);
107014
+ return [...attackers].some((a) => ts.every((x) => x === t || conceded.has(x) || ownerOf9(x) === a));
107015
+ }
107016
+ function deadAdvanceLine(pc, t, d) {
107017
+ const members2 = d.members.map(pc.label).join(", ");
107018
+ const its = d.members.length === 1 ? "its member" : "its members";
107019
+ return d.carried ? `Do not take ${pc.label(t)} toward bonus ${pc.bonusName(d.bonusId)}: the plan that took it conceded ${its} ${members2}, so the capture builds a bonus this turn gives up: its armies are left to the plan's other orders (#593).` : `Do not take ${pc.label(t)} toward bonus ${pc.bonusName(d.bonusId)}: this plan concedes ${its} ${members2}, so the capture builds a bonus this turn gives up: its armies are left to the plan's other orders (#593).`;
107020
+ }
107021
+
106593
107022
  // src/analysis/plan/captures.ts
106594
107023
  function capturesPhase(pc, ps, pass, book, threats, hd, tgt) {
106595
107024
  const c0 = captureRules(pc, ps, book, threats, hd);
@@ -107423,11 +107852,26 @@ function bonusPasses(pc, ps, book, hd, tgt, prev) {
107423
107852
  if (!stopped.some((x) => x.t === t)) stopped.push({ t, holdCost: f.holdCost, income: next });
107424
107853
  return why;
107425
107854
  };
107855
+ const completableIds = new Set(tgt.plans.filter((p) => p.completable).map((p) => p.bonusId));
107856
+ const completableNow = (id) => completableIds.has(id);
107857
+ const givenUp = (t) => moves.every((m) => m.kind !== "attack" || m.to !== t || hd.conceded.has(m.from) && !(deployed.get(m.from) ?? 0));
107426
107858
  const tryExpand = (t, reason, bare = false, force) => {
107427
107859
  const restore = snapshot();
107428
107860
  if (!tryCapture(t, reason, force, void 0, bare)) return false;
107861
+ const dead = noLossNeutral(pc, tgt, t) ? null : deadAdvanceOf(pc, t, heldNow(), hd.conceded, tgt.deadBonuses, completableNow);
107862
+ if (dead && !givenUp(t)) {
107863
+ restore();
107864
+ for (const d of dead) {
107865
+ const line2 = deadAdvanceLine(pc, t, d);
107866
+ if (!rationale.includes(line2)) rationale.push(line2);
107867
+ }
107868
+ return false;
107869
+ }
107429
107870
  const why = outgrows(t);
107430
- if (why === null) return true;
107871
+ if (why === null) {
107872
+ ps.expanded.add(t);
107873
+ return true;
107874
+ }
107431
107875
  restore();
107432
107876
  if (leadSteps.has(t)) leadTry.set(t, { kind: "frontier" });
107433
107877
  if (!rationale.includes(why)) rationale.push(why);
@@ -107494,7 +107938,7 @@ function bonusPasses(pc, ps, book, hd, tgt, prev) {
107494
107938
  run2(todo);
107495
107939
  if (closest) run2(todo.filter((t) => leadSteps.has(t) && !captured.has(t)), true);
107496
107940
  };
107497
- return { snapshot, complete: complete2, unstaged, stage, stopped, stoppedLine, denied, outgrows, gateStop, tryExpand, advance: advance2 };
107941
+ return { snapshot, complete: complete2, unstaged, stage, stopped, stoppedLine, denied, outgrows, gateStop, givenUp, completableNow, tryExpand, advance: advance2 };
107498
107942
  }
107499
107943
 
107500
107944
  // src/analysis/plan/spread-bind.ts
@@ -111641,6 +112085,8 @@ function reportOffence(pc, ps, book, threats, hd, tgt, holdLocked, leadSpareFor)
111641
112085
  if (lead.spare < sure)
111642
112086
  return `a lead strike (my army lead is ${leadText()}, over ${SECOND_FRONT_LEAD}\xD7) needs ${sure} \u2014 sized for its ${defenceAt(n)} defenders plus player ${p}'s ~${extra} deploy \u2014 and the most a neighbour of mine can spare for it is ${lead.spare}${lead.spare > 0 ? ` (${label3(lead.x)})` : ""}${deployText}`;
111643
112087
  }
112088
+ if (tgt.foggedMember.has(n))
112089
+ return `${label3(best.x)} could spare ${best.spare} for it, and it probably breaks a bonus behind the fog (#593), but that break, sized for a partial deploy, did not fit or ranked below what the turn funded`;
111644
112090
  return `${label3(best.x)} could spare ${best.spare} for it, but it breaks no bonus and is no counter-attack, finishing blow or strike \u2014 the only reasons the plan attacks a player's territory (rule 2), besides rule 4e's fallback when nothing else is captured${!ffaLead ? "" : !leadLever ? ` (a lead strike takes one only with an army lead over ${SECOND_FRONT_LEAD}\xD7; mine is ${leadText()})` : noSplit ? ` (no lead strike under No-Split: an order carries the whole stack)` : ""}`;
111645
112091
  };
111646
112092
  const capNote = (n) => {
@@ -111837,7 +112283,7 @@ function settledPass(input2, shared, cut, relaxAttacks) {
111837
112283
  function planTurn(input2) {
111838
112284
  const seats = staticSeats(input2.game?.players, input2.game?.endRules, input2.me);
111839
112285
  const held = seatTerritories(input2.board, seats);
111840
- const plan = planPushed(withoutStaticSeats(input2, seats));
112286
+ const plan = planAlive(withoutStaticSeats(input2, seats));
111841
112287
  for (const [p, n] of [...held].sort((a, b) => a[0] - b[0]))
111842
112288
  plan.rationale.push(
111843
112289
  `Player ${p} is out (${seats.get(p)}) and no AI plays its seat: it deploys and attacks nothing, so its ${n} territor${n === 1 ? "y is" : "ies are"} planned as neutrals \u2014 static armies to take, no hold needed beside them (#270).`
@@ -111863,6 +112309,28 @@ function withoutStaticSeats(input2, seats) {
111863
112309
  ...input2.game && opening ? { game: { ...input2.game, opening: new Map([...opening].filter(([p]) => !seats.has(p))) } } : {}
111864
112310
  };
111865
112311
  }
112312
+ var deadOutcome = /* @__PURE__ */ new WeakMap();
112313
+ var DEAD_PASSES = 3;
112314
+ function planAlive(input2) {
112315
+ let plan = planPushed(input2);
112316
+ const carried = new Map(input2.deadAdvance ?? []);
112317
+ for (let i2 = 0; i2 < DEAD_PASSES; i2++) {
112318
+ const found = deadOutcome.get(plan);
112319
+ if (!found?.size) return plan;
112320
+ let grew = false;
112321
+ for (const [id, ms] of found) {
112322
+ const was = carried.get(id) ?? [];
112323
+ const next = [.../* @__PURE__ */ new Set([...was, ...ms])].sort(byNum2);
112324
+ if (next.length > was.length) {
112325
+ carried.set(id, next);
112326
+ grew = true;
112327
+ }
112328
+ }
112329
+ if (!grew) return plan;
112330
+ plan = planPushed({ ...input2, deadAdvance: new Map(carried) });
112331
+ }
112332
+ return plan;
112333
+ }
111866
112334
  var allInOutcome = /* @__PURE__ */ new WeakMap();
111867
112335
  function planPushed(input2) {
111868
112336
  const plan = planAttempts(input2);
@@ -112164,11 +112632,13 @@ function planPass(input2, pass) {
112164
112632
  committing,
112165
112633
  byCloseness,
112166
112634
  retakeChecks,
112167
- retakeWarning
112635
+ retakeWarning,
112636
+ foggedBreaks
112168
112637
  } = tgt;
112169
112638
  for (const p of plans) if (p.completable) hd.completable.set(p.bonusId, p.cost);
112170
112639
  const caps = capturesPhase(pc, ps, pass, book, threats, hd, tgt);
112171
112640
  const { strikes, worstCase, defendersAt, tryCapture, snapshot, complete: complete2, tryExpand, advance: advance2 } = caps;
112641
+ const partialSized = /* @__PURE__ */ new Map();
112172
112642
  const stages = twoMoveStages(pc, tgt);
112173
112643
  const bind = spreadBind(pc, ps, tgt);
112174
112644
  const bound = (exempt, f) => bind ? bind.bound(exempt, f) : f();
@@ -112297,13 +112767,14 @@ function planPass(input2, pass) {
112297
112767
  withoutTransit(pc, tgt, r.t, () => tryExpand(r.t, `races for land player ${pc.vacated.get(r.t)} left (out, no AI), ahead of the 1v1 "expansion last" rule (#417)`));
112298
112768
  })
112299
112769
  });
112300
- const breakOption = (t) => {
112301
- const landing = ffaLeader ? defenceAt(t) + reinforcementAt(t) : void 0;
112770
+ const breakOption = (t, partial2) => {
112771
+ const landing = ffaLeader ? defenceAt(t) + reinforcementAt(t) : partial2 !== void 0 ? defenceAt(t) + partial2 : void 0;
112302
112772
  const cost = (landing !== void 0 ? captureCost(landing, s) : null) ?? targets.get(t).cost;
112303
112773
  const survivors = cost - straightKills(defenceAt(t), rates.defensiveKillRate);
112304
112774
  const counter = counterThreat(t);
112305
112775
  const take = toTake(survivors);
112306
- return { t, cost, survivors, counter, take, survives: take === null || take > counter, scoreCost: landScoreCost(t) };
112776
+ const scoreCost = partial2 !== void 0 ? Math.max(1, landScoreCost(t) + cost - targets.get(t).cost) : landScoreCost(t);
112777
+ return { t, cost, survivors, counter, take, survives: take === null || take > counter, scoreCost };
112307
112778
  };
112308
112779
  const strikeWorth = (lost, o) => weight * (lost + (o.take ?? o.survivors) / paybackTurns);
112309
112780
  const round211 = (v) => Math.round(v * 100) / 100;
@@ -112361,7 +112832,7 @@ function planPass(input2, pass) {
112361
112832
  });
112362
112833
  return true;
112363
112834
  };
112364
- const breakOptionOf = (b) => bonusTerritories(g, b.bonusId).filter((t) => targets.has(t)).map(breakOption).sort((a, b2) => a.cost - b2.cost || a.scoreCost - b2.scoreCost || a.t - b2.t)[0];
112835
+ const breakOptionOf = (b) => bonusTerritories(g, b.bonusId).filter((t) => targets.has(t)).map((t) => breakOption(t)).sort((a, b2) => a.cost - b2.cost || a.scoreCost - b2.scoreCost || a.t - b2.t)[0];
112365
112836
  const pileBreak = (() => {
112366
112837
  if (!pc.pile) return void 0;
112367
112838
  const strongest = pc.estimateList.filter((e) => foe(e.playerId)).sort((a, b) => incomeOfPlayer(b.playerId) - incomeOfPlayer(a.playerId) || a.playerId - b.playerId)[0]?.playerId;
@@ -112376,7 +112847,7 @@ function planPass(input2, pass) {
112376
112847
  `Stockpile spend (#421): ${pc.pile.my} armies of mine stand on the board, ${pc.pile.turns} turns of my flat ${income} income, so the turn tries first to break the strongest opponent's cheapest visible bonus, player ${pileBreak.b.player}'s ${bonusName(pileBreak.b.bonusId)} (+${pileBreak.b.value}) through ${label3(pileBreak.o.t)} (${pileBreak.o.cost} armies), before any other capture.`
112377
112848
  );
112378
112849
  for (const b of breakable) {
112379
- const options = bonusTerritories(g, b.bonusId).filter((t) => targets.has(t)).map(breakOption).sort((a, b2) => a.cost - b2.cost || a.scoreCost - b2.scoreCost || a.t - b2.t);
112850
+ const options = bonusTerritories(g, b.bonusId).filter((t) => targets.has(t)).map((t) => breakOption(t)).sort((a, b2) => a.cost - b2.cost || a.scoreCost - b2.scoreCost || a.t - b2.t);
112380
112851
  const o = options[0];
112381
112852
  if (!o) continue;
112382
112853
  const worth = besieged(b) ? strikeWorth(b.value, o) * SIEGE_BREAK_WEIGHT / weight : strikeWorth(b.value, o);
@@ -112431,6 +112902,65 @@ function planPass(input2, pass) {
112431
112902
  })
112432
112903
  });
112433
112904
  }
112905
+ const frontsOf = (p) => [...state].filter(([id, st]) => visibleState(st)?.owner.kind === "player" && st.owner.playerId === p && neighborsOf(g, id).some((n) => mineSet.has(n))).length;
112906
+ for (const fb of foggedBreaks) {
112907
+ const fronts = frontsOf(fb.player);
112908
+ const sizing = (t) => {
112909
+ const estimate2 = reinforcementAt(t);
112910
+ return { estimate: estimate2, partial: partialDeploy(estimate2, fronts) };
112911
+ };
112912
+ const o = fb.members.filter((t) => targets.has(t) && !tgt.droppedMembers.has(t)).map((t) => breakOption(t, sizing(t).partial)).sort((a, b) => a.cost - b.cost || a.scoreCost - b.scoreCost || a.t - b.t)[0];
112913
+ if (!o) continue;
112914
+ const { estimate, partial: partial2 } = sizing(o.t);
112915
+ const value = fb.shortOf !== void 0 ? fb.value * ONE_SHORT_WEIGHT : fb.value;
112916
+ const worth = strikeWorth(value, o);
112917
+ const score = worth / Math.max(1, o.scoreCost);
112918
+ const split = fronts > 1 ? `split over the ${fronts} territories of its beside my land, #593` : `its only territory beside my land, so the whole of it, #593`;
112919
+ const sized = `sized to land if player ${fb.player} deploys up to ${partial2} of its ~${estimate} there first (${split})`;
112920
+ const head = fb.shortOf !== void 0 ? `denies player ${fb.player} bonus ${bonusName(fb.bonusId)} (+${fb.value}), one territory short of complete (${label3(fb.shortOf)} still neutral; opening strike, #593)` : `breaks probable enemy bonus ${bonusName(fb.bonusId)} (+${fb.value} from player ${fb.player}; ${fb.probable})`;
112921
+ const reason = `${head}, ${sized}`;
112922
+ rationale.push(
112923
+ fb.shortOf !== void 0 ? `Player ${fb.player} is one territory short of bonus ${bonusName(fb.bonusId)} (+${fb.value}): ${label3(o.t)} in view is its, beside my land, and ${label3(fb.shortOf)} is still neutral; on an opening turn a strike there denies it (worth ${ONE_SHORT_WEIGHT} \xD7 the bonus) (#593).` : `Player ${fb.player} probably holds bonus ${bonusName(fb.bonusId)} (+${fb.value}): ${label3(o.t)} in view is its, beside my land, and its ${fb.fogged} fogged member${fb.fogged > 1 ? "s" : ""} could all be its (#593).`
112924
+ );
112925
+ offence.set(`break:${fb.bonusId}`, { bonusId: fb.bonusId, target: o.t, kind: "break", cost: o.cost, value: round211(worth), taken: false, why: head });
112926
+ candidates2.push({
112927
+ kind: "break",
112928
+ score,
112929
+ cost: o.cost,
112930
+ id: fb.bonusId,
112931
+ value,
112932
+ focus: false,
112933
+ borders: analyzeBonus(g, fb.bonusId).borderTerritoryIds.length,
112934
+ target: o.t,
112935
+ owner: fb.player,
112936
+ run: spend(() => {
112937
+ if (captured.has(o.t) || bonusTerritories(g, fb.bonusId).some((x) => captured.has(x))) return;
112938
+ const tg = targets.get(o.t);
112939
+ const raised = o.cost > tg.cost;
112940
+ const was = worstCase.get(o.t);
112941
+ if (raised) targets.set(o.t, { ...tg, cost: o.cost });
112942
+ worstCase.set(o.t, Math.max(was ?? 0, defenceAt(o.t) + partial2));
112943
+ const ok = tryCapture(o.t, reason);
112944
+ if (raised) targets.set(o.t, tg);
112945
+ if (!ok) {
112946
+ if (was === void 0) worstCase.delete(o.t);
112947
+ else worstCase.set(o.t, was);
112948
+ return;
112949
+ }
112950
+ const sent = moves.filter((m) => m.kind === "attack" && m.to === o.t).reduce((n, m) => n + m.armies, 0);
112951
+ const whole2 = costAt(o.t, defenceAt(o.t) + estimate);
112952
+ if (whole2 !== null && sent >= whole2 && !combined.has(o.t)) worstCase.set(o.t, Math.max(was ?? 0, defenceAt(o.t) + estimate));
112953
+ else {
112954
+ if (was === void 0) worstCase.delete(o.t);
112955
+ else worstCase.set(o.t, was);
112956
+ const assumes2 = `Attack on enemy ${label3(o.t)} assumes its owner does not reinforce it first.`;
112957
+ if (was === void 0 && !warnings.includes(assumes2)) warnings.push(assumes2);
112958
+ }
112959
+ partialSized.set(o.t, partial2);
112960
+ ps.anchor ??= moves[moves.length - 1].from;
112961
+ })
112962
+ });
112963
+ }
112434
112964
  for (const [t, c] of counterAt) {
112435
112965
  if (!targets.has(t)) continue;
112436
112966
  const o = breakOption(t);
@@ -113094,7 +113624,9 @@ function planPass(input2, pass) {
113094
113624
  const d = defenceAt(m.to);
113095
113625
  const full = costAt(m.to, d + extra);
113096
113626
  const aim = chanceAt(m.to);
113097
- warnings[w] = `Attack on enemy ${label3(m.to)} assumes its owner does not reinforce it first: if player ${st.owner.playerId} deploys its ~${extra} there, ${m.armies} attack ${d + extra} (win chance ${pct(chanceOf(m.armies, d + extra))})${full !== null ? `; ${full} would ${aim >= 1 ? "be sure" : `reach ${pct(aim)}`}` : ""}.`;
113627
+ const part = partialSized.get(m.to);
113628
+ const sizedFor = part !== void 0 && part > 0 && part < extra ? ` (sized for a partial deploy of ${part} (#593))` : "";
113629
+ warnings[w] = `Attack on enemy ${label3(m.to)} assumes its owner does not reinforce it first${sizedFor}: if player ${st.owner.playerId} deploys its ~${extra} there, ${m.armies} attack ${d + extra} (win chance ${pct(chanceOf(m.armies, d + extra))})${full !== null ? `; ${full} would ${aim >= 1 ? "be sure" : `reach ${pct(aim)}`}` : ""}.`;
113098
113630
  }
113099
113631
  const jabsOn = pc.opts.jabs ?? pc.siege !== void 0;
113100
113632
  const thin = (x, have) => {
@@ -113156,6 +113688,16 @@ function planPass(input2, pass) {
113156
113688
  for (const m of u.members) if (!heldBorders.has(m.id)) unheld.add(m.id);
113157
113689
  }
113158
113690
  runOutcome.set(plan, { bareSteps: [...caps.bareTaken].filter(gone).sort(byNum2), held, unheld });
113691
+ {
113692
+ const dead = /* @__PURE__ */ new Map();
113693
+ const after = book.heldNow();
113694
+ for (const t of [...ps.expanded].filter(gone).sort(byNum2)) {
113695
+ if (caps.givenUp(t) || noLossNeutral(pc, tgt, t)) continue;
113696
+ for (const d of deadAdvanceOf(pc, t, after, conceded, /* @__PURE__ */ new Map()) ?? [])
113697
+ dead.set(d.bonusId, [.../* @__PURE__ */ new Set([...dead.get(d.bonusId) ?? [], ...d.members])].sort(byNum2));
113698
+ }
113699
+ if (dead.size) deadOutcome.set(plan, dead);
113700
+ }
113159
113701
  if (tgt.allInTries.size) allInOutcome.set(plan, tgt.allInTries);
113160
113702
  if (pc.strikeShare > 0) shareOutcome.set(plan, pc.strikeShare);
113161
113703
  {
@@ -114230,6 +114772,14 @@ function trackOpponents(g, boards, me, settings = {}, game) {
114230
114772
  }
114231
114773
 
114232
114774
  // src/analysis/plan/deploy-estimates.ts
114775
+ var MIN_TRACK_CALIBRATION_SAMPLES = 5;
114776
+ var TRACK_CALIBRATION_DAMPING = 0.5;
114777
+ function trackCalibrationFactor(calibration, share) {
114778
+ const band = coverageBucket(share);
114779
+ const c = calibration?.[band];
114780
+ if (!c || c.n < MIN_TRACK_CALIBRATION_SAMPLES || !(c.geoMean > 0) || c.geoMean >= 1) return void 0;
114781
+ return { band, geoMean: c.geoMean, n: c.n, factor: c.geoMean ** TRACK_CALIBRATION_DAMPING };
114782
+ }
114233
114783
  function openingArmies(g, board, when = {}) {
114234
114784
  if (when.previous !== void 0 || when.turn !== null && when.turn !== void 0 && when.turn > 1) return null;
114235
114785
  const counts = /* @__PURE__ */ new Set();
@@ -114389,6 +114939,16 @@ function enemyDeployEstimates(g, board, me, settings = {}, previous, tracks, pri
114389
114939
  const observedCap = observation ? couldEarn : null;
114390
114940
  const observedRaw = observation?.deploy ?? null;
114391
114941
  const observed = observation ? Math.min(observation.deploy, observedCap) : null;
114942
+ const coverage2 = usable2 ? trackCoverage(usable2.turns.filter((x) => usable2.incomeTurns.includes(x.from))) : null;
114943
+ let trackCalibration = null;
114944
+ if (usable2 && tracked !== null && tracked > 0) {
114945
+ const c = trackCalibrationFactor(when.calibration, coverage2 ? coverage2.share : null);
114946
+ const figure = c ? Math.min(Math.max(couldEarn, tracked), Math.round(tracked / c.factor)) : tracked;
114947
+ if (c && figure > tracked) {
114948
+ trackCalibration = { raw: tracked, band: c.band, geoMean: c.geoMean, n: c.n, factor: c.factor, figure };
114949
+ tracked = figure;
114950
+ }
114951
+ }
114392
114952
  const seenSource = tracked !== null ? tracked > visible ? "tracked" : "visible" : observed !== null && observed > visible ? "observed" : "visible";
114393
114953
  const seen2 = seenSource === "tracked" ? tracked : seenSource === "observed" ? observed : visible;
114394
114954
  let priorBlend = null;
@@ -114410,7 +114970,6 @@ function enemyDeployEstimates(g, board, me, settings = {}, previous, tracks, pri
114410
114970
  }
114411
114971
  const priorUsed = priorBlend ? priorBlend.figure : priorFigure;
114412
114972
  const source = exact2 !== null ? "exact" : priorUsed !== null && priorUsed > seen2 ? "prior" : seenSource;
114413
- const coverage2 = usable2 ? trackCoverage(usable2.turns.filter((x) => usable2.incomeTurns.includes(x.from))) : null;
114414
114973
  const statedMid = statedRatio !== null && source === "prior" && !usable2 ? seen2 + Math.ceil((priorUsed - seen2) / 2 - 1e-9) : null;
114415
114974
  const chosen = source === "exact" ? exact2 : source === "prior" ? statedMid ?? priorUsed : seen2;
114416
114975
  let thinEvidence = null;
@@ -114508,6 +115067,7 @@ function enemyDeployEstimates(g, board, me, settings = {}, previous, tracks, pri
114508
115067
  cardPlayed,
114509
115068
  ...cardSeen ? { cardSeen: true } : {},
114510
115069
  ...cardInTrack ? { cardInTrack } : {},
115070
+ ...trackCalibration ? { trackCalibration } : {},
114511
115071
  ...priorFull !== null && priorFigure < priorFull ? { stated: { full: priorFull, scaled: priorFigure, lower: seen2, midpoint: statedMid } } : {}
114512
115072
  };
114513
115073
  });
@@ -114549,6 +115109,9 @@ function incomeDetail(g, board, me, settings) {
114549
115109
  var PAYBACK_TURNS = 10;
114550
115110
  var BREACH_WEIGHT = 0.5;
114551
115111
  var OPENS_WEIGHT = 0.5;
115112
+ var HUB_MIN_MEMBERS = 4;
115113
+ var HUB_DEGREE = 0.75;
115114
+ var HUB_WEIGHT = 0.6;
114552
115115
  var DECIDED_PAYBACK_MIN = 3;
114553
115116
  var WASTELAND_FACTOR = 5;
114554
115117
  var PLAIN_EXPANSION_LOSS = 2;
@@ -115671,7 +116234,7 @@ function serverBuild() {
115671
116234
  }
115672
116235
 
115673
116236
  // src/version.ts
115674
- var VERSION2 = "0.18.0";
116237
+ var VERSION2 = "0.19.0";
115675
116238
 
115676
116239
  // src/decision-log.ts
115677
116240
  var DECISION_LOG_VERSION = 1;
@@ -152453,6 +153016,7 @@ function stressOpponents(input2) {
152453
153016
  ...unevenStart(game.settings) ? { unevenStart: unevenStart(game.settings) } : {},
152454
153017
  ...input2.opening ? { opening: input2.opening } : {},
152455
153018
  ...input2.mapPace ? { mapPace: input2.mapPace } : {},
153019
+ ...input2.trackCalibration ? { trackCalibration: input2.trackCalibration } : {},
152456
153020
  ...game.settings?.fog !== void 0 ? { fog: game.settings.fog } : {},
152457
153021
  ...opponentReinforcement(game.settings, hand) ? { reinforcement: opponentReinforcement(game.settings, hand) } : {}
152458
153022
  },
@@ -154322,6 +154886,8 @@ async function livePlanSetup(ctx, a) {
154322
154886
  // #166: the opponent's opening simulated from the starts the award proved, as the prior.
154323
154887
  ...opening ? { opening } : {},
154324
154888
  ...mapPace ? { mapPace } : {},
154889
+ // #568: the same calibration raises each tracked figure by its coverage band's damped factor.
154890
+ ...calibration ? { trackCalibration: calibration } : {},
154325
154891
  // #164: an opponent's Reinforcement card, from the turn the card clock says one can be in hand.
154326
154892
  ...opponentReinforcement(game.settings, hand) ? { reinforcement: opponentReinforcement(game.settings, hand) } : {},
154327
154893
  // #427: the Reinforcement plays seen in the turns' orders (card plays not fogged): a play restarts the clock.
@@ -154763,6 +155329,7 @@ async function commanderCheck(ctx, a) {
154763
155329
  ]);
154764
155330
  const opening = openingThreat(award, a.game, graph, a.seen, a.turn);
154765
155331
  const mapPace = await fogPaceFor(ctx.dataDir, void 0, a.game.settings?.mapId ?? a.map.id, mapMatchOf(profileFormatOf(a.game.players), a.game.settings), a.turn === null ? null : a.turn - 1);
155332
+ const trackCalibration = await outlookCalibrationFor(ctx.dataDir, void 0, profileFormatOf(a.game.players));
154766
155333
  const so = stressOpponents({
154767
155334
  graph,
154768
155335
  map: a.map,
@@ -154777,7 +155344,8 @@ async function commanderCheck(ctx, a) {
154777
155344
  hand: a.hand,
154778
155345
  info: a.info,
154779
155346
  ...opening ? { opening } : {},
154780
- ...mapPace ? { mapPace } : {}
155347
+ ...mapPace ? { mapPace } : {},
155348
+ ...trackCalibration ? { trackCalibration } : {}
154781
155349
  });
154782
155350
  const tripwires = a.tripwires ?? (await readTripwires({
154783
155351
  dataDir: ctx.dataDir,
@@ -159923,6 +160491,7 @@ function registerCheckPlanTool(server, ctx) {
159923
160491
  const opening = openingThreat(award, game, graph, seen2, turn);
159924
160492
  const settings = plannerSettings(game.settings);
159925
160493
  const mapPace = await fogPaceFor(ctx.dataDir, void 0, game.settings?.mapId ?? map2.id, mapMatchOf(profileFormatOf(game.players), game.settings), turn === null ? null : turn - 1);
160494
+ const trackCalibration = await outlookCalibrationFor(ctx.dataDir, void 0, profileFormatOf(game.players));
159926
160495
  const deploys = [];
159927
160496
  const moves = [];
159928
160497
  const refused = /* @__PURE__ */ new Set();
@@ -160049,6 +160618,7 @@ function registerCheckPlanTool(server, ctx) {
160049
160618
  info,
160050
160619
  ...opening ? { opening } : {},
160051
160620
  ...mapPace ? { mapPace } : {},
160621
+ ...trackCalibration ? { trackCalibration } : {},
160052
160622
  ...enemy_deploy !== void 0 ? { enemyDeploy: enemy_deploy } : {},
160053
160623
  assumeCards,
160054
160624
  // #444: the stated incomes scale the other opponents' prior, as warapp_plan_turn has them.