@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
@@ -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";
@@ -2269,6 +2195,15 @@ var NavigationService = class {
2269
2195
  if (result.errorText) {
2270
2196
  throw new Error(`Navigation failed: ${result.errorText}`);
2271
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
+ }
2272
2207
  if (waitUntil === "commit") {
2273
2208
  this.options.setUrl(url);
2274
2209
  return {
@@ -2291,42 +2226,41 @@ var NavigationService = class {
2291
2226
  };
2292
2227
  }
2293
2228
  async goBack(opts = {}) {
2294
- try {
2295
- const navHistory = await this.options.conn.send("Page.getNavigationHistory", void 0, this.options.sessionId);
2296
- if (navHistory.currentIndex > 0) {
2297
- const prevUrl = navHistory.entries[navHistory.currentIndex - 1]?.url;
2298
- if (prevUrl && prevUrl !== "about:blank") {
2299
- await this.options.conn.send("Page.navigate", { url: prevUrl }, this.options.sessionId);
2300
- await this.options.waitForLoadState(opts.waitUntil ?? "domcontentloaded", opts.timeout ?? 1e4).catch(() => {
2301
- });
2302
- this.options.setUrl(prevUrl);
2303
- return;
2304
- }
2305
- }
2306
- } catch {
2307
- }
2308
- await this.options.evaluate("() => history.back()");
2309
- await this.options.waitForTimeout(3e3);
2310
- this.options.setUrl(await this.options.evaluate("location.href").catch(() => this.options.currentUrl()));
2229
+ await this.traverseHistory(-1, opts);
2311
2230
  }
2312
2231
  async goForward(opts = {}) {
2313
- try {
2314
- const navHistory = await this.options.conn.send("Page.getNavigationHistory", void 0, this.options.sessionId);
2315
- if (navHistory.currentIndex < navHistory.entries.length - 1) {
2316
- const nextUrl = navHistory.entries[navHistory.currentIndex + 1]?.url;
2317
- if (nextUrl && nextUrl !== "about:blank") {
2318
- await this.options.conn.send("Page.navigate", { url: nextUrl }, this.options.sessionId);
2319
- await this.options.waitForLoadState(opts.waitUntil ?? "domcontentloaded", opts.timeout ?? 1e4).catch(() => {
2320
- });
2321
- 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
+ }
2322
2258
  return;
2323
2259
  }
2324
2260
  }
2325
- } catch {
2326
- }
2327
- await this.options.evaluate("() => history.forward()");
2328
- await this.options.waitForTimeout(3e3);
2329
- 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`);
2330
2264
  }
2331
2265
  async reload(opts = {}) {
2332
2266
  this.options.state.loadFired = false;
@@ -3009,7 +2943,6 @@ var XBPageImpl = class _XBPageImpl {
3009
2943
  setUrl: (url) => {
3010
2944
  this._url = url;
3011
2945
  },
3012
- currentUrl: () => this.url(),
3013
2946
  waitForLoadState: (state, timeout) => this.waitForLoadState(state, timeout),
3014
2947
  waitForTimeout: (ms) => this.waitForTimeout(ms),
3015
2948
  evaluate: (script) => this.evaluate(script)
@@ -3858,7 +3791,23 @@ var XBContextImpl = class {
3858
3791
  _emitter = new EventEmitter2();
3859
3792
  _browser;
3860
3793
  contextId;
3861
- _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();
3862
3811
  closed = false;
3863
3812
  options;
3864
3813
  targetAttachedHandler = null;
@@ -3885,28 +3834,30 @@ var XBContextImpl = class {
3885
3834
  async newPage() {
3886
3835
  if (this.closed) throw new Error("Context is closed");
3887
3836
  const { targetId } = await this._browser._createTarget(this.contextId);
3888
- const sessionId = await this._browser._attachToTarget(targetId);
3889
- const page = new XBPageImpl(this.conn, sessionId, targetId, this, this._browser);
3890
- await page._init();
3891
- this._pages.push(page);
3892
- this.forwardPageEvents(page);
3893
- if (this.options.viewport) {
3894
- await page.setViewportSize(this.options.viewport).catch(() => {
3895
- });
3896
- }
3897
- if (this.options.userAgent) {
3898
- await page._setUserAgent(this.options.userAgent);
3899
- }
3900
- if (this.options.extraHTTPHeaders) {
3901
- 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
+ }
3902
3850
  }
3903
- for (const script of this._initScripts) {
3904
- await page.addInitScript(script);
3851
+ const page = await pending;
3852
+ if (explicitSessionId && page.sessionId !== explicitSessionId) {
3853
+ this._browser._detachFromTarget(explicitSessionId).catch(() => {
3854
+ });
3905
3855
  }
3856
+ await this._applyNewPageOptions(page);
3906
3857
  return page;
3907
3858
  }
3908
3859
  pages() {
3909
- return [...this._pages];
3860
+ return [...this._pages.values()];
3910
3861
  }
3911
3862
  browser() {
3912
3863
  return this._browser;
@@ -3914,11 +3865,12 @@ var XBContextImpl = class {
3914
3865
  async close() {
3915
3866
  if (this.closed) return;
3916
3867
  this.closed = true;
3917
- for (const page of this._pages) {
3868
+ for (const page of this._pages.values()) {
3918
3869
  await page.close().catch(() => {
3919
3870
  });
3920
3871
  }
3921
- this._pages = [];
3872
+ this._pages.clear();
3873
+ this._pendingRegistrations.clear();
3922
3874
  if (this.targetAttachedHandler) {
3923
3875
  this.conn.off("Target.attachedToTarget", this.targetAttachedHandler);
3924
3876
  this.targetAttachedHandler = null;
@@ -3939,14 +3891,23 @@ var XBContextImpl = class {
3939
3891
  }
3940
3892
  async addInitScript(script) {
3941
3893
  this._initScripts.push(script);
3942
- for (const page of this._pages) {
3894
+ for (const page of this._pages.values()) {
3943
3895
  await page.addInitScript(script);
3944
3896
  }
3945
3897
  }
3946
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
+ }
3947
3907
  async cookies(urls) {
3948
3908
  const urlList = typeof urls === "string" ? [urls] : urls;
3949
- 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;
3950
3911
  try {
3951
3912
  const result = await this.conn.send("Storage.getCookies", params);
3952
3913
  return result.cookies;
@@ -3970,15 +3931,18 @@ var XBContextImpl = class {
3970
3931
  secure: c.secure,
3971
3932
  sameSite: c.sameSite
3972
3933
  }));
3934
+ const bcId = this.storageContextId;
3935
+ const params = bcId ? { cookies: cdpCookies, browserContextId: bcId } : { cookies: cdpCookies };
3973
3936
  try {
3974
- await this.conn.send("Storage.setCookies", { cookies: cdpCookies });
3937
+ await this.conn.send("Storage.setCookies", params);
3975
3938
  } catch {
3976
3939
  await this.conn.send("Network.setCookies", { cookies: cdpCookies });
3977
3940
  }
3978
3941
  }
3979
3942
  async clearCookies() {
3943
+ const bcId = this.storageContextId;
3980
3944
  try {
3981
- await this.conn.send("Storage.clearCookies");
3945
+ await this.conn.send("Storage.clearCookies", bcId ? { browserContextId: bcId } : void 0);
3982
3946
  } catch {
3983
3947
  await this.conn.send("Network.clearBrowserCookies");
3984
3948
  }
@@ -3990,18 +3954,92 @@ var XBContextImpl = class {
3990
3954
  this._emitter.off(event, handler);
3991
3955
  }
3992
3956
  /**
3993
- * Register a page that was attached to an existing target (discovered via
3994
- * Target.getTargets). Used by XBBrowserImpl.discoverContexts() to wire up
3995
- * pages from the user's existing browser session into the context wrapper
3996
- * 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() 可用。
3997
3965
  */
3998
- _addDiscoveredPage(page) {
3999
- const exists = this._pages.some((p) => p._targetId === page._targetId);
4000
- if (exists) return;
4001
- this._pages.push(page);
4002
- 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
+ }
4003
3995
  }
4004
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
+ }
4005
4043
  /** Forward page-level events (request, response, etc.) to context listeners */
4006
4044
  forwardPageEvents(page) {
4007
4045
  const forward = (event) => {
@@ -4017,30 +4055,25 @@ var XBContextImpl = class {
4017
4055
  setupAutoAttach() {
4018
4056
  this.targetAttachedHandler = (paramsRaw) => {
4019
4057
  const params = paramsRaw;
4020
- if (this.contextId !== "default" && params.targetInfo.browserContextId !== this.contextId) return;
4021
4058
  if (params.targetInfo.type !== "page") return;
4022
- const exists = this._pages.some(
4023
- (p) => p._targetId === params.targetInfo.targetId
4024
- );
4025
- if (exists) return;
4026
- const page = new XBPageImpl(
4027
- this.conn,
4028
- params.sessionId,
4029
- params.targetInfo.targetId,
4030
- this,
4031
- this._browser
4032
- );
4059
+ const bcId = params.targetInfo.browserContextId;
4060
+ if (this.contextId === "default") {
4061
+ if (bcId) return;
4062
+ } else if (bcId !== this.contextId) {
4063
+ return;
4064
+ }
4033
4065
  this.conn.send("Runtime.runIfWaitingForDebugger", void 0, params.sessionId).catch(() => {
4034
4066
  });
4035
- page._init().then(async () => {
4036
- for (const script of this._initScripts) {
4037
- await page.addInitScript(script).catch(() => {
4038
- });
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
+ () => {
4039
4075
  }
4040
- this._pages.push(page);
4041
- this.forwardPageEvents(page);
4042
- this._emitter.emit("page", page);
4043
- });
4076
+ );
4044
4077
  };
4045
4078
  this.conn.on("Target.attachedToTarget", this.targetAttachedHandler);
4046
4079
  }
@@ -4111,7 +4144,7 @@ var XBBrowserImpl = class {
4111
4144
  this._exitHandler = null;
4112
4145
  }
4113
4146
  if (this.childProcess) {
4114
- const { killChrome: killChrome2 } = await import("./launcher-ZYB32LSZ.js");
4147
+ const { killChrome: killChrome2 } = await import("./launcher-QBAZ6F5L.js");
4115
4148
  await killChrome2(this.childProcess, this.tmpDir);
4116
4149
  }
4117
4150
  await this.conn.close();
@@ -4291,8 +4324,8 @@ var XBBrowserImpl = class {
4291
4324
  if (pageTargets.length === 0 && httpFallbackUrl) {
4292
4325
  console.log(`[discoverContexts] Target.getTargets returned ${targetInfos.length} targets (0 page type). Falling back to HTTP /json/list at ${httpFallbackUrl}`);
4293
4326
  try {
4294
- const { getCDPTargets: getCDPTargets3 } = await import("./launcher-ZYB32LSZ.js");
4295
- const httpPages = await getCDPTargets3(httpFallbackUrl);
4327
+ const { getCDPTargets: getCDPTargets2 } = await import("./launcher-QBAZ6F5L.js");
4328
+ const httpPages = await getCDPTargets2(httpFallbackUrl);
4296
4329
  console.log(`[discoverContexts] HTTP /json/list returned ${httpPages.length} pages`);
4297
4330
  for (const p of httpPages) {
4298
4331
  if (p.type !== "page") continue;
@@ -4323,13 +4356,7 @@ var XBBrowserImpl = class {
4323
4356
  if (this._contexts.has(ctxId)) continue;
4324
4357
  const context = new XBContextImpl(this.conn, ctxId, this, {});
4325
4358
  for (const p of pages) {
4326
- try {
4327
- const sessionId = await this._attachToTarget(p.targetId);
4328
- const page = new XBPageImpl(this.conn, sessionId, p.targetId, context, this);
4329
- await page._init();
4330
- context._addDiscoveredPage(page);
4331
- } catch {
4332
- }
4359
+ await context._attachExistingPage(p.targetId).catch(() => null);
4333
4360
  }
4334
4361
  this._contexts.set(ctxId, { contextId: ctxId, context });
4335
4362
  }
@@ -5745,6 +5772,66 @@ var CDPProtocolError = class extends Error {
5745
5772
  }
5746
5773
  };
5747
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
+
5748
5835
  // src/cdp-driver/index.ts
5749
5836
  async function launch(options = {}) {
5750
5837
  let wsEndpoint;
@@ -5787,1296 +5874,21 @@ async function launch(options = {}) {
5787
5874
  return { browser, wsEndpoint };
5788
5875
  }
5789
5876
 
5790
- // src/browser/connection.ts
5791
- import { existsSync } from "fs";
5792
-
5793
- // src/cdp-interceptor/proxy.ts
5794
- import { WebSocketServer, WebSocket as WebSocket2 } from "ws";
5795
-
5796
- // src/cdp-interceptor/logger.ts
5797
- function createLogger(config) {
5798
- const buffer = [];
5799
- const MAX_BUFFER = 2e3;
5800
- return {
5801
- info(message, meta) {
5802
- if (!config.enableLogging) return;
5803
- const ts = (/* @__PURE__ */ new Date()).toISOString();
5804
- if (meta) {
5805
- console.log(`[CDPInterceptor ${ts}] ${message}`, JSON.stringify(meta));
5806
- } else {
5807
- console.log(`[CDPInterceptor ${ts}] ${message}`);
5808
- }
5809
- },
5810
- log(method, direction, sessionId, payload, decision) {
5811
- const entry = {
5812
- timestamp: Date.now(),
5813
- direction,
5814
- sessionId,
5815
- method,
5816
- payload: sanitizePayload(payload),
5817
- decision: decision ?? void 0
5818
- };
5819
- if (config.enableLogging) {
5820
- buffer.push(entry);
5821
- if (buffer.length > MAX_BUFFER) buffer.shift();
5822
- const tag = decision ? decision.action === "block" ? "\u{1F6AB}BLOCK" : decision.action === "transform" ? "\u{1F504}XFMR" : "\u2705" : " ";
5823
- const reason = decision ? ` [${decision.severity}] ${decision.reason}` : "";
5824
- console.log(`[CDP] ${tag} ${direction} ${method}${reason}`);
5825
- }
5826
- return entry;
5827
- },
5828
- getRecent(count) {
5829
- return buffer.slice(-count);
5830
- },
5831
- flush() {
5832
- buffer.length = 0;
5833
- }
5834
- };
5835
- }
5836
- function sanitizePayload(payload) {
5837
- if (typeof payload !== "object" || payload === null) return { raw: String(payload) };
5838
- const obj = payload;
5839
- const cleaned = {};
5840
- for (const [key, value] of Object.entries(obj)) {
5841
- if (key === "data" && typeof value === "string" && value.length > 200) {
5842
- cleaned[key] = `<binary: ${value.length} chars>`;
5843
- } else if (key === "expression" && typeof value === "string" && value.length > 500) {
5844
- cleaned[key] = value.substring(0, 500) + "...";
5845
- } else {
5846
- cleaned[key] = value;
5847
- }
5848
- }
5849
- return cleaned;
5850
- }
5851
-
5852
- // src/cdp-interceptor/advisor.ts
5853
- function formatBlockMessage(decision, method) {
5854
- const adv = advise(decision, method);
5855
- const lines = [
5856
- `[CDP-FIREWALL-BLOCK] rule=${decision.ruleId}`,
5857
- `method=${method}`,
5858
- `reason=${decision.reason}`,
5859
- `suggestion=${decision.suggestion ?? adv.detail}`
5860
- ];
5861
- if (adv.codeExample) {
5862
- lines.push(`code-example=`);
5863
- lines.push(adv.codeExample);
5864
- }
5865
- return lines.join("\n");
5866
- }
5867
- function advise(decision, originalMethod) {
5868
- const baseAdvice = getBaseAdvice(decision, originalMethod);
5869
- return {
5870
- ruleId: decision.ruleId,
5871
- title: baseAdvice.title,
5872
- detail: decision.suggestion ?? baseAdvice.detail,
5873
- codeExample: baseAdvice.codeExample
5874
- };
5875
- }
5876
- function getBaseAdvice(decision, method) {
5877
- switch (decision.ruleId) {
5878
- case "dom-mutation":
5879
- return {
5880
- title: "Direct DOM property mutation blocked",
5881
- 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.`,
5882
- codeExample: [
5883
- "# \u274C BLOCKED \u2014 what you tried to do:",
5884
- `page.evaluate(\`el.value = 'hello'\`) # triggers isTrusted=false`,
5885
- "",
5886
- "# \u2705 USE INSTEAD \u2014 proper CDP input dispatch:",
5887
- "page.fill('#selector', 'hello') # Playwright: dispatches input+change events",
5888
- "page.type('#selector', 'hello', {delay}) # Playwright: real keystrokes",
5889
- "page.locator('#selector').fill('hello') # Playwright: recommended API"
5890
- ].join("\n")
5891
- };
5892
- case "mouse-trajectory":
5893
- return {
5894
- title: "Unnatural mouse trajectory blocked",
5895
- 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.`,
5896
- codeExample: [
5897
- "# \u274C BLOCKED \u2014 linear interpolation:",
5898
- "for i in range(20):",
5899
- " page.mouse.move(x0 + (x1-x0)*(i/20), y0 + (y1-y0)*(i/20))",
5900
- "",
5901
- "# \u2705 USE INSTEAD \u2014 Bezier curves with overshoot:",
5902
- '# Use "ghost-cursor" or similar library',
5903
- "from ghost_cursor import path_to",
5904
- "path_to(page, (x1, y1))"
5905
- ].join("\n")
5906
- };
5907
- case "input-keystroke":
5908
- if (method === "Input.insertText") {
5909
- return {
5910
- title: "Input.insertText detected (logged, not blocked)",
5911
- detail: "Input.insertText bypasses native keyDown\u2192keyPress\u2192input\u2192keyUp events. Playwright uses this internally for page.fill(). Logged for observability."
5912
- };
5913
- }
5914
- return {
5915
- title: "Unnatural keystroke timing blocked",
5916
- detail: `Your ${method} calls have unnaturally constant timing (e.g., exact 50ms intervals). Human typing always has variation (CV > 0.2).`,
5917
- codeExample: [
5918
- "# \u274C BLOCKED \u2014 exact constant delay:",
5919
- "page.type('#input', 'hello', {delay: 50}) # every keystroke exactly 50ms apart",
5920
- "",
5921
- "# \u2705 USE INSTEAD \u2014 variable delay (human-like):",
5922
- "page.fill('#input', 'hello') # recommended, dispatches events properly",
5923
- "# OR: type with randomized delay",
5924
- "page.type('#input', 'hello', {delay: 50 + Math.floor(Math.random() * 80)})"
5925
- ].join("\n")
5926
- };
5927
- case "automation-signals":
5928
- return {
5929
- title: "Browser automation marker detected",
5930
- 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.`,
5931
- codeExample: [
5932
- "# \u274C BLOCKED \u2014 don't check for automation markers:",
5933
- "navigator.webdriver # NEVER check this",
5934
- "window.__playwright # NEVER check this",
5935
- "chrome.runtime # NEVER check this",
5936
- "",
5937
- "# \u2705 Just go about your business normally.",
5938
- "# Anti-detection is handled by the CDP firewall automatically."
5939
- ].join("\n")
5940
- };
5941
- case "fingerprinting":
5942
- return {
5943
- title: "Browser fingerprinting API access blocked",
5944
- 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.`,
5945
- codeExample: [
5946
- "# \u274C BLOCKED \u2014 fingerprinting vector:",
5947
- "canvas.toDataURL() # returns unique browser hash",
5948
- 'gl.getParameter(gl.VENDOR) # returns "SwiftShader" in headless',
5949
- "screen.availWidth - screen.availHeight # no OS chrome in headless",
5950
- "",
5951
- "# \u2705 Avoid accessing these APIs. They are only used for fingerprinting."
5952
- ].join("\n")
5953
- };
5954
- case "event-simulation":
5955
- return {
5956
- title: "Synthetic event simulation blocked",
5957
- 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.`,
5958
- codeExample: [
5959
- "# \u274C BLOCKED \u2014 synthetic events (isTrusted=false):",
5960
- "el.click() # isTrusted=false",
5961
- 'el.dispatchEvent(new Event("click")) # isTrusted=false',
5962
- "el.focus() # isTrusted=false",
5963
- "",
5964
- "# \u2705 USE INSTEAD \u2014 CDP-level input dispatch (isTrusted=true):",
5965
- "page.click(selector) # uses Input.dispatchMouseEvent",
5966
- "page.fill(selector, value) # dispatches real input events"
5967
- ].join("\n")
5968
- };
5969
- case "emulation-override":
5970
- return {
5971
- title: "CDP emulation override blocked",
5972
- 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.`,
5973
- codeExample: [
5974
- "# \u274C BLOCKED \u2014 detectable emulation override:",
5975
- "Emulation.setUserAgentOverride(...) # JS vs HTTP header mismatch",
5976
- "Emulation.setGeolocationOverride(...) # IP geo vs overridden geo mismatch",
5977
- "Emulation.setDeviceMetricsOverride(...) # matchMedia vs actual viewport",
5978
- "",
5979
- "# \u2705 These are handled automatically by the CDP firewall.",
5980
- "# Do NOT call them manually."
5981
- ].join("\n")
5982
- };
5983
- case "network-anomaly":
5984
- return {
5985
- title: "Network anomaly detected",
5986
- detail: `Your ${method} call triggered a network pattern that is characteristic of scrapers: blocking URLs, clearing caches, or intercepting requests.`,
5987
- codeExample: [
5988
- "# \u274C BLOCKED \u2014 scraper optimization:",
5989
- "Network.clearBrowserCache() # natural users never do this",
5990
- 'Network.setBlockedURLs(["*fonts*"]) # blocking resources is detectable',
5991
- "Fetch.enable() # MITM-style interception",
5992
- "",
5993
- "# \u2705 Let the browser manage its own cache and network normally."
5994
- ].join("\n")
5995
- };
5996
- case "page-lifecycle":
5997
- return {
5998
- title: "Suspicious page lifecycle pattern blocked",
5999
- 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).`,
6000
- codeExample: [
6001
- "# \u274C BLOCKED \u2014 unnatural lifecycle:",
6002
- "page.goto(url); page.pdf() # PDF = scraper giveaway",
6003
- "page.goto(url); page.screenshot() <500ms # screenshot before render",
6004
- "page.goto(url) 3x in <100ms # rapid navigation barrage",
6005
- "",
6006
- "# \u2705 Add proper waits between actions:",
6007
- 'page.goto(url, {waitUntil: "networkidle"})',
6008
- 'page.waitForSelector("body")',
6009
- "page.screenshot() # after rendering"
6010
- ].join("\n")
6011
- };
6012
- default:
6013
- return {
6014
- title: decision.reason,
6015
- detail: decision.suggestion ?? `The CDP call "${method}" was blocked by rule "${decision.ruleId}".`
6016
- };
6017
- }
6018
- }
6019
-
6020
- // src/cdp-interceptor/proxy.ts
6021
- function makeCompoundId(cdpSessionId, rawSessionId) {
6022
- return `${cdpSessionId ?? "nil"}::${rawSessionId ?? "nil"}`;
6023
- }
6024
- var CDPInterceptorProxy = class {
6025
- wss = null;
6026
- engine;
6027
- config;
6028
- logger;
6029
- started = false;
6030
- stats = {
6031
- totalMessages: 0,
6032
- blockedMessages: 0,
6033
- transformedMessages: 0,
6034
- passedMessages: 0,
6035
- byRule: {}
6036
- };
6037
- constructor(config) {
6038
- this.config = config;
6039
- this.engine = createRuleEngine(config.rules);
6040
- this.logger = createLogger({
6041
- enableLogging: config.enableLogging ?? true,
6042
- logDir: config.logDir
6043
- });
6044
- }
6045
- /** The port the proxy is listening on (only valid after start()) */
6046
- get port() {
6047
- const addr = this.wss?.address();
6048
- if (addr && typeof addr === "object") return addr.port;
6049
- return 0;
6050
- }
6051
- /** Start the proxy server */
6052
- async start() {
6053
- if (this.started) return this.port;
6054
- return new Promise((resolve, reject) => {
6055
- this.wss = new WebSocketServer({ port: this.config.listenPort ?? 0 }, () => {
6056
- const port = this.port;
6057
- this.engine.start();
6058
- this.started = true;
6059
- this.logger.info("CDP interceptor proxy started", { port, endpoint: this.config.cdpEndpoint });
6060
- resolve(port);
6061
- });
6062
- this.wss.on("error", reject);
6063
- this.wss.on("connection", (clientWs, _req) => {
6064
- this.handleConnection(clientWs);
6065
- });
6066
- });
6067
- }
6068
- /** Stop the proxy server */
6069
- async stop() {
6070
- this.engine.stop();
6071
- this.logger.flush();
6072
- this.started = false;
6073
- return new Promise((resolve) => {
6074
- if (!this.wss) return resolve();
6075
- this.wss.close(() => resolve());
6076
- this.wss = null;
6077
- });
6078
- }
6079
- /** Get accumulated statistics */
6080
- getStats() {
6081
- return { ...this.stats };
6082
- }
6083
- /** Get recent log entries (for inspection) */
6084
- getRecentLogs(count = 50) {
6085
- return this.logger.getRecent(count);
6086
- }
6087
- // ── Connection handling ──────────────────────────────────────
6088
- handleConnection(clientWs) {
6089
- let browserWs = null;
6090
- let isAlive = true;
6091
- const pendingMessages = [];
6092
- browserWs = new WebSocket2(this.config.cdpEndpoint);
6093
- clientWs.on("message", (raw) => {
6094
- if (browserWs && browserWs.readyState === WebSocket2.OPEN) {
6095
- this.handleClientMessage(clientWs, browserWs, raw);
6096
- } else {
6097
- pendingMessages.push(raw);
6098
- }
6099
- });
6100
- browserWs.on("open", () => {
6101
- for (const buf of pendingMessages) {
6102
- this.handleClientMessage(clientWs, browserWs, buf);
6103
- }
6104
- pendingMessages.length = 0;
6105
- });
6106
- browserWs.on("error", (err) => {
6107
- this.logger.info("Browser WebSocket error", { error: String(err) });
6108
- });
6109
- browserWs.on("close", (code, reason) => {
6110
- if (isAlive && clientWs.readyState === WebSocket2.OPEN) {
6111
- this.logger.info("Browser WS closed, closing client", { code, reason: String(reason) });
6112
- clientWs.close();
6113
- }
6114
- });
6115
- browserWs.on("message", (raw) => {
6116
- this.handleBrowserMessage(clientWs, browserWs, raw);
6117
- });
6118
- const cleanup = () => {
6119
- isAlive = false;
6120
- if (browserWs && browserWs.readyState === WebSocket2.OPEN) {
6121
- browserWs.close();
6122
- }
6123
- };
6124
- clientWs.on("close", cleanup);
6125
- clientWs.on("error", cleanup);
6126
- browserWs.on("close", () => {
6127
- if (isAlive && clientWs.readyState === WebSocket2.OPEN) {
6128
- clientWs.close();
6129
- }
6130
- });
6131
- browserWs.on("error", cleanup);
6132
- }
6133
- // ── Message processing ───────────────────────────────────────
6134
- handleClientMessage(clientWs, browserWs, raw) {
6135
- const msg = this.parseMessage(raw);
6136
- if (!msg) return;
6137
- this.stats.totalMessages++;
6138
- if (!("method" in msg)) {
6139
- browserWs.send(raw.toString());
6140
- return;
6141
- }
6142
- const request = msg;
6143
- const ctx = {
6144
- method: request.method,
6145
- params: request.params ?? {},
6146
- sessionId: makeCompoundId("_cdpSession" in browserWs ? browserWs._cdpSession : void 0, request.sessionId),
6147
- direction: "client\u2192browser"
6148
- };
6149
- const decision = this.engine.evaluate(ctx);
6150
- this.logger.log(ctx.method, "client\u2192browser", ctx.sessionId, { method: ctx.method, params: ctx.params }, decision);
6151
- if (decision) {
6152
- this.recordDecision(decision);
6153
- }
6154
- if (decision?.action === "block") {
6155
- const blockMsg = formatBlockMessage(decision, ctx.method);
6156
- const errorResponse = {
6157
- id: request.id,
6158
- error: {
6159
- code: decision.errorCode ?? -32e3,
6160
- message: blockMsg
6161
- },
6162
- sessionId: request.sessionId
6163
- };
6164
- this.stats.blockedMessages++;
6165
- console.error(`
6166
- ${blockMsg}
6167
- `);
6168
- clientWs.send(JSON.stringify(errorResponse));
6169
- return;
6170
- }
6171
- if (decision?.action === "transform" && decision.transformedParams) {
6172
- const sequence = decision.transformedParams.__sequence;
6173
- if (Array.isArray(sequence)) {
6174
- this.stats.transformedMessages++;
6175
- const dispatch = async () => {
6176
- for (const step of sequence) {
6177
- if (step.delayMs) await new Promise((resolve) => setTimeout(resolve, step.delayMs));
6178
- const transformed2 = { id: request.id, method: step.method, params: step.params, sessionId: request.sessionId };
6179
- browserWs.send(JSON.stringify(transformed2));
6180
- }
6181
- };
6182
- void dispatch();
6183
- return;
6184
- }
6185
- const transformed = { ...request, params: decision.transformedParams };
6186
- this.stats.transformedMessages++;
6187
- browserWs.send(JSON.stringify(transformed));
6188
- return;
6189
- }
6190
- this.stats.passedMessages++;
6191
- browserWs.send(raw.toString());
6192
- }
6193
- handleBrowserMessage(clientWs, _browserWs, raw) {
6194
- const msg = this.parseMessage(raw);
6195
- if (!msg) {
6196
- clientWs.send(raw.toString());
6197
- return;
6198
- }
6199
- if ("method" in msg) {
6200
- const event = msg;
6201
- const ctx = {
6202
- method: event.method,
6203
- params: event.params ?? {},
6204
- sessionId: event.sessionId ?? "browser",
6205
- direction: "browser\u2192client"
6206
- };
6207
- const decision = this.engine.evaluate(ctx);
6208
- if (decision?.action === "block") {
6209
- return;
6210
- }
6211
- }
6212
- clientWs.send(raw.toString());
6213
- }
6214
- // ── Utilities ────────────────────────────────────────────────
6215
- parseMessage(raw) {
6216
- try {
6217
- return JSON.parse(raw.toString());
6218
- } catch {
6219
- return null;
6220
- }
6221
- }
6222
- recordDecision(decision) {
6223
- if (!this.stats.byRule[decision.ruleId]) {
6224
- this.stats.byRule[decision.ruleId] = { matched: 0, blocked: 0, transformed: 0 };
6225
- }
6226
- this.stats.byRule[decision.ruleId].matched++;
6227
- if (decision.action === "block") {
6228
- this.stats.byRule[decision.ruleId].blocked++;
6229
- } else if (decision.action === "transform") {
6230
- this.stats.byRule[decision.ruleId].transformed++;
6231
- }
6232
- }
6233
- };
6234
-
6235
- // src/browser/connection.ts
6236
- async function getCDPTargets2(cdpEndpoint) {
6237
- try {
6238
- const endpoint = String(cdpEndpoint);
6239
- let url = "http://localhost:9222/json/list";
6240
- if (endpoint.startsWith("http://") || endpoint.startsWith("https://")) {
6241
- const parsed = new URL(endpoint);
6242
- parsed.pathname = (parsed.pathname.replace(/\/+$/, "") || "") + "/json/list";
6243
- url = parsed.toString();
6244
- } else if (/^\d+$/.test(endpoint)) {
6245
- url = `http://localhost:${endpoint}/json/list`;
6246
- }
6247
- const response = await fetch(url);
6248
- return await response.json();
6249
- } catch {
6250
- return [];
6251
- }
6252
- }
6253
- async function findTargetPage(cdpEndpoint, target) {
6254
- const targets = await getCDPTargets2(cdpEndpoint);
6255
- 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://"));
6256
- const byId = pages.find((item) => item.id === target);
6257
- if (byId) return { pageId: byId.id, wsUrl: byId.webSocketDebuggerUrl, title: byId.title, url: byId.url };
6258
- const lowerTarget = target.toLowerCase();
6259
- const byTitle = pages.find((item) => item.title?.toLowerCase().includes(lowerTarget));
6260
- if (byTitle) return { pageId: byTitle.id, wsUrl: byTitle.webSocketDebuggerUrl, title: byTitle.title, url: byTitle.url };
6261
- const byUrl = pages.find((item) => item.url.toLowerCase().includes(lowerTarget));
6262
- if (byUrl) return { pageId: byUrl.id, wsUrl: byUrl.webSocketDebuggerUrl, title: byUrl.title, url: byUrl.url };
6263
- return null;
6264
- }
6265
- function resolveLaunchOpts(ctx) {
6266
- return ctx.cdpEndpoint ? { cdpEndpoint: ctx.cdpEndpoint } : { headless: true };
6267
- }
6268
- var CHROMIUM_CANDIDATES = [
6269
- "/Applications/Chromium.app/Contents/MacOS/Chromium",
6270
- "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
6271
- "/usr/bin/chromium-browser",
6272
- "/usr/bin/chromium",
6273
- "/usr/bin/google-chrome"
6274
- ];
6275
- function discoverChromiumPath() {
6276
- return CHROMIUM_CANDIDATES.find((path) => existsSync(path));
6277
- }
6278
- var browserPool = /* @__PURE__ */ new Map();
6279
- var sharedCdpProxy = null;
6280
- function getSharedCdpProxy() {
6281
- return sharedCdpProxy;
6282
- }
6283
- function setSharedCdpProxy(proxy) {
6284
- sharedCdpProxy = proxy;
6285
- }
6286
- async function createBrowser(options) {
6287
- if (options?.cdpEndpoint) {
6288
- const realEndpoint = await resolveCDPEndpoint(options.cdpEndpoint);
6289
- if (!options.intercept) {
6290
- const pooled = browserPool.get(realEndpoint);
6291
- if (pooled && !pooled.disconnected) return pooled;
6292
- if (pooled) browserPool.delete(realEndpoint);
6293
- }
6294
- if (options.intercept) {
6295
- const config = typeof options.intercept === "object" ? { ...options.intercept, cdpEndpoint: realEndpoint } : { cdpEndpoint: realEndpoint };
6296
- sharedCdpProxy = new CDPInterceptorProxy(config);
6297
- const proxyPort = await sharedCdpProxy.start();
6298
- console.error(`[CDP Interceptor] Proxy running on ws://localhost:${proxyPort}, forwarding to ${realEndpoint}`);
6299
- const { browser: browser3 } = await launch({ cdpEndpoint: `ws://localhost:${proxyPort}` });
6300
- return browser3;
6301
- }
6302
- const { browser: browser2 } = await launch({ cdpEndpoint: realEndpoint });
6303
- await browser2.discoverContexts().catch((error) => {
6304
- console.error(`[browser] discoverContexts failed: ${errMsg(error)}`);
6305
- });
6306
- browserPool.set(realEndpoint, browser2);
6307
- return browser2;
6308
- }
6309
- const executablePath = options?.executablePath || process.env.XBROWSER_CHROMIUM_PATH || discoverChromiumPath();
6310
- const { browser } = await launch({ executablePath, headless: options?.headless ?? true });
6311
- return browser;
6312
- }
6313
-
6314
- // src/browser/state.ts
6315
- import { randomUUID } from "crypto";
6316
- import { existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync, readdirSync, unlinkSync, writeFileSync } from "fs";
6317
- import { join as join2 } from "path";
6318
- import { homedir } from "os";
6319
- import { SessionStore } from "@dyyz1993/xcli-core";
6320
- var SESSION_DIR = join2(homedir(), ".xbrowser", "sessions");
6321
- var sessions = new SessionStore();
6322
- var sharedState = { browser: null, idleTimer: null };
6323
- function sessionFile(name) {
6324
- return join2(SESSION_DIR, `${name}.json`);
6325
- }
6326
- function ensureSessionDir() {
6327
- mkdirSync2(SESSION_DIR, { recursive: true });
6328
- }
6329
- function saveSessionDiskMeta(name, data) {
6330
- ensureSessionDir();
6331
- const file = sessionFile(name);
6332
- let existing = {};
6333
- try {
6334
- existing = JSON.parse(readFileSync(file, "utf8"));
6335
- } catch {
6336
- }
6337
- Object.assign(existing, data, { name });
6338
- writeFileSync(file, JSON.stringify(existing, null, 2));
6339
- }
6340
- function readSessionDiskMeta(name) {
6341
- try {
6342
- return JSON.parse(readFileSync(sessionFile(name), "utf8"));
6343
- } catch {
6344
- return null;
6345
- }
6346
- }
6347
- function deleteSessionDiskMeta(name) {
6348
- try {
6349
- unlinkSync(sessionFile(name));
6350
- } catch {
6351
- }
6352
- }
6353
- function newSessionId() {
6354
- return randomUUID();
6355
- }
6356
-
6357
- // src/browser/lifecycle.ts
6358
- function registerSession(session) {
6359
- const complete = {
6360
- id: session.id ?? newSessionId(),
6361
- createdAt: session.createdAt ?? (/* @__PURE__ */ new Date()).toISOString(),
6362
- lastActivityAt: session.lastActivityAt ?? Date.now(),
6363
- ...session
6364
- };
6365
- sessions.set(complete);
6366
- resetIdleTimer();
6367
- return complete;
6368
- }
6369
-
6370
- // src/browser/restore.ts
6371
- function logSessionEvent(event, details) {
6372
- const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace("T", " ").substring(0, 19);
6373
- console.error(`[SESSION] ${timestamp} [PID:${process.pid}] ${event} | ${details}`);
6374
- }
6375
- async function isSessionPageAlive(session) {
6376
- const page = session.page;
6377
- if (!page || typeof page.evaluate !== "function") return false;
6378
- for (let attempt = 0; attempt < 3; attempt++) {
6379
- try {
6380
- await Promise.race([
6381
- page.evaluate("1"),
6382
- new Promise((_, reject) => setTimeout(() => reject(new Error("liveness probe timeout")), 1500))
6383
- ]);
6384
- return true;
6385
- } catch {
6386
- await new Promise((resolve) => setTimeout(resolve, 400));
6387
- }
6388
- }
6389
- return false;
6390
- }
6391
- async function findOrRestoreSession(name, cdpEndpoint, cleanup = async () => false, installNetworkCapture2 = async () => {
6392
- }) {
6393
- const inMemory = findSession(name);
6394
- if (inMemory) {
6395
- if (await isSessionPageAlive(inMemory)) return inMemory;
6396
- logSessionEvent("stale_session", `name="${name}" \u2014 page probe failed; rebuilding`);
6397
- try {
6398
- await cleanup(name);
6399
- } catch {
6400
- }
6401
- }
6402
- const meta = readSessionDiskMeta(name);
6403
- if (!meta) return void 0;
6404
- const endpoint = cdpEndpoint || meta.cdpEndpoint;
6405
- if (!endpoint) return void 0;
6406
- try {
6407
- const browser = await createBrowser({ cdpEndpoint: endpoint });
6408
- await new Promise((resolve) => setTimeout(resolve, 500));
6409
- let contexts = browser.contexts();
6410
- if (contexts.length === 0) {
6411
- await new Promise((resolve) => setTimeout(resolve, 500));
6412
- contexts = browser.contexts();
6413
- }
6414
- const context = contexts[0] || await browser.newContext();
6415
- const savedUrl = meta.conversationUrl || meta.url;
6416
- let targetHostname = "";
6417
- if (savedUrl) {
6418
- try {
6419
- targetHostname = new URL(savedUrl).hostname;
6420
- } catch {
6421
- targetHostname = "";
6422
- }
6423
- }
6424
- let page = null;
6425
- let fallbackPage = null;
6426
- for (const browserContext of contexts) {
6427
- for (const candidate of browserContext.pages()) {
6428
- const url = candidate.url();
6429
- if (!url || url === "about:blank" || url.startsWith("chrome://") || url.startsWith("chrome-untrusted://") || url.startsWith("chrome-error://")) continue;
6430
- if (targetHostname && url.includes(targetHostname)) {
6431
- page = candidate;
6432
- break;
6433
- }
6434
- fallbackPage ??= candidate;
6435
- }
6436
- if (page) break;
6437
- }
6438
- page ??= fallbackPage;
6439
- if (!page) {
6440
- const targets = await getCDPTargets2(endpoint);
6441
- 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)));
6442
- if (match?.url) {
6443
- page = await context.newPage();
6444
- await page.goto(match.url, { waitUntil: "domcontentloaded", timeout: 15e3 }).catch(() => {
6445
- });
6446
- }
6447
- }
6448
- if (!page) {
6449
- const pages = context.pages();
6450
- page = pages.length > 0 ? pages[0] : await context.newPage();
6451
- }
6452
- try {
6453
- await Promise.race([
6454
- page.evaluate(() => true),
6455
- new Promise((_, reject) => setTimeout(() => reject(new Error("timeout")), 3e3))
6456
- ]);
6457
- } catch {
6458
- deleteSessionDiskMeta(name);
6459
- return void 0;
6460
- }
6461
- const targetUrl = meta.conversationUrl || meta.url;
6462
- if (targetUrl && page.url() !== targetUrl) {
6463
- try {
6464
- if (!page.url().includes(new URL(targetUrl).hostname)) {
6465
- await page.goto(targetUrl, { waitUntil: "domcontentloaded", timeout: 3e4 }).catch(() => {
6466
- });
6467
- }
6468
- } catch {
6469
- }
6470
- }
6471
- const session = {
6472
- id: meta.id,
6473
- name,
6474
- context,
6475
- page,
6476
- browser,
6477
- createdAt: meta.createdAt,
6478
- lastActivityAt: Date.now(),
6479
- isCDP: true,
6480
- cdpEndpoint: endpoint
6481
- };
6482
- for (const existing of sessions.list()) {
6483
- if (existing.name === name) sessions.removeById(existing.id);
6484
- }
6485
- sessions.set(session);
6486
- await installNetworkCapture2(session.page, name);
6487
- return session;
6488
- } catch (error) {
6489
- console.error(`[Session Restore] Failed for "${name}":`, errMsg(error));
6490
- deleteSessionDiskMeta(name);
6491
- return void 0;
6492
- }
6493
- }
6494
-
6495
- // src/browser/create-session.ts
6496
- async function createSessionImpl(name, url, options, deps) {
6497
- const existing = findSession(name);
6498
- if (existing) {
6499
- deps.logSessionEvent("replace_session", `name="${name}" id="${existing.id}" \u2014 closing existing session before creating new one`);
6500
- await deps.closeSessionByName(name);
6501
- }
6502
- const b = await createBrowser(options);
6503
- const isCDP = !!options?.cdpEndpoint;
6504
- let context;
6505
- let page;
6506
- let reusedExistingPage = false;
6507
- if (isCDP) {
6508
- const targetHostname = url ? (() => {
6509
- try {
6510
- return new URL(url).hostname;
6511
- } catch {
6512
- return "";
6513
- }
6514
- })() : "";
6515
- const isRealPageUrl = (u) => !!u && u !== "about:blank" && !u.startsWith("chrome://") && !u.startsWith("chrome-untrusted://") && !u.startsWith("chrome-error://");
6516
- const resolvePageUrl = async (p) => {
6517
- const u = p.url();
6518
- if (u && u !== "about:blank") return u;
6519
- try {
6520
- return await p.evaluate("location.href");
6521
- } catch {
6522
- return u ?? "";
6523
- }
6524
- };
6525
- const pollStart = Date.now();
6526
- for (; ; ) {
6527
- const ctxs = b.contexts();
6528
- let hostHit = false;
6529
- let anyHit = false;
6530
- for (const ctx of ctxs) {
6531
- for (const p of ctx.pages()) {
6532
- const u = await resolvePageUrl(p);
6533
- if (!isRealPageUrl(u)) continue;
6534
- anyHit = true;
6535
- if (targetHostname && u.includes(targetHostname)) {
6536
- hostHit = true;
6537
- break;
6538
- }
6539
- }
6540
- if (hostHit) break;
6541
- }
6542
- if (process.env.XB_DEBUG_SESSION_POLL) {
6543
- console.error(`[poll] t=${Date.now() - pollStart}ms ctxs=${ctxs.length} hostHit=${hostHit} anyHit=${anyHit}`);
6544
- }
6545
- if (hostHit) break;
6546
- if (anyHit && Date.now() - pollStart >= 2e3) break;
6547
- if (Date.now() - pollStart >= 5e3) break;
6548
- await new Promise((r) => setTimeout(r, 200));
6549
- }
6550
- let contexts = b.contexts();
6551
- if (contexts.length === 0) {
6552
- await new Promise((r) => setTimeout(r, 500));
6553
- contexts = b.contexts();
6554
- }
6555
- context = contexts[0] || await b.newContext();
6556
- let targetPage = null;
6557
- const ownedUrls = /* @__PURE__ */ new Set();
6558
- for (const ssn of sessions.list()) {
6559
- try {
6560
- const u = ssn.page?.url();
6561
- if (u && u !== "about:blank") ownedUrls.add(u);
6562
- } catch {
6563
- }
6564
- }
6565
- if (url) {
6566
- for (const ctx of contexts) {
6567
- for (const p of ctx.pages()) {
6568
- try {
6569
- const pUrl = await resolvePageUrl(p);
6570
- if (ownedUrls.has(pUrl)) continue;
6571
- if (pUrl === url) {
6572
- targetPage = p;
6573
- break;
6574
- }
6575
- } catch {
6576
- }
6577
- }
6578
- if (targetPage) break;
6579
- }
6580
- }
6581
- if (!targetPage && targetHostname) {
6582
- for (const ctx of contexts) {
6583
- const pages = ctx.pages();
6584
- for (const p of pages) {
6585
- const pUrl0 = await resolvePageUrl(p);
6586
- if (ownedUrls.has(pUrl0)) continue;
6587
- const pUrl = pUrl0;
6588
- let hostnameMatches = false;
6589
- try {
6590
- hostnameMatches = new URL(pUrl).hostname === targetHostname;
6591
- } catch {
6592
- }
6593
- if (isRealPageUrl(pUrl) && hostnameMatches) {
6594
- targetPage = p;
6595
- break;
6596
- }
6597
- }
6598
- if (targetPage) break;
6599
- }
6600
- }
6601
- if (!targetPage && options?.cdpEndpoint) {
6602
- const targets = await deps.getCDPTargets(options.cdpEndpoint);
6603
- const ownedUrlsT = /* @__PURE__ */ new Set();
6604
- for (const ssn of sessions.list()) {
6605
- try {
6606
- const u = ssn.page?.url();
6607
- if (u && u !== "about:blank") ownedUrlsT.add(u);
6608
- } catch {
6609
- }
6610
- }
6611
- const matchTarget = targets.find((t) => {
6612
- if (!t.url || !isRealPageUrl(t.url) || ownedUrlsT.has(t.url)) return false;
6613
- if (!url) return false;
6614
- try {
6615
- return new URL(t.url).hostname === targetHostname;
6616
- } catch {
6617
- return false;
6618
- }
6619
- });
6620
- if (matchTarget && matchTarget.url) {
6621
- const ownedUrls2 = /* @__PURE__ */ new Set();
6622
- for (const ssn of sessions.list()) {
6623
- try {
6624
- const u = ssn.page?.url();
6625
- if (u && u !== "about:blank") ownedUrls2.add(u);
6626
- } catch {
6627
- }
6628
- }
6629
- const isOwned = (p) => {
6630
- try {
6631
- return ownedUrls2.has(p.url());
6632
- } catch {
6633
- return false;
6634
- }
6635
- };
6636
- const existing2 = context.pages().find((p) => {
6637
- try {
6638
- return p.url() === matchTarget.url && !isOwned(p);
6639
- } catch {
6640
- return false;
6641
- }
6642
- });
6643
- if (existing2) {
6644
- targetPage = existing2;
6645
- } else {
6646
- targetPage = await context.newPage();
6647
- await targetPage.goto(matchTarget.url, { waitUntil: "domcontentloaded", timeout: 15e3 }).catch(() => {
6648
- });
6649
- }
6650
- }
6651
- }
6652
- const targetPageExisted = !!targetPage;
6653
- if (!targetPage) {
6654
- targetPage = await context.newPage();
6655
- }
6656
- page = targetPage;
6657
- reusedExistingPage = targetPageExisted;
6658
- if (isCDP) {
6659
- await Promise.resolve(targetPage.bringToFront?.()).catch(() => {
6660
- });
6661
- }
6662
- } else {
6663
- context = await b.newContext({ viewport: { width: 1920, height: 1080 } });
6664
- page = await context.newPage();
6665
- }
6666
- if (url && page.url() !== url) {
6667
- await page.goto(url, { waitUntil: "domcontentloaded", timeout: 15e3 }).catch(() => {
6668
- });
6669
- }
6670
- const session = deps.registerSession({
6671
- name,
6672
- context,
6673
- page,
6674
- browser: b,
6675
- isCDP,
6676
- cdpEndpoint: options?.cdpEndpoint,
6677
- ...isCDP ? { reusedExistingPage } : {}
6678
- });
6679
- deps.logSessionEvent("create_session", `name="${name}" id="${session.id}" url="${url || "(no url)"}" isCDP=${isCDP} cdpEndpoint=${options?.cdpEndpoint || "(none)"}`);
6680
- await deps.installNetworkCapture(page, name);
6681
- return session;
6682
- }
6683
-
6684
- // src/browser.ts
6685
- function logSessionEvent2(event, details) {
6686
- const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace("T", " ").substring(0, 19);
6687
- console.error(`[SESSION] ${timestamp} [PID:${process.pid}] ${event} | ${details}`);
6688
- }
6689
- var IDLE_TIMEOUT_MS = (process.env.XBROWSER_IDLE_TIMEOUT ? parseInt(process.env.XBROWSER_IDLE_TIMEOUT, 10) : 30) * 60 * 1e3;
6690
- function resetIdleTimer() {
6691
- if (sharedState.idleTimer) clearTimeout(sharedState.idleTimer);
6692
- sharedState.idleTimer = setTimeout(async () => {
6693
- const now = Date.now();
6694
- let allIdle = true;
6695
- const idleSessions = [];
6696
- for (const s of sessions) {
6697
- if (now - s.lastActivityAt < IDLE_TIMEOUT_MS) {
6698
- allIdle = false;
6699
- } else {
6700
- idleSessions.push(`${s.name}(${(now - s.lastActivityAt) / 1e3}s idle)`);
6701
- }
6702
- }
6703
- if (allIdle && (sessions.size > 0 || sharedState.browser)) {
6704
- logSessionEvent2("idle_timeout", `Sessions idle for >${IDLE_TIMEOUT_MS / 6e4}min. Sessions: ${idleSessions.join(", ") || "all"}. Calling destroyBrowser()`);
6705
- await destroyBrowser().catch(() => {
6706
- });
6707
- }
6708
- }, IDLE_TIMEOUT_MS);
6709
- if (sharedState.idleTimer && typeof sharedState.idleTimer.unref === "function") {
6710
- sharedState.idleTimer.unref();
6711
- }
6712
- }
6713
- async function findOrRestoreSession2(name, cdpEndpoint) {
6714
- return findOrRestoreSession(
6715
- name,
6716
- cdpEndpoint,
6717
- closeSessionByName,
6718
- installNetworkCapture
6719
- );
6720
- }
6721
- function touchSession(id) {
6722
- const s = sessions.get(id);
6723
- if (s) s.lastActivityAt = Date.now();
6724
- resetIdleTimer();
6725
- }
6726
- process.on("exit", () => {
6727
- for (const session of sessions.list()) {
6728
- if (session.isCDP) {
6729
- logSessionEvent2("process_exit", `Session "${session.name}": CDP connection (not closing external browser).`);
6730
- } else {
6731
- logSessionEvent2("process_exit", `Session "${session.name}": Closing self-launched browser.`);
6732
- try {
6733
- session.browser?.close();
6734
- } catch {
6735
- }
6736
- }
6737
- }
6738
- if (sharedState.browser) {
6739
- logSessionEvent2("process_exit", "Closing shared browser (self-launched only, external CDP is safe).");
6740
- try {
6741
- sharedState.browser.close();
6742
- } catch {
6743
- }
6744
- sharedState.browser = null;
6745
- }
6746
- const cdpProxy = getSharedCdpProxy();
6747
- if (cdpProxy) {
6748
- try {
6749
- cdpProxy.stop();
6750
- } catch {
6751
- }
6752
- setSharedCdpProxy(null);
6753
- }
6754
- sessions.clear();
6755
- });
6756
- async function getBrowser(options) {
6757
- if (sharedState.browser) return sharedState.browser;
6758
- sharedState.browser = await createBrowser(options);
6759
- if (options?.cdpEndpoint && options.intercept) {
6760
- }
6761
- return sharedState.browser;
6762
- }
6763
- function findSession(name) {
6764
- return sessions.find(name);
6765
- }
6766
- function getSessionById2(id) {
6767
- return sessions.get(id);
6768
- }
6769
- function setActivePage2(session, page) {
6770
- session.page = page;
6771
- session.lastActivityAt = Date.now();
6772
- }
6773
- async function createEphemeralContext(options) {
6774
- if (options?.cdpEndpoint) {
6775
- const endpoint = await resolveCDPEndpoint(options.cdpEndpoint);
6776
- const { browser: b2 } = await launch({ cdpEndpoint: endpoint });
6777
- const contexts = b2.contexts();
6778
- const ctx = contexts[0] || await b2.newContext();
6779
- const allPages = ctx.pages();
6780
- const existingPages = allPages.filter((p) => {
6781
- const url = p.url();
6782
- return url !== "about:blank" && !url.startsWith("chrome://") && !url.startsWith("chrome-untrusted://") && !url.startsWith("chrome-error://");
6783
- });
6784
- const page2 = existingPages.length > 0 ? existingPages[0] : allPages.length > 0 ? allPages[0] : await ctx.newPage();
6785
- resetIdleTimer();
6786
- ephemeralConnections.set(page2, b2);
6787
- return { context: ctx, page: page2 };
6788
- }
6789
- const b = await getBrowser(options);
6790
- const context = await b.newContext();
6791
- const page = await context.newPage();
6792
- resetIdleTimer();
6793
- return { context, page };
6794
- }
6795
- var ephemeralConnections = /* @__PURE__ */ new WeakMap();
6796
- async function closeEphemeralContext(context) {
6797
- try {
6798
- const pages = context.pages();
6799
- for (const p of pages) {
6800
- const conn = ephemeralConnections.get(p);
6801
- if (conn) {
6802
- ephemeralConnections.delete(p);
6803
- await conn.close();
6804
- break;
6805
- }
6806
- }
6807
- await context.close();
6808
- } catch {
6809
- }
6810
- if (sessions.size === 0 && sharedState.idleTimer) {
6811
- clearTimeout(sharedState.idleTimer);
6812
- sharedState.idleTimer = null;
6813
- }
6814
- }
6815
- function getAllSessions2() {
6816
- return sessions.list();
6817
- }
6818
- async function installNetworkCapture(page, sessionName) {
6819
- if (process.env.XBROWSER_DAEMON_WORKER !== "1") return;
6820
- const { networkStore } = await import("./network-store-YVDNUREI.js");
6821
- const requestData = /* @__PURE__ */ new Map();
6822
- const responseMeta = /* @__PURE__ */ new Map();
6823
- const xbPage = page;
6824
- xbPage.on("request", (params) => {
6825
- try {
6826
- const p = params;
6827
- requestData.set(p.requestId, {
6828
- method: p.request.method,
6829
- headers: p.request.headers,
6830
- postData: p.request.postData ?? null,
6831
- resourceType: p.type
6832
- });
6833
- } catch {
6834
- }
6835
- });
6836
- xbPage.on("response", (params) => {
6837
- try {
6838
- const p = params;
6839
- responseMeta.set(p.requestId, {
6840
- status: p.response.status,
6841
- url: p.response.url,
6842
- headers: p.response.headers,
6843
- mimeType: p.response.mimeType,
6844
- type: p.type
6845
- });
6846
- } catch {
6847
- }
6848
- });
6849
- xbPage.on("requestfinished", async (params) => {
6850
- try {
6851
- const p = params;
6852
- const meta = responseMeta.get(p.requestId);
6853
- if (!meta) return;
6854
- const req = requestData.get(p.requestId);
6855
- const method = req?.method ?? "GET";
6856
- const contentType = meta.headers["content-type"] || meta.headers["Content-Type"] || "";
6857
- const resourceType = req?.resourceType ?? meta.type;
6858
- const requestHeaders = req?.headers ?? {};
6859
- let requestBody = void 0;
6860
- const isPostLike = ["POST", "PATCH", "PUT"].includes(method);
6861
- if (isPostLike && requestHeaders["content-type"]?.includes("application/json")) {
6862
- const postData = req?.postData;
6863
- if (postData) {
6864
- try {
6865
- requestBody = JSON.parse(postData);
6866
- } catch {
6867
- requestBody = postData;
6868
- }
6869
- }
6870
- }
6871
- let responseBody = void 0;
6872
- let size = 0;
6873
- const isJsonish = contentType.includes("json") || contentType.includes("javascript") || contentType.includes("text/");
6874
- if (isJsonish) {
6875
- try {
6876
- const bodyResult = await xbPage._cdpSend(
6877
- "Network.getResponseBody",
6878
- { requestId: p.requestId }
6879
- );
6880
- const text = bodyResult.body ?? "";
6881
- size = text.length;
6882
- if (size <= 10240) {
6883
- try {
6884
- responseBody = JSON.parse(text);
6885
- } catch {
6886
- responseBody = text.slice(0, 200);
6887
- }
6888
- }
6889
- } catch {
6890
- }
6891
- } else {
6892
- try {
6893
- const bodyResult = await xbPage._cdpSend(
6894
- "Network.getResponseBody",
6895
- { requestId: p.requestId }
6896
- );
6897
- size = bodyResult.body?.length ?? 0;
6898
- } catch {
6899
- size = 0;
6900
- }
6901
- }
6902
- networkStore.add(sessionName, {
6903
- timestamp: Date.now(),
6904
- method,
6905
- url: meta.url,
6906
- path: new URL(meta.url).pathname,
6907
- status: meta.status,
6908
- contentType,
6909
- size,
6910
- headers: meta.headers,
6911
- body: responseBody,
6912
- requestHeaders,
6913
- requestBody,
6914
- resourceType
6915
- });
6916
- requestData.delete(p.requestId);
6917
- responseMeta.delete(p.requestId);
6918
- } catch {
6919
- }
6920
- });
6921
- }
6922
- async function createSession(name, url, options) {
6923
- return createSessionImpl(name, url, options, {
6924
- closeSessionByName,
6925
- installNetworkCapture,
6926
- registerSession,
6927
- logSessionEvent: logSessionEvent2,
6928
- getCDPTargets: getCDPTargets2
6929
- });
6930
- }
6931
- async function closeSessionByName(name) {
6932
- for (const session of sessions) {
6933
- if (session.name === name || session.id === name) {
6934
- logSessionEvent2("close_session", `name="${session.name}" id="${session.id}" url="${session.page.url()}"`);
6935
- if (session.isCDP) {
6936
- if (session.reusedExistingPage) {
6937
- logSessionEvent2("close_session", `name="${session.name}" \u2014 reused existing tab, disconnecting only`);
6938
- await session.browser.disconnect().catch(() => {
6939
- });
6940
- } else {
6941
- await session.page.close().catch(() => {
6942
- });
6943
- await session.browser.disconnect().catch(() => {
6944
- });
6945
- }
6946
- } else {
6947
- await session.context.close();
6948
- if (session.browser) {
6949
- await session.browser.close().catch(() => {
6950
- });
6951
- }
6952
- }
6953
- sessions.removeById(session.id);
6954
- const file2 = sessionFile(session.name);
6955
- try {
6956
- unlinkSync2(file2);
6957
- } catch {
6958
- }
6959
- try {
6960
- const { networkStore, commandLogStore } = await import("./network-store-YVDNUREI.js");
6961
- networkStore.clear(session.name);
6962
- commandLogStore.clear(session.name);
6963
- } catch {
6964
- }
6965
- try {
6966
- const { SessionRecorder } = await import("./session-recorder-RUNQOJ7T.js");
6967
- SessionRecorder.cleanup(session.name);
6968
- } catch {
6969
- }
6970
- return true;
6971
- }
6972
- }
6973
- const file = sessionFile(name);
6974
- try {
6975
- unlinkSync2(file);
6976
- } catch {
6977
- }
6978
- return false;
6979
- }
6980
- async function closeAllSessions() {
6981
- const names = sessions.list().map((s) => `${s.name}(${s.page.url()})`).join(", ");
6982
- if (names) logSessionEvent2("close_all_sessions", `Closing ${sessions.size} sessions: ${names}`);
6983
- for (const session of sessions.list()) {
6984
- try {
6985
- if (session.isCDP) {
6986
- if (session.browser) {
6987
- await session.browser.close().catch(() => {
6988
- });
6989
- }
6990
- } else {
6991
- await session.context.close();
6992
- if (session.browser) {
6993
- await session.browser.close().catch(() => {
6994
- });
6995
- }
6996
- }
6997
- sessions.removeById(session.id);
6998
- } catch {
6999
- sessions.removeById(session.id);
7000
- }
7001
- }
7002
- }
7003
- async function destroyBrowser() {
7004
- logSessionEvent2("destroy_browser", `Sessions count: ${sessions.size}. Clearing idle timer and closing all sessions.`);
7005
- if (sharedState.idleTimer) {
7006
- clearTimeout(sharedState.idleTimer);
7007
- sharedState.idleTimer = null;
7008
- }
7009
- await closeAllSessions();
7010
- if (sharedState.browser) {
7011
- await sharedState.browser.close().catch(() => {
7012
- });
7013
- sharedState.browser = null;
7014
- }
7015
- if (getSharedCdpProxy()) {
7016
- await getSharedCdpProxy().stop().catch(() => {
7017
- });
7018
- setSharedCdpProxy(null);
7019
- }
7020
- }
7021
- function resetForTesting() {
7022
- sessions.clear();
7023
- sharedState.browser = null;
7024
- sharedState.idleTimer = null;
7025
- setSharedCdpProxy(null);
7026
- try {
7027
- for (const file of readdirSync2(SESSION_DIR)) unlinkSync2(join3(SESSION_DIR, file));
7028
- } catch {
7029
- }
7030
- }
7031
- async function ensureProcessCanExit() {
7032
- if (sharedState.idleTimer) {
7033
- clearTimeout(sharedState.idleTimer);
7034
- sharedState.idleTimer = null;
7035
- }
7036
- for (const session of sessions.list()) {
7037
- if (session.browser) {
7038
- if (session.isCDP) {
7039
- } else {
7040
- await session.browser.close().catch(() => {
7041
- });
7042
- }
7043
- }
7044
- }
7045
- sessions.clear();
7046
- if (sharedState.browser) {
7047
- await sharedState.browser.close().catch(() => {
7048
- });
7049
- sharedState.browser = null;
7050
- }
7051
- if (getSharedCdpProxy()) {
7052
- await getSharedCdpProxy().stop().catch(() => {
7053
- });
7054
- setSharedCdpProxy(null);
7055
- }
7056
- }
7057
-
7058
5877
  export {
7059
5878
  createRuleEngine,
7060
- findTargetPage,
7061
- resolveLaunchOpts,
7062
- createBrowser,
7063
- saveSessionDiskMeta,
7064
- readSessionDiskMeta,
7065
- deleteSessionDiskMeta,
7066
- resetIdleTimer,
7067
- findOrRestoreSession2 as findOrRestoreSession,
7068
- touchSession,
7069
- getBrowser,
7070
- findSession,
7071
- getSessionById2 as getSessionById,
7072
- setActivePage2 as setActivePage,
7073
- createEphemeralContext,
7074
- closeEphemeralContext,
7075
- getAllSessions2 as getAllSessions,
7076
- createSession,
7077
- closeSessionByName,
7078
- closeAllSessions,
7079
- destroyBrowser,
7080
- resetForTesting,
7081
- 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
7082
5894
  };