@xbrowser/cli 1.34.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 (63) hide show
  1. package/README.md +137 -80
  2. package/dist/{browser-ZWEJ663M.js → browser-IEZOLTHA.js} +3 -3
  3. package/dist/{browser-GXL6V2JW.js → browser-NHQDQRXB.js} +3 -2
  4. package/dist/{browser-X7LO42UI.js → browser-XELRNYBL.js} +3 -3
  5. package/dist/cdp-driver-CCG3OJUQ.js +49 -0
  6. package/dist/{cdp-driver-GCFEMRFJ.js → cdp-driver-HBMCD7NU.js} +2 -2
  7. package/dist/{cdp-driver-QOUSRPR2.js → cdp-driver-MJD7YIQI.js} +2 -2
  8. package/dist/{cdp-driver-4MNHDU2J.js → cdp-driver-YJU4GRSV.js} +196 -95
  9. package/dist/chunk-2IOFJ6A3.js +149 -0
  10. package/dist/chunk-3SZTCI33.js +147 -0
  11. package/dist/{chunk-VYTQLZAX.js → chunk-5UXRFNXG.js} +28 -2
  12. package/dist/{chunk-NAIHOVDZ.js → chunk-63526WET.js} +2 -8
  13. package/dist/{chunk-YIL44YDX.js → chunk-6DS3T6UK.js} +196 -95
  14. package/dist/{chunk-J4NOL5XX.js → chunk-7KVH6MQG.js} +1099 -204
  15. package/dist/{chunk-N7DFS4V7.js → chunk-ENTENDF5.js} +9 -3
  16. package/dist/{chunk-R57Z5KZX.js → chunk-GVJ2UY65.js} +1078 -185
  17. package/dist/{chunk-3E6VVMK2.js → chunk-GYGVHWG3.js} +272 -1460
  18. package/dist/{chunk-2KPI5GKP.js → chunk-IYCB2KJL.js} +2 -8
  19. package/dist/chunk-KSB4PMCY.js +1380 -0
  20. package/dist/{chunk-RMYKVZIZ.js → chunk-L6QJUB33.js} +28 -2
  21. package/dist/{chunk-TBJUSUKF.js → chunk-NBT2CE3H.js} +140 -96
  22. package/dist/{chunk-DZ6XEPAH.js → chunk-PGEZJ6V3.js} +9 -3
  23. package/dist/chunk-RGL2YTWQ.js +64 -0
  24. package/dist/chunk-RL5FFY2Q.js +150 -0
  25. package/dist/{chunk-43TEMG4U.js → chunk-SBMVECDS.js} +3 -1
  26. package/dist/{chunk-BND5O5KC.js → chunk-SQLICOPZ.js} +177 -240
  27. package/dist/{chunk-O5PASNI7.js → chunk-UUW5EGES.js} +139 -237
  28. package/dist/{chunk-SH6OTPXN.js → chunk-WGWPWNIA.js} +78 -17
  29. package/dist/chunk-YW4BIJQL.js +489 -0
  30. package/dist/{chunk-R7AG7ONI.js → chunk-ZCZELQCS.js} +196 -95
  31. package/dist/chunk-ZR4NHTUV.js +39 -0
  32. package/dist/cli.js +2284 -307
  33. package/dist/convert-JNOM6H6A.js +490 -0
  34. package/dist/{convert-R3XXYKC6.js → convert-K6TLQEPX.js} +5 -3
  35. package/dist/{daemon-client-7D6EZNOE.js → daemon-client-AKQK5IIB.js} +79 -18
  36. package/dist/{daemon-client-HEGAXWGK.js → daemon-client-BBPQWLUX.js} +7 -1
  37. package/dist/daemon-main.js +2305 -164
  38. package/dist/human-interaction-BGAZC3JR.js +12 -0
  39. package/dist/human-interaction-TPKPEE7A.js +11 -0
  40. package/dist/human-interaction-ZSD3IX6Q.js +12 -0
  41. package/dist/index.d.ts +251 -97
  42. package/dist/index.js +2929 -298
  43. package/dist/{launcher-TOLF23ET.js → launcher-AUJK5QQM.js} +1 -1
  44. package/dist/{launcher-ZYB32LSZ.js → launcher-QBAZ6F5L.js} +1 -1
  45. package/dist/mistake-ledger-2B4N54CO.js +29 -0
  46. package/dist/{recovery-ORHJSBDN.js → recovery-5AGY7CV3.js} +4 -5
  47. package/dist/{recovery-XDKN63O5.js → recovery-7NRRHLS4.js} +2 -2
  48. package/dist/{recovery-JFGV3DBX.js → recovery-TIBRFGRP.js} +2 -2
  49. package/dist/run-routes-64IBBVOX.js +24 -0
  50. package/dist/run-routes-FG4LIACU.js +26 -0
  51. package/dist/{server-5U56MQD2.js → server-K22LJBO2.js} +5 -4
  52. package/dist/{server-R4OYD7ZC.js → server-ZHZDJJMG.js} +5 -3
  53. package/dist/{session-recorder-RUNQOJ7T.js → session-recorder-CNTY5KXF.js} +1 -1
  54. package/dist/{session-recorder-N7VEKJVW.js → session-recorder-KMKSQWEP.js} +1 -1
  55. package/dist/{session-replayer-GHEFFNGV.js → session-replayer-4TCLQI76.js} +1 -1
  56. package/dist/viewer-routes-CEO7HWCB.js +11 -0
  57. package/package.json +3 -2
  58. package/dist/chunk-ETCO4SNK.js +0 -206
  59. package/dist/chunk-QCV2PI7U.js +0 -184
  60. package/dist/convert-LB3GJTLR.js +0 -207
  61. package/dist/human-interaction-ISMMOJOK.js +0 -8
  62. package/dist/human-interaction-STTZZZ5N.js +0 -8
  63. package/dist/human-interaction-UXFYV7DU.js +0 -8
