@webcrawl/mcp 1.4.3 → 1.4.5

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.
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Minimal Chrome DevTools Protocol client for local JS rendering.
3
+ *
4
+ * Drive a real Chrome over CDP instead of dump-dom, wait until the DOM is
5
+ * actually ready, and always bound the session with a hard timeout. No
6
+ * puppeteer/playwright dependency.
7
+ */
8
+ import { spawn } from "node:child_process";
9
+ import { type ChromeHeadlessMode } from "./chrome-launch.js";
10
+ /** Chrome spawned but CDP never became ready. `hung` is true when the process was still alive. */
11
+ export declare class ChromeConnectError extends Error {
12
+ readonly hung: boolean;
13
+ constructor(message: string, hung?: boolean);
14
+ }
15
+ export interface CdpSnapshot {
16
+ html: string;
17
+ title: string;
18
+ textLen: number;
19
+ readyState: string;
20
+ }
21
+ export interface CdpRenderOptions {
22
+ timeoutMs: number;
23
+ /** CDP launch/connect budget. Defaults to 4s (`WEBCRAWL_CHROME_CONNECT_TIMEOUT_MS`). */
24
+ connectTimeoutMs?: number;
25
+ headless: ChromeHeadlessMode;
26
+ /** Injected for tests. */
27
+ spawnChrome?: typeof spawn;
28
+ }
29
+ export declare function renderUrlViaCdp(chromePath: string, url: string, opts: CdpRenderOptions): Promise<CdpSnapshot>;
@@ -0,0 +1,339 @@
1
+ /**
2
+ * Minimal Chrome DevTools Protocol client for local JS rendering.
3
+ *
4
+ * Drive a real Chrome over CDP instead of dump-dom, wait until the DOM is
5
+ * actually ready, and always bound the session with a hard timeout. No
6
+ * puppeteer/playwright dependency.
7
+ */
8
+ import { spawn } from "node:child_process";
9
+ import { mkdtempSync, rmSync } from "node:fs";
10
+ import { tmpdir } from "node:os";
11
+ import { join } from "node:path";
12
+ import { chromeCdpArgs, killProcessGroup, resolveChromeConnectTimeoutMs, } from "./chrome-launch.js";
13
+ /** Chrome spawned but CDP never became ready. `hung` is true when the process was still alive. */
14
+ export class ChromeConnectError extends Error {
15
+ hung;
16
+ constructor(message, hung = false) {
17
+ super(message);
18
+ this.name = "ChromeConnectError";
19
+ this.hung = hung;
20
+ }
21
+ }
22
+ const SNAPSHOT_JS = `(() => {
23
+ const body = document.body;
24
+ const text = body && typeof body.innerText === "string" ? body.innerText.trim() : "";
25
+ return {
26
+ html: document.documentElement ? document.documentElement.outerHTML : "",
27
+ title: document.title || "",
28
+ textLen: text.length,
29
+ readyState: document.readyState || "",
30
+ };
31
+ })()`;
32
+ /** mutationIdle (200ms quiet) plus readyState complete, capped. */
33
+ const WAIT_FOR_CONTENT_JS = `(async () => {
34
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
35
+ const snap = () => {
36
+ const body = document.body;
37
+ const text = body && typeof body.innerText === "string" ? body.innerText.trim() : "";
38
+ return {
39
+ html: document.documentElement ? document.documentElement.outerHTML : "",
40
+ title: document.title || "",
41
+ textLen: text.length,
42
+ readyState: document.readyState || "",
43
+ elemCount: document.getElementsByTagName("*").length,
44
+ };
45
+ };
46
+ let lastMut = Date.now();
47
+ let observer = null;
48
+ try {
49
+ observer = new MutationObserver(() => { lastMut = Date.now(); });
50
+ if (document.documentElement) {
51
+ observer.observe(document.documentElement, {
52
+ subtree: true,
53
+ childList: true,
54
+ characterData: true,
55
+ });
56
+ }
57
+ } catch (_) { /* ignore */ }
58
+ const start = Date.now();
59
+ let last = snap();
60
+ while (Date.now() - start < 2500) {
61
+ await sleep(150);
62
+ const now = snap();
63
+ const quiet = Date.now() - lastMut >= 200;
64
+ const grown = now.elemCount > last.elemCount + 2 || now.textLen > last.textLen + 20;
65
+ last = now;
66
+ if (
67
+ now.readyState === "complete" &&
68
+ now.textLen >= 80 &&
69
+ quiet &&
70
+ !grown
71
+ ) break;
72
+ }
73
+ try { observer && observer.disconnect(); } catch (_) { /* ignore */ }
74
+ return last;
75
+ })()`;
76
+ function childStillRunning(child) {
77
+ return Boolean(child && child.pid && child.exitCode == null && !child.killed);
78
+ }
79
+ export async function renderUrlViaCdp(chromePath, url, opts) {
80
+ const timeoutMs = Math.max(1_500, opts.timeoutMs);
81
+ const connectTimeoutMs = resolveChromeConnectTimeoutMs(opts.connectTimeoutMs);
82
+ const profile = mkdtempSync(join(tmpdir(), "wc-cdp-"));
83
+ const port = 40000 + Math.floor(Math.random() * 20000);
84
+ const spawnFn = opts.spawnChrome ?? spawn;
85
+ const args = chromeCdpArgs({
86
+ port,
87
+ profile,
88
+ headless: opts.headless,
89
+ binaryPath: chromePath,
90
+ });
91
+ let child;
92
+ let cdpReady = false;
93
+ const ac = new AbortController();
94
+ // Page budget covers navigation after connect; connect has its own deadline.
95
+ const timer = setTimeout(() => ac.abort(), timeoutMs);
96
+ try {
97
+ child = spawnFn(chromePath, args, {
98
+ stdio: ["ignore", "ignore", "pipe"],
99
+ detached: true,
100
+ });
101
+ if (!child.pid) {
102
+ throw new Error("Chrome failed to start (no pid)");
103
+ }
104
+ child.once("exit", () => {
105
+ if (!cdpReady && !ac.signal.aborted)
106
+ ac.abort();
107
+ });
108
+ const wsUrl = await waitForPageWebSocket(port, connectTimeoutMs, ac.signal);
109
+ cdpReady = true;
110
+ const snapshot = await withCdpSession(wsUrl, url, timeoutMs, ac.signal);
111
+ if (!snapshot.html || snapshot.html.length < 40) {
112
+ throw new Error("CDP returned empty HTML");
113
+ }
114
+ return snapshot;
115
+ }
116
+ catch (err) {
117
+ if (!cdpReady) {
118
+ const hung = childStillRunning(child);
119
+ const detail = err instanceof Error ? err.message : String(err);
120
+ throw new ChromeConnectError(hung
121
+ ? `Chrome did not respond over CDP within ${connectTimeoutMs}ms`
122
+ : `Chrome CDP failed to start (${detail})`, hung);
123
+ }
124
+ if (ac.signal.aborted) {
125
+ throw new Error(`CDP timed out after ${timeoutMs}ms`);
126
+ }
127
+ throw err;
128
+ }
129
+ finally {
130
+ clearTimeout(timer);
131
+ if (child?.pid)
132
+ killProcessGroup(child.pid, child);
133
+ try {
134
+ rmSync(profile, { recursive: true, force: true });
135
+ }
136
+ catch {
137
+ /* leftover profile is in /tmp */
138
+ }
139
+ }
140
+ }
141
+ async function waitForPageWebSocket(port, connectTimeoutMs, signal) {
142
+ const deadline = Date.now() + connectTimeoutMs;
143
+ let lastErr = "CDP HTTP endpoint never became ready";
144
+ while (Date.now() < deadline) {
145
+ if (signal.aborted)
146
+ throw new Error("Chrome CDP timed out while starting");
147
+ try {
148
+ const res = await fetch(`http://127.0.0.1:${port}/json/list`, {
149
+ signal: AbortSignal.timeout(400),
150
+ });
151
+ if (res.ok) {
152
+ const json = (await res.json());
153
+ const page = (Array.isArray(json) ? json : []).find((t) => t.webSocketDebuggerUrl && (t.type === "page" || !t.type));
154
+ if (page?.webSocketDebuggerUrl)
155
+ return page.webSocketDebuggerUrl;
156
+ lastErr = "CDP /json/list had no page websocket";
157
+ }
158
+ else {
159
+ lastErr = `CDP /json/list HTTP ${res.status}`;
160
+ }
161
+ }
162
+ catch (err) {
163
+ lastErr = err instanceof Error ? err.message : String(err);
164
+ }
165
+ await delay(80, signal);
166
+ }
167
+ throw new Error(lastErr);
168
+ }
169
+ async function withCdpSession(wsUrl, url, timeoutMs, signal) {
170
+ const client = await CdpClient.connect(wsUrl, signal);
171
+ const onAbort = () => client.close();
172
+ signal.addEventListener("abort", onAbort);
173
+ try {
174
+ await client.send("Page.enable");
175
+ await client.send("Runtime.enable");
176
+ const load = client.waitForEvent("Page.loadEventFired", Math.min(timeoutMs, 12_000));
177
+ const nav = await client.send("Page.navigate", { url });
178
+ if (nav.errorText) {
179
+ throw new Error(`Page.navigate failed: ${String(nav.errorText)}`);
180
+ }
181
+ try {
182
+ await load;
183
+ }
184
+ catch {
185
+ /* take a snapshot anyway if navigation load times out */
186
+ }
187
+ let snapshot = await evaluateSnapshot(client, WAIT_FOR_CONTENT_JS);
188
+ if (!snapshot || snapshot.textLen < 40 || snapshot.html.length < 80) {
189
+ snapshot = await evaluateSnapshot(client, SNAPSHOT_JS);
190
+ }
191
+ if (!snapshot)
192
+ throw new Error("Runtime.evaluate returned no snapshot");
193
+ return snapshot;
194
+ }
195
+ finally {
196
+ signal.removeEventListener("abort", onAbort);
197
+ client.close();
198
+ }
199
+ }
200
+ async function evaluateSnapshot(client, expression) {
201
+ const result = await client.send("Runtime.evaluate", { expression, returnByValue: true, awaitPromise: true });
202
+ const value = result.result?.value;
203
+ if (!value || typeof value.html !== "string")
204
+ return null;
205
+ return {
206
+ html: value.html,
207
+ title: String(value.title ?? ""),
208
+ textLen: Number(value.textLen ?? 0),
209
+ readyState: String(value.readyState ?? ""),
210
+ };
211
+ }
212
+ class CdpClient {
213
+ ws;
214
+ nextId = 0;
215
+ pending = new Map();
216
+ eventWaiters = [];
217
+ constructor(ws) {
218
+ this.ws = ws;
219
+ ws.addEventListener("message", (ev) => {
220
+ let msg;
221
+ try {
222
+ msg = JSON.parse(String(ev.data));
223
+ }
224
+ catch {
225
+ return;
226
+ }
227
+ if (msg.id != null) {
228
+ const p = this.pending.get(msg.id);
229
+ if (p) {
230
+ this.pending.delete(msg.id);
231
+ if (msg.error) {
232
+ p.reject(new Error(msg.error.message || `CDP error ${msg.error.code ?? ""}`));
233
+ }
234
+ else {
235
+ p.resolve(msg.result ?? {});
236
+ }
237
+ }
238
+ return;
239
+ }
240
+ if (msg.method) {
241
+ for (const w of [...this.eventWaiters]) {
242
+ if (w.method === msg.method) {
243
+ this.eventWaiters = this.eventWaiters.filter((x) => x !== w);
244
+ w.resolve();
245
+ }
246
+ }
247
+ }
248
+ });
249
+ }
250
+ static connect(url, signal) {
251
+ return new Promise((resolve, reject) => {
252
+ const ws = new WebSocket(url);
253
+ const onAbort = () => {
254
+ try {
255
+ ws.close();
256
+ }
257
+ catch {
258
+ /* ignore */
259
+ }
260
+ reject(new Error("Chrome CDP websocket timed out"));
261
+ };
262
+ if (signal.aborted) {
263
+ onAbort();
264
+ return;
265
+ }
266
+ signal.addEventListener("abort", onAbort, { once: true });
267
+ ws.addEventListener("open", () => {
268
+ signal.removeEventListener("abort", onAbort);
269
+ resolve(new CdpClient(ws));
270
+ });
271
+ ws.addEventListener("error", () => {
272
+ signal.removeEventListener("abort", onAbort);
273
+ reject(new Error("Chrome CDP websocket failed"));
274
+ });
275
+ });
276
+ }
277
+ send(method, params = {}) {
278
+ const id = ++this.nextId;
279
+ return new Promise((resolve, reject) => {
280
+ this.pending.set(id, { resolve, reject });
281
+ try {
282
+ this.ws.send(JSON.stringify({ id, method, params }));
283
+ }
284
+ catch (err) {
285
+ this.pending.delete(id);
286
+ reject(err instanceof Error ? err : new Error(String(err)));
287
+ }
288
+ });
289
+ }
290
+ waitForEvent(method, timeoutMs) {
291
+ return new Promise((resolve, reject) => {
292
+ const timer = setTimeout(() => {
293
+ this.eventWaiters = this.eventWaiters.filter((w) => w !== waiter);
294
+ reject(new Error(`Timed out waiting for ${method}`));
295
+ }, timeoutMs);
296
+ const waiter = {
297
+ method,
298
+ resolve: () => {
299
+ clearTimeout(timer);
300
+ resolve();
301
+ },
302
+ reject: (err) => {
303
+ clearTimeout(timer);
304
+ reject(err);
305
+ },
306
+ };
307
+ this.eventWaiters.push(waiter);
308
+ });
309
+ }
310
+ close() {
311
+ for (const p of this.pending.values()) {
312
+ p.reject(new Error("CDP session closed"));
313
+ }
314
+ this.pending.clear();
315
+ for (const w of this.eventWaiters) {
316
+ w.reject(new Error("CDP session closed"));
317
+ }
318
+ this.eventWaiters = [];
319
+ try {
320
+ this.ws.close();
321
+ }
322
+ catch {
323
+ /* ignore */
324
+ }
325
+ }
326
+ }
327
+ function delay(ms, signal) {
328
+ return new Promise((resolve, reject) => {
329
+ if (signal.aborted) {
330
+ reject(new Error("aborted"));
331
+ return;
332
+ }
333
+ const t = setTimeout(resolve, ms);
334
+ signal.addEventListener("abort", () => {
335
+ clearTimeout(t);
336
+ reject(new Error("aborted"));
337
+ }, { once: true });
338
+ });
339
+ }
@@ -0,0 +1,49 @@
1
+ import type { ChildProcess } from "node:child_process";
2
+ export declare const DUMP_MAX_BYTES: number;
3
+ /** Page navigation + DOM-wait budget once Chrome is answering over CDP. */
4
+ export declare const DEFAULT_TIMEOUT_MS = 18000;
5
+ /**
6
+ * How long to wait for Chrome to accept CDP after spawn. Kept short and
7
+ * separate from `DEFAULT_TIMEOUT_MS` so a hung binary fails fast while a
8
+ * slow but working JS page (often ~7s) still has time to render.
9
+ */
10
+ export declare const DEFAULT_CONNECT_TIMEOUT_MS = 4000;
11
+ export declare const VIRTUAL_TIME_MS = 10000;
12
+ /** `opts.timeoutMs`, else `WEBCRAWL_CHROME_TIMEOUT_MS`, else 18s. */
13
+ export declare function resolveChromeTimeoutMs(override?: number): number;
14
+ /** `opts.connectTimeoutMs`, else `WEBCRAWL_CHROME_CONNECT_TIMEOUT_MS`, else 4s. */
15
+ export declare function resolveChromeConnectTimeoutMs(override?: number): number;
16
+ export type ChromeHeadlessMode = "new" | "old" | "shell";
17
+ export declare function killProcessGroup(pid: number | undefined, child?: Pick<ChildProcess, "kill">): void;
18
+ export declare function headlessFlag(mode: ChromeHeadlessMode, binaryPath: string): string[];
19
+ export declare function chromeCdpArgs(opts: {
20
+ port: number;
21
+ profile: string;
22
+ headless: ChromeHeadlessMode;
23
+ binaryPath?: string;
24
+ }): string[];
25
+ export declare function chromeDumpDomArgs(opts: {
26
+ profile: string;
27
+ headless: ChromeHeadlessMode;
28
+ url: string;
29
+ timeoutMs: number;
30
+ binaryPath?: string;
31
+ }): string[];
32
+ /**
33
+ * First line of Chrome's DevToolsActivePort file is the chosen port when
34
+ * `--remote-debugging-port=0`.
35
+ */
36
+ export declare function parseDevToolsActivePort(text: string): number | null;
37
+ export declare function defaultChromeInstallPaths(): string[];
38
+ /** Playwright's chrome-headless-shell, if a previous `playwright install` left it on disk. */
39
+ export declare function findPlaywrightHeadlessShell(): string[];
40
+ /**
41
+ * Path to a real installed Chrome/Chromium, or null.
42
+ * Priority: WEBCRAWL_CHROME_PATH, INTERACT_CHROME_PATH, CHROME_PATH, then per-OS
43
+ * defaults (same locations `webcrawl doctor` checks). Env overrides are returned
44
+ * even if the file is missing so tests can point at a stub binary.
45
+ */
46
+ export declare function installedChromePath(): string | null;
47
+ export declare function isLocalChromeAvailable(): boolean;
48
+ /** Distinct binaries to try, env override first, then system Chrome, then headless-shell. */
49
+ export declare function discoverChromeBinaries(): string[];
@@ -0,0 +1,244 @@
1
+ /**
2
+ * Chrome process helpers shared by the CDP driver and the dump-dom fallback.
3
+ */
4
+ import { existsSync, readdirSync } from "node:fs";
5
+ import { homedir } from "node:os";
6
+ import { join } from "node:path";
7
+ export const DUMP_MAX_BYTES = 2 * 1024 * 1024;
8
+ /** Page navigation + DOM-wait budget once Chrome is answering over CDP. */
9
+ export const DEFAULT_TIMEOUT_MS = 18_000;
10
+ /**
11
+ * How long to wait for Chrome to accept CDP after spawn. Kept short and
12
+ * separate from `DEFAULT_TIMEOUT_MS` so a hung binary fails fast while a
13
+ * slow but working JS page (often ~7s) still has time to render.
14
+ */
15
+ export const DEFAULT_CONNECT_TIMEOUT_MS = 4_000;
16
+ export const VIRTUAL_TIME_MS = 10_000;
17
+ function envPositiveMs(name, fallback, min) {
18
+ const raw = process.env[name];
19
+ if (raw == null || raw.trim() === "")
20
+ return fallback;
21
+ const n = Number(raw);
22
+ if (!Number.isFinite(n) || n <= 0)
23
+ return fallback;
24
+ return Math.max(min, n);
25
+ }
26
+ /** `opts.timeoutMs`, else `WEBCRAWL_CHROME_TIMEOUT_MS`, else 18s. */
27
+ export function resolveChromeTimeoutMs(override) {
28
+ if (typeof override === "number" && Number.isFinite(override) && override > 0) {
29
+ return Math.max(1_500, override);
30
+ }
31
+ return envPositiveMs("WEBCRAWL_CHROME_TIMEOUT_MS", DEFAULT_TIMEOUT_MS, 1_500);
32
+ }
33
+ /** `opts.connectTimeoutMs`, else `WEBCRAWL_CHROME_CONNECT_TIMEOUT_MS`, else 4s. */
34
+ export function resolveChromeConnectTimeoutMs(override) {
35
+ if (typeof override === "number" && Number.isFinite(override) && override > 0) {
36
+ return Math.max(500, override);
37
+ }
38
+ return envPositiveMs("WEBCRAWL_CHROME_CONNECT_TIMEOUT_MS", DEFAULT_CONNECT_TIMEOUT_MS, 500);
39
+ }
40
+ export function killProcessGroup(pid, child) {
41
+ if (pid && pid > 0) {
42
+ try {
43
+ process.kill(-pid, "SIGKILL");
44
+ return;
45
+ }
46
+ catch {
47
+ /* process group kill is Unix-only; fall through */
48
+ }
49
+ try {
50
+ process.kill(pid, "SIGKILL");
51
+ return;
52
+ }
53
+ catch {
54
+ /* already gone */
55
+ }
56
+ }
57
+ try {
58
+ child?.kill("SIGKILL");
59
+ }
60
+ catch {
61
+ /* already gone */
62
+ }
63
+ }
64
+ const COMMON_CHROME_ARGS = [
65
+ "--no-sandbox",
66
+ "--disable-gpu",
67
+ "--disable-dev-shm-usage",
68
+ "--no-first-run",
69
+ "--no-default-browser-check",
70
+ "--disable-crash-reporter",
71
+ "--disable-breakpad",
72
+ "--disable-background-networking",
73
+ "--disable-sync",
74
+ "--disable-extensions",
75
+ "--disable-popup-blocking",
76
+ "--mute-audio",
77
+ "--hide-scrollbars",
78
+ "--disable-blink-features=AutomationControlled",
79
+ ];
80
+ export function headlessFlag(mode, binaryPath) {
81
+ const isShell = /headless[-_]?shell/i.test(binaryPath);
82
+ if (isShell || mode === "shell") {
83
+ // chrome-headless-shell is already a headless binary; --headless=new hangs
84
+ // on some Chrome 156 installs (the v1.4.3 smoke-test failure).
85
+ return ["--headless"];
86
+ }
87
+ if (mode === "old")
88
+ return ["--headless=old"];
89
+ return ["--headless=new"];
90
+ }
91
+ export function chromeCdpArgs(opts) {
92
+ return [
93
+ ...headlessFlag(opts.headless, opts.binaryPath ?? ""),
94
+ ...COMMON_CHROME_ARGS,
95
+ `--remote-debugging-port=${opts.port}`,
96
+ "--remote-debugging-address=127.0.0.1",
97
+ `--user-data-dir=${opts.profile}`,
98
+ `--window-size=1280,800`,
99
+ "about:blank",
100
+ ];
101
+ }
102
+ export function chromeDumpDomArgs(opts) {
103
+ return [
104
+ ...headlessFlag(opts.headless, opts.binaryPath ?? ""),
105
+ ...COMMON_CHROME_ARGS,
106
+ `--user-data-dir=${opts.profile}`,
107
+ `--virtual-time-budget=${VIRTUAL_TIME_MS}`,
108
+ `--timeout=${opts.timeoutMs}`,
109
+ "--dump-dom",
110
+ opts.url,
111
+ ];
112
+ }
113
+ /**
114
+ * First line of Chrome's DevToolsActivePort file is the chosen port when
115
+ * `--remote-debugging-port=0`.
116
+ */
117
+ export function parseDevToolsActivePort(text) {
118
+ const line = String(text ?? "")
119
+ .split(/\r?\n/)
120
+ .map((s) => s.trim())
121
+ .find(Boolean);
122
+ if (!line)
123
+ return null;
124
+ const port = Number(line);
125
+ return Number.isInteger(port) && port > 0 && port < 65536 ? port : null;
126
+ }
127
+ function envChromePath() {
128
+ const fromEnv = process.env.WEBCRAWL_CHROME_PATH?.trim() ||
129
+ process.env.INTERACT_CHROME_PATH?.trim() ||
130
+ process.env.CHROME_PATH?.trim();
131
+ return fromEnv || null;
132
+ }
133
+ export function defaultChromeInstallPaths() {
134
+ if (process.platform === "darwin") {
135
+ return [
136
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
137
+ `${process.env.HOME || homedir()}/Applications/Google Chrome.app/Contents/MacOS/Google Chrome`,
138
+ "/Applications/Chromium.app/Contents/MacOS/Chromium",
139
+ ];
140
+ }
141
+ if (process.platform === "win32") {
142
+ return [
143
+ `${process.env["ProgramFiles"] || "C:\\Program Files"}\\Google\\Chrome\\Application\\chrome.exe`,
144
+ `${process.env["ProgramFiles(x86)"] || "C:\\Program Files (x86)"}\\Google\\Chrome\\Application\\chrome.exe`,
145
+ ];
146
+ }
147
+ return [
148
+ "/usr/bin/google-chrome",
149
+ "/usr/bin/google-chrome-stable",
150
+ "/usr/bin/chromium-browser",
151
+ "/usr/bin/chromium",
152
+ "/snap/bin/chromium",
153
+ ];
154
+ }
155
+ /** Playwright's chrome-headless-shell, if a previous `playwright install` left it on disk. */
156
+ export function findPlaywrightHeadlessShell() {
157
+ const roots = [
158
+ process.env.PLAYWRIGHT_BROWSERS_PATH,
159
+ join(homedir(), ".cache", "ms-playwright"),
160
+ join(homedir(), "Library", "Caches", "ms-playwright"),
161
+ process.env.LOCALAPPDATA
162
+ ? join(process.env.LOCALAPPDATA, "ms-playwright")
163
+ : "",
164
+ ].filter(Boolean);
165
+ const out = [];
166
+ for (const root of roots) {
167
+ if (!existsSync(root))
168
+ continue;
169
+ let entries = [];
170
+ try {
171
+ entries = readdirSync(root);
172
+ }
173
+ catch {
174
+ continue;
175
+ }
176
+ for (const name of entries) {
177
+ if (!name.startsWith("chromium_headless_shell") && !name.startsWith("chromium-headless-shell")) {
178
+ continue;
179
+ }
180
+ const dir = join(root, name);
181
+ const candidates = [
182
+ join(dir, "chrome-headless-shell-linux64", "chrome-headless-shell"),
183
+ join(dir, "chrome-headless-shell-linux-arm64", "chrome-headless-shell"),
184
+ join(dir, "chrome-headless-shell-mac-arm64", "chrome-headless-shell"),
185
+ join(dir, "chrome-headless-shell-mac-x64", "chrome-headless-shell"),
186
+ join(dir, "chrome-headless-shell-win64", "chrome-headless-shell.exe"),
187
+ ];
188
+ for (const c of candidates) {
189
+ if (existsSync(c))
190
+ out.push(c);
191
+ }
192
+ }
193
+ }
194
+ return out;
195
+ }
196
+ /**
197
+ * Path to a real installed Chrome/Chromium, or null.
198
+ * Priority: WEBCRAWL_CHROME_PATH, INTERACT_CHROME_PATH, CHROME_PATH, then per-OS
199
+ * defaults (same locations `webcrawl doctor` checks). Env overrides are returned
200
+ * even if the file is missing so tests can point at a stub binary.
201
+ */
202
+ export function installedChromePath() {
203
+ const fromEnv = envChromePath();
204
+ if (fromEnv)
205
+ return fromEnv;
206
+ for (const p of defaultChromeInstallPaths()) {
207
+ try {
208
+ if (p && existsSync(p))
209
+ return p;
210
+ }
211
+ catch {
212
+ /* not installed here */
213
+ }
214
+ }
215
+ const shells = findPlaywrightHeadlessShell();
216
+ return shells[0] ?? null;
217
+ }
218
+ export function isLocalChromeAvailable() {
219
+ return installedChromePath() !== null;
220
+ }
221
+ /** Distinct binaries to try, env override first, then system Chrome, then headless-shell. */
222
+ export function discoverChromeBinaries() {
223
+ const seen = new Set();
224
+ const out = [];
225
+ const add = (p) => {
226
+ if (!p || seen.has(p))
227
+ return;
228
+ seen.add(p);
229
+ out.push(p);
230
+ };
231
+ add(envChromePath());
232
+ for (const p of defaultChromeInstallPaths()) {
233
+ try {
234
+ if (p && existsSync(p))
235
+ add(p);
236
+ }
237
+ catch {
238
+ /* skip */
239
+ }
240
+ }
241
+ for (const p of findPlaywrightHeadlessShell())
242
+ add(p);
243
+ return out;
244
+ }