@xbrowser/cli 1.33.0 → 1.35.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 (53) hide show
  1. package/dist/{browser-3LBSVDSS.js → browser-KY7AIRAB.js} +3 -2
  2. package/dist/{browser-23BMBCH2.js → browser-MLKP72XP.js} +3 -3
  3. package/dist/{browser-D7RFPTD4.js → browser-RZ7DPBI3.js} +3 -3
  4. package/dist/cdp-driver-CCG3OJUQ.js +49 -0
  5. package/dist/{cdp-driver-B5KVVI4O.js → cdp-driver-HBMCD7NU.js} +2 -2
  6. package/dist/{cdp-driver-GE6Y6LPI.js → cdp-driver-MJD7YIQI.js} +2 -2
  7. package/dist/{cdp-driver-6G77XM4H.js → cdp-driver-YJU4GRSV.js} +203 -95
  8. package/dist/chunk-3SZTCI33.js +147 -0
  9. package/dist/{chunk-OVAUGFM6.js → chunk-43U5VDLB.js} +8 -2
  10. package/dist/chunk-53VZHESL.js +150 -0
  11. package/dist/{chunk-NAIHOVDZ.js → chunk-63526WET.js} +2 -8
  12. package/dist/{chunk-YX5KVWGX.js → chunk-6DS3T6UK.js} +203 -95
  13. package/dist/{chunk-DDHHVII7.js → chunk-BLCBCESM.js} +8 -2
  14. package/dist/{chunk-SH6OTPXN.js → chunk-C5ZPXPD7.js} +31 -7
  15. package/dist/chunk-EGOWDZXP.js +149 -0
  16. package/dist/chunk-GNLZWHSP.js +1380 -0
  17. package/dist/{chunk-5MYC6LVL.js → chunk-GYGVHWG3.js} +279 -1460
  18. package/dist/{chunk-2KPI5GKP.js → chunk-IYCB2KJL.js} +2 -8
  19. package/dist/chunk-JYYKMSFH.js +39 -0
  20. package/dist/{chunk-TBJUSUKF.js → chunk-NBT2CE3H.js} +140 -96
  21. package/dist/{chunk-ACPMC47K.js → chunk-QRFM4NOV.js} +1025 -202
  22. package/dist/chunk-RGL2YTWQ.js +64 -0
  23. package/dist/{chunk-BND5O5KC.js → chunk-SQLICOPZ.js} +177 -240
  24. package/dist/{chunk-O5PASNI7.js → chunk-UUW5EGES.js} +139 -237
  25. package/dist/{chunk-43TEMG4U.js → chunk-WGS3Y6ZV.js} +3 -1
  26. package/dist/{chunk-AKT3WLZM.js → chunk-Y2GRCINH.js} +1004 -183
  27. package/dist/{chunk-H25ECCYJ.js → chunk-ZCZELQCS.js} +203 -95
  28. package/dist/cli.js +2237 -278
  29. package/dist/{daemon-client-7D6EZNOE.js → daemon-client-OXKRGLPQ.js} +32 -8
  30. package/dist/{daemon-client-HEGAXWGK.js → daemon-client-Z3NKNZRL.js} +5 -1
  31. package/dist/daemon-main.js +2214 -159
  32. package/dist/human-interaction-BGAZC3JR.js +12 -0
  33. package/dist/human-interaction-TPKPEE7A.js +11 -0
  34. package/dist/human-interaction-ZSD3IX6Q.js +12 -0
  35. package/dist/index.d.ts +225 -94
  36. package/dist/index.js +2880 -267
  37. package/dist/{launcher-TOLF23ET.js → launcher-AUJK5QQM.js} +1 -1
  38. package/dist/{launcher-ZYB32LSZ.js → launcher-QBAZ6F5L.js} +1 -1
  39. package/dist/mistake-ledger-2B4N54CO.js +29 -0
  40. package/dist/{recovery-ORHJSBDN.js → recovery-5AGY7CV3.js} +4 -5
  41. package/dist/{recovery-JFGV3DBX.js → recovery-7NRRHLS4.js} +4 -4
  42. package/dist/{recovery-XDKN63O5.js → recovery-TIBRFGRP.js} +4 -4
  43. package/dist/run-routes-SJKVZ34L.js +26 -0
  44. package/dist/run-routes-TFNV5BBR.js +24 -0
  45. package/dist/{server-5JHB4TML.js → server-HUSX7EFE.js} +5 -4
  46. package/dist/{server-6CTC3RHV.js → server-KSP5H4HD.js} +5 -3
  47. package/dist/{session-replayer-IGRRA2QC.js → session-replayer-4TCLQI76.js} +1 -1
  48. package/dist/viewer-routes-YOS5GTCV.js +11 -0
  49. package/package.json +1 -1
  50. package/dist/chunk-QCV2PI7U.js +0 -184
  51. package/dist/human-interaction-ISMMOJOK.js +0 -8
  52. package/dist/human-interaction-STTZZZ5N.js +0 -8
  53. package/dist/human-interaction-UXFYV7DU.js +0 -8
@@ -9,7 +9,7 @@ import {
9
9
  import {
10
10
  connectToCDP,
11
11
  launchChrome
12
- } from "./chunk-2KPI5GKP.js";
12
+ } from "./chunk-IYCB2KJL.js";
13
13
  import {
14
14
  errMsg
15
15
  } from "./chunk-GDKLH7ZY.js";
@@ -17,80 +17,6 @@ import {
17
17
  __require
18
18
  } from "./chunk-KFQGP6VL.js";
19
19
 
20
- // src/browser.ts
21
- import { readdirSync as readdirSync2, unlinkSync as unlinkSync2 } from "fs";
22
- import { join as join3 } from "path";
23
-
24
- // src/utils/cdp.ts
25
- async function fetchNoProxy(url) {
26
- const savedProxy = {
27
- http_proxy: process.env.http_proxy,
28
- https_proxy: process.env.https_proxy,
29
- HTTP_PROXY: process.env.HTTP_PROXY,
30
- HTTPS_PROXY: process.env.HTTPS_PROXY,
31
- all_proxy: process.env.all_proxy,
32
- ALL_PROXY: process.env.ALL_PROXY
33
- };
34
- for (const key of Object.keys(savedProxy)) delete process.env[key];
35
- try {
36
- return await fetch(url);
37
- } finally {
38
- for (const [key, val] of Object.entries(savedProxy)) {
39
- if (val !== void 0) process.env[key] = val;
40
- }
41
- }
42
- }
43
- async function resolveCDPEndpoint(raw) {
44
- if (raw === "auto") {
45
- const ports = [9222, 9221, 9223, 9224];
46
- for (const port of ports) {
47
- try {
48
- const httpResp = await fetchNoProxy(`http://localhost:${port}/json/version`);
49
- if (httpResp.ok) {
50
- const data = await httpResp.json();
51
- if (data.webSocketDebuggerUrl) {
52
- return data.webSocketDebuggerUrl;
53
- }
54
- }
55
- } catch {
56
- }
57
- }
58
- throw new Error(
59
- `Could not auto-discover CDP endpoint. Tried ports: ${ports.join(", ")}.
60
- \u53EF\u80FD\u539F\u56E0\uFF1A\u6CA1\u6709 Chrome \u4EE5 --remote-debugging-port \u542F\u52A8\u3002
61
- \u89E3\u51B3\u65B9\u6CD5\uFF1A
62
- 1. \u542F\u52A8 Chrome: google-chrome --remote-debugging-port=9222
63
- 2. \u6216\u7528 cdp-tunnel: npx cdp-tunnel setup
64
- 3. \u6216\u6307\u5B9A\u7AEF\u53E3: --cdp <port>`
65
- );
66
- }
67
- if (/^\d+$/.test(raw)) {
68
- const port = raw;
69
- const httpResp = await fetchNoProxy(`http://localhost:${port}/json/version`);
70
- const data = await httpResp.json();
71
- if (!data.webSocketDebuggerUrl) {
72
- throw new Error(`Could not discover CDP endpoint from localhost:${port}`);
73
- }
74
- return data.webSocketDebuggerUrl;
75
- }
76
- if (raw.startsWith("http://") || raw.startsWith("https://")) {
77
- try {
78
- const u = new URL(raw);
79
- u.pathname = (u.pathname.replace(/\/+$/, "") || "") + "/json/version";
80
- const httpResp = await fetchNoProxy(u.toString());
81
- const data = await httpResp.json();
82
- if (!data.webSocketDebuggerUrl) {
83
- throw new Error(`Could not discover CDP endpoint from ${raw}`);
84
- }
85
- return data.webSocketDebuggerUrl;
86
- } catch (error) {
87
- console.warn(`Failed to fetch WebSocket URL from ${raw}, using endpoint directly: ${error instanceof Error ? error.message : String(error)}`);
88
- return raw;
89
- }
90
- }
91
- return raw;
92
- }
93
-
94
20
  // src/cdp-driver/browser.ts
95
21
  import { EventEmitter as EventEmitter3 } from "events";
96
22
  import { mkdirSync } from "fs";
@@ -1954,6 +1880,13 @@ function setupPageEvents(options) {
1954
1880
  options.emit("framenavigated", options.mainFrame());
1955
1881
  })
1956
1882
  );
