@xbrowser/cli 1.28.0 → 1.29.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{browser-NYYCR4O7.js → browser-2K3XYAKM.js} +5 -3
- package/dist/{browser-ZD53IMUJ.js → browser-OTEMG5NL.js} +6 -4
- package/dist/{browser-4IYIHZ6R.js → browser-XD3IOU5I.js} +8 -6
- package/dist/{cdp-driver-EFEW4ZEN.js → cdp-driver-AAS55KT2.js} +4 -4
- package/dist/{cdp-driver-4X6Q62WI.js → cdp-driver-O5I7SJ24.js} +3 -3
- package/dist/{cdp-driver-HB744QB4.js → cdp-driver-XTPY7EXP.js} +1296 -852
- package/dist/{chunk-SEEWE5SJ.js → chunk-2KPI5GKP.js} +3 -0
- package/dist/{chunk-75DNUI6M.js → chunk-6UJU2FJK.js} +146 -0
- package/dist/{chunk-3PUOISKE.js → chunk-CO2ZVOVT.js} +496 -452
- package/dist/{chunk-V6KGBU5J.js → chunk-FCPVQFTQ.js} +1011 -1038
- package/dist/{chunk-WK3INZLA.js → chunk-GDKKVT2P.js} +750 -651
- package/dist/{chunk-HSYRAV3H.js → chunk-LFSLNHW5.js} +1846 -1358
- package/dist/{chunk-OSZNJT4U.js → chunk-LM32MNBB.js} +79 -8
- package/dist/{chunk-J3HXZVSN.js → chunk-N5XTLNKS.js} +1166 -868
- package/dist/{chunk-T2AI24A5.js → chunk-NAIHOVDZ.js} +3 -0
- package/dist/{chunk-WYETQ5C7.js → chunk-NEE6EMYA.js} +14 -1
- package/dist/{chunk-ME5FO5YV.js → chunk-NQPXZ74W.js} +1296 -852
- package/dist/{chunk-KECYFWJO.js → chunk-P33R7F2D.js} +413 -384
- package/dist/{chunk-OEC7ZSFW.js → chunk-SCYBNSOG.js} +1560 -1461
- package/dist/{chunk-R3F4K2SB.js → chunk-SMYSNO4M.js} +10 -0
- package/dist/{chunk-IR6C24P7.js → chunk-UZ6XPUBD.js} +1030 -1048
- package/dist/cli.js +3398 -3357
- package/dist/daemon-main.js +737 -707
- package/dist/index.d.ts +362 -474
- package/dist/index.js +5730 -5689
- package/dist/{launcher-SJ44X25U.js → launcher-TOLF23ET.js} +1 -1
- package/dist/{launcher-XHKIC4GP.js → launcher-ZYB32LSZ.js} +1 -1
- package/dist/{plugin-singleton-GGSBI3EG.js → plugin-singleton-A6RNITJW.js} +1 -1
- package/dist/{proxy-NKCYE76M.js → proxy-H3RIUOCN.js} +2 -2
- package/dist/{server-JXF3JOAM.js → server-LNZTDAKT.js} +4 -4
- package/dist/{server-26SE6YZR.js → server-ZTI2K5YJ.js} +7 -7
- package/dist/{session-recorder-GEZVQBKW.js → session-recorder-DF2YGH2E.js} +1 -1
- package/dist/{session-recorder-563ISSJK.js → session-recorder-R3GDGXLJ.js} +1 -1
- package/dist/{session-replayer-TXTNTG33.js → session-replayer-CLTZ2URU.js} +1 -1
- package/dist/{stealth-QNSMIHQK.js → stealth-FMPZO2OB.js} +1 -1
- package/dist/{stealth-MHJNBJY7.js → stealth-MCKFKPZ6.js} +1 -1
- package/package.json +6 -3
|
@@ -1,16 +1,87 @@
|
|
|
1
1
|
import {
|
|
2
2
|
createRuleEngine,
|
|
3
3
|
launch
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-NQPXZ74W.js";
|
|
5
5
|
import {
|
|
6
6
|
errMsg
|
|
7
7
|
} from "./chunk-GDKLH7ZY.js";
|
|
8
8
|
|
|
9
9
|
// src/browser.ts
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
12
|
-
|
|
13
|
-
|
|
10
|
+
import { readdirSync as readdirSync2, unlinkSync as unlinkSync2 } from "fs";
|
|
11
|
+
import { join as join2 } from "path";
|
|
12
|
+
|
|
13
|
+
// src/utils/cdp.ts
|
|
14
|
+
async function fetchNoProxy(url) {
|
|
15
|
+
const savedProxy = {
|
|
16
|
+
http_proxy: process.env.http_proxy,
|
|
17
|
+
https_proxy: process.env.https_proxy,
|
|
18
|
+
HTTP_PROXY: process.env.HTTP_PROXY,
|
|
19
|
+
HTTPS_PROXY: process.env.HTTPS_PROXY,
|
|
20
|
+
all_proxy: process.env.all_proxy,
|
|
21
|
+
ALL_PROXY: process.env.ALL_PROXY
|
|
22
|
+
};
|
|
23
|
+
for (const key of Object.keys(savedProxy)) delete process.env[key];
|
|
24
|
+
try {
|
|
25
|
+
return await fetch(url);
|
|
26
|
+
} finally {
|
|
27
|
+
for (const [key, val] of Object.entries(savedProxy)) {
|
|
28
|
+
if (val !== void 0) process.env[key] = val;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
async function resolveCDPEndpoint(raw) {
|
|
33
|
+
if (raw === "auto") {
|
|
34
|
+
const ports = [9222, 9221, 9223, 9224];
|
|
35
|
+
for (const port of ports) {
|
|
36
|
+
try {
|
|
37
|
+
const httpResp = await fetchNoProxy(`http://localhost:${port}/json/version`);
|
|
38
|
+
if (httpResp.ok) {
|
|
39
|
+
const data = await httpResp.json();
|
|
40
|
+
if (data.webSocketDebuggerUrl) {
|
|
41
|
+
return data.webSocketDebuggerUrl;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
} catch {
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
throw new Error(
|
|
48
|
+
`Could not auto-discover CDP endpoint. Tried ports: ${ports.join(", ")}.
|
|
49
|
+
\u53EF\u80FD\u539F\u56E0\uFF1A\u6CA1\u6709 Chrome \u4EE5 --remote-debugging-port \u542F\u52A8\u3002
|
|
50
|
+
\u89E3\u51B3\u65B9\u6CD5\uFF1A
|
|
51
|
+
1. \u542F\u52A8 Chrome: google-chrome --remote-debugging-port=9222
|
|
52
|
+
2. \u6216\u7528 cdp-tunnel: npx cdp-tunnel setup
|
|
53
|
+
3. \u6216\u6307\u5B9A\u7AEF\u53E3: --cdp <port>`
|
|
54
|
+
);
|
|
55
|
+
}
|
|
56
|
+
if (/^\d+$/.test(raw)) {
|
|
57
|
+
const port = raw;
|
|
58
|
+
const httpResp = await fetchNoProxy(`http://localhost:${port}/json/version`);
|
|
59
|
+
const data = await httpResp.json();
|
|
60
|
+
if (!data.webSocketDebuggerUrl) {
|
|
61
|
+
throw new Error(`Could not discover CDP endpoint from localhost:${port}`);
|
|
62
|
+
}
|
|
63
|
+
return data.webSocketDebuggerUrl;
|
|
64
|
+
}
|
|
65
|
+
if (raw.startsWith("http://") || raw.startsWith("https://")) {
|
|
66
|
+
try {
|
|
67
|
+
const u = new URL(raw);
|
|
68
|
+
u.pathname = (u.pathname.replace(/\/+$/, "") || "") + "/json/version";
|
|
69
|
+
const httpResp = await fetchNoProxy(u.toString());
|
|
70
|
+
const data = await httpResp.json();
|
|
71
|
+
if (!data.webSocketDebuggerUrl) {
|
|
72
|
+
throw new Error(`Could not discover CDP endpoint from ${raw}`);
|
|
73
|
+
}
|
|
74
|
+
return data.webSocketDebuggerUrl;
|
|
75
|
+
} catch (error) {
|
|
76
|
+
console.warn(`Failed to fetch WebSocket URL from ${raw}, using endpoint directly: ${error instanceof Error ? error.message : String(error)}`);
|
|
77
|
+
return raw;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
return raw;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// src/browser/connection.ts
|
|
84
|
+
import { existsSync } from "fs";
|
|
14
85
|
|
|
15
86
|
// src/cdp-interceptor/proxy.ts
|
|
16
87
|
import { WebSocketServer, WebSocket } from "ws";
|
|
@@ -391,6 +462,19 @@ ${blockMsg}
|
|
|
391
462
|
return;
|
|
392
463
|
}
|
|
393
464
|
if (decision?.action === "transform" && decision.transformedParams) {
|
|
465
|
+
const sequence = decision.transformedParams.__sequence;
|
|
466
|
+
if (Array.isArray(sequence)) {
|
|
467
|
+
this.stats.transformedMessages++;
|
|
468
|
+
const dispatch = async () => {
|
|
469
|
+
for (const step of sequence) {
|
|
470
|
+
if (step.delayMs) await new Promise((resolve) => setTimeout(resolve, step.delayMs));
|
|
471
|
+
const transformed2 = { id: request.id, method: step.method, params: step.params, sessionId: request.sessionId };
|
|
472
|
+
browserWs.send(JSON.stringify(transformed2));
|
|
473
|
+
}
|
|
474
|
+
};
|
|
475
|
+
void dispatch();
|
|
476
|
+
return;
|
|
477
|
+
}
|
|
394
478
|
const transformed = { ...request, params: decision.transformedParams };
|
|
395
479
|
this.stats.transformedMessages++;
|
|
396
480
|
browserWs.send(JSON.stringify(transformed));
|
|
@@ -441,186 +525,38 @@ ${blockMsg}
|
|
|
441
525
|
}
|
|
442
526
|
};
|
|
443
527
|
|
|
444
|
-
// src/
|
|
445
|
-
async function fetchNoProxy(url) {
|
|
446
|
-
const savedProxy = {
|
|
447
|
-
http_proxy: process.env.http_proxy,
|
|
448
|
-
https_proxy: process.env.https_proxy,
|
|
449
|
-
HTTP_PROXY: process.env.HTTP_PROXY,
|
|
450
|
-
HTTPS_PROXY: process.env.HTTPS_PROXY,
|
|
451
|
-
all_proxy: process.env.all_proxy,
|
|
452
|
-
ALL_PROXY: process.env.ALL_PROXY
|
|
453
|
-
};
|
|
454
|
-
for (const key of Object.keys(savedProxy)) delete process.env[key];
|
|
455
|
-
try {
|
|
456
|
-
return await fetch(url);
|
|
457
|
-
} finally {
|
|
458
|
-
for (const [key, val] of Object.entries(savedProxy)) {
|
|
459
|
-
if (val !== void 0) process.env[key] = val;
|
|
460
|
-
}
|
|
461
|
-
}
|
|
462
|
-
}
|
|
463
|
-
async function resolveCDPEndpoint(raw) {
|
|
464
|
-
if (raw === "auto") {
|
|
465
|
-
const ports = [9222, 9221, 9223, 9224];
|
|
466
|
-
for (const port of ports) {
|
|
467
|
-
try {
|
|
468
|
-
const httpResp = await fetchNoProxy(`http://localhost:${port}/json/version`);
|
|
469
|
-
if (httpResp.ok) {
|
|
470
|
-
const data = await httpResp.json();
|
|
471
|
-
if (data.webSocketDebuggerUrl) {
|
|
472
|
-
return data.webSocketDebuggerUrl;
|
|
473
|
-
}
|
|
474
|
-
}
|
|
475
|
-
} catch {
|
|
476
|
-
}
|
|
477
|
-
}
|
|
478
|
-
throw new Error(
|
|
479
|
-
`Could not auto-discover CDP endpoint. Tried ports: ${ports.join(", ")}.
|
|
480
|
-
\u53EF\u80FD\u539F\u56E0\uFF1A\u6CA1\u6709 Chrome \u4EE5 --remote-debugging-port \u542F\u52A8\u3002
|
|
481
|
-
\u89E3\u51B3\u65B9\u6CD5\uFF1A
|
|
482
|
-
1. \u542F\u52A8 Chrome: google-chrome --remote-debugging-port=9222
|
|
483
|
-
2. \u6216\u7528 cdp-tunnel: npx cdp-tunnel setup
|
|
484
|
-
3. \u6216\u6307\u5B9A\u7AEF\u53E3: --cdp <port>`
|
|
485
|
-
);
|
|
486
|
-
}
|
|
487
|
-
if (/^\d+$/.test(raw)) {
|
|
488
|
-
const port = raw;
|
|
489
|
-
const httpResp = await fetchNoProxy(`http://localhost:${port}/json/version`);
|
|
490
|
-
const data = await httpResp.json();
|
|
491
|
-
if (!data.webSocketDebuggerUrl) {
|
|
492
|
-
throw new Error(`Could not discover CDP endpoint from localhost:${port}`);
|
|
493
|
-
}
|
|
494
|
-
return data.webSocketDebuggerUrl;
|
|
495
|
-
}
|
|
496
|
-
if (raw.startsWith("http://") || raw.startsWith("https://")) {
|
|
497
|
-
try {
|
|
498
|
-
const u = new URL(raw);
|
|
499
|
-
u.pathname = (u.pathname.replace(/\/+$/, "") || "") + "/json/version";
|
|
500
|
-
const httpResp = await fetchNoProxy(u.toString());
|
|
501
|
-
const data = await httpResp.json();
|
|
502
|
-
if (!data.webSocketDebuggerUrl) {
|
|
503
|
-
throw new Error(`Could not discover CDP endpoint from ${raw}`);
|
|
504
|
-
}
|
|
505
|
-
return data.webSocketDebuggerUrl;
|
|
506
|
-
} catch (error) {
|
|
507
|
-
console.warn(`Failed to fetch WebSocket URL from ${raw}, using endpoint directly: ${error instanceof Error ? error.message : String(error)}`);
|
|
508
|
-
return raw;
|
|
509
|
-
}
|
|
510
|
-
}
|
|
511
|
-
return raw;
|
|
512
|
-
}
|
|
513
|
-
|
|
514
|
-
// src/browser.ts
|
|
515
|
-
import { SessionStore } from "@dyyz1993/xcli-core";
|
|
516
|
-
function logSessionEvent(event, details) {
|
|
517
|
-
const ts = (/* @__PURE__ */ new Date()).toISOString().replace("T", " ").substring(0, 19);
|
|
518
|
-
const pid = process.pid;
|
|
519
|
-
console.error(`[SESSION] ${ts} [PID:${pid}] ${event} | ${details}`);
|
|
520
|
-
}
|
|
521
|
-
var SESSION_DIR = join(homedir(), ".xbrowser", "sessions");
|
|
522
|
-
function sessionFile(name) {
|
|
523
|
-
return join(SESSION_DIR, `${name}.json`);
|
|
524
|
-
}
|
|
525
|
-
function ensureSessionDir() {
|
|
526
|
-
mkdirSync(SESSION_DIR, { recursive: true });
|
|
527
|
-
}
|
|
528
|
-
var sessions = new SessionStore();
|
|
529
|
-
var _sharedBrowser = null;
|
|
530
|
-
var _sharedCdpProxy = null;
|
|
531
|
-
var IDLE_TIMEOUT_MS = (process.env.XBROWSER_IDLE_TIMEOUT ? parseInt(process.env.XBROWSER_IDLE_TIMEOUT, 10) : 30) * 60 * 1e3;
|
|
532
|
-
var idleTimer = null;
|
|
533
|
-
function resetIdleTimer() {
|
|
534
|
-
if (idleTimer) clearTimeout(idleTimer);
|
|
535
|
-
idleTimer = setTimeout(async () => {
|
|
536
|
-
const now = Date.now();
|
|
537
|
-
let allIdle = true;
|
|
538
|
-
const idleSessions = [];
|
|
539
|
-
for (const s of sessions) {
|
|
540
|
-
if (now - s.lastActivityAt < IDLE_TIMEOUT_MS) {
|
|
541
|
-
allIdle = false;
|
|
542
|
-
} else {
|
|
543
|
-
idleSessions.push(`${s.name}(${(now - s.lastActivityAt) / 1e3}s idle)`);
|
|
544
|
-
}
|
|
545
|
-
}
|
|
546
|
-
if (allIdle && (sessions.size > 0 || _sharedBrowser)) {
|
|
547
|
-
logSessionEvent("idle_timeout", `Sessions idle for >${IDLE_TIMEOUT_MS / 6e4}min. Sessions: ${idleSessions.join(", ") || "all"}. Calling destroyBrowser()`);
|
|
548
|
-
await destroyBrowser().catch(() => {
|
|
549
|
-
});
|
|
550
|
-
}
|
|
551
|
-
}, IDLE_TIMEOUT_MS);
|
|
552
|
-
if (idleTimer && typeof idleTimer.unref === "function") {
|
|
553
|
-
idleTimer.unref();
|
|
554
|
-
}
|
|
555
|
-
}
|
|
556
|
-
function touchSession(id) {
|
|
557
|
-
const s = sessions.get(id);
|
|
558
|
-
if (s) s.lastActivityAt = Date.now();
|
|
559
|
-
resetIdleTimer();
|
|
560
|
-
}
|
|
561
|
-
process.on("exit", () => {
|
|
562
|
-
for (const session of sessions.list()) {
|
|
563
|
-
if (session.isCDP) {
|
|
564
|
-
logSessionEvent("process_exit", `Session "${session.name}": CDP connection (not closing external browser).`);
|
|
565
|
-
} else {
|
|
566
|
-
logSessionEvent("process_exit", `Session "${session.name}": Closing self-launched browser.`);
|
|
567
|
-
try {
|
|
568
|
-
session.browser?.close();
|
|
569
|
-
} catch {
|
|
570
|
-
}
|
|
571
|
-
}
|
|
572
|
-
}
|
|
573
|
-
if (_sharedBrowser) {
|
|
574
|
-
logSessionEvent("process_exit", "Closing shared browser (self-launched only, external CDP is safe).");
|
|
575
|
-
try {
|
|
576
|
-
_sharedBrowser.close();
|
|
577
|
-
} catch {
|
|
578
|
-
}
|
|
579
|
-
_sharedBrowser = null;
|
|
580
|
-
}
|
|
581
|
-
if (_sharedCdpProxy) {
|
|
582
|
-
try {
|
|
583
|
-
_sharedCdpProxy.stop();
|
|
584
|
-
} catch {
|
|
585
|
-
}
|
|
586
|
-
_sharedCdpProxy = null;
|
|
587
|
-
}
|
|
588
|
-
sessions.clear();
|
|
589
|
-
});
|
|
528
|
+
// src/browser/connection.ts
|
|
590
529
|
async function getCDPTargets(cdpEndpoint) {
|
|
591
530
|
try {
|
|
592
|
-
const
|
|
531
|
+
const endpoint = String(cdpEndpoint);
|
|
593
532
|
let url = "http://localhost:9222/json/list";
|
|
594
|
-
if (
|
|
595
|
-
const
|
|
596
|
-
|
|
597
|
-
url =
|
|
598
|
-
} else if (/^\d+$/.test(
|
|
599
|
-
url = `http://localhost:${
|
|
533
|
+
if (endpoint.startsWith("http://") || endpoint.startsWith("https://")) {
|
|
534
|
+
const parsed = new URL(endpoint);
|
|
535
|
+
parsed.pathname = (parsed.pathname.replace(/\/+$/, "") || "") + "/json/list";
|
|
536
|
+
url = parsed.toString();
|
|
537
|
+
} else if (/^\d+$/.test(endpoint)) {
|
|
538
|
+
url = `http://localhost:${endpoint}/json/list`;
|
|
600
539
|
}
|
|
601
|
-
const
|
|
602
|
-
return await
|
|
540
|
+
const response = await fetch(url);
|
|
541
|
+
return await response.json();
|
|
603
542
|
} catch {
|
|
604
543
|
return [];
|
|
605
544
|
}
|
|
606
545
|
}
|
|
607
546
|
async function findTargetPage(cdpEndpoint, target) {
|
|
608
547
|
const targets = await getCDPTargets(cdpEndpoint);
|
|
609
|
-
const pages = targets.filter((
|
|
610
|
-
const byId = pages.find((
|
|
548
|
+
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://"));
|
|
549
|
+
const byId = pages.find((item) => item.id === target);
|
|
611
550
|
if (byId) return { pageId: byId.id, wsUrl: byId.webSocketDebuggerUrl, title: byId.title, url: byId.url };
|
|
612
551
|
const lowerTarget = target.toLowerCase();
|
|
613
|
-
const byTitle = pages.find((
|
|
552
|
+
const byTitle = pages.find((item) => item.title?.toLowerCase().includes(lowerTarget));
|
|
614
553
|
if (byTitle) return { pageId: byTitle.id, wsUrl: byTitle.webSocketDebuggerUrl, title: byTitle.title, url: byTitle.url };
|
|
615
|
-
const byUrl = pages.find((
|
|
554
|
+
const byUrl = pages.find((item) => item.url.toLowerCase().includes(lowerTarget));
|
|
616
555
|
if (byUrl) return { pageId: byUrl.id, wsUrl: byUrl.webSocketDebuggerUrl, title: byUrl.title, url: byUrl.url };
|
|
617
556
|
return null;
|
|
618
557
|
}
|
|
619
558
|
function resolveLaunchOpts(ctx) {
|
|
620
|
-
|
|
621
|
-
return { cdpEndpoint: ctx.cdpEndpoint };
|
|
622
|
-
}
|
|
623
|
-
return { headless: true };
|
|
559
|
+
return ctx.cdpEndpoint ? { cdpEndpoint: ctx.cdpEndpoint } : { headless: true };
|
|
624
560
|
}
|
|
625
561
|
var CHROMIUM_CANDIDATES = [
|
|
626
562
|
"/Applications/Chromium.app/Contents/MacOS/Chromium",
|
|
@@ -630,57 +566,58 @@ var CHROMIUM_CANDIDATES = [
|
|
|
630
566
|
"/usr/bin/google-chrome"
|
|
631
567
|
];
|
|
632
568
|
function discoverChromiumPath() {
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
569
|
+
return CHROMIUM_CANDIDATES.find((path) => existsSync(path));
|
|
570
|
+
}
|
|
571
|
+
var browserPool = /* @__PURE__ */ new Map();
|
|
572
|
+
var sharedCdpProxy = null;
|
|
573
|
+
function getSharedCdpProxy() {
|
|
574
|
+
return sharedCdpProxy;
|
|
575
|
+
}
|
|
576
|
+
function setSharedCdpProxy(proxy) {
|
|
577
|
+
sharedCdpProxy = proxy;
|
|
637
578
|
}
|
|
638
|
-
var _browserPool = /* @__PURE__ */ new Map();
|
|
639
579
|
async function createBrowser(options) {
|
|
640
580
|
if (options?.cdpEndpoint) {
|
|
641
581
|
const realEndpoint = await resolveCDPEndpoint(options.cdpEndpoint);
|
|
642
582
|
if (!options.intercept) {
|
|
643
|
-
const pooled =
|
|
644
|
-
if (pooled && !pooled.disconnected)
|
|
645
|
-
|
|
646
|
-
}
|
|
647
|
-
if (pooled) _browserPool.delete(realEndpoint);
|
|
583
|
+
const pooled = browserPool.get(realEndpoint);
|
|
584
|
+
if (pooled && !pooled.disconnected) return pooled;
|
|
585
|
+
if (pooled) browserPool.delete(realEndpoint);
|
|
648
586
|
}
|
|
649
587
|
if (options.intercept) {
|
|
650
588
|
const config = typeof options.intercept === "object" ? { ...options.intercept, cdpEndpoint: realEndpoint } : { cdpEndpoint: realEndpoint };
|
|
651
|
-
|
|
652
|
-
const proxyPort = await
|
|
589
|
+
sharedCdpProxy = new CDPInterceptorProxy(config);
|
|
590
|
+
const proxyPort = await sharedCdpProxy.start();
|
|
653
591
|
console.error(`[CDP Interceptor] Proxy running on ws://localhost:${proxyPort}, forwarding to ${realEndpoint}`);
|
|
654
592
|
const { browser: browser3 } = await launch({ cdpEndpoint: `ws://localhost:${proxyPort}` });
|
|
655
593
|
return browser3;
|
|
656
594
|
}
|
|
657
595
|
const { browser: browser2 } = await launch({ cdpEndpoint: realEndpoint });
|
|
658
|
-
await browser2.discoverContexts().catch((
|
|
659
|
-
console.error(`[browser] discoverContexts failed: ${errMsg(
|
|
596
|
+
await browser2.discoverContexts().catch((error) => {
|
|
597
|
+
console.error(`[browser] discoverContexts failed: ${errMsg(error)}`);
|
|
660
598
|
});
|
|
661
|
-
|
|
599
|
+
browserPool.set(realEndpoint, browser2);
|
|
662
600
|
return browser2;
|
|
663
601
|
}
|
|
664
602
|
const executablePath = options?.executablePath || process.env.XBROWSER_CHROMIUM_PATH || discoverChromiumPath();
|
|
665
603
|
const { browser } = await launch({ executablePath, headless: options?.headless ?? true });
|
|
666
604
|
return browser;
|
|
667
605
|
}
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
}
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
}
|
|
678
|
-
function
|
|
679
|
-
return
|
|
606
|
+
|
|
607
|
+
// src/browser/state.ts
|
|
608
|
+
import { randomUUID } from "crypto";
|
|
609
|
+
import { existsSync as existsSync2, mkdirSync, readFileSync, readdirSync, unlinkSync, writeFileSync } from "fs";
|
|
610
|
+
import { join } from "path";
|
|
611
|
+
import { homedir } from "os";
|
|
612
|
+
import { SessionStore } from "@dyyz1993/xcli-core";
|
|
613
|
+
var SESSION_DIR = join(homedir(), ".xbrowser", "sessions");
|
|
614
|
+
var sessions = new SessionStore();
|
|
615
|
+
var sharedState = { browser: null, idleTimer: null };
|
|
616
|
+
function sessionFile(name) {
|
|
617
|
+
return join(SESSION_DIR, `${name}.json`);
|
|
680
618
|
}
|
|
681
|
-
function
|
|
682
|
-
|
|
683
|
-
session.lastActivityAt = Date.now();
|
|
619
|
+
function ensureSessionDir() {
|
|
620
|
+
mkdirSync(SESSION_DIR, { recursive: true });
|
|
684
621
|
}
|
|
685
622
|
function saveSessionDiskMeta(name, data) {
|
|
686
623
|
ensureSessionDir();
|
|
@@ -694,20 +631,40 @@ function saveSessionDiskMeta(name, data) {
|
|
|
694
631
|
writeFileSync(file, JSON.stringify(existing, null, 2));
|
|
695
632
|
}
|
|
696
633
|
function readSessionDiskMeta(name) {
|
|
697
|
-
const file = sessionFile(name);
|
|
698
634
|
try {
|
|
699
|
-
return JSON.parse(readFileSync(
|
|
635
|
+
return JSON.parse(readFileSync(sessionFile(name), "utf8"));
|
|
700
636
|
} catch {
|
|
701
637
|
return null;
|
|
702
638
|
}
|
|
703
639
|
}
|
|
704
640
|
function deleteSessionDiskMeta(name) {
|
|
705
|
-
const file = sessionFile(name);
|
|
706
641
|
try {
|
|
707
|
-
unlinkSync(
|
|
642
|
+
unlinkSync(sessionFile(name));
|
|
708
643
|
} catch {
|
|
709
644
|
}
|
|
710
645
|
}
|
|
646
|
+
function newSessionId() {
|
|
647
|
+
return randomUUID();
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
// src/browser/lifecycle.ts
|
|
651
|
+
function registerSession(session) {
|
|
652
|
+
const complete = {
|
|
653
|
+
id: session.id ?? newSessionId(),
|
|
654
|
+
createdAt: session.createdAt ?? (/* @__PURE__ */ new Date()).toISOString(),
|
|
655
|
+
lastActivityAt: session.lastActivityAt ?? Date.now(),
|
|
656
|
+
...session
|
|
657
|
+
};
|
|
658
|
+
sessions.set(complete);
|
|
659
|
+
resetIdleTimer();
|
|
660
|
+
return complete;
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
// src/browser/restore.ts
|
|
664
|
+
function logSessionEvent(event, details) {
|
|
665
|
+
const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace("T", " ").substring(0, 19);
|
|
666
|
+
console.error(`[SESSION] ${timestamp} [PID:${process.pid}] ${event} | ${details}`);
|
|
667
|
+
}
|
|
711
668
|
async function isSessionPageAlive(session) {
|
|
712
669
|
const page = session.page;
|
|
713
670
|
if (!page || typeof page.evaluate !== "function") return false;
|
|
@@ -719,69 +676,65 @@ async function isSessionPageAlive(session) {
|
|
|
719
676
|
]);
|
|
720
677
|
return true;
|
|
721
678
|
} catch {
|
|
722
|
-
await new Promise((
|
|
679
|
+
await new Promise((resolve) => setTimeout(resolve, 400));
|
|
723
680
|
}
|
|
724
681
|
}
|
|
725
682
|
return false;
|
|
726
683
|
}
|
|
727
|
-
async function findOrRestoreSession(name, cdpEndpoint) {
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
684
|
+
async function findOrRestoreSession(name, cdpEndpoint, cleanup = async () => false, installNetworkCapture2 = async () => {
|
|
685
|
+
}) {
|
|
686
|
+
const inMemory = findSession(name);
|
|
687
|
+
if (inMemory) {
|
|
688
|
+
if (await isSessionPageAlive(inMemory)) return inMemory;
|
|
689
|
+
logSessionEvent("stale_session", `name="${name}" \u2014 page probe failed; rebuilding`);
|
|
732
690
|
try {
|
|
733
|
-
await
|
|
691
|
+
await cleanup(name);
|
|
734
692
|
} catch {
|
|
735
693
|
}
|
|
736
694
|
}
|
|
737
695
|
const meta = readSessionDiskMeta(name);
|
|
738
696
|
if (!meta) return void 0;
|
|
739
|
-
const
|
|
740
|
-
if (!
|
|
697
|
+
const endpoint = cdpEndpoint || meta.cdpEndpoint;
|
|
698
|
+
if (!endpoint) return void 0;
|
|
741
699
|
try {
|
|
742
|
-
const
|
|
743
|
-
await new Promise((
|
|
744
|
-
let contexts =
|
|
700
|
+
const browser = await createBrowser({ cdpEndpoint: endpoint });
|
|
701
|
+
await new Promise((resolve) => setTimeout(resolve, 500));
|
|
702
|
+
let contexts = browser.contexts();
|
|
745
703
|
if (contexts.length === 0) {
|
|
746
|
-
await new Promise((
|
|
747
|
-
contexts =
|
|
704
|
+
await new Promise((resolve) => setTimeout(resolve, 500));
|
|
705
|
+
contexts = browser.contexts();
|
|
748
706
|
}
|
|
749
|
-
const context = contexts[0] || await
|
|
707
|
+
const context = contexts[0] || await browser.newContext();
|
|
750
708
|
const savedUrl = meta.conversationUrl || meta.url;
|
|
751
|
-
|
|
709
|
+
let targetHostname = "";
|
|
710
|
+
if (savedUrl) {
|
|
752
711
|
try {
|
|
753
|
-
|
|
712
|
+
targetHostname = new URL(savedUrl).hostname;
|
|
754
713
|
} catch {
|
|
755
|
-
|
|
714
|
+
targetHostname = "";
|
|
756
715
|
}
|
|
757
|
-
}
|
|
716
|
+
}
|
|
758
717
|
let page = null;
|
|
759
718
|
let fallbackPage = null;
|
|
760
|
-
for (const
|
|
761
|
-
const
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
if (
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
break;
|
|
768
|
-
}
|
|
769
|
-
if (!fallbackPage) {
|
|
770
|
-
fallbackPage = p;
|
|
771
|
-
}
|
|
719
|
+
for (const browserContext of contexts) {
|
|
720
|
+
for (const candidate of browserContext.pages()) {
|
|
721
|
+
const url = candidate.url();
|
|
722
|
+
if (!url || url === "about:blank" || url.startsWith("chrome://") || url.startsWith("chrome-untrusted://") || url.startsWith("chrome-error://")) continue;
|
|
723
|
+
if (targetHostname && url.includes(targetHostname)) {
|
|
724
|
+
page = candidate;
|
|
725
|
+
break;
|
|
772
726
|
}
|
|
727
|
+
fallbackPage ??= candidate;
|
|
773
728
|
}
|
|
774
729
|
if (page) break;
|
|
775
730
|
}
|
|
776
|
-
page
|
|
731
|
+
page ??= fallbackPage;
|
|
777
732
|
if (!page) {
|
|
778
|
-
const targets = await getCDPTargets(
|
|
779
|
-
const
|
|
780
|
-
|
|
781
|
-
);
|
|
782
|
-
if (matchTarget && matchTarget.url) {
|
|
733
|
+
const targets = await getCDPTargets(endpoint);
|
|
734
|
+
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)));
|
|
735
|
+
if (match?.url) {
|
|
783
736
|
page = await context.newPage();
|
|
784
|
-
await page.goto(
|
|
737
|
+
await page.goto(match.url, { waitUntil: "domcontentloaded", timeout: 15e3 }).catch(() => {
|
|
785
738
|
});
|
|
786
739
|
}
|
|
787
740
|
}
|
|
@@ -795,7 +748,6 @@ async function findOrRestoreSession(name, cdpEndpoint) {
|
|
|
795
748
|
new Promise((_, reject) => setTimeout(() => reject(new Error("timeout")), 3e3))
|
|
796
749
|
]);
|
|
797
750
|
} catch {
|
|
798
|
-
console.log(`[Session] "${name}" restored page unresponsive, creating fresh session`);
|
|
799
751
|
deleteSessionDiskMeta(name);
|
|
800
752
|
return void 0;
|
|
801
753
|
}
|
|
@@ -810,186 +762,35 @@ async function findOrRestoreSession(name, cdpEndpoint) {
|
|
|
810
762
|
}
|
|
811
763
|
}
|
|
812
764
|
const session = {
|
|
813
|
-
id: meta.id
|
|
765
|
+
id: meta.id,
|
|
814
766
|
name,
|
|
815
767
|
context,
|
|
816
768
|
page,
|
|
817
|
-
browser
|
|
818
|
-
createdAt: meta.createdAt
|
|
769
|
+
browser,
|
|
770
|
+
createdAt: meta.createdAt,
|
|
819
771
|
lastActivityAt: Date.now(),
|
|
820
772
|
isCDP: true,
|
|
821
|
-
cdpEndpoint:
|
|
773
|
+
cdpEndpoint: endpoint
|
|
822
774
|
};
|
|
823
|
-
for (const
|
|
824
|
-
if (
|
|
825
|
-
logSessionEvent("remove_stale", `Removing stale session name="${name}" id="${existingSession.id}" during restore`);
|
|
826
|
-
sessions.removeById(existingSession.id);
|
|
827
|
-
}
|
|
775
|
+
for (const existing of sessions.list()) {
|
|
776
|
+
if (existing.name === name) sessions.removeById(existing.id);
|
|
828
777
|
}
|
|
829
778
|
sessions.set(session);
|
|
830
|
-
|
|
831
|
-
await installNetworkCapture(page, name);
|
|
779
|
+
await installNetworkCapture2(session.page, name);
|
|
832
780
|
return session;
|
|
833
|
-
} catch (
|
|
834
|
-
console.error(`[Session Restore] Failed for "${name}":`, errMsg(
|
|
781
|
+
} catch (error) {
|
|
782
|
+
console.error(`[Session Restore] Failed for "${name}":`, errMsg(error));
|
|
835
783
|
deleteSessionDiskMeta(name);
|
|
836
784
|
return void 0;
|
|
837
785
|
}
|
|
838
786
|
}
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
const { browser: b2 } = await launch({ cdpEndpoint: endpoint });
|
|
843
|
-
const contexts = b2.contexts();
|
|
844
|
-
const ctx = contexts[0] || await b2.newContext();
|
|
845
|
-
const allPages = ctx.pages();
|
|
846
|
-
const existingPages = allPages.filter((p) => {
|
|
847
|
-
const url = p.url();
|
|
848
|
-
return url !== "about:blank" && !url.startsWith("chrome://") && !url.startsWith("chrome-untrusted://") && !url.startsWith("chrome-error://");
|
|
849
|
-
});
|
|
850
|
-
const page2 = existingPages.length > 0 ? existingPages[0] : allPages.length > 0 ? allPages[0] : await ctx.newPage();
|
|
851
|
-
resetIdleTimer();
|
|
852
|
-
ephemeralConnections.set(page2, b2);
|
|
853
|
-
return { context: ctx, page: page2 };
|
|
854
|
-
}
|
|
855
|
-
const b = await getBrowser(options);
|
|
856
|
-
const context = await b.newContext();
|
|
857
|
-
const page = await context.newPage();
|
|
858
|
-
resetIdleTimer();
|
|
859
|
-
return { context, page };
|
|
860
|
-
}
|
|
861
|
-
var ephemeralConnections = /* @__PURE__ */ new WeakMap();
|
|
862
|
-
async function closeEphemeralContext(context) {
|
|
863
|
-
try {
|
|
864
|
-
const pages = context.pages();
|
|
865
|
-
for (const p of pages) {
|
|
866
|
-
const conn = ephemeralConnections.get(p);
|
|
867
|
-
if (conn) {
|
|
868
|
-
ephemeralConnections.delete(p);
|
|
869
|
-
await conn.close();
|
|
870
|
-
break;
|
|
871
|
-
}
|
|
872
|
-
}
|
|
873
|
-
await context.close();
|
|
874
|
-
} catch {
|
|
875
|
-
}
|
|
876
|
-
if (sessions.size === 0 && idleTimer) {
|
|
877
|
-
clearTimeout(idleTimer);
|
|
878
|
-
idleTimer = null;
|
|
879
|
-
}
|
|
880
|
-
}
|
|
881
|
-
function getAllSessions() {
|
|
882
|
-
return sessions.list();
|
|
883
|
-
}
|
|
884
|
-
async function installNetworkCapture(page, sessionName) {
|
|
885
|
-
if (process.env.XBROWSER_DAEMON_WORKER !== "1") return;
|
|
886
|
-
const { networkStore } = await import("./network-store-XGZ25FFC.js");
|
|
887
|
-
const requestData = /* @__PURE__ */ new Map();
|
|
888
|
-
const responseMeta = /* @__PURE__ */ new Map();
|
|
889
|
-
const xbPage = page;
|
|
890
|
-
xbPage.on("request", (params) => {
|
|
891
|
-
try {
|
|
892
|
-
const p = params;
|
|
893
|
-
requestData.set(p.requestId, {
|
|
894
|
-
method: p.request.method,
|
|
895
|
-
headers: p.request.headers,
|
|
896
|
-
postData: p.request.postData ?? null,
|
|
897
|
-
resourceType: p.type
|
|
898
|
-
});
|
|
899
|
-
} catch {
|
|
900
|
-
}
|
|
901
|
-
});
|
|
902
|
-
xbPage.on("response", (params) => {
|
|
903
|
-
try {
|
|
904
|
-
const p = params;
|
|
905
|
-
responseMeta.set(p.requestId, {
|
|
906
|
-
status: p.response.status,
|
|
907
|
-
url: p.response.url,
|
|
908
|
-
headers: p.response.headers,
|
|
909
|
-
mimeType: p.response.mimeType,
|
|
910
|
-
type: p.type
|
|
911
|
-
});
|
|
912
|
-
} catch {
|
|
913
|
-
}
|
|
914
|
-
});
|
|
915
|
-
xbPage.on("requestfinished", async (params) => {
|
|
916
|
-
try {
|
|
917
|
-
const p = params;
|
|
918
|
-
const meta = responseMeta.get(p.requestId);
|
|
919
|
-
if (!meta) return;
|
|
920
|
-
const req = requestData.get(p.requestId);
|
|
921
|
-
const method = req?.method ?? "GET";
|
|
922
|
-
const contentType = meta.headers["content-type"] || meta.headers["Content-Type"] || "";
|
|
923
|
-
const resourceType = req?.resourceType ?? meta.type;
|
|
924
|
-
const requestHeaders = req?.headers ?? {};
|
|
925
|
-
let requestBody = void 0;
|
|
926
|
-
const isPostLike = ["POST", "PATCH", "PUT"].includes(method);
|
|
927
|
-
if (isPostLike && requestHeaders["content-type"]?.includes("application/json")) {
|
|
928
|
-
const postData = req?.postData;
|
|
929
|
-
if (postData) {
|
|
930
|
-
try {
|
|
931
|
-
requestBody = JSON.parse(postData);
|
|
932
|
-
} catch {
|
|
933
|
-
requestBody = postData;
|
|
934
|
-
}
|
|
935
|
-
}
|
|
936
|
-
}
|
|
937
|
-
let responseBody = void 0;
|
|
938
|
-
let size = 0;
|
|
939
|
-
const isJsonish = contentType.includes("json") || contentType.includes("javascript") || contentType.includes("text/");
|
|
940
|
-
if (isJsonish) {
|
|
941
|
-
try {
|
|
942
|
-
const bodyResult = await xbPage._cdpSend(
|
|
943
|
-
"Network.getResponseBody",
|
|
944
|
-
{ requestId: p.requestId }
|
|
945
|
-
);
|
|
946
|
-
const text = bodyResult.body ?? "";
|
|
947
|
-
size = text.length;
|
|
948
|
-
if (size <= 10240) {
|
|
949
|
-
try {
|
|
950
|
-
responseBody = JSON.parse(text);
|
|
951
|
-
} catch {
|
|
952
|
-
responseBody = text.slice(0, 200);
|
|
953
|
-
}
|
|
954
|
-
}
|
|
955
|
-
} catch {
|
|
956
|
-
}
|
|
957
|
-
} else {
|
|
958
|
-
try {
|
|
959
|
-
const bodyResult = await xbPage._cdpSend(
|
|
960
|
-
"Network.getResponseBody",
|
|
961
|
-
{ requestId: p.requestId }
|
|
962
|
-
);
|
|
963
|
-
size = bodyResult.body?.length ?? 0;
|
|
964
|
-
} catch {
|
|
965
|
-
size = 0;
|
|
966
|
-
}
|
|
967
|
-
}
|
|
968
|
-
networkStore.add(sessionName, {
|
|
969
|
-
timestamp: Date.now(),
|
|
970
|
-
method,
|
|
971
|
-
url: meta.url,
|
|
972
|
-
path: new URL(meta.url).pathname,
|
|
973
|
-
status: meta.status,
|
|
974
|
-
contentType,
|
|
975
|
-
size,
|
|
976
|
-
headers: meta.headers,
|
|
977
|
-
body: responseBody,
|
|
978
|
-
requestHeaders,
|
|
979
|
-
requestBody,
|
|
980
|
-
resourceType
|
|
981
|
-
});
|
|
982
|
-
requestData.delete(p.requestId);
|
|
983
|
-
responseMeta.delete(p.requestId);
|
|
984
|
-
} catch {
|
|
985
|
-
}
|
|
986
|
-
});
|
|
987
|
-
}
|
|
988
|
-
async function createSession(name, url, options) {
|
|
787
|
+
|
|
788
|
+
// src/browser/create-session.ts
|
|
789
|
+
async function createSessionImpl(name, url, options, deps) {
|
|
989
790
|
const existing = findSession(name);
|
|
990
791
|
if (existing) {
|
|
991
|
-
logSessionEvent("replace_session", `name="${name}" id="${existing.id}" \u2014 closing existing session before creating new one`);
|
|
992
|
-
await closeSessionByName(name);
|
|
792
|
+
deps.logSessionEvent("replace_session", `name="${name}" id="${existing.id}" \u2014 closing existing session before creating new one`);
|
|
793
|
+
await deps.closeSessionByName(name);
|
|
993
794
|
}
|
|
994
795
|
const b = await createBrowser(options);
|
|
995
796
|
const isCDP = !!options?.cdpEndpoint;
|
|
@@ -1100,7 +901,7 @@ async function createSession(name, url, options) {
|
|
|
1100
901
|
}
|
|
1101
902
|
}
|
|
1102
903
|
if (!targetPage && options?.cdpEndpoint) {
|
|
1103
|
-
const targets = await getCDPTargets(options.cdpEndpoint);
|
|
904
|
+
const targets = await deps.getCDPTargets(options.cdpEndpoint);
|
|
1104
905
|
const ownedUrlsT = /* @__PURE__ */ new Set();
|
|
1105
906
|
for (const ssn of sessions.list()) {
|
|
1106
907
|
try {
|
|
@@ -1181,27 +982,270 @@ async function createSession(name, url, options) {
|
|
|
1181
982
|
await page.goto(url, { waitUntil: "domcontentloaded", timeout: 15e3 }).catch(() => {
|
|
1182
983
|
});
|
|
1183
984
|
}
|
|
1184
|
-
const session = {
|
|
1185
|
-
id: randomUUID(),
|
|
985
|
+
const session = deps.registerSession({
|
|
1186
986
|
name,
|
|
1187
987
|
context,
|
|
1188
988
|
page,
|
|
1189
989
|
browser: b,
|
|
1190
|
-
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1191
|
-
lastActivityAt: Date.now(),
|
|
1192
990
|
isCDP,
|
|
1193
991
|
cdpEndpoint: options?.cdpEndpoint
|
|
1194
|
-
};
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
resetIdleTimer();
|
|
1198
|
-
await installNetworkCapture(page, name);
|
|
992
|
+
});
|
|
993
|
+
deps.logSessionEvent("create_session", `name="${name}" id="${session.id}" url="${url || "(no url)"}" isCDP=${isCDP} cdpEndpoint=${options?.cdpEndpoint || "(none)"}`);
|
|
994
|
+
await deps.installNetworkCapture(page, name);
|
|
1199
995
|
return session;
|
|
1200
996
|
}
|
|
997
|
+
|
|
998
|
+
// src/browser.ts
|
|
999
|
+
function logSessionEvent2(event, details) {
|
|
1000
|
+
const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace("T", " ").substring(0, 19);
|
|
1001
|
+
console.error(`[SESSION] ${timestamp} [PID:${process.pid}] ${event} | ${details}`);
|
|
1002
|
+
}
|
|
1003
|
+
var IDLE_TIMEOUT_MS = (process.env.XBROWSER_IDLE_TIMEOUT ? parseInt(process.env.XBROWSER_IDLE_TIMEOUT, 10) : 30) * 60 * 1e3;
|
|
1004
|
+
function resetIdleTimer() {
|
|
1005
|
+
if (sharedState.idleTimer) clearTimeout(sharedState.idleTimer);
|
|
1006
|
+
sharedState.idleTimer = setTimeout(async () => {
|
|
1007
|
+
const now = Date.now();
|
|
1008
|
+
let allIdle = true;
|
|
1009
|
+
const idleSessions = [];
|
|
1010
|
+
for (const s of sessions) {
|
|
1011
|
+
if (now - s.lastActivityAt < IDLE_TIMEOUT_MS) {
|
|
1012
|
+
allIdle = false;
|
|
1013
|
+
} else {
|
|
1014
|
+
idleSessions.push(`${s.name}(${(now - s.lastActivityAt) / 1e3}s idle)`);
|
|
1015
|
+
}
|
|
1016
|
+
}
|
|
1017
|
+
if (allIdle && (sessions.size > 0 || sharedState.browser)) {
|
|
1018
|
+
logSessionEvent2("idle_timeout", `Sessions idle for >${IDLE_TIMEOUT_MS / 6e4}min. Sessions: ${idleSessions.join(", ") || "all"}. Calling destroyBrowser()`);
|
|
1019
|
+
await destroyBrowser().catch(() => {
|
|
1020
|
+
});
|
|
1021
|
+
}
|
|
1022
|
+
}, IDLE_TIMEOUT_MS);
|
|
1023
|
+
if (sharedState.idleTimer && typeof sharedState.idleTimer.unref === "function") {
|
|
1024
|
+
sharedState.idleTimer.unref();
|
|
1025
|
+
}
|
|
1026
|
+
}
|
|
1027
|
+
async function findOrRestoreSession2(name, cdpEndpoint) {
|
|
1028
|
+
return findOrRestoreSession(
|
|
1029
|
+
name,
|
|
1030
|
+
cdpEndpoint,
|
|
1031
|
+
closeSessionByName,
|
|
1032
|
+
installNetworkCapture
|
|
1033
|
+
);
|
|
1034
|
+
}
|
|
1035
|
+
function touchSession(id) {
|
|
1036
|
+
const s = sessions.get(id);
|
|
1037
|
+
if (s) s.lastActivityAt = Date.now();
|
|
1038
|
+
resetIdleTimer();
|
|
1039
|
+
}
|
|
1040
|
+
process.on("exit", () => {
|
|
1041
|
+
for (const session of sessions.list()) {
|
|
1042
|
+
if (session.isCDP) {
|
|
1043
|
+
logSessionEvent2("process_exit", `Session "${session.name}": CDP connection (not closing external browser).`);
|
|
1044
|
+
} else {
|
|
1045
|
+
logSessionEvent2("process_exit", `Session "${session.name}": Closing self-launched browser.`);
|
|
1046
|
+
try {
|
|
1047
|
+
session.browser?.close();
|
|
1048
|
+
} catch {
|
|
1049
|
+
}
|
|
1050
|
+
}
|
|
1051
|
+
}
|
|
1052
|
+
if (sharedState.browser) {
|
|
1053
|
+
logSessionEvent2("process_exit", "Closing shared browser (self-launched only, external CDP is safe).");
|
|
1054
|
+
try {
|
|
1055
|
+
sharedState.browser.close();
|
|
1056
|
+
} catch {
|
|
1057
|
+
}
|
|
1058
|
+
sharedState.browser = null;
|
|
1059
|
+
}
|
|
1060
|
+
const cdpProxy = getSharedCdpProxy();
|
|
1061
|
+
if (cdpProxy) {
|
|
1062
|
+
try {
|
|
1063
|
+
cdpProxy.stop();
|
|
1064
|
+
} catch {
|
|
1065
|
+
}
|
|
1066
|
+
setSharedCdpProxy(null);
|
|
1067
|
+
}
|
|
1068
|
+
sessions.clear();
|
|
1069
|
+
});
|
|
1070
|
+
async function getBrowser(options) {
|
|
1071
|
+
if (sharedState.browser) return sharedState.browser;
|
|
1072
|
+
sharedState.browser = await createBrowser(options);
|
|
1073
|
+
if (options?.cdpEndpoint && options.intercept) {
|
|
1074
|
+
}
|
|
1075
|
+
return sharedState.browser;
|
|
1076
|
+
}
|
|
1077
|
+
function findSession(name) {
|
|
1078
|
+
return sessions.find(name);
|
|
1079
|
+
}
|
|
1080
|
+
function getSessionById2(id) {
|
|
1081
|
+
return sessions.get(id);
|
|
1082
|
+
}
|
|
1083
|
+
function setActivePage2(session, page) {
|
|
1084
|
+
session.page = page;
|
|
1085
|
+
session.lastActivityAt = Date.now();
|
|
1086
|
+
}
|
|
1087
|
+
async function createEphemeralContext(options) {
|
|
1088
|
+
if (options?.cdpEndpoint) {
|
|
1089
|
+
const endpoint = await resolveCDPEndpoint(options.cdpEndpoint);
|
|
1090
|
+
const { browser: b2 } = await launch({ cdpEndpoint: endpoint });
|
|
1091
|
+
const contexts = b2.contexts();
|
|
1092
|
+
const ctx = contexts[0] || await b2.newContext();
|
|
1093
|
+
const allPages = ctx.pages();
|
|
1094
|
+
const existingPages = allPages.filter((p) => {
|
|
1095
|
+
const url = p.url();
|
|
1096
|
+
return url !== "about:blank" && !url.startsWith("chrome://") && !url.startsWith("chrome-untrusted://") && !url.startsWith("chrome-error://");
|
|
1097
|
+
});
|
|
1098
|
+
const page2 = existingPages.length > 0 ? existingPages[0] : allPages.length > 0 ? allPages[0] : await ctx.newPage();
|
|
1099
|
+
resetIdleTimer();
|
|
1100
|
+
ephemeralConnections.set(page2, b2);
|
|
1101
|
+
return { context: ctx, page: page2 };
|
|
1102
|
+
}
|
|
1103
|
+
const b = await getBrowser(options);
|
|
1104
|
+
const context = await b.newContext();
|
|
1105
|
+
const page = await context.newPage();
|
|
1106
|
+
resetIdleTimer();
|
|
1107
|
+
return { context, page };
|
|
1108
|
+
}
|
|
1109
|
+
var ephemeralConnections = /* @__PURE__ */ new WeakMap();
|
|
1110
|
+
async function closeEphemeralContext(context) {
|
|
1111
|
+
try {
|
|
1112
|
+
const pages = context.pages();
|
|
1113
|
+
for (const p of pages) {
|
|
1114
|
+
const conn = ephemeralConnections.get(p);
|
|
1115
|
+
if (conn) {
|
|
1116
|
+
ephemeralConnections.delete(p);
|
|
1117
|
+
await conn.close();
|
|
1118
|
+
break;
|
|
1119
|
+
}
|
|
1120
|
+
}
|
|
1121
|
+
await context.close();
|
|
1122
|
+
} catch {
|
|
1123
|
+
}
|
|
1124
|
+
if (sessions.size === 0 && sharedState.idleTimer) {
|
|
1125
|
+
clearTimeout(sharedState.idleTimer);
|
|
1126
|
+
sharedState.idleTimer = null;
|
|
1127
|
+
}
|
|
1128
|
+
}
|
|
1129
|
+
function getAllSessions2() {
|
|
1130
|
+
return sessions.list();
|
|
1131
|
+
}
|
|
1132
|
+
async function installNetworkCapture(page, sessionName) {
|
|
1133
|
+
if (process.env.XBROWSER_DAEMON_WORKER !== "1") return;
|
|
1134
|
+
const { networkStore } = await import("./network-store-XGZ25FFC.js");
|
|
1135
|
+
const requestData = /* @__PURE__ */ new Map();
|
|
1136
|
+
const responseMeta = /* @__PURE__ */ new Map();
|
|
1137
|
+
const xbPage = page;
|
|
1138
|
+
xbPage.on("request", (params) => {
|
|
1139
|
+
try {
|
|
1140
|
+
const p = params;
|
|
1141
|
+
requestData.set(p.requestId, {
|
|
1142
|
+
method: p.request.method,
|
|
1143
|
+
headers: p.request.headers,
|
|
1144
|
+
postData: p.request.postData ?? null,
|
|
1145
|
+
resourceType: p.type
|
|
1146
|
+
});
|
|
1147
|
+
} catch {
|
|
1148
|
+
}
|
|
1149
|
+
});
|
|
1150
|
+
xbPage.on("response", (params) => {
|
|
1151
|
+
try {
|
|
1152
|
+
const p = params;
|
|
1153
|
+
responseMeta.set(p.requestId, {
|
|
1154
|
+
status: p.response.status,
|
|
1155
|
+
url: p.response.url,
|
|
1156
|
+
headers: p.response.headers,
|
|
1157
|
+
mimeType: p.response.mimeType,
|
|
1158
|
+
type: p.type
|
|
1159
|
+
});
|
|
1160
|
+
} catch {
|
|
1161
|
+
}
|
|
1162
|
+
});
|
|
1163
|
+
xbPage.on("requestfinished", async (params) => {
|
|
1164
|
+
try {
|
|
1165
|
+
const p = params;
|
|
1166
|
+
const meta = responseMeta.get(p.requestId);
|
|
1167
|
+
if (!meta) return;
|
|
1168
|
+
const req = requestData.get(p.requestId);
|
|
1169
|
+
const method = req?.method ?? "GET";
|
|
1170
|
+
const contentType = meta.headers["content-type"] || meta.headers["Content-Type"] || "";
|
|
1171
|
+
const resourceType = req?.resourceType ?? meta.type;
|
|
1172
|
+
const requestHeaders = req?.headers ?? {};
|
|
1173
|
+
let requestBody = void 0;
|
|
1174
|
+
const isPostLike = ["POST", "PATCH", "PUT"].includes(method);
|
|
1175
|
+
if (isPostLike && requestHeaders["content-type"]?.includes("application/json")) {
|
|
1176
|
+
const postData = req?.postData;
|
|
1177
|
+
if (postData) {
|
|
1178
|
+
try {
|
|
1179
|
+
requestBody = JSON.parse(postData);
|
|
1180
|
+
} catch {
|
|
1181
|
+
requestBody = postData;
|
|
1182
|
+
}
|
|
1183
|
+
}
|
|
1184
|
+
}
|
|
1185
|
+
let responseBody = void 0;
|
|
1186
|
+
let size = 0;
|
|
1187
|
+
const isJsonish = contentType.includes("json") || contentType.includes("javascript") || contentType.includes("text/");
|
|
1188
|
+
if (isJsonish) {
|
|
1189
|
+
try {
|
|
1190
|
+
const bodyResult = await xbPage._cdpSend(
|
|
1191
|
+
"Network.getResponseBody",
|
|
1192
|
+
{ requestId: p.requestId }
|
|
1193
|
+
);
|
|
1194
|
+
const text = bodyResult.body ?? "";
|
|
1195
|
+
size = text.length;
|
|
1196
|
+
if (size <= 10240) {
|
|
1197
|
+
try {
|
|
1198
|
+
responseBody = JSON.parse(text);
|
|
1199
|
+
} catch {
|
|
1200
|
+
responseBody = text.slice(0, 200);
|
|
1201
|
+
}
|
|
1202
|
+
}
|
|
1203
|
+
} catch {
|
|
1204
|
+
}
|
|
1205
|
+
} else {
|
|
1206
|
+
try {
|
|
1207
|
+
const bodyResult = await xbPage._cdpSend(
|
|
1208
|
+
"Network.getResponseBody",
|
|
1209
|
+
{ requestId: p.requestId }
|
|
1210
|
+
);
|
|
1211
|
+
size = bodyResult.body?.length ?? 0;
|
|
1212
|
+
} catch {
|
|
1213
|
+
size = 0;
|
|
1214
|
+
}
|
|
1215
|
+
}
|
|
1216
|
+
networkStore.add(sessionName, {
|
|
1217
|
+
timestamp: Date.now(),
|
|
1218
|
+
method,
|
|
1219
|
+
url: meta.url,
|
|
1220
|
+
path: new URL(meta.url).pathname,
|
|
1221
|
+
status: meta.status,
|
|
1222
|
+
contentType,
|
|
1223
|
+
size,
|
|
1224
|
+
headers: meta.headers,
|
|
1225
|
+
body: responseBody,
|
|
1226
|
+
requestHeaders,
|
|
1227
|
+
requestBody,
|
|
1228
|
+
resourceType
|
|
1229
|
+
});
|
|
1230
|
+
requestData.delete(p.requestId);
|
|
1231
|
+
responseMeta.delete(p.requestId);
|
|
1232
|
+
} catch {
|
|
1233
|
+
}
|
|
1234
|
+
});
|
|
1235
|
+
}
|
|
1236
|
+
async function createSession(name, url, options) {
|
|
1237
|
+
return createSessionImpl(name, url, options, {
|
|
1238
|
+
closeSessionByName,
|
|
1239
|
+
installNetworkCapture,
|
|
1240
|
+
registerSession,
|
|
1241
|
+
logSessionEvent: logSessionEvent2,
|
|
1242
|
+
getCDPTargets
|
|
1243
|
+
});
|
|
1244
|
+
}
|
|
1201
1245
|
async function closeSessionByName(name) {
|
|
1202
1246
|
for (const session of sessions) {
|
|
1203
1247
|
if (session.name === name || session.id === name) {
|
|
1204
|
-
|
|
1248
|
+
logSessionEvent2("close_session", `name="${session.name}" id="${session.id}" url="${session.page.url()}"`);
|
|
1205
1249
|
if (session.isCDP) {
|
|
1206
1250
|
if (session.browser) {
|
|
1207
1251
|
await session.browser.close().catch(() => {
|
|
@@ -1217,7 +1261,7 @@ async function closeSessionByName(name) {
|
|
|
1217
1261
|
sessions.removeById(session.id);
|
|
1218
1262
|
const file2 = sessionFile(session.name);
|
|
1219
1263
|
try {
|
|
1220
|
-
|
|
1264
|
+
unlinkSync2(file2);
|
|
1221
1265
|
} catch {
|
|
1222
1266
|
}
|
|
1223
1267
|
try {
|
|
@@ -1227,7 +1271,7 @@ async function closeSessionByName(name) {
|
|
|
1227
1271
|
} catch {
|
|
1228
1272
|
}
|
|
1229
1273
|
try {
|
|
1230
|
-
const { SessionRecorder } = await import("./session-recorder-
|
|
1274
|
+
const { SessionRecorder } = await import("./session-recorder-DF2YGH2E.js");
|
|
1231
1275
|
SessionRecorder.cleanup(session.name);
|
|
1232
1276
|
} catch {
|
|
1233
1277
|
}
|
|
@@ -1236,14 +1280,14 @@ async function closeSessionByName(name) {
|
|
|
1236
1280
|
}
|
|
1237
1281
|
const file = sessionFile(name);
|
|
1238
1282
|
try {
|
|
1239
|
-
|
|
1283
|
+
unlinkSync2(file);
|
|
1240
1284
|
} catch {
|
|
1241
1285
|
}
|
|
1242
1286
|
return false;
|
|
1243
1287
|
}
|
|
1244
1288
|
async function closeAllSessions() {
|
|
1245
1289
|
const names = sessions.list().map((s) => `${s.name}(${s.page.url()})`).join(", ");
|
|
1246
|
-
if (names)
|
|
1290
|
+
if (names) logSessionEvent2("close_all_sessions", `Closing ${sessions.size} sessions: ${names}`);
|
|
1247
1291
|
for (const session of sessions.list()) {
|
|
1248
1292
|
try {
|
|
1249
1293
|
if (session.isCDP) {
|
|
@@ -1265,38 +1309,37 @@ async function closeAllSessions() {
|
|
|
1265
1309
|
}
|
|
1266
1310
|
}
|
|
1267
1311
|
async function destroyBrowser() {
|
|
1268
|
-
|
|
1269
|
-
if (idleTimer) {
|
|
1270
|
-
clearTimeout(idleTimer);
|
|
1271
|
-
idleTimer = null;
|
|
1312
|
+
logSessionEvent2("destroy_browser", `Sessions count: ${sessions.size}. Clearing idle timer and closing all sessions.`);
|
|
1313
|
+
if (sharedState.idleTimer) {
|
|
1314
|
+
clearTimeout(sharedState.idleTimer);
|
|
1315
|
+
sharedState.idleTimer = null;
|
|
1272
1316
|
}
|
|
1273
1317
|
await closeAllSessions();
|
|
1274
|
-
if (
|
|
1275
|
-
await
|
|
1318
|
+
if (sharedState.browser) {
|
|
1319
|
+
await sharedState.browser.close().catch(() => {
|
|
1276
1320
|
});
|
|
1277
|
-
|
|
1321
|
+
sharedState.browser = null;
|
|
1278
1322
|
}
|
|
1279
|
-
if (
|
|
1280
|
-
await
|
|
1323
|
+
if (getSharedCdpProxy()) {
|
|
1324
|
+
await getSharedCdpProxy().stop().catch(() => {
|
|
1281
1325
|
});
|
|
1282
|
-
|
|
1326
|
+
setSharedCdpProxy(null);
|
|
1283
1327
|
}
|
|
1284
1328
|
}
|
|
1285
1329
|
function resetForTesting() {
|
|
1286
1330
|
sessions.clear();
|
|
1287
|
-
|
|
1288
|
-
|
|
1331
|
+
sharedState.browser = null;
|
|
1332
|
+
sharedState.idleTimer = null;
|
|
1333
|
+
setSharedCdpProxy(null);
|
|
1289
1334
|
try {
|
|
1290
|
-
for (const
|
|
1291
|
-
unlinkSync(join(SESSION_DIR, f));
|
|
1292
|
-
}
|
|
1335
|
+
for (const file of readdirSync2(SESSION_DIR)) unlinkSync2(join2(SESSION_DIR, file));
|
|
1293
1336
|
} catch {
|
|
1294
1337
|
}
|
|
1295
1338
|
}
|
|
1296
1339
|
async function ensureProcessCanExit() {
|
|
1297
|
-
if (idleTimer) {
|
|
1298
|
-
clearTimeout(idleTimer);
|
|
1299
|
-
idleTimer = null;
|
|
1340
|
+
if (sharedState.idleTimer) {
|
|
1341
|
+
clearTimeout(sharedState.idleTimer);
|
|
1342
|
+
sharedState.idleTimer = null;
|
|
1300
1343
|
}
|
|
1301
1344
|
for (const session of sessions.list()) {
|
|
1302
1345
|
if (session.browser) {
|
|
@@ -1308,35 +1351,36 @@ async function ensureProcessCanExit() {
|
|
|
1308
1351
|
}
|
|
1309
1352
|
}
|
|
1310
1353
|
sessions.clear();
|
|
1311
|
-
if (
|
|
1312
|
-
await
|
|
1354
|
+
if (sharedState.browser) {
|
|
1355
|
+
await sharedState.browser.close().catch(() => {
|
|
1313
1356
|
});
|
|
1314
|
-
|
|
1357
|
+
sharedState.browser = null;
|
|
1315
1358
|
}
|
|
1316
|
-
if (
|
|
1317
|
-
await
|
|
1359
|
+
if (getSharedCdpProxy()) {
|
|
1360
|
+
await getSharedCdpProxy().stop().catch(() => {
|
|
1318
1361
|
});
|
|
1319
|
-
|
|
1362
|
+
setSharedCdpProxy(null);
|
|
1320
1363
|
}
|
|
1321
1364
|
}
|
|
1322
1365
|
|
|
1323
1366
|
export {
|
|
1324
1367
|
resolveCDPEndpoint,
|
|
1325
|
-
touchSession,
|
|
1326
1368
|
findTargetPage,
|
|
1327
1369
|
resolveLaunchOpts,
|
|
1328
1370
|
createBrowser,
|
|
1329
|
-
getBrowser,
|
|
1330
|
-
findSession,
|
|
1331
|
-
getSessionById,
|
|
1332
|
-
setActivePage,
|
|
1333
1371
|
saveSessionDiskMeta,
|
|
1334
1372
|
readSessionDiskMeta,
|
|
1335
1373
|
deleteSessionDiskMeta,
|
|
1336
|
-
|
|
1374
|
+
resetIdleTimer,
|
|
1375
|
+
findOrRestoreSession2 as findOrRestoreSession,
|
|
1376
|
+
touchSession,
|
|
1377
|
+
getBrowser,
|
|
1378
|
+
findSession,
|
|
1379
|
+
getSessionById2 as getSessionById,
|
|
1380
|
+
setActivePage2 as setActivePage,
|
|
1337
1381
|
createEphemeralContext,
|
|
1338
1382
|
closeEphemeralContext,
|
|
1339
|
-
getAllSessions,
|
|
1383
|
+
getAllSessions2 as getAllSessions,
|
|
1340
1384
|
createSession,
|
|
1341
1385
|
closeSessionByName,
|
|
1342
1386
|
closeAllSessions,
|