@xbrowser/cli 1.35.0 → 1.36.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.
Files changed (35) hide show
  1. package/README.md +137 -80
  2. package/dist/{browser-MLKP72XP.js → browser-IEZOLTHA.js} +1 -1
  3. package/dist/{browser-KY7AIRAB.js → browser-NHQDQRXB.js} +1 -1
  4. package/dist/{browser-RZ7DPBI3.js → browser-XELRNYBL.js} +1 -1
  5. package/dist/{chunk-EGOWDZXP.js → chunk-2IOFJ6A3.js} +2 -2
  6. package/dist/{chunk-VYTQLZAX.js → chunk-5UXRFNXG.js} +28 -2
  7. package/dist/{chunk-QRFM4NOV.js → chunk-7KVH6MQG.js} +78 -6
  8. package/dist/{chunk-BLCBCESM.js → chunk-ENTENDF5.js} +1 -1
  9. package/dist/{chunk-Y2GRCINH.js → chunk-GVJ2UY65.js} +78 -6
  10. package/dist/{chunk-GNLZWHSP.js → chunk-KSB4PMCY.js} +1 -1
  11. package/dist/{chunk-RMYKVZIZ.js → chunk-L6QJUB33.js} +28 -2
  12. package/dist/{chunk-43U5VDLB.js → chunk-PGEZJ6V3.js} +1 -1
  13. package/dist/{chunk-53VZHESL.js → chunk-RL5FFY2Q.js} +2 -2
  14. package/dist/{chunk-WGS3Y6ZV.js → chunk-SBMVECDS.js} +1 -1
  15. package/dist/{chunk-C5ZPXPD7.js → chunk-WGWPWNIA.js} +53 -16
  16. package/dist/chunk-YW4BIJQL.js +489 -0
  17. package/dist/{chunk-JYYKMSFH.js → chunk-ZR4NHTUV.js} +1 -1
  18. package/dist/cli.js +69 -51
  19. package/dist/convert-JNOM6H6A.js +490 -0
  20. package/dist/{convert-R3XXYKC6.js → convert-K6TLQEPX.js} +5 -3
  21. package/dist/{daemon-client-OXKRGLPQ.js → daemon-client-AKQK5IIB.js} +53 -16
  22. package/dist/{daemon-client-Z3NKNZRL.js → daemon-client-BBPQWLUX.js} +3 -1
  23. package/dist/daemon-main.js +101 -15
  24. package/dist/index.d.ts +26 -3
  25. package/dist/index.js +68 -50
  26. package/dist/{run-routes-TFNV5BBR.js → run-routes-64IBBVOX.js} +4 -4
  27. package/dist/{run-routes-SJKVZ34L.js → run-routes-FG4LIACU.js} +4 -4
  28. package/dist/{server-HUSX7EFE.js → server-K22LJBO2.js} +2 -2
  29. package/dist/{server-KSP5H4HD.js → server-ZHZDJJMG.js} +2 -2
  30. package/dist/{session-recorder-RUNQOJ7T.js → session-recorder-CNTY5KXF.js} +1 -1
  31. package/dist/{session-recorder-N7VEKJVW.js → session-recorder-KMKSQWEP.js} +1 -1
  32. package/dist/{viewer-routes-YOS5GTCV.js → viewer-routes-CEO7HWCB.js} +2 -2
  33. package/package.json +3 -2
  34. package/dist/chunk-ETCO4SNK.js +0 -206
  35. package/dist/convert-LB3GJTLR.js +0 -207
@@ -13,7 +13,7 @@ import {
13
13
  saveSessionDiskMeta,
14
14
  sessions,
15
15
  setActivePage
16
- } from "./chunk-GNLZWHSP.js";
16
+ } from "./chunk-KSB4PMCY.js";
17
17
  import {
18
18
  detectAntiBot,
19
19
  formatDetectionMessage
@@ -3357,6 +3357,19 @@ function stripHashAnchorQuery(url) {
3357
3357
  return url;
3358
3358
  }
3359
3359
  }