@@ -13,7 +13,7 @@ import {
13
13
  getCDPTargets,
14
14
  killChrome,
15
15
  launchChrome
16
- } from "./chunk-NAIHOVDZ.js";
16
+ } from "./chunk-63526WET.js";
17
17
  import {
18
18
  __require
19
19
  } from "./chunk-3RG5ZIWI.js";
@@ -2196,6 +2196,15 @@ var NavigationService = class {
2196
2196
  if (result.errorText) {
2197
2197
  throw new Error(`Navigation failed: ${result.errorText}`);
2198
2198
  }
2199
+ if (!result.loaderId) {
2200
+ this.options.setUrl(url);
2201
+ return {
2202
+ status: () => 200,
2203
+ ok: () => true,
2204
+ url: () => url,
2205
+ headers: () => ({})
2206
+ };
2207
+ }
2199
2208
  if (waitUntil === "commit") {
2200
2209
  this.options.setUrl(url);
2201
2210
  return {
@@ -2218,42 +2227,41 @@ var NavigationService = class {
2218
2227
  };
2219
2228
  }
2220
2229
  async goBack(opts = {}) {
2221
- try {
2222
- const navHistory = await this.options.conn.send("Page.getNavigationHistory", void 0, this.options.sessionId);
2223
- if (navHistory.currentIndex > 0) {
2224
- const prevUrl = navHistory.entries[navHistory.currentIndex - 1]?.url;
2225
- if (prevUrl && prevUrl !== "about:blank") {
2226
- await this.options.conn.send("Page.navigate", { url: prevUrl }, this.options.sessionId);
2227
- await this.options.waitForLoadState(opts.waitUntil ?? "domcontentloaded", opts.timeout ?? 1e4).catch(() => {
2228
- });
2229
- this.options.setUrl(prevUrl);
2230
- return;
2231
- }
2232
- }
2233
- } catch {
2234
- }
2235
- await this.options.evaluate("() => history.back()");
2236
- await this.options.waitForTimeout(3e3);
2237
- this.options.setUrl(await this.options.evaluate("location.href").catch(() => this.options.currentUrl()));
2230
+ await this.traverseHistory(-1, opts);
2238
2231
  }
2239
2232
  async goForward(opts = {}) {
2240
- try {
2241
- const navHistory = await this.options.conn.send("Page.getNavigationHistory", void 0, this.options.sessionId);
2242
- if (navHistory.currentIndex < navHistory.entries.length - 1) {
2243
- const nextUrl = navHistory.entries[navHistory.currentIndex + 1]?.url;
2244
- if (nextUrl && nextUrl !== "about:blank") {
2245
- await this.options.conn.send("Page.navigate", { url: nextUrl }, this.options.sessionId);
2246
- await this.options.waitForLoadState(opts.waitUntil ?? "domcontentloaded", opts.timeout ?? 1e4).catch(() => {
2247
- });
2248
- this.options.setUrl(nextUrl);
2233
+ await this.traverseHistory(1, opts);
2234
+ }
2235
+ async traverseHistory(offset, { timeout = 1e4, waitUntil = "domcontentloaded" }) {
2236
+ if (this.options.isClosed()) throw new Error("Page is closed");
2237
+ const { conn, sessionId } = this.options;
2238
+ const getHistory = () => conn.send(
2239
+ "Page.getNavigationHistory",
2240
+ void 0,
2241
+ sessionId
2242
+ );
2243
+ const history = await getHistory();
2244
+ const entry = history.entries[history.currentIndex + offset];
2245
+ if (!entry) return;
2246
+ await conn.send("Page.navigateToHistoryEntry", { entryId: entry.id }, sessionId);
2247
+ const deadline = Date.now() + timeout;
2248
+ do {
2249
+ const updated = await getHistory();
2250
+ if (updated.entries[updated.currentIndex]?.id === entry.id) {
2251
+ const document = await this.options.evaluate(
2252
+ "({ url: location.href, ready: document.readyState })"
2253
+ ).catch(() => null);
2254
+ if (document?.url === updated.entries[updated.currentIndex].url && (waitUntil === "commit" || (waitUntil === "load" ? document.ready === "complete" : document.ready !== "loading"))) {
2255
+ this.options.setUrl(document.url);
2256
+ if (waitUntil === "networkidle") {
2257
+ await this.options.waitForLoadState(waitUntil, Math.max(0, deadline - Date.now()));
2258
+ }
2249
2259
  return;
2250
2260
  }
2251
2261
  }
2252
- } catch {
2253
- }
2254
- await this.options.evaluate("() => history.forward()");
2255
- await this.options.waitForTimeout(3e3);
2256
- this.options.setUrl(await this.options.evaluate("location.href").catch(() => this.options.currentUrl()));
2262
+ await this.options.waitForTimeout(50);
2263
+ } while (Date.now() < deadline);
2264
+ throw new Error(`History navigation timed out after ${timeout}ms`);
2257
2265
  }
2258
2266
  async reload(opts = {}) {
2259
2267
  this.options.state.loadFired = false;
@@ -2936,7 +2944,6 @@ var XBPageImpl = class _XBPageImpl {
2936
2944
  setUrl: (url) => {
2937
2945
  this._url = url;
2938
2946
  },
2939
- currentUrl: () => this.url(),
2940
2947
  waitForLoadState: (state, timeout) => this.waitForLoadState(state, timeout),
2941
2948
  waitForTimeout: (ms) => this.waitForTimeout(ms),
2942
2949
  evaluate: (script) => this.evaluate(script)
@@ -3785,7 +3792,23 @@ var XBContextImpl = class {
3785
3792
  _emitter = new EventEmitter2();
3786
3793
  _browser;
3787
3794
  contextId;
3788
- _pages = [];
3795
+ /**
3796
+ * 单一规范注册表(dup 回归修复):targetId → wrapper。
3797
+ *
3798
+ * 同一 target 的 wrapper 有三条并发创建路径——newPage() 显式创建、
3799
+ * setAutoAttach 对新建 target 的自动附着事件、Target.attachToTarget 的
3800
+ * attachedToTarget 回显事件(CDP 规范:显式 attach 也会发该事件)。旧实现
3801
+ * 用数组在 `await page._init()` 之后去重,事件在 _init 期间到达时全部穿透
3802
+ * ——headless E2E 实测同一 target 出 3 个 wrapper,且随事件顺序抖动。
3803
+ *
3804
+ * 现在所有路径先**同步预约**(`_reserveTarget` + 同步 set 进
3805
+ * `_pendingRegistrations`),再异步初始化;后到者直接 join 同一个注册
3806
+ * Promise 拿同一个 wrapper,事件顺序无关。注册 Promise 覆盖到 init
3807
+ * scripts 应用完成——join 者拿到的必然是完整初始化的 wrapper。
3808
+ */
3809
+ _pages = /* @__PURE__ */ new Map();
3810
+ /** in-flight 注册(targetId → 注册 Promise),完成后移除并落入 _pages */
3811
+ _pendingRegistrations = /* @__PURE__ */ new Map();
3789
3812
  closed = false;
3790
3813
  options;
3791
3814
  targetAttachedHandler = null;
@@ -3812,28 +3835,30 @@ var XBContextImpl = class {
3812
3835
  async newPage() {
3813
3836
  if (this.closed) throw new Error("Context is closed");
3814
3837
  const { targetId } = await this._browser._createTarget(this.contextId);
3815
- const sessionId = await this._browser._attachToTarget(targetId);
3816
- const page = new XBPageImpl(this.conn, sessionId, targetId, this, this._browser);
3817
- await page._init();
3818
- this._pages.push(page);
3819
- this.forwardPageEvents(page);
3820
- if (this.options.viewport) {
3821
- await page.setViewportSize(this.options.viewport).catch(() => {
3822
- });
3823
- }
3824
- if (this.options.userAgent) {
3825
- await page._setUserAgent(this.options.userAgent);
3826
- }
3827
- if (this.options.extraHTTPHeaders) {
3828
- await page._setExtraHTTPHeaders(this.options.extraHTTPHeaders);
3838
+ let pending = this._reserveTarget(targetId);
3839
+ let explicitSessionId;
3840
+ if (!pending) {
3841
+ const sessionId = await this._browser._attachToTarget(targetId);
3842
+ pending = this._reserveTarget(targetId);
3843
+ if (!pending) {
3844
+ const registration = this._registerTarget(targetId, sessionId);
3845
+ this._pendingRegistrations.set(targetId, registration);
3846
+ pending = registration;
3847
+ explicitSessionId = void 0;
3848
+ } else {
3849
+ explicitSessionId = sessionId;
3850
+ }
3829
3851
  }
3830
- for (const script of this._initScripts) {
3831
- await page.addInitScript(script);
3852
+ const page = await pending;
3853
+ if (explicitSessionId && page.sessionId !== explicitSessionId) {
3854
+ this._browser._detachFromTarget(explicitSessionId).catch(() => {
3855
+ });
3832
3856
  }
3857
+ await this._applyNewPageOptions(page);
3833
3858
  return page;
3834
3859
  }
3835
3860
  pages() {
3836
- return [...this._pages];
3861
+ return [...this._pages.values()];
3837
3862
  }
3838
3863
  browser() {
3839
3864
  return this._browser;
@@ -3841,11 +3866,12 @@ var XBContextImpl = class {
3841
3866
  async close() {
3842
3867
  if (this.closed) return;
3843
3868
  this.closed = true;
3844
- for (const page of this._pages) {
3869
+ for (const page of this._pages.values()) {
3845
3870
  await page.close().catch(() => {
3846
3871
  });
3847
3872
  }
3848
- this._pages = [];
3873
+ this._pages.clear();
3874
+ this._pendingRegistrations.clear();
3849
3875
  if (this.targetAttachedHandler) {
3850
3876
  this.conn.off("Target.attachedToTarget", this.targetAttachedHandler);
3851
3877
  this.targetAttachedHandler = null;
@@ -3866,14 +3892,23 @@ var XBContextImpl = class {
3866
3892
  }
3867
3893
  async addInitScript(script) {
3868
3894
  this._initScripts.push(script);
3869
- for (const page of this._pages) {
3895
+ for (const page of this._pages.values()) {
3870
3896
  await page.addInitScript(script);
3871
3897
  }
3872
3898
  }
3873
3899
  // ── Cookies ─────────────────────────────────────────────────
3900
+ /**
3901
+ * Real CDP browserContextId (from Target.createBrowserContext), or undefined
3902
+ * for the default context (contextId 'default' / '' is not a CDP id — passing
3903
+ * it to Storage.* makes CDP reject the whole call).
3904
+ */
3905
+ get storageContextId() {
3906
+ return this.contextId && this.contextId !== "default" ? this.contextId : void 0;
3907
+ }
3874
3908
  async cookies(urls) {
3875
3909
  const urlList = typeof urls === "string" ? [urls] : urls;
3876
- const params = urlList ? { urls: urlList } : void 0;
3910
+ const bcId = this.storageContextId;
3911
+ const params = bcId ? { ...urlList ? { urls: urlList } : {}, browserContextId: bcId } : urlList ? { urls: urlList } : void 0;
3877
3912
  try {
3878
3913
  const result = await this.conn.send("Storage.getCookies", params);
3879
3914
  return result.cookies;
@@ -3897,15 +3932,18 @@ var XBContextImpl = class {
3897
3932
  secure: c.secure,
3898
3933
  sameSite: c.sameSite
3899
3934
  }));
3935
+ const bcId = this.storageContextId;
3936
+ const params = bcId ? { cookies: cdpCookies, browserContextId: bcId } : { cookies: cdpCookies };
3900
3937
  try {
3901
- await this.conn.send("Storage.setCookies", { cookies: cdpCookies });
3938
+ await this.conn.send("Storage.setCookies", params);
3902
3939
  } catch {
3903
3940
  await this.conn.send("Network.setCookies", { cookies: cdpCookies });
3904
3941
  }
3905
3942
  }
3906
3943
  async clearCookies() {
3944
+ const bcId = this.storageContextId;
3907
3945
  try {
3908
- await this.conn.send("Storage.clearCookies");
3946
+ await this.conn.send("Storage.clearCookies", bcId ? { browserContextId: bcId } : void 0);
3909
3947
  } catch {
3910
3948
  await this.conn.send("Network.clearBrowserCookies");
3911
3949
  }
@@ -3917,18 +3955,92 @@ var XBContextImpl = class {
3917
3955
  this._emitter.off(event, handler);
3918
3956
  }
3919
3957
  /**
3920
- * Register a page that was attached to an existing target (discovered via
3921
- * Target.getTargets). Used by XBBrowserImpl.discoverContexts() to wire up
3922
- * pages from the user's existing browser session into the context wrapper
3923
- * so they appear in `context.pages()` and can be reused by plugins.
3958
+ * Attach an existing target (discovered via Target.getTargets / HTTP
3959
+ * /json/list) and register exactly one wrapper for it. Used by
3960
+ * XBBrowserImpl.discoverContexts() to wire up pages from the user's
3961
+ * existing browser session so they appear in `context.pages()`.
3962
+ *
3963
+ * 显式 attach 同样会触发 attachedToTarget 回显事件(auto-attach 也会对
3964
+ * 既有 target 补附着)——全部经注册表预约去重。attach 失败(如 target
3965
+ * 已被其他客户端占用)返回 null:context 仍注册,后续 newPage() 可用。
3924
3966
  */
3925
- _addDiscoveredPage(page) {
3926
- const exists = this._pages.some((p) => p._targetId === page._targetId);
3927
- if (exists) return;
3928
- this._pages.push(page);
3929
- this.forwardPageEvents(page);
3967
+ async _attachExistingPage(targetId) {
3968
+ let pending = this._reserveTarget(targetId);
3969
+ let explicitSessionId;
3970
+ if (!pending) {
3971
+ let sessionId;
3972
+ try {
3973
+ sessionId = await this._browser._attachToTarget(targetId);
3974
+ } catch {
3975
+ return null;
3976
+ }
3977
+ pending = this._reserveTarget(targetId);
3978
+ if (!pending) {
3979
+ const registration = this._registerTarget(targetId, sessionId);
3980
+ this._pendingRegistrations.set(targetId, registration);
3981
+ pending = registration;
3982
+ } else {
3983
+ explicitSessionId = sessionId;
3984
+ }
3985
+ }
3986
+ try {
3987
+ const page = await pending;
3988
+ if (explicitSessionId && page.sessionId !== explicitSessionId) {
3989
+ this._browser._detachFromTarget(explicitSessionId).catch(() => {
3990
+ });
3991
+ }
3992
+ return page;
3993
+ } catch {
3994
+ return null;
3995
+ }
3930
3996
  }
3931
3997
  // ── Private ─────────────────────────────────────────────────
3998
+ /**
3999
+ * 同步查询/预约 target:已注册返回其 resolved Promise;in-flight 返回
4000
+ * 注册 Promise(join 同一 wrapper);否则返回 null,调用方须同步发起
4001
+ * 注册并 set 进 `_pendingRegistrations`(在任意 await 之前)。
4002
+ */
4003
+ _reserveTarget(targetId) {
4004
+ const registered = this._pages.get(targetId);
4005
+ if (registered) return Promise.resolve(registered);
4006
+ return this._pendingRegistrations.get(targetId) ?? null;
4007
+ }
4008
+ /**
4009
+ * 执行注册:创建 wrapper → _init → 应用 init scripts → 入注册表。
4010
+ * Promise 覆盖到 init scripts 应用完成;成功/失败都从 in-flight 表移除
4011
+ * (失败向上抛给所有 join 者,后续可重新预约重试)。
4012
+ */
4013
+ async _registerTarget(targetId, sessionId) {
4014
+ try {
4015
+ const page = new XBPageImpl(this.conn, sessionId, targetId, this, this._browser);
4016
+ await page._init();
4017
+ for (const script of this._initScripts) {
4018
+ await page.addInitScript(script).catch(() => {
4019
+ });
4020
+ }
4021
+ this._pages.set(targetId, page);
4022
+ page.on("close", () => {
4023
+ if (this._pages.get(targetId) === page) this._pages.delete(targetId);
4024
+ });
4025
+ this.forwardPageEvents(page);
4026
+ return page;
4027
+ } finally {
4028
+ this._pendingRegistrations.delete(targetId);
4029
+ }
4030
+ }
4031
+ /** newPage 的上下文选项(viewport/UA/headers)——自建与 join 路径共用 */
4032
+ async _applyNewPageOptions(page) {
4033
+ if (this.options.viewport) {
4034
+ await page.setViewportSize(this.options.viewport).catch(() => {
4035
+ });
4036
+ }
4037
+ if (this.options.userAgent) {
4038
+ await page._setUserAgent(this.options.userAgent);
4039
+ }
4040
+ if (this.options.extraHTTPHeaders) {
4041
+ await page._setExtraHTTPHeaders(this.options.extraHTTPHeaders);
4042
+ }
4043
+ }
3932
4044
  /** Forward page-level events (request, response, etc.) to context listeners */
3933
4045
  forwardPageEvents(page) {
3934
4046
  const forward = (event) => {
@@ -3944,30 +4056,25 @@ var XBContextImpl = class {
3944
4056
  setupAutoAttach() {
3945
4057
  this.targetAttachedHandler = (paramsRaw) => {
3946
4058
  const params = paramsRaw;
3947
- if (this.contextId !== "default" && params.targetInfo.browserContextId !== this.contextId) return;
3948
4059
  if (params.targetInfo.type !== "page") return;
3949
- const exists = this._pages.some(
3950
- (p) => p._targetId === params.targetInfo.targetId
3951
- );
3952
- if (exists) return;
3953
- const page = new XBPageImpl(
3954
- this.conn,
3955
- params.sessionId,
3956
- params.targetInfo.targetId,
3957
- this,
3958
- this._browser
3959
- );
4060
+ const bcId = params.targetInfo.browserContextId;
4061
+ if (this.contextId === "default") {
4062
+ if (bcId) return;
4063
+ } else if (bcId !== this.contextId) {
4064
+ return;
4065
+ }
3960
4066
  this.conn.send("Runtime.runIfWaitingForDebugger", void 0, params.sessionId).catch(() => {
3961
4067
  });
3962
- page._init().then(async () => {
3963
- for (const script of this._initScripts) {
3964
- await page.addInitScript(script).catch(() => {
3965
- });
4068
+ if (this._reserveTarget(params.targetInfo.targetId)) return;
4069
+ const registration = this._registerTarget(params.targetInfo.targetId, params.sessionId);
4070
+ this._pendingRegistrations.set(params.targetInfo.targetId, registration);
4071
+ registration.then(
4072
+ (page) => {
4073
+ this._emitter.emit("page", page);
4074
+ },
4075
+ () => {
3966
4076
  }
3967
- this._pages.push(page);
3968
- this.forwardPageEvents(page);
3969
- this._emitter.emit("page", page);
3970
- });
4077
+ );
3971
4078
  };
3972
4079
  this.conn.on("Target.attachedToTarget", this.targetAttachedHandler);
3973
4080
  }
@@ -4038,7 +4145,7 @@ var XBBrowserImpl = class {
4038
4145
  this._exitHandler = null;
4039
4146
  }
4040
4147
  if (this.childProcess) {
4041
- const { killChrome: killChrome2 } = await import("./launcher-TOLF23ET.js");
4148
+ const { killChrome: killChrome2 } = await import("./launcher-AUJK5QQM.js");
4042
4149
  await killChrome2(this.childProcess, this.tmpDir);
4043
4150
  }
4044
4151
  await this.conn.close();
@@ -4218,7 +4325,7 @@ var XBBrowserImpl = class {
4218
4325
  if (pageTargets.length === 0 && httpFallbackUrl) {
4219
4326
  console.log(`[discoverContexts] Target.getTargets returned ${targetInfos.length} targets (0 page type). Falling back to HTTP /json/list at ${httpFallbackUrl}`);
4220
4327
  try {
4221
- const { getCDPTargets: getCDPTargets2 } = await import("./launcher-TOLF23ET.js");
4328
+ const { getCDPTargets: getCDPTargets2 } = await import("./launcher-AUJK5QQM.js");
4222
4329
  const httpPages = await getCDPTargets2(httpFallbackUrl);
4223
4330
  console.log(`[discoverContexts] HTTP /json/list returned ${httpPages.length} pages`);
4224
4331
  for (const p of httpPages) {
@@ -4250,13 +4357,7 @@ var XBBrowserImpl = class {
4250
4357
  if (this._contexts.has(ctxId)) continue;
4251
4358
  const context = new XBContextImpl(this.conn, ctxId, this, {});
4252
4359
  for (const p of pages) {
4253
- try {
4254
- const sessionId = await this._attachToTarget(p.targetId);
4255
- const page = new XBPageImpl(this.conn, sessionId, p.targetId, context, this);
4256
- await page._init();
4257
- context._addDiscoveredPage(page);
4258
- } catch {
4259
- }
4360
+ await context._attachExistingPage(p.targetId).catch(() => null);
4260
4361
  }
4261
4362
  this._contexts.set(ctxId, { contextId: ctxId, context });
4262
4363
  }
@@ -0,0 +1,149 @@
1
+ import {
2
+ executeChain
3
+ } from "./chunk-7KVH6MQG.js";
4
+ import {
5
+ outputEnvelope,
6
+ outputError
7
+ } from "./chunk-RGL2YTWQ.js";
8
+ import {
9
+ forwardManagedRun
10
+ } from "./chunk-WGWPWNIA.js";
11
+ import {
12
+ errMsg
13
+ } from "./chunk-GDKLH7ZY.js";
14
+
15
+ // src/stdin.ts
16
+ import { readStdin, readCommandFile, splitFileLine } from "@dyyz1993/xcli-core";
17
+
18
+ // src/cli/run-routes.ts
19
+ import { readFileSync as readFileSync2 } from "fs";
20
+ import { z } from "zod/v4";
21
+
22
+ // src/browser/session-persistence.ts
23
+ import {
24
+ lstatSync,
25
+ existsSync,
26
+ mkdirSync,
27
+ readdirSync,
28
+ readFileSync,
29
+ renameSync,
30
+ unlinkSync,
31
+ writeFileSync
32
+ } from "fs";
33
+ import { homedir } from "os";
34
+ import { join } from "path";
35
+ import { randomUUID } from "crypto";
36
+ function sanitizeSessionName(name) {
37
+ if (!name || name === "." || name === "..") {
38
+ throw new Error(`Invalid session name "${name}": must be a non-empty file-safe name`);
39
+ }
40
+ if (name.length > 64) {
41
+ throw new Error(`Invalid session name: too long (max 64 chars, got ${name.length})`);
42
+ }
43
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(name)) {
44
+ throw new Error(
45
+ `Invalid session name "${name}": only [A-Za-z0-9._-] allowed and it must start with an alphanumeric character`
46
+ );
47
+ }
48
+ return name;
49
+ }
50
+
51
+ // src/cli/run-routes.ts
52
+ var manifest = z.object({
53
+ jobs: z.array(z.object({
54
+ session: z.string(),
55
+ chain: z.string().trim().min(1)
56
+ })).min(1).max(100)
57
+ });
58
+ async function runNamedJobs(jobs, limit, run = forwardManagedRun) {
59
+ if (!Number.isInteger(limit) || limit < 1 || limit > 8) throw new Error("--parallel must be an integer from 1 to 8");
60
+ const names = jobs.map((job) => sanitizeSessionName(job.session));
61
+ if (new Set(names).size !== names.length) throw new Error("Each job must use a different session name");
62
+ const results = [];
63
+ let next = 0;
64
+ await Promise.all(Array.from({ length: Math.min(limit, jobs.length) }, async () => {
65
+ while (next < jobs.length) {
66
+ const index = next++;
67
+ const { session, chain } = jobs[index];
68
+ try {
69
+ const result = await run(chain, session);
70
+ results[index] = { session, success: result.success, result };
71
+ } catch (error) {
72
+ results[index] = { session, success: false, error: errMsg(error) };
73
+ }
74
+ }
75
+ }));
76
+ return results;
77
+ }
78
+ async function handleManagedRunFile(filePath, options) {
79
+ try {
80
+ if (filePath.endsWith(".json")) {
81
+ const { jobs } = manifest.parse(JSON.parse(readFileSync2(filePath, "utf8")));
82
+ const results = await runNamedJobs(jobs, options.parallel === void 0 ? 2 : Number(options.parallel));
83
+ const success = results.every((job) => job.success);
84
+ const failures = results.filter((job) => !job.success);
85
+ const message2 = failures.length ? `Jobs failed: ${failures.map((job) => job.session).join(", ")}` : void 0;
86
+ outputEnvelope({ success, data: { jobs: results }, message: message2 }, { command: "run" }, options.mode);
87
+ if (!success) process.exitCode = 1;
88
+ return;
89
+ }
90
+ if (options.parallel !== void 0) throw new Error("--parallel requires a JSON job manifest");
91
+ const commands = readCommandFile(filePath);
92
+ if (commands.length === 0) throw new Error("No commands found in file");
93
+ const session = sanitizeSessionName(options.sessionName);
94
+ const result = await forwardManagedRun(commands.join(" ; "), session, true);
95
+ const failed = result.steps.find((step) => !step.success);
96
+ const message = result.success ? void 0 : result.stoppedReason ?? failed?.message ?? "Run failed";
97
+ outputEnvelope({ success: result.success, data: result, message }, { command: "run", session }, options.mode);
98
+ if (!result.success) process.exitCode = 1;
99
+ } catch (error) {
100
+ outputEnvelope({ success: false, data: null, message: errMsg(error) }, { command: "run" }, options.mode);
101
+ process.exitCode = 1;
102
+ }
103
+ }
104
+ async function handleRun(filePath, options) {
105
+ let commands;
106
+ try {
107
+ commands = readCommandFile(filePath);
108
+ } catch (e) {
109
+ outputError(`Failed to read file '${filePath}': ${errMsg(e)}`);
110
+ return;
111
+ }
112
+ if (commands.length === 0) {
113
+ outputError("No commands found in file");
114
+ return;
115
+ }
116
+ const chain = commands.join(" ; ");
117
+ const chainResult = await executeChain(chain, {
118
+ cdpEndpoint: options?.cdpEndpoint,
119
+ sessionName: options?.sessionName,
120
+ fileMode: true
121
+ });
122
+ for (const step of chainResult.steps) {
123
+ if (step.success) {
124
+ process.stdout.write(`[OK] ${step.raw}
125
+ `);
126
+ if (step.data && typeof step.data === "object") {
127
+ const d = step.data;
128
+ for (const [k, v] of Object.entries(d)) {
129
+ if (k !== "ok")
130
+ process.stdout.write(` ${k}: ${typeof v === "string" ? v : JSON.stringify(v)}
131
+ `);
132
+ }
133
+ }
134
+ } else {
135
+ outputError(`[FAIL] ${step.raw}: ${step.message}`);
136
+ }
137
+ }
138
+ if (chainResult.stoppedReason) {
139
+ outputError(`Stopped: ${chainResult.stoppedReason}`);
140
+ }
141
+ if (!chainResult.success) process.exit(1);
142
+ }
143
+
144
+ export {
145
+ readStdin,
146
+ runNamedJobs,
147
+ handleManagedRunFile,
148
+ handleRun
149
+ };