1883
+ options.addSubscription(
1884
+ options.conn.subscribe("Page.navigatedWithinDocument", options.sessionId, (params) => {
1885
+ const p = params;
1886
+ const url = p?.url ?? p?.frame?.url;
1887
+ if (url) options.setUrl(url);
1888
+ })
1889
+ );
1957
1890
  options.addSubscription(
1958
1891
  options.conn.subscribe("Page.loadEventFired", options.sessionId, () => {
1959
1892
  options.markLoadFired();
@@ -2262,6 +2195,15 @@ var NavigationService = class {
2262
2195
  if (result.errorText) {
2263
2196
  throw new Error(`Navigation failed: ${result.errorText}`);
2264
2197
  }
2198
+ if (!result.loaderId) {
2199
+ this.options.setUrl(url);
2200
+ return {
2201
+ status: () => 200,
2202
+ ok: () => true,
2203
+ url: () => url,
2204
+ headers: () => ({})
2205
+ };
2206
+ }
2265
2207
  if (waitUntil === "commit") {
2266
2208
  this.options.setUrl(url);
2267
2209
  return {
@@ -2284,42 +2226,41 @@ var NavigationService = class {
2284
2226
  };
2285
2227
  }
2286
2228
  async goBack(opts = {}) {
2287
- try {
2288
- const navHistory = await this.options.conn.send("Page.getNavigationHistory", void 0, this.options.sessionId);
2289
- if (navHistory.currentIndex > 0) {
2290
- const prevUrl = navHistory.entries[navHistory.currentIndex - 1]?.url;
2291
- if (prevUrl && prevUrl !== "about:blank") {
2292
- await this.options.conn.send("Page.navigate", { url: prevUrl }, this.options.sessionId);
2293
- await this.options.waitForLoadState(opts.waitUntil ?? "domcontentloaded", opts.timeout ?? 1e4).catch(() => {
2294
- });
2295
- this.options.setUrl(prevUrl);
2296
- return;
2297
- }
2298
- }
2299
- } catch {
2300
- }
2301
- await this.options.evaluate("() => history.back()");
2302
- await this.options.waitForTimeout(3e3);
2303
- this.options.setUrl(await this.options.evaluate("location.href").catch(() => this.options.currentUrl()));
2229
+ await this.traverseHistory(-1, opts);
2304
2230
  }
2305
2231
  async goForward(opts = {}) {
2306
- try {
2307
- const navHistory = await this.options.conn.send("Page.getNavigationHistory", void 0, this.options.sessionId);
2308
- if (navHistory.currentIndex < navHistory.entries.length - 1) {
2309
- const nextUrl = navHistory.entries[navHistory.currentIndex + 1]?.url;
2310
- if (nextUrl && nextUrl !== "about:blank") {
2311
- await this.options.conn.send("Page.navigate", { url: nextUrl }, this.options.sessionId);
2312
- await this.options.waitForLoadState(opts.waitUntil ?? "domcontentloaded", opts.timeout ?? 1e4).catch(() => {
2313
- });
2314
- this.options.setUrl(nextUrl);
2232
+ await this.traverseHistory(1, opts);
2233
+ }
2234
+ async traverseHistory(offset, { timeout = 1e4, waitUntil = "domcontentloaded" }) {
2235
+ if (this.options.isClosed()) throw new Error("Page is closed");
2236
+ const { conn, sessionId } = this.options;
2237
+ const getHistory = () => conn.send(
2238
+ "Page.getNavigationHistory",
2239
+ void 0,
2240
+ sessionId
2241
+ );
2242
+ const history = await getHistory();
2243
+ const entry = history.entries[history.currentIndex + offset];
2244
+ if (!entry) return;
2245
+ await conn.send("Page.navigateToHistoryEntry", { entryId: entry.id }, sessionId);
2246
+ const deadline = Date.now() + timeout;
2247
+ do {
2248
+ const updated = await getHistory();
2249
+ if (updated.entries[updated.currentIndex]?.id === entry.id) {
2250
+ const document = await this.options.evaluate(
2251
+ "({ url: location.href, ready: document.readyState })"
2252
+ ).catch(() => null);
2253
+ if (document?.url === updated.entries[updated.currentIndex].url && (waitUntil === "commit" || (waitUntil === "load" ? document.ready === "complete" : document.ready !== "loading"))) {
2254
+ this.options.setUrl(document.url);
2255
+ if (waitUntil === "networkidle") {
2256
+ await this.options.waitForLoadState(waitUntil, Math.max(0, deadline - Date.now()));
2257
+ }
2315
2258
  return;
2316
2259
  }
2317
2260
  }
2318
- } catch {
2319
- }
2320
- await this.options.evaluate("() => history.forward()");
2321
- await this.options.waitForTimeout(3e3);
2322
- this.options.setUrl(await this.options.evaluate("location.href").catch(() => this.options.currentUrl()));
2261
+ await this.options.waitForTimeout(50);
2262
+ } while (Date.now() < deadline);
2263
+ throw new Error(`History navigation timed out after ${timeout}ms`);
2323
2264
  }
2324
2265
  async reload(opts = {}) {
2325
2266
  this.options.state.loadFired = false;
@@ -3002,7 +2943,6 @@ var XBPageImpl = class _XBPageImpl {
3002
2943
  setUrl: (url) => {
3003
2944
  this._url = url;
3004
2945
  },
3005
- currentUrl: () => this.url(),
3006
2946
  waitForLoadState: (state, timeout) => this.waitForLoadState(state, timeout),
3007
2947
  waitForTimeout: (ms) => this.waitForTimeout(ms),
3008
2948
  evaluate: (script) => this.evaluate(script)
@@ -3851,7 +3791,23 @@ var XBContextImpl = class {
3851
3791
  _emitter = new EventEmitter2();
3852
3792
  _browser;
3853
3793
  contextId;
3854
- _pages = [];
3794
+ /**
3795
+ * 单一规范注册表(dup 回归修复):targetId → wrapper。
3796
+ *
3797
+ * 同一 target 的 wrapper 有三条并发创建路径——newPage() 显式创建、
3798
+ * setAutoAttach 对新建 target 的自动附着事件、Target.attachToTarget 的
3799
+ * attachedToTarget 回显事件(CDP 规范:显式 attach 也会发该事件)。旧实现
3800
+ * 用数组在 `await page._init()` 之后去重,事件在 _init 期间到达时全部穿透
3801
+ * ——headless E2E 实测同一 target 出 3 个 wrapper,且随事件顺序抖动。
3802
+ *
3803
+ * 现在所有路径先**同步预约**(`_reserveTarget` + 同步 set 进
3804
+ * `_pendingRegistrations`),再异步初始化;后到者直接 join 同一个注册
3805
+ * Promise 拿同一个 wrapper,事件顺序无关。注册 Promise 覆盖到 init
3806
+ * scripts 应用完成——join 者拿到的必然是完整初始化的 wrapper。
3807
+ */
3808
+ _pages = /* @__PURE__ */ new Map();
3809
+ /** in-flight 注册(targetId → 注册 Promise),完成后移除并落入 _pages */
3810
+ _pendingRegistrations = /* @__PURE__ */ new Map();
3855
3811
  closed = false;
3856
3812
  options;
3857
3813
  targetAttachedHandler = null;
@@ -3878,28 +3834,30 @@ var XBContextImpl = class {
3878
3834
  async newPage() {
3879
3835
  if (this.closed) throw new Error("Context is closed");
3880
3836
  const { targetId } = await this._browser._createTarget(this.contextId);
3881
- const sessionId = await this._browser._attachToTarget(targetId);
3882
- const page = new XBPageImpl(this.conn, sessionId, targetId, this, this._browser);
3883
- await page._init();
3884
- this._pages.push(page);
3885
- this.forwardPageEvents(page);
3886
- if (this.options.viewport) {
3887
- await page.setViewportSize(this.options.viewport).catch(() => {
3888
- });
3889
- }
3890
- if (this.options.userAgent) {
3891
- await page._setUserAgent(this.options.userAgent);
3892
- }
3893
- if (this.options.extraHTTPHeaders) {
3894
- await page._setExtraHTTPHeaders(this.options.extraHTTPHeaders);
3837
+ let pending = this._reserveTarget(targetId);
3838
+ let explicitSessionId;
3839
+ if (!pending) {
3840
+ const sessionId = await this._browser._attachToTarget(targetId);
3841
+ pending = this._reserveTarget(targetId);
3842
+ if (!pending) {
3843
+ const registration = this._registerTarget(targetId, sessionId);
3844
+ this._pendingRegistrations.set(targetId, registration);
3845
+ pending = registration;
3846
+ explicitSessionId = void 0;
3847
+ } else {
3848
+ explicitSessionId = sessionId;
3849
+ }
3895
3850
  }
3896
- for (const script of this._initScripts) {
3897
- await page.addInitScript(script);
3851
+ const page = await pending;
3852
+ if (explicitSessionId && page.sessionId !== explicitSessionId) {
3853
+ this._browser._detachFromTarget(explicitSessionId).catch(() => {
3854
+ });
3898
3855
  }
3856
+ await this._applyNewPageOptions(page);
3899
3857
  return page;
3900
3858
  }
3901
3859
  pages() {
3902
- return [...this._pages];
3860
+ return [...this._pages.values()];
3903
3861
  }
3904
3862
  browser() {
3905
3863
  return this._browser;
@@ -3907,11 +3865,12 @@ var XBContextImpl = class {
3907
3865
  async close() {
3908
3866
  if (this.closed) return;
3909
3867
  this.closed = true;
3910
- for (const page of this._pages) {
3868
+ for (const page of this._pages.values()) {
3911
3869
  await page.close().catch(() => {
3912
3870
  });
3913
3871
  }
3914
- this._pages = [];
3872
+ this._pages.clear();
3873
+ this._pendingRegistrations.clear();
3915
3874
  if (this.targetAttachedHandler) {
3916
3875
  this.conn.off("Target.attachedToTarget", this.targetAttachedHandler);
3917
3876
  this.targetAttachedHandler = null;
@@ -3932,14 +3891,23 @@ var XBContextImpl = class {
3932
3891
  }
3933
3892
  async addInitScript(script) {
3934
3893
  this._initScripts.push(script);
3935
- for (const page of this._pages) {
3894
+ for (const page of this._pages.values()) {
3936
3895
  await page.addInitScript(script);
3937
3896
  }
3938
3897
  }
3939
3898
  // ── Cookies ─────────────────────────────────────────────────
3899
+ /**
3900
+ * Real CDP browserContextId (from Target.createBrowserContext), or undefined
3901
+ * for the default context (contextId 'default' / '' is not a CDP id — passing
3902
+ * it to Storage.* makes CDP reject the whole call).
3903
+ */
3904
+ get storageContextId() {
3905
+ return this.contextId && this.contextId !== "default" ? this.contextId : void 0;
3906
+ }
3940
3907
  async cookies(urls) {
3941
3908
  const urlList = typeof urls === "string" ? [urls] : urls;
3942
- const params = urlList ? { urls: urlList } : void 0;
3909
+ const bcId = this.storageContextId;
3910
+ const params = bcId ? { ...urlList ? { urls: urlList } : {}, browserContextId: bcId } : urlList ? { urls: urlList } : void 0;
3943
3911
  try {
3944
3912
  const result = await this.conn.send("Storage.getCookies", params);
3945
3913
  return result.cookies;
@@ -3963,15 +3931,18 @@ var XBContextImpl = class {
3963
3931
  secure: c.secure,
3964
3932
  sameSite: c.sameSite
3965
3933
  }));
3934
+ const bcId = this.storageContextId;
3935
+ const params = bcId ? { cookies: cdpCookies, browserContextId: bcId } : { cookies: cdpCookies };
3966
3936
  try {
3967
- await this.conn.send("Storage.setCookies", { cookies: cdpCookies });
3937
+ await this.conn.send("Storage.setCookies", params);
3968
3938
  } catch {
3969
3939
  await this.conn.send("Network.setCookies", { cookies: cdpCookies });
3970
3940
  }
3971
3941
  }
3972
3942
  async clearCookies() {
3943
+ const bcId = this.storageContextId;
3973
3944
  try {
3974
- await this.conn.send("Storage.clearCookies");
3945
+ await this.conn.send("Storage.clearCookies", bcId ? { browserContextId: bcId } : void 0);
3975
3946
  } catch {
3976
3947
  await this.conn.send("Network.clearBrowserCookies");
3977
3948
  }
@@ -3983,18 +3954,92 @@ var XBContextImpl = class {
3983
3954
  this._emitter.off(event, handler);
3984
3955
  }
3985
3956
  /**
3986
- * Register a page that was attached to an existing target (discovered via
3987
- * Target.getTargets). Used by XBBrowserImpl.discoverContexts() to wire up
3988
- * pages from the user's existing browser session into the context wrapper
3989
- * so they appear in `context.pages()` and can be reused by plugins.
3957
+ * Attach an existing target (discovered via Target.getTargets / HTTP
3958
+ * /json/list) and register exactly one wrapper for it. Used by
3959
+ * XBBrowserImpl.discoverContexts() to wire up pages from the user's
3960
+ * existing browser session so they appear in `context.pages()`.
3961
+ *
3962
+ * 显式 attach 同样会触发 attachedToTarget 回显事件(auto-attach 也会对
3963
+ * 既有 target 补附着)——全部经注册表预约去重。attach 失败(如 target
3964
+ * 已被其他客户端占用)返回 null:context 仍注册,后续 newPage() 可用。
3990
3965
  */
3991
- _addDiscoveredPage(page) {
3992
- const exists = this._pages.some((p) => p._targetId === page._targetId);
3993
- if (exists) return;
3994
- this._pages.push(page);
3995
- this.forwardPageEvents(page);
3966
+ async _attachExistingPage(targetId) {
3967
+ let pending = this._reserveTarget(targetId);
3968
+ let explicitSessionId;
3969
+ if (!pending) {
3970
+ let sessionId;
3971
+ try {
3972
+ sessionId = await this._browser._attachToTarget(targetId);
3973
+ } catch {
3974
+ return null;
3975
+ }
3976
+ pending = this._reserveTarget(targetId);
3977
+ if (!pending) {
3978
+ const registration = this._registerTarget(targetId, sessionId);
3979
+ this._pendingRegistrations.set(targetId, registration);
3980
+ pending = registration;
3981
+ } else {
3982
+ explicitSessionId = sessionId;
3983
+ }
3984
+ }
3985
+ try {
3986
+ const page = await pending;
3987
+ if (explicitSessionId && page.sessionId !== explicitSessionId) {
3988
+ this._browser._detachFromTarget(explicitSessionId).catch(() => {
3989
+ });
3990
+ }
3991
+ return page;
3992
+ } catch {
3993
+ return null;
3994
+ }
3996
3995
  }
3997
3996
  // ── Private ─────────────────────────────────────────────────
3997
+ /**
3998
+ * 同步查询/预约 target:已注册返回其 resolved Promise;in-flight 返回
3999
+ * 注册 Promise(join 同一 wrapper);否则返回 null,调用方须同步发起
4000
+ * 注册并 set 进 `_pendingRegistrations`(在任意 await 之前)。
4001
+ */
4002
+ _reserveTarget(targetId) {
4003
+ const registered = this._pages.get(targetId);
4004
+ if (registered) return Promise.resolve(registered);
4005
+ return this._pendingRegistrations.get(targetId) ?? null;
4006
+ }
4007
+ /**
4008
+ * 执行注册:创建 wrapper → _init → 应用 init scripts → 入注册表。
4009
+ * Promise 覆盖到 init scripts 应用完成;成功/失败都从 in-flight 表移除
4010
+ * (失败向上抛给所有 join 者,后续可重新预约重试)。
4011
+ */
4012
+ async _registerTarget(targetId, sessionId) {
4013
+ try {
4014
+ const page = new XBPageImpl(this.conn, sessionId, targetId, this, this._browser);
4015
+ await page._init();
4016
+ for (const script of this._initScripts) {
4017
+ await page.addInitScript(script).catch(() => {
4018
+ });
4019
+ }
4020
+ this._pages.set(targetId, page);
4021
+ page.on("close", () => {
4022
+ if (this._pages.get(targetId) === page) this._pages.delete(targetId);
4023
+ });
4024
+ this.forwardPageEvents(page);
4025
+ return page;
4026
+ } finally {
4027
+ this._pendingRegistrations.delete(targetId);
4028
+ }
4029
+ }
4030
+ /** newPage 的上下文选项(viewport/UA/headers)——自建与 join 路径共用 */
4031
+ async _applyNewPageOptions(page) {
4032
+ if (this.options.viewport) {
4033
+ await page.setViewportSize(this.options.viewport).catch(() => {
4034
+ });
4035
+ }
4036
+ if (this.options.userAgent) {
4037
+ await page._setUserAgent(this.options.userAgent);
4038
+ }
4039
+ if (this.options.extraHTTPHeaders) {
4040
+ await page._setExtraHTTPHeaders(this.options.extraHTTPHeaders);
4041
+ }
4042
+ }
3998
4043
  /** Forward page-level events (request, response, etc.) to context listeners */
3999
4044
  forwardPageEvents(page) {
4000
4045
  const forward = (event) => {
@@ -4010,30 +4055,25 @@ var XBContextImpl = class {
4010
4055
  setupAutoAttach() {
4011
4056
  this.targetAttachedHandler = (paramsRaw) => {
4012
4057
  const params = paramsRaw;
4013
- if (this.contextId !== "default" && params.targetInfo.browserContextId !== this.contextId) return;
4014
4058
  if (params.targetInfo.type !== "page") return;
4015
- const exists = this._pages.some(
4016
- (p) => p._targetId === params.targetInfo.targetId
4017
- );
4018
- if (exists) return;
4019
- const page = new XBPageImpl(
4020
- this.conn,
4021
- params.sessionId,
4022
- params.targetInfo.targetId,
4023
- this,
4024
- this._browser
4025
- );
4059
+ const bcId = params.targetInfo.browserContextId;
4060
+ if (this.contextId === "default") {
4061
+ if (bcId) return;
4062
+ } else if (bcId !== this.contextId) {
4063
+ return;
4064
+ }
4026
4065
  this.conn.send("Runtime.runIfWaitingForDebugger", void 0, params.sessionId).catch(() => {
4027
4066
  });
4028
- page._init().then(async () => {
4029
- for (const script of this._initScripts) {
4030
- await page.addInitScript(script).catch(() => {
4031
- });
4067
+ if (this._reserveTarget(params.targetInfo.targetId)) return;
4068
+ const registration = this._registerTarget(params.targetInfo.targetId, params.sessionId);
4069
+ this._pendingRegistrations.set(params.targetInfo.targetId, registration);
4070
+ registration.then(
4071
+ (page) => {
4072
+ this._emitter.emit("page", page);
4073
+ },
4074
+ () => {
4032
4075
  }
4033
- this._pages.push(page);
4034
- this.forwardPageEvents(page);
4035
- this._emitter.emit("page", page);
4036
- });
4076
+ );
4037
4077
  };
4038
4078
  this.conn.on("Target.attachedToTarget", this.targetAttachedHandler);
4039
4079
  }
@@ -4104,7 +4144,7 @@ var XBBrowserImpl = class {
4104
4144
  this._exitHandler = null;
4105
4145
  }
4106
4146
  if (this.childProcess) {
4107
- const { killChrome: killChrome2 } = await import("./launcher-ZYB32LSZ.js");
4147
+ const { killChrome: killChrome2 } = await import("./launcher-QBAZ6F5L.js");
4108
4148
  await killChrome2(this.childProcess, this.tmpDir);
4109
4149
  }
4110
4150
  await this.conn.close();
@@ -4284,8 +4324,8 @@ var XBBrowserImpl = class {
4284
4324
  if (pageTargets.length === 0 && httpFallbackUrl) {
4285
4325
  console.log(`[discoverContexts] Target.getTargets returned ${targetInfos.length} targets (0 page type). Falling back to HTTP /json/list at ${httpFallbackUrl}`);
4286
4326
  try {
4287
- const { getCDPTargets: getCDPTargets3 } = await import("./launcher-ZYB32LSZ.js");
4288
- const httpPages = await getCDPTargets3(httpFallbackUrl);
4327
+ const { getCDPTargets: getCDPTargets2 } = await import("./launcher-QBAZ6F5L.js");
4328
+ const httpPages = await getCDPTargets2(httpFallbackUrl);
4289
4329
  console.log(`[discoverContexts] HTTP /json/list returned ${httpPages.length} pages`);
4290
4330
  for (const p of httpPages) {
4291
4331
  if (p.type !== "page") continue;
@@ -4316,13 +4356,7 @@ var XBBrowserImpl = class {
4316
4356
  if (this._contexts.has(ctxId)) continue;
4317
4357
  const context = new XBContextImpl(this.conn, ctxId, this, {});
4318
4358
  for (const p of pages) {
4319
- try {
4320
- const sessionId = await this._attachToTarget(p.targetId);
4321
- const page = new XBPageImpl(this.conn, sessionId, p.targetId, context, this);
4322
- await page._init();
4323
- context._addDiscoveredPage(page);
4324
- } catch {
4325
- }
4359
+ await context._attachExistingPage(p.targetId).catch(() => null);
4326
4360
  }
4327
4361
  this._contexts.set(ctxId, { contextId: ctxId, context });
4328
4362
  }
@@ -5738,6 +5772,66 @@ var CDPProtocolError = class extends Error {
5738
5772
  }
5739
5773
  };
5740
5774
 
5775
+ // src/cdp-driver/wait.ts
5776
+ async function waitForNetworkIdle(conn, sessionId, opts = {}) {
5777
+ const idleTime = opts.idleTime ?? 500;
5778
+ const timeout = opts.timeout ?? 3e4;
5779
+ const maxInflight = opts.maxInflight ?? 0;
5780
+ return new Promise((resolve, reject) => {
5781
+ let inflight = 0;
5782
+ let idleTimer = null;
5783
+ let timeoutTimer = null;
5784
+ let unsub1 = null;
5785
+ let unsub2 = null;
5786
+ let unsub3 = null;
5787
+ const cleanup = () => {
5788
+ if (unsub1) unsub1();
5789
+ if (unsub2) unsub2();
5790
+ if (unsub3) unsub3();
5791
+ if (idleTimer) clearTimeout(idleTimer);
5792
+ if (timeoutTimer) clearTimeout(timeoutTimer);
5793
+ };
5794
+ const checkIdle = () => {
5795
+ if (inflight <= maxInflight) {
5796
+ if (!idleTimer) {
5797
+ idleTimer = setTimeout(() => {
5798
+ cleanup();
5799
+ resolve();
5800
+ }, idleTime);
5801
+ }
5802
+ } else {
5803
+ if (idleTimer) {
5804
+ clearTimeout(idleTimer);
5805
+ idleTimer = null;
5806
+ }
5807
+ }
5808
+ };
5809
+ const onRequest = () => {
5810
+ inflight++;
5811
+ if (idleTimer) {
5812
+ clearTimeout(idleTimer);
5813
+ idleTimer = null;
5814
+ }
5815
+ };
5816
+ const onFinish = () => {
5817
+ inflight = Math.max(0, inflight - 1);
5818
+ checkIdle();
5819
+ };
5820
+ const onFail = () => {
5821
+ inflight = Math.max(0, inflight - 1);
5822
+ checkIdle();
5823
+ };
5824
+ timeoutTimer = setTimeout(() => {
5825
+ cleanup();
5826
+ reject(new Error(`waitForNetworkIdle timeout after ${timeout}ms`));
5827
+ }, timeout);
5828
+ unsub1 = conn.subscribe("Network.requestWillBeSent", sessionId, onRequest);
5829
+ unsub2 = conn.subscribe("Network.loadingFinished", sessionId, onFinish);
5830
+ unsub3 = conn.subscribe("Network.loadingFailed", sessionId, onFail);
5831
+ checkIdle();
5832
+ });
5833
+ }
5834
+
5741
5835
  // src/cdp-driver/index.ts
5742
5836
  async function launch(options = {}) {
5743
5837
  let wsEndpoint;
@@ -5780,1296 +5874,21 @@ async function launch(options = {}) {
5780
5874
  return { browser, wsEndpoint };
5781
5875
  }
5782
5876
 
5783
- // src/browser/connection.ts
5784
- import { existsSync } from "fs";
5785
-
5786
- // src/cdp-interceptor/proxy.ts
5787
- import { WebSocketServer, WebSocket as WebSocket2 } from "ws";
5788
-
5789
- // src/cdp-interceptor/logger.ts
5790
- function createLogger(config) {
5791
- const buffer = [];
5792
- const MAX_BUFFER = 2e3;
5793
- return {
5794
- info(message, meta) {
5795
- if (!config.enableLogging) return;
5796
- const ts = (/* @__PURE__ */ new Date()).toISOString();
5797
- if (meta) {
5798
- console.log(`[CDPInterceptor ${ts}] ${message}`, JSON.stringify(meta));
5799
- } else {
5800
- console.log(`[CDPInterceptor ${ts}] ${message}`);
5801
- }
5802
- },
5803
- log(method, direction, sessionId, payload, decision) {
5804
- const entry = {
5805
- timestamp: Date.now(),
5806
- direction,
5807
- sessionId,
5808
- method,
5809
- payload: sanitizePayload(payload),
5810
- decision: decision ?? void 0
5811
- };
5812
- if (config.enableLogging) {
5813
- buffer.push(entry);
5814
- if (buffer.length > MAX_BUFFER) buffer.shift();
5815
- const tag = decision ? decision.action === "block" ? "\u{1F6AB}BLOCK" : decision.action === "transform" ? "\u{1F504}XFMR" : "\u2705" : " ";
5816
- const reason = decision ? ` [${decision.severity}] ${decision.reason}` : "";
5817
- console.log(`[CDP] ${tag} ${direction} ${method}${reason}`);
5818
- }
5819
- return entry;
5820
- },
5821
- getRecent(count) {
5822
- return buffer.slice(-count);
5823
- },
5824
- flush() {
5825
- buffer.length = 0;
5826
- }
5827
- };
5828
- }
5829
- function sanitizePayload(payload) {
5830
- if (typeof payload !== "object" || payload === null) return { raw: String(payload) };
5831
- const obj = payload;
5832
- const cleaned = {};
5833
- for (const [key, value] of Object.entries(obj)) {
5834
- if (key === "data" && typeof value === "string" && value.length > 200) {
5835
- cleaned[key] = `<binary: ${value.length} chars>`;
5836
- } else if (key === "expression" && typeof value === "string" && value.length > 500) {
5837
- cleaned[key] = value.substring(0, 500) + "...";
5838
- } else {
5839
- cleaned[key] = value;
5840
- }
5841
- }
5842
- return cleaned;
5843
- }
5844
-
5845
- // src/cdp-interceptor/advisor.ts
5846
- function formatBlockMessage(decision, method) {
5847
- const adv = advise(decision, method);
5848
- const lines = [
5849
- `[CDP-FIREWALL-BLOCK] rule=${decision.ruleId}`,
5850
- `method=${method}`,
5851
- `reason=${decision.reason}`,
5852
- `suggestion=${decision.suggestion ?? adv.detail}`
5853
- ];
5854
- if (adv.codeExample) {
5855
- lines.push(`code-example=`);
5856
- lines.push(adv.codeExample);
5857
- }
5858
- return lines.join("\n");
5859
- }
5860
- function advise(decision, originalMethod) {
5861
- const baseAdvice = getBaseAdvice(decision, originalMethod);
5862
- return {
5863
- ruleId: decision.ruleId,
5864
- title: baseAdvice.title,
5865
- detail: decision.suggestion ?? baseAdvice.detail,
5866
- codeExample: baseAdvice.codeExample
5867
- };
5868
- }
5869
- function getBaseAdvice(decision, method) {
5870
- switch (decision.ruleId) {
5871
- case "dom-mutation":
5872
- return {
5873
- title: "Direct DOM property mutation blocked",
5874
- detail: `Your ${method} call tried to set a DOM property directly. In React/Vue/Angular, this bypasses the framework's virtual DOM completely meaning onChange/onInput never fires. The website CAN detect this mismatch as automation.`,
5875
- codeExample: [
5876
- "# \u274C BLOCKED \u2014 what you tried to do:",
5877
- `page.evaluate(\`el.value = 'hello'\`) # triggers isTrusted=false`,
5878
- "",
5879
- "# \u2705 USE INSTEAD \u2014 proper CDP input dispatch:",
5880
- "page.fill('#selector', 'hello') # Playwright: dispatches input+change events",
5881
- "page.type('#selector', 'hello', {delay}) # Playwright: real keystrokes",
5882
- "page.locator('#selector').fill('hello') # Playwright: recommended API"
5883
- ].join("\n")
5884
- };
5885
- case "mouse-trajectory":
5886
- return {
5887
- title: "Unnatural mouse trajectory blocked",
5888
- detail: `Your ${method} sequence formed a perfectly linear path. Human hands have micro-tremors (1-3px variation at any point along the arc), acceleration curves, and never draw straight lines between distant points.`,
5889
- codeExample: [
5890
- "# \u274C BLOCKED \u2014 linear interpolation:",
5891
- "for i in range(20):",
5892
- " page.mouse.move(x0 + (x1-x0)*(i/20), y0 + (y1-y0)*(i/20))",
5893
- "",
5894
- "# \u2705 USE INSTEAD \u2014 Bezier curves with overshoot:",
5895
- '# Use "ghost-cursor" or similar library',
5896
- "from ghost_cursor import path_to",
5897
- "path_to(page, (x1, y1))"
5898
- ].join("\n")
5899
- };
5900
- case "input-keystroke":
5901
- if (method === "Input.insertText") {
5902
- return {
5903
- title: "Input.insertText detected (logged, not blocked)",
5904
- detail: "Input.insertText bypasses native keyDown\u2192keyPress\u2192input\u2192keyUp events. Playwright uses this internally for page.fill(). Logged for observability."
5905
- };
5906
- }
5907
- return {
5908
- title: "Unnatural keystroke timing blocked",
5909
- detail: `Your ${method} calls have unnaturally constant timing (e.g., exact 50ms intervals). Human typing always has variation (CV > 0.2).`,
5910
- codeExample: [
5911
- "# \u274C BLOCKED \u2014 exact constant delay:",
5912
- "page.type('#input', 'hello', {delay: 50}) # every keystroke exactly 50ms apart",
5913
- "",
5914
- "# \u2705 USE INSTEAD \u2014 variable delay (human-like):",
5915
- "page.fill('#input', 'hello') # recommended, dispatches events properly",
5916
- "# OR: type with randomized delay",
5917
- "page.type('#input', 'hello', {delay: 50 + Math.floor(Math.random() * 80)})"
5918
- ].join("\n")
5919
- };
5920
- case "automation-signals":
5921
- return {
5922
- title: "Browser automation marker detected",
5923
- detail: `Your ${method} call accessed a property/marker that anti-crawler systems check to detect automation. These markers (navigator.webdriver, window.__playwright, etc.) are the #1 detection vector.`,
5924
- codeExample: [
5925
- "# \u274C BLOCKED \u2014 don't check for automation markers:",
5926
- "navigator.webdriver # NEVER check this",
5927
- "window.__playwright # NEVER check this",
5928
- "chrome.runtime # NEVER check this",
5929
- "",
5930
- "# \u2705 Just go about your business normally.",
5931
- "# Anti-detection is handled by the CDP firewall automatically."
5932
- ].join("\n")
5933
- };
5934
- case "fingerprinting":
5935
- return {
5936
- title: "Browser fingerprinting API access blocked",
5937
- detail: `Your ${method} call accessed a known fingerprinting API. These APIs (canvas.toDataURL, WebGL getParameter, AudioContext, etc.) are used by anti-crawler systems to build a unique device fingerprint.`,
5938
- codeExample: [
5939
- "# \u274C BLOCKED \u2014 fingerprinting vector:",
5940
- "canvas.toDataURL() # returns unique browser hash",
5941
- 'gl.getParameter(gl.VENDOR) # returns "SwiftShader" in headless',
5942
- "screen.availWidth - screen.availHeight # no OS chrome in headless",
5943
- "",
5944
- "# \u2705 Avoid accessing these APIs. They are only used for fingerprinting."
5945
- ].join("\n")
5946
- };
5947
- case "event-simulation":
5948
- return {
5949
- title: "Synthetic event simulation blocked",
5950
- detail: `Your ${method} call simulated user interaction via el.click() or dispatchEvent(new Event(...)). These produce isTrusted=false events, which are 100% detectable by any anti-crawler that checks isTrusted on critical events.`,
5951
- codeExample: [
5952
- "# \u274C BLOCKED \u2014 synthetic events (isTrusted=false):",
5953
- "el.click() # isTrusted=false",
5954
- 'el.dispatchEvent(new Event("click")) # isTrusted=false',
5955
- "el.focus() # isTrusted=false",
5956
- "",
5957
- "# \u2705 USE INSTEAD \u2014 CDP-level input dispatch (isTrusted=true):",
5958
- "page.click(selector) # uses Input.dispatchMouseEvent",
5959
- "page.fill(selector, value) # dispatches real input events"
5960
- ].join("\n")
5961
- };
5962
- case "emulation-override":
5963
- return {
5964
- title: "CDP emulation override blocked",
5965
- detail: `Your ${method} call overrides browser behavior in a way that creates detectable inconsistencies. Anti-crawler systems cross-check multiple sources (e.g., navigator.userAgent vs HTTP User-Agent header) to catch these mismatches.`,
5966
- codeExample: [
5967
- "# \u274C BLOCKED \u2014 detectable emulation override:",
5968
- "Emulation.setUserAgentOverride(...) # JS vs HTTP header mismatch",
5969
- "Emulation.setGeolocationOverride(...) # IP geo vs overridden geo mismatch",
5970
- "Emulation.setDeviceMetricsOverride(...) # matchMedia vs actual viewport",
5971
- "",
5972
- "# \u2705 These are handled automatically by the CDP firewall.",
5973
- "# Do NOT call them manually."
5974
- ].join("\n")
5975
- };
5976
- case "network-anomaly":
5977
- return {
5978
- title: "Network anomaly detected",
5979
- detail: `Your ${method} call triggered a network pattern that is characteristic of scrapers: blocking URLs, clearing caches, or intercepting requests.`,
5980
- codeExample: [
5981
- "# \u274C BLOCKED \u2014 scraper optimization:",
5982
- "Network.clearBrowserCache() # natural users never do this",
5983
- 'Network.setBlockedURLs(["*fonts*"]) # blocking resources is detectable',
5984
- "Fetch.enable() # MITM-style interception",
5985
- "",
5986
- "# \u2705 Let the browser manage its own cache and network normally."
5987
- ].join("\n")
5988
- };
5989
- case "page-lifecycle":
5990
- return {
5991
- title: "Suspicious page lifecycle pattern blocked",
5992
- detail: `Your ${method} call reveals an unnatural page interaction sequence: navigating too fast, taking screenshots before the page renders, or generating PDFs (a telltale scraper giveaway).`,
5993
- codeExample: [
5994
- "# \u274C BLOCKED \u2014 unnatural lifecycle:",
5995
- "page.goto(url); page.pdf() # PDF = scraper giveaway",
5996
- "page.goto(url); page.screenshot() <500ms # screenshot before render",
5997
- "page.goto(url) 3x in <100ms # rapid navigation barrage",
5998
- "",
5999
- "# \u2705 Add proper waits between actions:",
6000
- 'page.goto(url, {waitUntil: "networkidle"})',
6001
- 'page.waitForSelector("body")',
6002
- "page.screenshot() # after rendering"
6003
- ].join("\n")
6004
- };
6005
- default:
6006
- return {
6007
- title: decision.reason,
6008
- detail: decision.suggestion ?? `The CDP call "${method}" was blocked by rule "${decision.ruleId}".`
6009
- };
6010
- }
6011
- }
6012
-
6013
- // src/cdp-interceptor/proxy.ts
6014
- function makeCompoundId(cdpSessionId, rawSessionId) {
6015
- return `${cdpSessionId ?? "nil"}::${rawSessionId ?? "nil"}`;
6016
- }
6017
- var CDPInterceptorProxy = class {
6018
- wss = null;
6019
- engine;
6020
- config;
6021
- logger;
6022
- started = false;
6023
- stats = {
6024
- totalMessages: 0,
6025
- blockedMessages: 0,
6026
- transformedMessages: 0,
6027
- passedMessages: 0,
6028
- byRule: {}
6029
- };
6030
- constructor(config) {
6031
- this.config = config;
6032
- this.engine = createRuleEngine(config.rules);
6033
- this.logger = createLogger({
6034
- enableLogging: config.enableLogging ?? true,
6035
- logDir: config.logDir
6036
- });
6037
- }
6038
- /** The port the proxy is listening on (only valid after start()) */
6039
- get port() {
6040
- const addr = this.wss?.address();
6041
- if (addr && typeof addr === "object") return addr.port;
6042
- return 0;
6043
- }
6044
- /** Start the proxy server */
6045
- async start() {
6046
- if (this.started) return this.port;
6047
- return new Promise((resolve, reject) => {
6048
- this.wss = new WebSocketServer({ port: this.config.listenPort ?? 0 }, () => {
6049
- const port = this.port;
6050
- this.engine.start();
6051
- this.started = true;
6052
- this.logger.info("CDP interceptor proxy started", { port, endpoint: this.config.cdpEndpoint });
6053
- resolve(port);
6054
- });
6055
- this.wss.on("error", reject);
6056
- this.wss.on("connection", (clientWs, _req) => {
6057
- this.handleConnection(clientWs);
6058
- });
6059
- });
6060
- }
6061
- /** Stop the proxy server */
6062
- async stop() {
6063
- this.engine.stop();
6064
- this.logger.flush();
6065
- this.started = false;
6066
- return new Promise((resolve) => {
6067
- if (!this.wss) return resolve();
6068
- this.wss.close(() => resolve());
6069
- this.wss = null;
6070
- });
6071
- }
6072
- /** Get accumulated statistics */
6073
- getStats() {
6074
- return { ...this.stats };
6075
- }
6076
- /** Get recent log entries (for inspection) */
6077
- getRecentLogs(count = 50) {
6078
- return this.logger.getRecent(count);
6079
- }
6080
- // ── Connection handling ──────────────────────────────────────
6081
- handleConnection(clientWs) {
6082
- let browserWs = null;
6083
- let isAlive = true;
6084
- const pendingMessages = [];
6085
- browserWs = new WebSocket2(this.config.cdpEndpoint);
6086
- clientWs.on("message", (raw) => {
6087
- if (browserWs && browserWs.readyState === WebSocket2.OPEN) {
6088
- this.handleClientMessage(clientWs, browserWs, raw);
6089
- } else {
6090
- pendingMessages.push(raw);
6091
- }
6092
- });
6093
- browserWs.on("open", () => {
6094
- for (const buf of pendingMessages) {
6095
- this.handleClientMessage(clientWs, browserWs, buf);
6096
- }
6097
- pendingMessages.length = 0;
6098
- });
6099
- browserWs.on("error", (err) => {
6100
- this.logger.info("Browser WebSocket error", { error: String(err) });
6101
- });
6102
- browserWs.on("close", (code, reason) => {
6103
- if (isAlive && clientWs.readyState === WebSocket2.OPEN) {
6104
- this.logger.info("Browser WS closed, closing client", { code, reason: String(reason) });
6105
- clientWs.close();
6106
- }
6107
- });
6108
- browserWs.on("message", (raw) => {
6109
- this.handleBrowserMessage(clientWs, browserWs, raw);
6110
- });
6111
- const cleanup = () => {
6112
- isAlive = false;
6113
- if (browserWs && browserWs.readyState === WebSocket2.OPEN) {
6114
- browserWs.close();
6115
- }
6116
- };
6117
- clientWs.on("close", cleanup);
6118
- clientWs.on("error", cleanup);
6119
- browserWs.on("close", () => {
6120
- if (isAlive && clientWs.readyState === WebSocket2.OPEN) {
6121
- clientWs.close();
6122
- }
6123
- });
6124
- browserWs.on("error", cleanup);
6125
- }
6126
- // ── Message processing ───────────────────────────────────────
6127
- handleClientMessage(clientWs, browserWs, raw) {
6128
- const msg = this.parseMessage(raw);
6129
- if (!msg) return;
6130
- this.stats.totalMessages++;
6131
- if (!("method" in msg)) {
6132
- browserWs.send(raw.toString());
6133
- return;
6134
- }
6135
- const request = msg;
6136
- const ctx = {
6137
- method: request.method,
6138
- params: request.params ?? {},
6139
- sessionId: makeCompoundId("_cdpSession" in browserWs ? browserWs._cdpSession : void 0, request.sessionId),
6140
- direction: "client\u2192browser"
6141
- };
6142
- const decision = this.engine.evaluate(ctx);
6143
- this.logger.log(ctx.method, "client\u2192browser", ctx.sessionId, { method: ctx.method, params: ctx.params }, decision);
6144
- if (decision) {
6145
- this.recordDecision(decision);
6146
- }
6147
- if (decision?.action === "block") {
6148
- const blockMsg = formatBlockMessage(decision, ctx.method);
6149
- const errorResponse = {
6150
- id: request.id,
6151
- error: {
6152
- code: decision.errorCode ?? -32e3,
6153
- message: blockMsg
6154
- },
6155
- sessionId: request.sessionId
6156
- };
6157
- this.stats.blockedMessages++;
6158
- console.error(`
6159
- ${blockMsg}
6160
- `);
6161
- clientWs.send(JSON.stringify(errorResponse));
6162
- return;
6163
- }
6164
- if (decision?.action === "transform" && decision.transformedParams) {
6165
- const sequence = decision.transformedParams.__sequence;
6166
- if (Array.isArray(sequence)) {
6167
- this.stats.transformedMessages++;
6168
- const dispatch = async () => {
6169
- for (const step of sequence) {
6170
- if (step.delayMs) await new Promise((resolve) => setTimeout(resolve, step.delayMs));
6171
- const transformed2 = { id: request.id, method: step.method, params: step.params, sessionId: request.sessionId };
6172
- browserWs.send(JSON.stringify(transformed2));
6173
- }
6174
- };
6175
- void dispatch();
6176
- return;
6177
- }
6178
- const transformed = { ...request, params: decision.transformedParams };
6179
- this.stats.transformedMessages++;
6180
- browserWs.send(JSON.stringify(transformed));
6181
- return;
6182
- }
6183
- this.stats.passedMessages++;
6184
- browserWs.send(raw.toString());
6185
- }
6186
- handleBrowserMessage(clientWs, _browserWs, raw) {
6187
- const msg = this.parseMessage(raw);
6188
- if (!msg) {
6189
- clientWs.send(raw.toString());
6190
- return;
6191
- }
6192
- if ("method" in msg) {
6193
- const event = msg;
6194
- const ctx = {
6195
- method: event.method,
6196
- params: event.params ?? {},
6197
- sessionId: event.sessionId ?? "browser",
6198
- direction: "browser\u2192client"
6199
- };
6200
- const decision = this.engine.evaluate(ctx);
6201
- if (decision?.action === "block") {
6202
- return;
6203
- }
6204
- }
6205
- clientWs.send(raw.toString());
6206
- }
6207
- // ── Utilities ────────────────────────────────────────────────
6208
- parseMessage(raw) {
6209
- try {
6210
- return JSON.parse(raw.toString());
6211
- } catch {
6212
- return null;
6213
- }
6214
- }
6215
- recordDecision(decision) {
6216
- if (!this.stats.byRule[decision.ruleId]) {
6217
- this.stats.byRule[decision.ruleId] = { matched: 0, blocked: 0, transformed: 0 };
6218
- }
6219
- this.stats.byRule[decision.ruleId].matched++;
6220
- if (decision.action === "block") {
6221
- this.stats.byRule[decision.ruleId].blocked++;
6222
- } else if (decision.action === "transform") {
6223
- this.stats.byRule[decision.ruleId].transformed++;
6224
- }
6225
- }
6226
- };
6227
-
6228
- // src/browser/connection.ts
6229
- async function getCDPTargets2(cdpEndpoint) {
6230
- try {
6231
- const endpoint = String(cdpEndpoint);
6232
- let url = "http://localhost:9222/json/list";
6233
- if (endpoint.startsWith("http://") || endpoint.startsWith("https://")) {
6234
- const parsed = new URL(endpoint);
6235
- parsed.pathname = (parsed.pathname.replace(/\/+$/, "") || "") + "/json/list";
6236
- url = parsed.toString();
6237
- } else if (/^\d+$/.test(endpoint)) {
6238
- url = `http://localhost:${endpoint}/json/list`;
6239
- }
6240
- const response = await fetch(url);
6241
- return await response.json();
6242
- } catch {
6243
- return [];
6244
- }
6245
- }
6246
- async function findTargetPage(cdpEndpoint, target) {
6247
- const targets = await getCDPTargets2(cdpEndpoint);
6248
- const pages = targets.filter((item) => item.url && !item.url.startsWith("about:blank") && !item.url.startsWith("chrome://") && !item.url.startsWith("chrome-untrusted://") && !item.url.startsWith("chrome-error://"));
6249
- const byId = pages.find((item) => item.id === target);
6250
- if (byId) return { pageId: byId.id, wsUrl: byId.webSocketDebuggerUrl, title: byId.title, url: byId.url };
6251
- const lowerTarget = target.toLowerCase();
6252
- const byTitle = pages.find((item) => item.title?.toLowerCase().includes(lowerTarget));
6253
- if (byTitle) return { pageId: byTitle.id, wsUrl: byTitle.webSocketDebuggerUrl, title: byTitle.title, url: byTitle.url };
6254
- const byUrl = pages.find((item) => item.url.toLowerCase().includes(lowerTarget));
6255
- if (byUrl) return { pageId: byUrl.id, wsUrl: byUrl.webSocketDebuggerUrl, title: byUrl.title, url: byUrl.url };
6256
- return null;
6257
- }
6258
- function resolveLaunchOpts(ctx) {
6259
- return ctx.cdpEndpoint ? { cdpEndpoint: ctx.cdpEndpoint } : { headless: true };
6260
- }
6261
- var CHROMIUM_CANDIDATES = [
6262
- "/Applications/Chromium.app/Contents/MacOS/Chromium",
6263
- "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
6264
- "/usr/bin/chromium-browser",
6265
- "/usr/bin/chromium",
6266
- "/usr/bin/google-chrome"
6267
- ];
6268
- function discoverChromiumPath() {
6269
- return CHROMIUM_CANDIDATES.find((path) => existsSync(path));
6270
- }
6271
- var browserPool = /* @__PURE__ */ new Map();
6272
- var sharedCdpProxy = null;
6273
- function getSharedCdpProxy() {
6274
- return sharedCdpProxy;
6275
- }
6276
- function setSharedCdpProxy(proxy) {
6277
- sharedCdpProxy = proxy;
6278
- }
6279
- async function createBrowser(options) {
6280
- if (options?.cdpEndpoint) {
6281
- const realEndpoint = await resolveCDPEndpoint(options.cdpEndpoint);
6282
- if (!options.intercept) {
6283
- const pooled = browserPool.get(realEndpoint);
6284
- if (pooled && !pooled.disconnected) return pooled;
6285
- if (pooled) browserPool.delete(realEndpoint);
6286
- }
6287
- if (options.intercept) {
6288
- const config = typeof options.intercept === "object" ? { ...options.intercept, cdpEndpoint: realEndpoint } : { cdpEndpoint: realEndpoint };
6289
- sharedCdpProxy = new CDPInterceptorProxy(config);
6290
- const proxyPort = await sharedCdpProxy.start();
6291
- console.error(`[CDP Interceptor] Proxy running on ws://localhost:${proxyPort}, forwarding to ${realEndpoint}`);
6292
- const { browser: browser3 } = await launch({ cdpEndpoint: `ws://localhost:${proxyPort}` });
6293
- return browser3;
6294
- }
6295
- const { browser: browser2 } = await launch({ cdpEndpoint: realEndpoint });
6296
- await browser2.discoverContexts().catch((error) => {
6297
- console.error(`[browser] discoverContexts failed: ${errMsg(error)}`);
6298
- });
6299
- browserPool.set(realEndpoint, browser2);
6300
- return browser2;
6301
- }
6302
- const executablePath = options?.executablePath || process.env.XBROWSER_CHROMIUM_PATH || discoverChromiumPath();
6303
- const { browser } = await launch({ executablePath, headless: options?.headless ?? true });
6304
- return browser;
6305
- }
6306
-
6307
- // src/browser/state.ts
6308
- import { randomUUID } from "crypto";
6309
- import { existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync, readdirSync, unlinkSync, writeFileSync } from "fs";
6310
- import { join as join2 } from "path";
6311
- import { homedir } from "os";
6312
- import { SessionStore } from "@dyyz1993/xcli-core";
6313
- var SESSION_DIR = join2(homedir(), ".xbrowser", "sessions");
6314
- var sessions = new SessionStore();
6315
- var sharedState = { browser: null, idleTimer: null };
6316
- function sessionFile(name) {
6317
- return join2(SESSION_DIR, `${name}.json`);
6318
- }
6319
- function ensureSessionDir() {
6320
- mkdirSync2(SESSION_DIR, { recursive: true });
6321
- }
6322
- function saveSessionDiskMeta(name, data) {
6323
- ensureSessionDir();
6324
- const file = sessionFile(name);
6325
- let existing = {};
6326
- try {
6327
- existing = JSON.parse(readFileSync(file, "utf8"));
6328
- } catch {
6329
- }
6330
- Object.assign(existing, data, { name });
6331
- writeFileSync(file, JSON.stringify(existing, null, 2));
6332
- }
6333
- function readSessionDiskMeta(name) {
6334
- try {
6335
- return JSON.parse(readFileSync(sessionFile(name), "utf8"));
6336
- } catch {
6337
- return null;
6338
- }
6339
- }
6340
- function deleteSessionDiskMeta(name) {
6341
- try {
6342
- unlinkSync(sessionFile(name));
6343
- } catch {
6344
- }
6345
- }
6346
- function newSessionId() {
6347
- return randomUUID();
6348
- }
6349
-
6350
- // src/browser/lifecycle.ts
6351
- function registerSession(session) {
6352
- const complete = {
6353
- id: session.id ?? newSessionId(),
6354
- createdAt: session.createdAt ?? (/* @__PURE__ */ new Date()).toISOString(),
6355
- lastActivityAt: session.lastActivityAt ?? Date.now(),
6356
- ...session
6357
- };
6358
- sessions.set(complete);
6359
- resetIdleTimer();
6360
- return complete;
6361
- }
6362
-
6363
- // src/browser/restore.ts
6364
- function logSessionEvent(event, details) {
6365
- const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace("T", " ").substring(0, 19);
6366
- console.error(`[SESSION] ${timestamp} [PID:${process.pid}] ${event} | ${details}`);
6367
- }
6368
- async function isSessionPageAlive(session) {
6369
- const page = session.page;
6370
- if (!page || typeof page.evaluate !== "function") return false;
6371
- for (let attempt = 0; attempt < 3; attempt++) {
6372
- try {
6373
- await Promise.race([
6374
- page.evaluate("1"),
6375
- new Promise((_, reject) => setTimeout(() => reject(new Error("liveness probe timeout")), 1500))
6376
- ]);
6377
- return true;
6378
- } catch {
6379
- await new Promise((resolve) => setTimeout(resolve, 400));
6380
- }
6381
- }
6382
- return false;
6383
- }
6384
- async function findOrRestoreSession(name, cdpEndpoint, cleanup = async () => false, installNetworkCapture2 = async () => {
6385
- }) {
6386
- const inMemory = findSession(name);
6387
- if (inMemory) {
6388
- if (await isSessionPageAlive(inMemory)) return inMemory;
6389
- logSessionEvent("stale_session", `name="${name}" \u2014 page probe failed; rebuilding`);
6390
- try {
6391
- await cleanup(name);
6392
- } catch {
6393
- }
6394
- }
6395
- const meta = readSessionDiskMeta(name);
6396
- if (!meta) return void 0;
6397
- const endpoint = cdpEndpoint || meta.cdpEndpoint;
6398
- if (!endpoint) return void 0;
6399
- try {
6400
- const browser = await createBrowser({ cdpEndpoint: endpoint });
6401
- await new Promise((resolve) => setTimeout(resolve, 500));
6402
- let contexts = browser.contexts();
6403
- if (contexts.length === 0) {
6404
- await new Promise((resolve) => setTimeout(resolve, 500));
6405
- contexts = browser.contexts();
6406
- }
6407
- const context = contexts[0] || await browser.newContext();
6408
- const savedUrl = meta.conversationUrl || meta.url;
6409
- let targetHostname = "";
6410
- if (savedUrl) {
6411
- try {
6412
- targetHostname = new URL(savedUrl).hostname;
6413
- } catch {
6414
- targetHostname = "";
6415
- }
6416
- }
6417
- let page = null;
6418
- let fallbackPage = null;
6419
- for (const browserContext of contexts) {
6420
- for (const candidate of browserContext.pages()) {
6421
- const url = candidate.url();
6422
- if (!url || url === "about:blank" || url.startsWith("chrome://") || url.startsWith("chrome-untrusted://") || url.startsWith("chrome-error://")) continue;
6423
- if (targetHostname && url.includes(targetHostname)) {
6424
- page = candidate;
6425
- break;
6426
- }
6427
- fallbackPage ??= candidate;
6428
- }
6429
- if (page) break;
6430
- }
6431
- page ??= fallbackPage;
6432
- if (!page) {
6433
- const targets = await getCDPTargets2(endpoint);
6434
- const match = targets.find((target) => target.url && target.url !== "about:blank" && !target.url.startsWith("chrome://") && !target.url.startsWith("chrome-untrusted://") && !target.url.startsWith("chrome-error://") && (!targetHostname || target.url.includes(targetHostname)));
6435
- if (match?.url) {
6436
- page = await context.newPage();
6437
- await page.goto(match.url, { waitUntil: "domcontentloaded", timeout: 15e3 }).catch(() => {
6438
- });
6439
- }
6440
- }
6441
- if (!page) {
6442
- const pages = context.pages();
6443
- page = pages.length > 0 ? pages[0] : await context.newPage();
6444
- }
6445
- try {
6446
- await Promise.race([
6447
- page.evaluate(() => true),
6448
- new Promise((_, reject) => setTimeout(() => reject(new Error("timeout")), 3e3))
6449
- ]);
6450
- } catch {
6451
- deleteSessionDiskMeta(name);
6452
- return void 0;
6453
- }
6454
- const targetUrl = meta.conversationUrl || meta.url;
6455
- if (targetUrl && page.url() !== targetUrl) {
6456
- try {
6457
- if (!page.url().includes(new URL(targetUrl).hostname)) {
6458
- await page.goto(targetUrl, { waitUntil: "domcontentloaded", timeout: 3e4 }).catch(() => {
6459
- });
6460
- }
6461
- } catch {
6462
- }
6463
- }
6464
- const session = {
6465
- id: meta.id,
6466
- name,
6467
- context,
6468
- page,
6469
- browser,
6470
- createdAt: meta.createdAt,
6471
- lastActivityAt: Date.now(),
6472
- isCDP: true,
6473
- cdpEndpoint: endpoint
6474
- };
6475
- for (const existing of sessions.list()) {
6476
- if (existing.name === name) sessions.removeById(existing.id);
6477
- }
6478
- sessions.set(session);
6479
- await installNetworkCapture2(session.page, name);
6480
- return session;
6481
- } catch (error) {
6482
- console.error(`[Session Restore] Failed for "${name}":`, errMsg(error));
6483
- deleteSessionDiskMeta(name);
6484
- return void 0;
6485
- }
6486
- }
6487
-
6488
- // src/browser/create-session.ts
6489
- async function createSessionImpl(name, url, options, deps) {
6490
- const existing = findSession(name);
6491
- if (existing) {
6492
- deps.logSessionEvent("replace_session", `name="${name}" id="${existing.id}" \u2014 closing existing session before creating new one`);
6493
- await deps.closeSessionByName(name);
6494
- }
6495
- const b = await createBrowser(options);
6496
- const isCDP = !!options?.cdpEndpoint;
6497
- let context;
6498
- let page;
6499
- let reusedExistingPage = false;
6500
- if (isCDP) {
6501
- const targetHostname = url ? (() => {
6502
- try {
6503
- return new URL(url).hostname;
6504
- } catch {
6505
- return "";
6506
- }
6507
- })() : "";
6508
- const isRealPageUrl = (u) => !!u && u !== "about:blank" && !u.startsWith("chrome://") && !u.startsWith("chrome-untrusted://") && !u.startsWith("chrome-error://");
6509
- const resolvePageUrl = async (p) => {
6510
- const u = p.url();
6511
- if (u && u !== "about:blank") return u;
6512
- try {
6513
- return await p.evaluate("location.href");
6514
- } catch {
6515
- return u ?? "";
6516
- }
6517
- };
6518
- const pollStart = Date.now();
6519
- for (; ; ) {
6520
- const ctxs = b.contexts();
6521
- let hostHit = false;
6522
- let anyHit = false;
6523
- for (const ctx of ctxs) {
6524
- for (const p of ctx.pages()) {
6525
- const u = await resolvePageUrl(p);
6526
- if (!isRealPageUrl(u)) continue;
6527
- anyHit = true;
6528
- if (targetHostname && u.includes(targetHostname)) {
6529
- hostHit = true;
6530
- break;
6531
- }
6532
- }
6533
- if (hostHit) break;
6534
- }
6535
- if (process.env.XB_DEBUG_SESSION_POLL) {
6536
- console.error(`[poll] t=${Date.now() - pollStart}ms ctxs=${ctxs.length} hostHit=${hostHit} anyHit=${anyHit}`);
6537
- }
6538
- if (hostHit) break;
6539
- if (anyHit && Date.now() - pollStart >= 2e3) break;
6540
- if (Date.now() - pollStart >= 5e3) break;
6541
- await new Promise((r) => setTimeout(r, 200));
6542
- }
6543
- let contexts = b.contexts();
6544
- if (contexts.length === 0) {
6545
- await new Promise((r) => setTimeout(r, 500));
6546
- contexts = b.contexts();
6547
- }
6548
- context = contexts[0] || await b.newContext();
6549
- let targetPage = null;
6550
- const ownedUrls = /* @__PURE__ */ new Set();
6551
- for (const ssn of sessions.list()) {
6552
- try {
6553
- const u = ssn.page?.url();
6554
- if (u && u !== "about:blank") ownedUrls.add(u);
6555
- } catch {
6556
- }
6557
- }
6558
- if (url) {
6559
- for (const ctx of contexts) {
6560
- for (const p of ctx.pages()) {
6561
- try {
6562
- const pUrl = await resolvePageUrl(p);
6563
- if (ownedUrls.has(pUrl)) continue;
6564
- if (pUrl === url) {
6565
- targetPage = p;
6566
- break;
6567
- }
6568
- } catch {
6569
- }
6570
- }
6571
- if (targetPage) break;
6572
- }
6573
- }
6574
- if (!targetPage && targetHostname) {
6575
- for (const ctx of contexts) {
6576
- const pages = ctx.pages();
6577
- for (const p of pages) {
6578
- const pUrl0 = await resolvePageUrl(p);
6579
- if (ownedUrls.has(pUrl0)) continue;
6580
- const pUrl = pUrl0;
6581
- let hostnameMatches = false;
6582
- try {
6583
- hostnameMatches = new URL(pUrl).hostname === targetHostname;
6584
- } catch {
6585
- }
6586
- if (isRealPageUrl(pUrl) && hostnameMatches) {
6587
- targetPage = p;
6588
- break;
6589
- }
6590
- }
6591
- if (targetPage) break;
6592
- }
6593
- }
6594
- if (!targetPage && options?.cdpEndpoint) {
6595
- const targets = await deps.getCDPTargets(options.cdpEndpoint);
6596
- const ownedUrlsT = /* @__PURE__ */ new Set();
6597
- for (const ssn of sessions.list()) {
6598
- try {
6599
- const u = ssn.page?.url();
6600
- if (u && u !== "about:blank") ownedUrlsT.add(u);
6601
- } catch {
6602
- }
6603
- }
6604
- const matchTarget = targets.find((t) => {
6605
- if (!t.url || !isRealPageUrl(t.url) || ownedUrlsT.has(t.url)) return false;
6606
- if (!url) return false;
6607
- try {
6608
- return new URL(t.url).hostname === targetHostname;
6609
- } catch {
6610
- return false;
6611
- }
6612
- });
6613
- if (matchTarget && matchTarget.url) {
6614
- const ownedUrls2 = /* @__PURE__ */ new Set();
6615
- for (const ssn of sessions.list()) {
6616
- try {
6617
- const u = ssn.page?.url();
6618
- if (u && u !== "about:blank") ownedUrls2.add(u);
6619
- } catch {
6620
- }
6621
- }
6622
- const isOwned = (p) => {
6623
- try {
6624
- return ownedUrls2.has(p.url());
6625
- } catch {
6626
- return false;
6627
- }
6628
- };
6629
- const existing2 = context.pages().find((p) => {
6630
- try {
6631
- return p.url() === matchTarget.url && !isOwned(p);
6632
- } catch {
6633
- return false;
6634
- }
6635
- });
6636
- if (existing2) {
6637
- targetPage = existing2;
6638
- } else {
6639
- targetPage = await context.newPage();
6640
- await targetPage.goto(matchTarget.url, { waitUntil: "domcontentloaded", timeout: 15e3 }).catch(() => {
6641
- });
6642
- }
6643
- }
6644
- }
6645
- const targetPageExisted = !!targetPage;
6646
- if (!targetPage) {
6647
- targetPage = await context.newPage();
6648
- }
6649
- page = targetPage;
6650
- reusedExistingPage = targetPageExisted;
6651
- if (isCDP) {
6652
- await Promise.resolve(targetPage.bringToFront?.()).catch(() => {
6653
- });
6654
- }
6655
- } else {
6656
- context = await b.newContext({ viewport: { width: 1920, height: 1080 } });
6657
- page = await context.newPage();
6658
- }
6659
- if (url && page.url() !== url) {
6660
- await page.goto(url, { waitUntil: "domcontentloaded", timeout: 15e3 }).catch(() => {
6661
- });
6662
- }
6663
- const session = deps.registerSession({
6664
- name,
6665
- context,
6666
- page,
6667
- browser: b,
6668
- isCDP,
6669
- cdpEndpoint: options?.cdpEndpoint,
6670
- ...isCDP ? { reusedExistingPage } : {}
6671
- });
6672
- deps.logSessionEvent("create_session", `name="${name}" id="${session.id}" url="${url || "(no url)"}" isCDP=${isCDP} cdpEndpoint=${options?.cdpEndpoint || "(none)"}`);
6673
- await deps.installNetworkCapture(page, name);
6674
- return session;
6675
- }
6676
-
6677
- // src/browser.ts
6678
- function logSessionEvent2(event, details) {
6679
- const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace("T", " ").substring(0, 19);
6680
- console.error(`[SESSION] ${timestamp} [PID:${process.pid}] ${event} | ${details}`);
6681
- }
6682
- var IDLE_TIMEOUT_MS = (process.env.XBROWSER_IDLE_TIMEOUT ? parseInt(process.env.XBROWSER_IDLE_TIMEOUT, 10) : 30) * 60 * 1e3;
6683
- function resetIdleTimer() {
6684
- if (sharedState.idleTimer) clearTimeout(sharedState.idleTimer);
6685
- sharedState.idleTimer = setTimeout(async () => {
6686
- const now = Date.now();
6687
- let allIdle = true;
6688
- const idleSessions = [];
6689
- for (const s of sessions) {
6690
- if (now - s.lastActivityAt < IDLE_TIMEOUT_MS) {
6691
- allIdle = false;
6692
- } else {
6693
- idleSessions.push(`${s.name}(${(now - s.lastActivityAt) / 1e3}s idle)`);
6694
- }
6695
- }
6696
- if (allIdle && (sessions.size > 0 || sharedState.browser)) {
6697
- logSessionEvent2("idle_timeout", `Sessions idle for >${IDLE_TIMEOUT_MS / 6e4}min. Sessions: ${idleSessions.join(", ") || "all"}. Calling destroyBrowser()`);
6698
- await destroyBrowser().catch(() => {
6699
- });
6700
- }
6701
- }, IDLE_TIMEOUT_MS);
6702
- if (sharedState.idleTimer && typeof sharedState.idleTimer.unref === "function") {
6703
- sharedState.idleTimer.unref();
6704
- }
6705
- }
6706
- async function findOrRestoreSession2(name, cdpEndpoint) {
6707
- return findOrRestoreSession(
6708
- name,
6709
- cdpEndpoint,
6710
- closeSessionByName,
6711
- installNetworkCapture
6712
- );
6713
- }
6714
- function touchSession(id) {
6715
- const s = sessions.get(id);
6716
- if (s) s.lastActivityAt = Date.now();
6717
- resetIdleTimer();
6718
- }
6719
- process.on("exit", () => {
6720
- for (const session of sessions.list()) {
6721
- if (session.isCDP) {
6722
- logSessionEvent2("process_exit", `Session "${session.name}": CDP connection (not closing external browser).`);
6723
- } else {
6724
- logSessionEvent2("process_exit", `Session "${session.name}": Closing self-launched browser.`);
6725
- try {
6726
- session.browser?.close();
6727
- } catch {
6728
- }
6729
- }
6730
- }
6731
- if (sharedState.browser) {
6732
- logSessionEvent2("process_exit", "Closing shared browser (self-launched only, external CDP is safe).");
6733
- try {
6734
- sharedState.browser.close();
6735
- } catch {
6736
- }
6737
- sharedState.browser = null;
6738
- }
6739
- const cdpProxy = getSharedCdpProxy();
6740
- if (cdpProxy) {
6741
- try {
6742
- cdpProxy.stop();
6743
- } catch {
6744
- }
6745
- setSharedCdpProxy(null);
6746
- }
6747
- sessions.clear();
6748
- });
6749
- async function getBrowser(options) {
6750
- if (sharedState.browser) return sharedState.browser;
6751
- sharedState.browser = await createBrowser(options);
6752
- if (options?.cdpEndpoint && options.intercept) {
6753
- }
6754
- return sharedState.browser;
6755
- }
6756
- function findSession(name) {
6757
- return sessions.find(name);
6758
- }
6759
- function getSessionById2(id) {
6760
- return sessions.get(id);
6761
- }
6762
- function setActivePage2(session, page) {
6763
- session.page = page;
6764
- session.lastActivityAt = Date.now();
6765
- }
6766
- async function createEphemeralContext(options) {
6767
- if (options?.cdpEndpoint) {
6768
- const endpoint = await resolveCDPEndpoint(options.cdpEndpoint);
6769
- const { browser: b2 } = await launch({ cdpEndpoint: endpoint });
6770
- const contexts = b2.contexts();
6771
- const ctx = contexts[0] || await b2.newContext();
6772
- const allPages = ctx.pages();
6773
- const existingPages = allPages.filter((p) => {
6774
- const url = p.url();
6775
- return url !== "about:blank" && !url.startsWith("chrome://") && !url.startsWith("chrome-untrusted://") && !url.startsWith("chrome-error://");
6776
- });
6777
- const page2 = existingPages.length > 0 ? existingPages[0] : allPages.length > 0 ? allPages[0] : await ctx.newPage();
6778
- resetIdleTimer();
6779
- ephemeralConnections.set(page2, b2);
6780
- return { context: ctx, page: page2 };
6781
- }
6782
- const b = await getBrowser(options);
6783
- const context = await b.newContext();
6784
- const page = await context.newPage();
6785
- resetIdleTimer();
6786
- return { context, page };
6787
- }
6788
- var ephemeralConnections = /* @__PURE__ */ new WeakMap();
6789
- async function closeEphemeralContext(context) {
6790
- try {
6791
- const pages = context.pages();
6792
- for (const p of pages) {
6793
- const conn = ephemeralConnections.get(p);
6794
- if (conn) {
6795
- ephemeralConnections.delete(p);
6796
- await conn.close();
6797
- break;
6798
- }
6799
- }
6800
- await context.close();
6801
- } catch {
6802
- }
6803
- if (sessions.size === 0 && sharedState.idleTimer) {
6804
- clearTimeout(sharedState.idleTimer);
6805
- sharedState.idleTimer = null;
6806
- }
6807
- }
6808
- function getAllSessions2() {
6809
- return sessions.list();
6810
- }
6811
- async function installNetworkCapture(page, sessionName) {
6812
- if (process.env.XBROWSER_DAEMON_WORKER !== "1") return;
6813
- const { networkStore } = await import("./network-store-YVDNUREI.js");
6814
- const requestData = /* @__PURE__ */ new Map();
6815
- const responseMeta = /* @__PURE__ */ new Map();
6816
- const xbPage = page;
6817
- xbPage.on("request", (params) => {
6818
- try {
6819
- const p = params;
6820
- requestData.set(p.requestId, {
6821
- method: p.request.method,
6822
- headers: p.request.headers,
6823
- postData: p.request.postData ?? null,
6824
- resourceType: p.type
6825
- });
6826
- } catch {
6827
- }
6828
- });
6829
- xbPage.on("response", (params) => {
6830
- try {
6831
- const p = params;
6832
- responseMeta.set(p.requestId, {
6833
- status: p.response.status,
6834
- url: p.response.url,
6835
- headers: p.response.headers,
6836
- mimeType: p.response.mimeType,
6837
- type: p.type
6838
- });
6839
- } catch {
6840
- }
6841
- });
6842
- xbPage.on("requestfinished", async (params) => {
6843
- try {
6844
- const p = params;
6845
- const meta = responseMeta.get(p.requestId);
6846
- if (!meta) return;
6847
- const req = requestData.get(p.requestId);
6848
- const method = req?.method ?? "GET";
6849
- const contentType = meta.headers["content-type"] || meta.headers["Content-Type"] || "";
6850
- const resourceType = req?.resourceType ?? meta.type;
6851
- const requestHeaders = req?.headers ?? {};
6852
- let requestBody = void 0;
6853
- const isPostLike = ["POST", "PATCH", "PUT"].includes(method);
6854
- if (isPostLike && requestHeaders["content-type"]?.includes("application/json")) {
6855
- const postData = req?.postData;
6856
- if (postData) {
6857
- try {
6858
- requestBody = JSON.parse(postData);
6859
- } catch {
6860
- requestBody = postData;
6861
- }
6862
- }
6863
- }
6864
- let responseBody = void 0;
6865
- let size = 0;
6866
- const isJsonish = contentType.includes("json") || contentType.includes("javascript") || contentType.includes("text/");
6867
- if (isJsonish) {
6868
- try {
6869
- const bodyResult = await xbPage._cdpSend(
6870
- "Network.getResponseBody",
6871
- { requestId: p.requestId }
6872
- );
6873
- const text = bodyResult.body ?? "";
6874
- size = text.length;
6875
- if (size <= 10240) {
6876
- try {
6877
- responseBody = JSON.parse(text);
6878
- } catch {
6879
- responseBody = text.slice(0, 200);
6880
- }
6881
- }
6882
- } catch {
6883
- }
6884
- } else {
6885
- try {
6886
- const bodyResult = await xbPage._cdpSend(
6887
- "Network.getResponseBody",
6888
- { requestId: p.requestId }
6889
- );
6890
- size = bodyResult.body?.length ?? 0;
6891
- } catch {
6892
- size = 0;
6893
- }
6894
- }
6895
- networkStore.add(sessionName, {
6896
- timestamp: Date.now(),
6897
- method,
6898
- url: meta.url,
6899
- path: new URL(meta.url).pathname,
6900
- status: meta.status,
6901
- contentType,
6902
- size,
6903
- headers: meta.headers,
6904
- body: responseBody,
6905
- requestHeaders,
6906
- requestBody,
6907
- resourceType
6908
- });
6909
- requestData.delete(p.requestId);
6910
- responseMeta.delete(p.requestId);
6911
- } catch {
6912
- }
6913
- });
6914
- }
6915
- async function createSession(name, url, options) {
6916
- return createSessionImpl(name, url, options, {
6917
- closeSessionByName,
6918
- installNetworkCapture,
6919
- registerSession,
6920
- logSessionEvent: logSessionEvent2,
6921
- getCDPTargets: getCDPTargets2
6922
- });
6923
- }
6924
- async function closeSessionByName(name) {
6925
- for (const session of sessions) {
6926
- if (session.name === name || session.id === name) {
6927
- logSessionEvent2("close_session", `name="${session.name}" id="${session.id}" url="${session.page.url()}"`);
6928
- if (session.isCDP) {
6929
- if (session.reusedExistingPage) {
6930
- logSessionEvent2("close_session", `name="${session.name}" \u2014 reused existing tab, disconnecting only`);
6931
- await session.browser.disconnect().catch(() => {
6932
- });
6933
- } else {
6934
- await session.page.close().catch(() => {
6935
- });
6936
- await session.browser.disconnect().catch(() => {
6937
- });
6938
- }
6939
- } else {
6940
- await session.context.close();
6941
- if (session.browser) {
6942
- await session.browser.close().catch(() => {
6943
- });
6944
- }
6945
- }
6946
- sessions.removeById(session.id);
6947
- const file2 = sessionFile(session.name);
6948
- try {
6949
- unlinkSync2(file2);
6950
- } catch {
6951
- }
6952
- try {
6953
- const { networkStore, commandLogStore } = await import("./network-store-YVDNUREI.js");
6954
- networkStore.clear(session.name);
6955
- commandLogStore.clear(session.name);
6956
- } catch {
6957
- }
6958
- try {
6959
- const { SessionRecorder } = await import("./session-recorder-RUNQOJ7T.js");
6960
- SessionRecorder.cleanup(session.name);
6961
- } catch {
6962
- }
6963
- return true;
6964
- }
6965
- }
6966
- const file = sessionFile(name);
6967
- try {
6968
- unlinkSync2(file);
6969
- } catch {
6970
- }
6971
- return false;
6972
- }
6973
- async function closeAllSessions() {
6974
- const names = sessions.list().map((s) => `${s.name}(${s.page.url()})`).join(", ");
6975
- if (names) logSessionEvent2("close_all_sessions", `Closing ${sessions.size} sessions: ${names}`);
6976
- for (const session of sessions.list()) {
6977
- try {
6978
- if (session.isCDP) {
6979
- if (session.browser) {
6980
- await session.browser.close().catch(() => {
6981
- });
6982
- }
6983
- } else {
6984
- await session.context.close();
6985
- if (session.browser) {
6986
- await session.browser.close().catch(() => {
6987
- });
6988
- }
6989
- }
6990
- sessions.removeById(session.id);
6991
- } catch {
6992
- sessions.removeById(session.id);
6993
- }
6994
- }
6995
- }
6996
- async function destroyBrowser() {
6997
- logSessionEvent2("destroy_browser", `Sessions count: ${sessions.size}. Clearing idle timer and closing all sessions.`);
6998
- if (sharedState.idleTimer) {
6999
- clearTimeout(sharedState.idleTimer);
7000
- sharedState.idleTimer = null;
7001
- }
7002
- await closeAllSessions();
7003
- if (sharedState.browser) {
7004
- await sharedState.browser.close().catch(() => {
7005
- });
7006
- sharedState.browser = null;
7007
- }
7008
- if (getSharedCdpProxy()) {
7009
- await getSharedCdpProxy().stop().catch(() => {
7010
- });
7011
- setSharedCdpProxy(null);
7012
- }
7013
- }
7014
- function resetForTesting() {
7015
- sessions.clear();
7016
- sharedState.browser = null;
7017
- sharedState.idleTimer = null;
7018
- setSharedCdpProxy(null);
7019
- try {
7020
- for (const file of readdirSync2(SESSION_DIR)) unlinkSync2(join3(SESSION_DIR, file));
7021
- } catch {
7022
- }
7023
- }
7024
- async function ensureProcessCanExit() {
7025
- if (sharedState.idleTimer) {
7026
- clearTimeout(sharedState.idleTimer);
7027
- sharedState.idleTimer = null;
7028
- }
7029
- for (const session of sessions.list()) {
7030
- if (session.browser) {
7031
- if (session.isCDP) {
7032
- } else {
7033
- await session.browser.close().catch(() => {
7034
- });
7035
- }
7036
- }
7037
- }
7038
- sessions.clear();
7039
- if (sharedState.browser) {
7040
- await sharedState.browser.close().catch(() => {
7041
- });
7042
- sharedState.browser = null;
7043
- }
7044
- if (getSharedCdpProxy()) {
7045
- await getSharedCdpProxy().stop().catch(() => {
7046
- });
7047
- setSharedCdpProxy(null);
7048
- }
7049
- }
7050
-
7051
5877
  export {
7052
5878
  createRuleEngine,
7053
- findTargetPage,
7054
- resolveLaunchOpts,
7055
- createBrowser,
7056
- saveSessionDiskMeta,
7057
- readSessionDiskMeta,
7058
- deleteSessionDiskMeta,
7059
- resetIdleTimer,
7060
- findOrRestoreSession2 as findOrRestoreSession,
7061
- touchSession,
7062
- getBrowser,
7063
- findSession,
7064
- getSessionById2 as getSessionById,
7065
- setActivePage2 as setActivePage,
7066
- createEphemeralContext,
7067
- closeEphemeralContext,
7068
- getAllSessions2 as getAllSessions,
7069
- createSession,
7070
- closeSessionByName,
7071
- closeAllSessions,
7072
- destroyBrowser,
7073
- resetForTesting,
7074
- ensureProcessCanExit
5879
+ XBMouseImpl,
5880
+ XBKeyboardImpl,
5881
+ waitForActionable,
5882
+ checkActionable,
5883
+ scrollIntoView,
5884
+ XBLocatorImpl,
5885
+ XBElementHandleImpl,
5886
+ XBPageImpl,
5887
+ XBCDPSessionImpl,
5888
+ XBContextImpl,
5889
+ XBBrowserImpl,
5890
+ CDPConnection,
5891
+ CDPProtocolError,
5892
+ waitForNetworkIdle,
5893
+ launch
7075
5894
  };