3360
+ function createPageBudget(limit, used) {
3361
+ let reserved = used;
3362
+ return {
3363
+ tryAcquire() {
3364
+ if (reserved >= limit) return false;
3365
+ reserved++;
3366
+ return true;
3367
+ },
3368
+ isExhausted() {
3369
+ return reserved >= limit;
3370
+ }
3371
+ };
3372
+ }
3360
3373
  async function extractLinks(page, origin) {
3361
3374
  return page.evaluate((evalOrigin) => {
3362
3375
  return Array.from(document.querySelectorAll("a[href]")).map((a) => {
@@ -3634,6 +3647,7 @@ var crawlCommand = registerCommand({
3634
3647
  await seedPage.close();
3635
3648
  const pagePool = [];
3636
3649
  const poolSize = Math.min(options.concurrency, options.limit);
3650
+ const budget = createPageBudget(options.limit, results.length);
3637
3651
  for (let i = 0; i < poolSize; i++) {
3638
3652
  const ctx2 = await browser.newContext();
3639
3653
  contexts.push(ctx2);
@@ -3651,7 +3665,7 @@ var crawlCommand = registerCommand({
3651
3665
  return null;
3652
3666
  };
3653
3667
  const crawlWorker = async (page) => {
3654
- while (results.length < options.limit) {
3668
+ while (budget.tryAcquire()) {
3655
3669
  const item = dequeueNext();
3656
3670
  if (!item) break;
3657
3671
  completedCount++;
@@ -3665,7 +3679,7 @@ var crawlCommand = registerCommand({
3665
3679
  const pageTitle = await page.title();
3666
3680
  const pageContent = options.format === "html" ? pageHtml : htmlToMarkdown(pageHtml, { onlyMainContent: options.onlyMainContent });
3667
3681
  results.push({ url: page.url(), title: pageTitle, content: pageContent });
3668
- if (results.length >= options.limit) break;
3682
+ if (budget.isExhausted()) break;
3669
3683
  const links = await extractLinks(page, startUrl.origin);
3670
3684
  for (const link of links) {
3671
3685
  try {
@@ -6327,6 +6341,25 @@ function isSpaceAround(input, pos, tokenLen) {
6327
6341
  const after = pos + tokenLen < input.length && input[pos + tokenLen] === " ";
6328
6342
  return before && after;
6329
6343
  }
6344
+ function splitOutsideQuotes(input, separator) {
6345
+ const parts = [];
6346
+ let inQuote = null;
6347
+ let current = "";
6348
+ for (const char of input) {
6349
+ if (!inQuote && (char === "'" || char === '"')) {
6350
+ inQuote = char;
6351
+ } else if (inQuote && char === inQuote) {
6352
+ inQuote = null;
6353
+ } else if (!inQuote && char === separator) {
6354
+ parts.push(current);
6355
+ current = "";
6356
+ continue;
6357
+ }
6358
+ current += char;
6359
+ }
6360
+ parts.push(current);
6361
+ return parts;
6362
+ }
6330
6363
  registerCommandDefinition("goto", ["url"]);
6331
6364
  registerCommandDefinition("click", ["selector"]);
6332
6365
  registerCommandDefinition("fill", ["selector", "value"]);
@@ -8710,6 +8743,41 @@ function getTipsManager() {
8710
8743
  return globalTipsManager;
8711
8744
  }
8712
8745
 
8746
+ // src/utils/zod-internal.ts
8747
+ function asZodSchema(value) {
8748
+ return value;
8749
+ }
8750
+
8751
+ // src/utils/kebab-params.ts
8752
+ function toCamelCase(key) {
8753
+ return key.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
8754
+ }
8755
+ function schemaParamNames(schema) {
8756
+ for (let node = schema, depth = 0; node != null && depth < 5; depth++) {
8757
+ const internal = asZodSchema(node);
8758
+ const shape = internal.shape ?? internal._def?.shape;
8759
+ if (shape) {
8760
+ return new Set(Object.keys(typeof shape === "function" ? shape() : shape));
8761
+ }
8762
+ node = internal._def?.innerType ?? internal._def?.schema;
8763
+ }
8764
+ return void 0;
8765
+ }
8766
+ function normalizeKebabParams(schema, params) {
8767
+ const names = schemaParamNames(schema);
8768
+ if (!names) return params;
8769
+ let renamed;
8770
+ for (const [key, value] of Object.entries(params)) {
8771
+ if (!key.includes("-")) continue;
8772
+ const camelKey = toCamelCase(key);
8773
+ if (camelKey === key || !names.has(camelKey) || names.has(key)) continue;
8774
+ renamed ??= { ...params };
8775
+ if (!(camelKey in params)) renamed[camelKey] = value;
8776
+ delete renamed[key];
8777
+ }
8778
+ return renamed ?? params;
8779
+ }
8780
+
8713
8781
  // src/hooks/loader.ts
8714
8782
  var FAIL_KEYWORDS = [
8715
8783
  "\u767B\u5F55",
@@ -9765,7 +9833,7 @@ async function executePluginChainStep(context) {
9765
9833
  }
9766
9834
  const needsBrowser = cmdEntry.scope === "page" || cmdEntry.scope === "browser";
9767
9835
  if (needsBrowser && !process.env.XBROWSER_DAEMON_WORKER) {
9768
- const { forwardPluginExec } = await import("./daemon-client-Z3NKNZRL.js");
9836
+ const { forwardPluginExec } = await import("./daemon-client-BBPQWLUX.js");
9769
9837
  const userTimeout = typeof pluginParams.timeout === "number" && pluginParams.timeout > 0 ? pluginParams.timeout * 1e3 + 3e4 : void 0;
9770
9838
  const startFwd = Date.now();
9771
9839
  const fwd = await forwardPluginExec(
@@ -9992,7 +10060,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
9992
10060
  }
9993
10061
  let targetPageOverride = null;
9994
10062
  if (_target && extraOpts?.cdpEndpoint) {
9995
- const { findTargetPage } = await import("./browser-KY7AIRAB.js");
10063
+ const { findTargetPage } = await import("./browser-NHQDQRXB.js");
9996
10064
  targetPageOverride = await findTargetPage(extraOpts.cdpEndpoint, _target);
9997
10065
  if (!targetPageOverride) {
9998
10066
  return errorResult(`Target "${_target}" not found. Use 'xbrowser targets --cdp ${extraOpts.cdpEndpoint}' to list available pages.`);
@@ -10000,6 +10068,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
10000
10068
  params = { ...params, url: targetPageOverride.url };
10001
10069
  }
10002
10070
  if (command.parameters) {
10071
+ params = normalizeKebabParams(command.parameters, params);
10003
10072
  const result = command.parameters.safeParse(params);
10004
10073
  if (!result.success) {
10005
10074
  return errorResult(
@@ -10009,7 +10078,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
10009
10078
  params = result.data;
10010
10079
  }
10011
10080
  if (command.scope !== "cli" && !process.env.XBROWSER_DAEMON_WORKER) {
10012
- const { forwardExec } = await import("./daemon-client-Z3NKNZRL.js");
10081
+ const { forwardExec } = await import("./daemon-client-BBPQWLUX.js");
10013
10082
  const longRunning = /^(vision-task|task|crawl|scrape|record|replay)$/.test(commandName);
10014
10083
  const result = await forwardExec(
10015
10084
  commandName,
@@ -10296,7 +10365,10 @@ export {
10296
10365
  getCommand,
10297
10366
  getAllCommands,
10298
10367
  getCommandNames,
10368
+ splitOutsideQuotes,
10299
10369
  attachDetectAntiBot,
10370
+ asZodSchema,
10371
+ normalizeKebabParams,
10300
10372
  loadHooks,
10301
10373
  readJsonFile,
10302
10374
  PluginMetadataParser,
@@ -817,7 +817,7 @@ async function closeSessionByName(name) {
817
817
  } catch {
818
818
  }
819
819
  try {
820
- const { SessionRecorder } = await import("./session-recorder-RUNQOJ7T.js");
820
+ const { SessionRecorder } = await import("./session-recorder-CNTY5KXF.js");
821
821
  SessionRecorder.cleanup(session.name);
822
822
  } catch {
823
823
  }
@@ -13,7 +13,7 @@ import {
13
13
  saveSessionDiskMeta,
14
14
  sessions,
15
15
  setActivePage
16
- } from "./chunk-BLCBCESM.js";
16
+ } from "./chunk-ENTENDF5.js";
17
17
  import {
18
18
  detectAntiBot,
19
19
  formatDetectionMessage
@@ -570,6 +570,25 @@ function isSpaceAround(input, pos, tokenLen) {
570
570
  const after = pos + tokenLen < input.length && input[pos + tokenLen] === " ";
571
571
  return before && after;
572
572
  }
573
+ function splitOutsideQuotes(input, separator) {
574
+ const parts = [];
575
+ let inQuote = null;
576
+ let current = "";
577
+ for (const char of input) {
578
+ if (!inQuote && (char === "'" || char === '"')) {
579
+ inQuote = char;
580
+ } else if (inQuote && char === inQuote) {
581
+ inQuote = null;
582
+ } else if (!inQuote && char === separator) {
583
+ parts.push(current);
584
+ current = "";
585
+ continue;
586
+ }
587
+ current += char;
588
+ }
589
+ parts.push(current);
590
+ return parts;
591
+ }
573
592
  registerCommandDefinition("goto", ["url"]);
574
593
  registerCommandDefinition("click", ["selector"]);
575
594
  registerCommandDefinition("fill", ["selector", "value"]);
@@ -3833,6 +3852,19 @@ function stripHashAnchorQuery(url) {
3833
3852
  return url;
3834
3853
  }
3835
3854
  }
3855
+ function createPageBudget(limit, used) {
3856
+ let reserved = used;
3857
+ return {
3858
+ tryAcquire() {
3859
+ if (reserved >= limit) return false;
3860
+ reserved++;
3861
+ return true;
3862
+ },
3863
+ isExhausted() {
3864
+ return reserved >= limit;
3865
+ }
3866
+ };
3867
+ }
3836
3868
  async function extractLinks(page, origin) {
3837
3869
  return page.evaluate((evalOrigin) => {
3838
3870
  return Array.from(document.querySelectorAll("a[href]")).map((a) => {
@@ -4110,6 +4142,7 @@ var crawlCommand = registerCommand({
4110
4142
  await seedPage.close();
4111
4143
  const pagePool = [];
4112
4144
  const poolSize = Math.min(options.concurrency, options.limit);
4145
+ const budget = createPageBudget(options.limit, results.length);
4113
4146
  for (let i = 0; i < poolSize; i++) {
4114
4147
  const ctx2 = await browser.newContext();
4115
4148
  contexts.push(ctx2);
@@ -4127,7 +4160,7 @@ var crawlCommand = registerCommand({
4127
4160
  return null;
4128
4161
  };
4129
4162
  const crawlWorker = async (page) => {
4130
- while (results.length < options.limit) {
4163
+ while (budget.tryAcquire()) {
4131
4164
  const item = dequeueNext();
4132
4165
  if (!item) break;
4133
4166
  completedCount++;
@@ -4141,7 +4174,7 @@ var crawlCommand = registerCommand({
4141
4174
  const pageTitle = await page.title();
4142
4175
  const pageContent = options.format === "html" ? pageHtml : htmlToMarkdown(pageHtml, { onlyMainContent: options.onlyMainContent });
4143
4176
  results.push({ url: page.url(), title: pageTitle, content: pageContent });
4144
- if (results.length >= options.limit) break;
4177
+ if (budget.isExhausted()) break;
4145
4178
  const links = await extractLinks(page, startUrl.origin);
4146
4179
  for (const link of links) {
4147
4180
  try {
@@ -9555,6 +9588,41 @@ function getTipsManager() {
9555
9588
  return globalTipsManager;
9556
9589
  }
9557
9590
 
9591
+ // src/utils/zod-internal.ts
9592
+ function asZodSchema(value) {
9593
+ return value;
9594
+ }
9595
+
9596
+ // src/utils/kebab-params.ts
9597
+ function toCamelCase(key) {
9598
+ return key.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
9599
+ }
9600
+ function schemaParamNames(schema) {
9601
+ for (let node = schema, depth = 0; node != null && depth < 5; depth++) {
9602
+ const internal = asZodSchema(node);
9603
+ const shape = internal.shape ?? internal._def?.shape;
9604
+ if (shape) {
9605
+ return new Set(Object.keys(typeof shape === "function" ? shape() : shape));
9606
+ }
9607
+ node = internal._def?.innerType ?? internal._def?.schema;
9608
+ }
9609
+ return void 0;
9610
+ }
9611
+ function normalizeKebabParams(schema, params) {
9612
+ const names = schemaParamNames(schema);
9613
+ if (!names) return params;
9614
+ let renamed;
9615
+ for (const [key, value] of Object.entries(params)) {
9616
+ if (!key.includes("-")) continue;
9617
+ const camelKey = toCamelCase(key);
9618
+ if (camelKey === key || !names.has(camelKey) || names.has(key)) continue;
9619
+ renamed ??= { ...params };
9620
+ if (!(camelKey in params)) renamed[camelKey] = value;
9621
+ delete renamed[key];
9622
+ }
9623
+ return renamed ?? params;
9624
+ }
9625
+
9558
9626
  // src/hooks/loader.ts
9559
9627
  var FAIL_KEYWORDS = [
9560
9628
  "\u767B\u5F55",
@@ -10080,7 +10148,7 @@ async function executePluginChainStep(context) {
10080
10148
  }
10081
10149
  const needsBrowser = cmdEntry.scope === "page" || cmdEntry.scope === "browser";
10082
10150
  if (needsBrowser && !process.env.XBROWSER_DAEMON_WORKER) {
10083
- const { forwardPluginExec } = await import("./daemon-client-Z3NKNZRL.js");
10151
+ const { forwardPluginExec } = await import("./daemon-client-BBPQWLUX.js");
10084
10152
  const userTimeout = typeof pluginParams.timeout === "number" && pluginParams.timeout > 0 ? pluginParams.timeout * 1e3 + 3e4 : void 0;
10085
10153
  const startFwd = Date.now();
10086
10154
  const fwd = await forwardPluginExec(
@@ -10307,7 +10375,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
10307
10375
  }
10308
10376
  let targetPageOverride = null;
10309
10377
  if (_target && extraOpts?.cdpEndpoint) {
10310
- const { findTargetPage } = await import("./browser-RZ7DPBI3.js");
10378
+ const { findTargetPage } = await import("./browser-XELRNYBL.js");
10311
10379
  targetPageOverride = await findTargetPage(extraOpts.cdpEndpoint, _target);
10312
10380
  if (!targetPageOverride) {
10313
10381
  return errorResult(`Target "${_target}" not found. Use 'xbrowser targets --cdp ${extraOpts.cdpEndpoint}' to list available pages.`);
@@ -10315,6 +10383,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
10315
10383
  params = { ...params, url: targetPageOverride.url };
10316
10384
  }
10317
10385
  if (command.parameters) {
10386
+ params = normalizeKebabParams(command.parameters, params);
10318
10387
  const result = command.parameters.safeParse(params);
10319
10388
  if (!result.success) {
10320
10389
  return errorResult(
@@ -10324,7 +10393,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
10324
10393
  params = result.data;
10325
10394
  }
10326
10395
  if (command.scope !== "cli" && !process.env.XBROWSER_DAEMON_WORKER) {
10327
- const { forwardExec } = await import("./daemon-client-Z3NKNZRL.js");
10396
+ const { forwardExec } = await import("./daemon-client-BBPQWLUX.js");
10328
10397
  const longRunning = /^(vision-task|task|crawl|scrape|record|replay)$/.test(commandName);
10329
10398
  const result = await forwardExec(
10330
10399
  commandName,
@@ -10626,6 +10695,7 @@ export {
10626
10695
  waitForPage,
10627
10696
  registerCommandDefinition,
10628
10697
  parseCommandChain,
10698
+ splitOutsideQuotes,
10629
10699
  splitCommand,
10630
10700
  parseCommandArgs,
10631
10701
  checkBrowserScope,
@@ -10634,6 +10704,8 @@ export {
10634
10704
  attachDetectAntiBot,
10635
10705
  getWSServerFromCache,
10636
10706
  setWSServerCache,
10707
+ asZodSchema,
10708
+ normalizeKebabParams,
10637
10709
  loadHooks,
10638
10710
  readJsonFile,
10639
10711
  PluginMetadataParser,
@@ -1259,7 +1259,7 @@ async function closeSessionByName(name) {
1259
1259
  } catch {
1260
1260
  }
1261
1261
  try {
1262
- const { SessionRecorder } = await import("./session-recorder-RUNQOJ7T.js");
1262
+ const { SessionRecorder } = await import("./session-recorder-CNTY5KXF.js");
1263
1263
  SessionRecorder.cleanup(session.name);
1264
1264
  } catch {
1265
1265
  }
@@ -2970,6 +2970,7 @@ var SessionRecorder = class _SessionRecorder {
2970
2970
  if (entry && entry.origin === "signal" && Date.now() < entry.expires) {
2971
2971
  return;
2972
2972
  }
2973
+ this.dedupMap.set(dedupFromAction, { expires: Date.now() + 4e3, origin: "command" });
2973
2974
  }
2974
2975
  this.actionCounter++;
2975
2976
  const ts = Date.now();
@@ -3011,6 +3012,28 @@ var SessionRecorder = class _SessionRecorder {
3011
3012
  this.lastKnownUrl = action.value;
3012
3013
  }
3013
3014
  }
3015
+ /**
3016
+ * Reserve the dedup entry for a command BEFORE it executes. Both sides used
3017
+ * to write their entry only after their awaited captures (element screenshot,
3018
+ * auto-snapshot, click context): a fast click's signal was flushed while the
3019
+ * command was still in flight, found no 'command' entry and recorded itself,
3020
+ * and the command then found no 'signal' entry and recorded again.
3021
+ * Returns an undo for commands that end up recording nothing (failed or
3022
+ * thrown) — a reservation left behind would swallow a later real action on
3023
+ * the same element. A live 'signal' entry is kept: the real action was
3024
+ * already recorded and must still suppress the duplicate command action.
3025
+ */
3026
+ reserveCommandAction(action) {
3027
+ const key = this.dedupKey(action.type, action.selector, void 0, action.value);
3028
+ const entry = this.dedupMap.get(key);
3029
+ if (entry && entry.origin === "signal" && Date.now() < entry.expires) return () => {
3030
+ };
3031
+ const reservation = { expires: Date.now() + 4e3, origin: "command" };
3032
+ this.dedupMap.set(key, reservation);
3033
+ return () => {
3034
+ if (this.dedupMap.get(key) === reservation) this.dedupMap.delete(key);
3035
+ };
3036
+ }
3014
3037
  /** Generate dedup key for an action (normalized type + selector/tag + value). */
3015
3038
  dedupKey(type, selector, tag, value) {
3016
3039
  const normType = type === "cdp-click" ? "click" : type === "cdp-fill" ? "input" : type === "cdp-eval" ? "eval" : type;
@@ -3605,8 +3628,11 @@ var SessionRecorder = class _SessionRecorder {
3605
3628
  this.lastActionTs = raw.ts;
3606
3629
  const dedupKey = this.dedupKey(raw.type, raw.element?.selector, raw.element?.tag, raw.value);
3607
3630
  if (dedupKey) {
3608
- this.dedupMap.set(dedupKey, { expires: Date.now() + 4e3, origin: "signal" });
3609
- this.dedupActionCount++;
3631
+ const current = this.dedupMap.get(dedupKey);
3632
+ if (!current || current.origin !== "command" || Date.now() >= current.expires) {
3633
+ this.dedupMap.set(dedupKey, { expires: Date.now() + 4e3, origin: "signal" });
3634
+ this.dedupActionCount++;
3635
+ }
3610
3636
  }
3611
3637
  const verifyTypes = /* @__PURE__ */ new Set(["click", "submit", "input", "change", "cdp-click", "cdp-fill"]);
3612
3638
  if (verifyTypes.has(raw.type)) {
@@ -1259,7 +1259,7 @@ async function closeSessionByName(name) {
1259
1259
  } catch {
1260
1260
  }
1261
1261
  try {
1262
- const { SessionRecorder } = await import("./session-recorder-N7VEKJVW.js");
1262
+ const { SessionRecorder } = await import("./session-recorder-KMKSQWEP.js");
1263
1263
  SessionRecorder.cleanup(session.name);
1264
1264
  } catch {
1265
1265
  }
@@ -4,10 +4,10 @@ import {
4
4
  } from "./chunk-RGL2YTWQ.js";
5
5
  import {
6
6
  executeChain
7
- } from "./chunk-Y2GRCINH.js";
7
+ } from "./chunk-GVJ2UY65.js";
8
8
  import {
9
9
  forwardManagedRun
10
- } from "./chunk-C5ZPXPD7.js";
10
+ } from "./chunk-WGWPWNIA.js";
11
11
  import {
12
12
  errMsg
13
13
  } from "./chunk-GDKLH7ZY.js";
@@ -3,7 +3,7 @@ import { createRequire } from "module";
3
3
  var require2 = createRequire(import.meta.url);
4
4
  var pkg = require2("../package.json");
5
5
  var version = pkg.version;
6
- var buildId = true ? "mwqkqwca" : "dev";
6
+ var buildId = true ? "mwuaecno" : "dev";
7
7
 
8
8
  export {
9
9
  version,
@@ -11,13 +11,45 @@ import { createRequire } from "module";
11
11
  var require2 = createRequire(import.meta.url);
12
12
  var pkg = require2("../package.json");
13
13
  var version = pkg.version;
14
- var buildId = true ? "mwqkqwca" : "dev";
14
+ var buildId = true ? "mwuaecno" : "dev";
15
15
 
16
16
  // src/client/daemon-client.ts
17
17
  import { request as httpRequest } from "http";
18
18
  var DAEMON_PORT = parseInt(process.env.XBROWSER_DAEMON_PORT || "9224", 10);
19
19
  var DAEMON_BASE = `http://localhost:${DAEMON_PORT}`;
20
20
  var _ensurePromise = null;
21
+ function checkDaemonHealth(health, cli, skipBuildCheck, sessionsKnown) {
22
+ if (health.version && health.version !== cli.version) {
23
+ return { action: "restart", reason: `version daemon=${health.version} cli=${cli.version}` };
24
+ }
25
+ if (skipBuildCheck || !health.buildId || health.buildId === "dev" || cli.buildId === "dev" || health.buildId === cli.buildId) {
26
+ return { action: "use", reason: "" };
27
+ }
28
+ const reason = `build daemon=${health.buildId} cli=${cli.buildId}`;
29
+ const sessions = typeof health.activeSessions === "number" ? health.activeSessions : sessionsKnown;
30
+ if (typeof sessions === "number" && sessions > 0) {
31
+ return {
32
+ action: "refuse",
33
+ reason: `Refusing to restart the daemon: this CLI comes from a different build (${reason}), but the daemon is holding ${sessions} active session(s) that a restart would close. Run this build on its own daemon with XBROWSER_DAEMON_PORT=<port>, or set XBROWSER_DAEMON_SKIP_BUILD_CHECK=1 to use the running daemon as is.`
34
+ };
35
+ }
36
+ return { action: "restart", reason };
37
+ }
38
+ async function countDaemonSessions() {
39
+ try {
40
+ const res = await fetch(`${DAEMON_BASE}/rpc`, {
41
+ method: "POST",
42
+ headers: { "Content-Type": "application/json" },
43
+ body: JSON.stringify({ method: "session:list", params: {} }),
44
+ signal: AbortSignal.timeout(2e3)
45
+ });
46
+ if (!res.ok) return null;
47
+ const data = await res.json();
48
+ return Array.isArray(data) ? data.length : null;
49
+ } catch {
50
+ return null;
51
+ }
52
+ }
21
53
  async function ensureDaemonRunning() {
22
54
  if (_ensurePromise) {
23
55
  try {
@@ -28,26 +60,30 @@ async function ensureDaemonRunning() {
28
60
  }
29
61
  const skipBuildCheck = process.env.XBROWSER_DAEMON_SKIP_BUILD_CHECK === "1";
30
62
  for (let attempt = 0; attempt < 3; attempt++) {
31
- const healthOk = await fetch(`${DAEMON_BASE}/health`, { signal: AbortSignal.timeout(2e3) }).then((r) => r.ok ? r.json() : null).then((d) => {
32
- if (d?.status === "ok") {
33
- if (d.version && d.version !== version) {
34
- return { needsRestart: true, reason: `version daemon=${d.version} cli=${version}` };
35
- }
36
- if (!skipBuildCheck && d.buildId && d.buildId !== "dev" && buildId !== "dev" && d.buildId !== buildId) {
37
- return { needsRestart: true, reason: `build daemon=${d.buildId} cli=${buildId}` };
38
- }
39
- return { needsRestart: false };
40
- }
41
- return null;
63
+ const probe = await fetch(`${DAEMON_BASE}/health`, { signal: AbortSignal.timeout(2e3) }).then((r) => r.ok ? r.json() : null).then((d) => {
64
+ if (d?.status !== "ok") return null;
65
+ const cli = { version, buildId };
66
+ return { health: d, check: checkDaemonHealth(d, cli, skipBuildCheck) };
42
67
  }).catch(() => null);
43
- if (healthOk?.needsRestart === false) return;
44
- if (healthOk?.needsRestart === true) {
45
- console.error(`\u26A0\uFE0F Daemon ${healthOk.reason} mismatch. Restarting...`);
68
+ if (!probe) {
69
+ if (attempt < 2) await new Promise((r) => setTimeout(r, 500));
70
+ continue;
71
+ }
72
+ let { check } = probe;
73
+ if (check.action === "restart" && check.reason.startsWith("build") && typeof probe.health.activeSessions !== "number") {
74
+ const sessions = await countDaemonSessions();
75
+ if (sessions !== null) {
76
+ check = checkDaemonHealth(probe.health, { version, buildId }, skipBuildCheck, sessions);
77
+ }
78
+ }
79
+ if (check.action === "use") return;
80
+ if (check.action === "refuse") throw new Error(check.reason);
81
+ if (check.action === "restart") {
82
+ console.error(`\u26A0\uFE0F Daemon ${check.reason} mismatch. Restarting...`);
46
83
  await stopDaemonProcess().catch(() => {
47
84
  });
48
85
  break;
49
86
  }
50
- if (attempt < 2) await new Promise((r) => setTimeout(r, 500));
51
87
  }
52
88
  console.error("\u{1F504} Starting daemon...");
53
89
  _ensurePromise = startDaemonProcess(DAEMON_PORT).then(() => {
@@ -273,6 +309,7 @@ async function forwardViewerCheckSelector(name, selector) {
273
309
 
274
310
  export {
275
311
  version,
312
+ checkDaemonHealth,
276
313
  isDaemonRunning,
277
314
  daemonPing,
278
315
  forwardSessionCreate,