@generativereality/browser-automation 0.6.1 → 0.7.1
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/.claude-plugin/plugin.json +1 -1
- package/README.md +23 -9
- package/dist/index.js +1434 -426
- package/package.json +7 -3
- package/scripts/windows-guest/README.md +40 -0
- package/scripts/windows-guest/cleanup.ps1 +5 -0
- package/scripts/windows-guest/rawpipe.mjs +16 -0
- package/scripts/windows-guest/run-in-session.ps1 +8 -0
- package/scripts/windows-guest/test.ps1 +59 -0
- package/skills/browser/SKILL.md +44 -28
- package/skills/browser/references/page-recipes.md +13 -22
- package/skills/browser/references/windows.md +7 -6
package/dist/index.js
CHANGED
|
@@ -1,17 +1,18 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import updateNotifier from "update-notifier";
|
|
3
3
|
import { cli, define } from "gunshi";
|
|
4
|
-
import {
|
|
4
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
5
|
+
import { accessSync, appendFileSync, chmodSync, closeSync, constants, copyFileSync, existsSync, linkSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, readlinkSync, renameSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs";
|
|
6
|
+
import { createConnection, createServer } from "node:net";
|
|
5
7
|
import { homedir, tmpdir } from "node:os";
|
|
6
8
|
import { basename, delimiter, dirname, extname, join, relative, resolve, sep } from "node:path";
|
|
7
|
-
import { accessSync, appendFileSync, constants, copyFileSync, existsSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, readlinkSync, renameSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs";
|
|
8
9
|
import { execFileSync, spawn, spawnSync } from "node:child_process";
|
|
9
10
|
import consola, { consola as consola$1 } from "consola";
|
|
10
11
|
import { fileURLToPath } from "node:url";
|
|
11
12
|
//#region package.json
|
|
12
13
|
var name = "@generativereality/browser-automation";
|
|
13
|
-
var version = "0.
|
|
14
|
-
var description = "
|
|
14
|
+
var version = "0.7.1";
|
|
15
|
+
var description = "Let many Claude Code sessions use your own signed-in Chrome at once, each in its own tab, without stealing your screen. Daemonless CLI over per-target CDP: persistent profile and extensions, no MCP server, nothing long-lived to crash.";
|
|
15
16
|
var package_default = {
|
|
16
17
|
name,
|
|
17
18
|
version,
|
|
@@ -40,7 +41,11 @@ var package_default = {
|
|
|
40
41
|
"cdp",
|
|
41
42
|
"chrome-devtools-protocol",
|
|
42
43
|
"playwright-alternative",
|
|
43
|
-
"ai-agents"
|
|
44
|
+
"ai-agents",
|
|
45
|
+
"chrome",
|
|
46
|
+
"claude-code-plugin",
|
|
47
|
+
"parallel-agents",
|
|
48
|
+
"cli"
|
|
44
49
|
],
|
|
45
50
|
author: "motin",
|
|
46
51
|
license: "MIT",
|
|
@@ -256,6 +261,78 @@ function cdpHost() {
|
|
|
256
261
|
return process.env.BROWSER_AUTOMATION_CDP || `http://localhost:${cdpPort()}`;
|
|
257
262
|
}
|
|
258
263
|
/**
|
|
264
|
+
* Pipe or port.
|
|
265
|
+
*
|
|
266
|
+
* The port is reachable by every process on the machine and has no
|
|
267
|
+
* authentication, so anything local could drive this user's signed-in browser.
|
|
268
|
+
* The pipe is not reachable at all except through the broker's socket, which
|
|
269
|
+
* lives in a 0700 directory under ~ and is itself 0600.
|
|
270
|
+
*
|
|
271
|
+
* Port stays only where somebody asked for it: `BROWSER_AUTOMATION_CDP` names one
|
|
272
|
+
* explicitly (a browser somebody else started, the test fakes). It does not
|
|
273
|
+
* apply to a login context, which is always this CLI's own Chrome, on its own
|
|
274
|
+
* broker. Windows and contexts were on the port until 0.7.0.
|
|
275
|
+
*/
|
|
276
|
+
function usesPipe() {
|
|
277
|
+
if (activeContext()) return true;
|
|
278
|
+
return !process.env.BROWSER_AUTOMATION_CDP;
|
|
279
|
+
}
|
|
280
|
+
function baseDir() {
|
|
281
|
+
return process.env.BROWSER_AUTOMATION_HOME || join(homedir(), ".browser-automation");
|
|
282
|
+
}
|
|
283
|
+
/**
|
|
284
|
+
* The broker's directory: state file, lock, broker and Chrome logs, and (macOS,
|
|
285
|
+
* Linux) the socket. 0700. A login context's is its own folder, beside its profile.
|
|
286
|
+
*/
|
|
287
|
+
function brokerDir() {
|
|
288
|
+
const ctx = activeContext();
|
|
289
|
+
return ctx ? join(contextsDir(), ctx.name) : baseDir();
|
|
290
|
+
}
|
|
291
|
+
/** The state file a broker writes once it serves: pids, profile, and where it listens. */
|
|
292
|
+
function brokerStatePath(dir = brokerDir()) {
|
|
293
|
+
return join(dir, "broker.json");
|
|
294
|
+
}
|
|
295
|
+
/**
|
|
296
|
+
* Where the broker for the active Chrome listens.
|
|
297
|
+
*
|
|
298
|
+
* macOS and Linux: a Unix socket in the broker's 0700 directory. Its path is
|
|
299
|
+
* capped at 104 bytes on macOS, and a context's folder can be longer than that
|
|
300
|
+
* allows (a 64-character name), so a long one gets a short socket in a 0700
|
|
301
|
+
* folder of its own, named after the directory it stands for.
|
|
302
|
+
*
|
|
303
|
+
* Windows: a named pipe. Named pipes have no directory to protect them, so the
|
|
304
|
+
* broker picks a random name when it starts and records it in its state file,
|
|
305
|
+
* which only this user can read. Nobody else can guess the name, so nobody can
|
|
306
|
+
* create it first and wait for us to connect, and the pipe's default ACL keeps
|
|
307
|
+
* other accounts from opening it for writing. Measured on Windows 11 ARM64
|
|
308
|
+
* (Node 22, 2026-10-27): full control for this user, SYSTEM and Administrators;
|
|
309
|
+
* Read only for Everyone and Anonymous, which drives nothing: a read-only
|
|
310
|
+
* connection cannot send the line that attaches it, and each connection is its
|
|
311
|
+
* own pipe instance. Before a broker has written its state, this is a name that
|
|
312
|
+
* answers nothing.
|
|
313
|
+
*/
|
|
314
|
+
function socketPath() {
|
|
315
|
+
if (process.env.BROWSER_AUTOMATION_SOCKET && !activeContext()) return process.env.BROWSER_AUTOMATION_SOCKET;
|
|
316
|
+
const dir = brokerDir();
|
|
317
|
+
if (process.platform === "win32") {
|
|
318
|
+
try {
|
|
319
|
+
const st = JSON.parse(readFileSync(brokerStatePath(dir), "utf8"));
|
|
320
|
+
if (typeof st.socket === "string" && st.socket.startsWith("\\\\.\\pipe\\")) return st.socket;
|
|
321
|
+
} catch {}
|
|
322
|
+
return "\\\\.\\pipe\\browser-automation-not-running";
|
|
323
|
+
}
|
|
324
|
+
const p = join(dir, "cdp.sock");
|
|
325
|
+
if (Buffer.byteLength(p) <= 100) return p;
|
|
326
|
+
return join(baseDir(), "sockets", `${createHash("sha256").update(dir).digest("hex").slice(0, 16)}.sock`);
|
|
327
|
+
}
|
|
328
|
+
/** What to call the browser we are driving, in messages. */
|
|
329
|
+
function endpointLabel() {
|
|
330
|
+
return usesPipe() ? `the browser behind ${socketPath()}` : cdpHost();
|
|
331
|
+
}
|
|
332
|
+
/** Endpoints handed around in place of webSocketDebuggerUrl when on the pipe. */
|
|
333
|
+
const PIPE_BROWSER = "pipe:browser";
|
|
334
|
+
const pipePage = (targetId) => `pipe:target:${targetId}`;
|
|
335
|
+
/**
|
|
259
336
|
* Ports for login contexts, decided here like every other port. A block well
|
|
260
337
|
* above the per-user range (BASE_PORT … BASE_PORT+999), so a context can never
|
|
261
338
|
* land on another account's Chrome. The first free one not already given to a
|
|
@@ -283,7 +360,7 @@ async function allocateContextPort(taken) {
|
|
|
283
360
|
var TargetGoneError = class extends Error {
|
|
284
361
|
targetId;
|
|
285
362
|
constructor(targetId) {
|
|
286
|
-
super(`target ${targetId} not found on ${
|
|
363
|
+
super(`target ${targetId} not found on ${endpointLabel()} (tab closed or Chrome restarted)`);
|
|
287
364
|
this.targetId = targetId;
|
|
288
365
|
this.name = "TargetGoneError";
|
|
289
366
|
}
|
|
@@ -294,10 +371,23 @@ async function httpJson(path) {
|
|
|
294
371
|
return await res.json();
|
|
295
372
|
}
|
|
296
373
|
async function browserWsUrl() {
|
|
374
|
+
if (usesPipe()) return PIPE_BROWSER;
|
|
297
375
|
return (await httpJson("/json/version")).webSocketDebuggerUrl;
|
|
298
376
|
}
|
|
377
|
+
/** `Browser.getVersion`, from either transport. Throws when nothing answers. */
|
|
378
|
+
async function browserVersion(timeout = 5e3) {
|
|
379
|
+
if (!usesPipe()) return { product: (await httpJson("/json/version")).Browser };
|
|
380
|
+
return withBrowser((s) => s.send("Browser.getVersion", {}, timeout), timeout);
|
|
381
|
+
}
|
|
299
382
|
async function listTargets() {
|
|
300
|
-
return httpJson("/json/list");
|
|
383
|
+
if (!usesPipe()) return httpJson("/json/list");
|
|
384
|
+
return (await withBrowser((s) => s.send("Target.getTargets"))).targetInfos.filter((t) => t.type !== "browser_ui" && t.type !== "browser").map((t) => ({
|
|
385
|
+
id: t.targetId,
|
|
386
|
+
type: t.type,
|
|
387
|
+
title: t.title,
|
|
388
|
+
url: t.url,
|
|
389
|
+
webSocketDebuggerUrl: pipePage(t.targetId)
|
|
390
|
+
}));
|
|
301
391
|
}
|
|
302
392
|
async function listPageTargets() {
|
|
303
393
|
return (await listTargets()).filter((t) => t.type === "page");
|
|
@@ -306,8 +396,10 @@ async function listPageTargets() {
|
|
|
306
396
|
async function targetWsUrl(targetId) {
|
|
307
397
|
return (await listTargets()).find((t) => t.id === targetId)?.webSocketDebuggerUrl ?? null;
|
|
308
398
|
}
|
|
309
|
-
/** Open a CDP session to an arbitrary webSocketDebuggerUrl (page or browser)
|
|
399
|
+
/** Open a CDP session to an arbitrary webSocketDebuggerUrl (page or browser), or
|
|
400
|
+
* to a `pipe:` endpoint from this module, which goes through the broker. */
|
|
310
401
|
function connect(wsUrl, { timeout = 15e3 } = {}) {
|
|
402
|
+
if (wsUrl.startsWith("pipe:")) return connectPipe(wsUrl, timeout);
|
|
311
403
|
return new Promise((resolve, reject) => {
|
|
312
404
|
const ws = new WebSocket(wsUrl);
|
|
313
405
|
let nextId = 1;
|
|
@@ -378,6 +470,109 @@ function connect(wsUrl, { timeout = 15e3 } = {}) {
|
|
|
378
470
|
});
|
|
379
471
|
});
|
|
380
472
|
}
|
|
473
|
+
/**
|
|
474
|
+
* One connection to the broker, bound to one target (or to the browser).
|
|
475
|
+
*
|
|
476
|
+
* The broker speaks CDP's own JSON, one message per line, after a one-line
|
|
477
|
+
* handshake naming what to attach to. It answers the handshake once the session
|
|
478
|
+
* exists, so a tab that has gone fails here, as a closed tab's WebSocket would.
|
|
479
|
+
*/
|
|
480
|
+
function connectPipe(endpoint, timeout) {
|
|
481
|
+
const attach = endpoint === PIPE_BROWSER ? { attach: "browser" } : {
|
|
482
|
+
attach: "target",
|
|
483
|
+
targetId: endpoint.slice(12)
|
|
484
|
+
};
|
|
485
|
+
return new Promise((resolve, reject) => {
|
|
486
|
+
const sock = createConnection(socketPath());
|
|
487
|
+
let nextId = 1;
|
|
488
|
+
let ready = false;
|
|
489
|
+
let buf = "";
|
|
490
|
+
const pending = /* @__PURE__ */ new Map();
|
|
491
|
+
const listeners = /* @__PURE__ */ new Map();
|
|
492
|
+
const fail = (e) => {
|
|
493
|
+
for (const p of pending.values()) p.reject(e);
|
|
494
|
+
pending.clear();
|
|
495
|
+
};
|
|
496
|
+
const openTimer = setTimeout(() => {
|
|
497
|
+
sock.destroy();
|
|
498
|
+
reject(/* @__PURE__ */ new Error(`CDP connect timeout ${timeout}ms to ${socketPath()}`));
|
|
499
|
+
}, timeout);
|
|
500
|
+
sock.setEncoding("utf8");
|
|
501
|
+
sock.on("connect", () => sock.write(JSON.stringify(attach) + "\n"));
|
|
502
|
+
sock.on("data", (chunk) => {
|
|
503
|
+
buf += chunk;
|
|
504
|
+
let nl;
|
|
505
|
+
while ((nl = buf.indexOf("\n")) >= 0) {
|
|
506
|
+
const line = buf.slice(0, nl);
|
|
507
|
+
buf = buf.slice(nl + 1);
|
|
508
|
+
let msg;
|
|
509
|
+
try {
|
|
510
|
+
msg = JSON.parse(line);
|
|
511
|
+
} catch {
|
|
512
|
+
continue;
|
|
513
|
+
}
|
|
514
|
+
if (!ready) {
|
|
515
|
+
clearTimeout(openTimer);
|
|
516
|
+
if (msg.error) {
|
|
517
|
+
sock.destroy();
|
|
518
|
+
reject(new Error(String(msg.error)));
|
|
519
|
+
return;
|
|
520
|
+
}
|
|
521
|
+
ready = true;
|
|
522
|
+
resolve(session);
|
|
523
|
+
continue;
|
|
524
|
+
}
|
|
525
|
+
if (typeof msg.id === "number" && pending.has(msg.id)) {
|
|
526
|
+
const p = pending.get(msg.id);
|
|
527
|
+
pending.delete(msg.id);
|
|
528
|
+
if (msg.error) p.reject(/* @__PURE__ */ new Error(`${p.method}: ${msg.error.message ?? JSON.stringify(msg.error)}`));
|
|
529
|
+
else p.resolve(msg.result);
|
|
530
|
+
} else if (msg.method) for (const cb of listeners.get(msg.method) ?? []) cb(msg.params);
|
|
531
|
+
}
|
|
532
|
+
});
|
|
533
|
+
sock.on("error", (e) => {
|
|
534
|
+
clearTimeout(openTimer);
|
|
535
|
+
const err = e?.code === "ENOENT" || e?.code === "ECONNREFUSED" ? /* @__PURE__ */ new Error(`no browser on ${socketPath()} — run: browser-automation launch`) : /* @__PURE__ */ new Error(`socket error on ${socketPath()}: ${e?.message ?? e}`);
|
|
536
|
+
if (!ready) reject(err);
|
|
537
|
+
fail(err);
|
|
538
|
+
});
|
|
539
|
+
sock.on("close", () => fail(/* @__PURE__ */ new Error("the browser connection closed (tab closed or Chrome quit)")));
|
|
540
|
+
const session = {
|
|
541
|
+
send(method, params = {}, timeoutMs = 3e4) {
|
|
542
|
+
return new Promise((res, rej) => {
|
|
543
|
+
const id = nextId++;
|
|
544
|
+
const t = setTimeout(() => {
|
|
545
|
+
if (pending.delete(id)) rej(/* @__PURE__ */ new Error(`CDP ${method} timed out after ${timeoutMs}ms`));
|
|
546
|
+
}, timeoutMs);
|
|
547
|
+
pending.set(id, {
|
|
548
|
+
resolve: (v) => {
|
|
549
|
+
clearTimeout(t);
|
|
550
|
+
res(v);
|
|
551
|
+
},
|
|
552
|
+
reject: (e) => {
|
|
553
|
+
clearTimeout(t);
|
|
554
|
+
rej(e);
|
|
555
|
+
},
|
|
556
|
+
method
|
|
557
|
+
});
|
|
558
|
+
sock.write(JSON.stringify({
|
|
559
|
+
id,
|
|
560
|
+
method,
|
|
561
|
+
params
|
|
562
|
+
}) + "\n");
|
|
563
|
+
});
|
|
564
|
+
},
|
|
565
|
+
on(method, cb) {
|
|
566
|
+
const arr = listeners.get(method) ?? [];
|
|
567
|
+
arr.push(cb);
|
|
568
|
+
listeners.set(method, arr);
|
|
569
|
+
},
|
|
570
|
+
close() {
|
|
571
|
+
sock.end();
|
|
572
|
+
}
|
|
573
|
+
};
|
|
574
|
+
});
|
|
575
|
+
}
|
|
381
576
|
/** Run `fn` against a session bound to a single page target, then close it. */
|
|
382
577
|
async function withPage(targetId, fn) {
|
|
383
578
|
const wsUrl = await targetWsUrl(targetId);
|
|
@@ -620,7 +815,7 @@ function resolveProfile() {
|
|
|
620
815
|
};
|
|
621
816
|
}
|
|
622
817
|
/** Is any Chrome of ours running with this --user-data-dir? */
|
|
623
|
-
function
|
|
818
|
+
function profileInUse(dir) {
|
|
624
819
|
try {
|
|
625
820
|
execFileSync("pgrep", [
|
|
626
821
|
"-u",
|
|
@@ -652,7 +847,7 @@ function migrateProfile() {
|
|
|
652
847
|
dir: legacy,
|
|
653
848
|
detail: `this process may not read ${legacy}. On macOS that is the app-data permission ("… would like to access data from other apps") for the app this is running under. Run \`browser-automation profile --migrate\` once from a terminal that can reach it, and every host will use the new location from then on.`
|
|
654
849
|
};
|
|
655
|
-
if (
|
|
850
|
+
if (profileInUse(legacy)) return {
|
|
656
851
|
outcome: "in-use",
|
|
657
852
|
dir: legacy,
|
|
658
853
|
detail: `a running Chrome has ${legacy} open, and a profile is never moved underneath one. It moves on the next launch after that Chrome quits — or now, with \`browser-automation launch --restart\`.`
|
|
@@ -763,7 +958,19 @@ const SITE_DATA = new Set([
|
|
|
763
958
|
"Device Bound Sessions",
|
|
764
959
|
"Device Bound Sessions-journal",
|
|
765
960
|
"passkey_enclave_state",
|
|
766
|
-
join("Service Worker", "CacheStorage")
|
|
961
|
+
join("Service Worker", "CacheStorage"),
|
|
962
|
+
...[
|
|
963
|
+
"Cookies",
|
|
964
|
+
"Cookies-journal",
|
|
965
|
+
"Network Persistent State",
|
|
966
|
+
"Reporting and NEL",
|
|
967
|
+
"Reporting and NEL-journal",
|
|
968
|
+
"Trust Tokens",
|
|
969
|
+
"Trust Tokens-journal",
|
|
970
|
+
"Device Bound Sessions",
|
|
971
|
+
"Device Bound Sessions-journal",
|
|
972
|
+
"SCT Auditing Pending Reports"
|
|
973
|
+
].map((f) => join("Network", f))
|
|
767
974
|
]);
|
|
768
975
|
function keep(src, root, mode) {
|
|
769
976
|
const rel = relative(root, src);
|
|
@@ -1326,199 +1533,980 @@ async function ensureRenderer(targetId, { grace, budget, allowWake = !process.en
|
|
|
1326
1533
|
};
|
|
1327
1534
|
}
|
|
1328
1535
|
//#endregion
|
|
1329
|
-
//#region src/core/
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
/** How many times we ask before we are willing to call a browser broken. */
|
|
1333
|
-
const DEFAULT_ATTEMPTS = 3;
|
|
1334
|
-
/** Breathing room between attempts — a browser mid-GC deserves a second look. */
|
|
1335
|
-
const RETRY_PAUSE = 400;
|
|
1336
|
-
/**
|
|
1337
|
-
* The verdict, from the probe and the corroborations — and from nothing else.
|
|
1338
|
-
*
|
|
1339
|
-
* Pure, and separate from the probing, because this is the decision that was
|
|
1340
|
-
* wrong: every failure used to become 'wedged' by default. Now 'wedged'
|
|
1341
|
-
* requires `rendezvous === false`, which is the only thing that has ever
|
|
1342
|
-
* actually meant it.
|
|
1343
|
-
*/
|
|
1344
|
-
function rendererVerdict(outcome, e) {
|
|
1345
|
-
if (outcome === "ok") return "healthy";
|
|
1346
|
-
if (e?.rendezvous === false) return "wedged";
|
|
1347
|
-
if (e?.rendezvous === true && (e.renderers ?? 0) > 0) return "busy";
|
|
1348
|
-
return "unknown";
|
|
1349
|
-
}
|
|
1350
|
-
/**
|
|
1351
|
-
* Create a throwaway tab, make its renderer prove it is alive, close it.
|
|
1352
|
-
*
|
|
1353
|
-
* Three things changed after 2026-09-11, and each of them is load-bearing:
|
|
1354
|
-
*
|
|
1355
|
-
* 1. It goes through `ensureRenderer`, so the probe opens its tab the way the
|
|
1356
|
-
* tool opens tabs AND gets the same wake treatment. A probe that is harsher
|
|
1357
|
-
* on itself than `goto` is on a real tab reports failures `goto` would not
|
|
1358
|
-
* have had.
|
|
1359
|
-
* 2. It retries with a doubling budget. One 5s timeout is not evidence of a
|
|
1360
|
-
* permanent condition; it is evidence of 5 seconds.
|
|
1361
|
-
* 3. It stops early when the Mach name is ABSENT — the one state where more
|
|
1362
|
-
* waiting is genuinely pointless — so the real failure is still reported
|
|
1363
|
-
* fast while a slow browser gets the benefit of the doubt.
|
|
1364
|
-
*/
|
|
1365
|
-
async function probeRenderer({ timeout, attempts } = {}) {
|
|
1366
|
-
const base = timeout ?? envInt("BROWSER_AUTOMATION_PROBE_TIMEOUT", DEFAULT_TIMEOUT);
|
|
1367
|
-
const maxAttempts = Math.max(1, attempts ?? envInt("BROWSER_AUTOMATION_PROBE_ATTEMPTS", DEFAULT_ATTEMPTS));
|
|
1368
|
-
const started = Date.now();
|
|
1369
|
-
let pageTargets = 0;
|
|
1370
|
-
try {
|
|
1371
|
-
pageTargets = (await listPageTargets()).length;
|
|
1372
|
-
} catch {}
|
|
1373
|
-
const tries = [];
|
|
1374
|
-
let evidence;
|
|
1375
|
-
for (let i = 0; i < maxAttempts; i++) {
|
|
1376
|
-
const budget = base * 2 ** i;
|
|
1377
|
-
tries.push(await probeOnce(budget));
|
|
1378
|
-
if (tries[tries.length - 1].outcome === "ok") return finish({
|
|
1379
|
-
ok: true,
|
|
1380
|
-
started,
|
|
1381
|
-
pageTargets,
|
|
1382
|
-
tries,
|
|
1383
|
-
evidence
|
|
1384
|
-
});
|
|
1385
|
-
evidence ??= gatherEvidence();
|
|
1386
|
-
if (evidence.rendezvous === false) break;
|
|
1387
|
-
if (i + 1 < maxAttempts) await new Promise((r) => setTimeout(r, RETRY_PAUSE));
|
|
1388
|
-
}
|
|
1389
|
-
return finish({
|
|
1390
|
-
ok: false,
|
|
1391
|
-
started,
|
|
1392
|
-
pageTargets,
|
|
1393
|
-
tries,
|
|
1394
|
-
evidence
|
|
1395
|
-
});
|
|
1536
|
+
//#region src/core/broker.ts
|
|
1537
|
+
function statePath(dir) {
|
|
1538
|
+
return join(dir, "broker.json");
|
|
1396
1539
|
}
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
ms: Date.now() - started,
|
|
1402
|
-
pageTargets,
|
|
1403
|
-
reason: last?.reason,
|
|
1404
|
-
outcome: last?.outcome ?? "error",
|
|
1405
|
-
verdict: rendererVerdict(last?.outcome ?? "error", evidence),
|
|
1406
|
-
attempts: tries,
|
|
1407
|
-
evidence
|
|
1408
|
-
};
|
|
1409
|
-
recordProbe(health);
|
|
1410
|
-
return health;
|
|
1540
|
+
const windows = process.platform === "win32";
|
|
1541
|
+
/** A named pipe nobody can predict, so nobody can create it before we do. */
|
|
1542
|
+
function windowsPipeName() {
|
|
1543
|
+
return `\\\\.\\pipe\\browser-automation-${randomUUID()}`;
|
|
1411
1544
|
}
|
|
1412
|
-
|
|
1413
|
-
async function probeOnce(budget) {
|
|
1414
|
-
const started = Date.now();
|
|
1415
|
-
let targetId;
|
|
1416
|
-
try {
|
|
1417
|
-
targetId = await createTab("about:blank", { timeout: budget });
|
|
1418
|
-
} catch (e) {
|
|
1419
|
-
return {
|
|
1420
|
-
outcome: "error",
|
|
1421
|
-
budget,
|
|
1422
|
-
ms: Date.now() - started,
|
|
1423
|
-
woke: false,
|
|
1424
|
-
reason: `could not create a target at all: ${e?.message ?? e}`
|
|
1425
|
-
};
|
|
1426
|
-
}
|
|
1545
|
+
function servedSocket(dir) {
|
|
1427
1546
|
try {
|
|
1428
|
-
|
|
1429
|
-
|
|
1430
|
-
|
|
1431
|
-
});
|
|
1432
|
-
return {
|
|
1433
|
-
outcome: r.outcome,
|
|
1434
|
-
budget,
|
|
1435
|
-
ms: Date.now() - started,
|
|
1436
|
-
woke: r.woke,
|
|
1437
|
-
reason: r.reason
|
|
1438
|
-
};
|
|
1439
|
-
} finally {
|
|
1440
|
-
if (targetId) await closeTab(targetId).catch(() => {});
|
|
1547
|
+
return JSON.parse(readFileSync(statePath(dir), "utf8")).socket ?? null;
|
|
1548
|
+
} catch {
|
|
1549
|
+
return null;
|
|
1441
1550
|
}
|
|
1442
1551
|
}
|
|
1443
|
-
/**
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1552
|
+
/** The flags Chrome is started with. The profile flag is also how `ps` finds it. */
|
|
1553
|
+
function chromeArgs(profile, extra = []) {
|
|
1554
|
+
return [
|
|
1555
|
+
"--remote-debugging-pipe",
|
|
1556
|
+
`--user-data-dir=${profile}`,
|
|
1557
|
+
"--no-first-run",
|
|
1558
|
+
"--no-default-browser-check",
|
|
1559
|
+
...extra,
|
|
1560
|
+
"about:blank"
|
|
1561
|
+
];
|
|
1453
1562
|
}
|
|
1454
|
-
/**
|
|
1455
|
-
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
|
|
1465
|
-
|
|
1466
|
-
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
|
|
1470
|
-
|
|
1471
|
-
|
|
1563
|
+
/** Does something answer on this socket? Connect-and-close; no CDP. */
|
|
1564
|
+
function socketAnswers(socket, timeout = 1e3) {
|
|
1565
|
+
return new Promise((resolve) => {
|
|
1566
|
+
const s = createConnection(socket);
|
|
1567
|
+
const t = setTimeout(() => {
|
|
1568
|
+
s.destroy();
|
|
1569
|
+
resolve(false);
|
|
1570
|
+
}, timeout);
|
|
1571
|
+
s.on("connect", () => {
|
|
1572
|
+
clearTimeout(t);
|
|
1573
|
+
s.destroy();
|
|
1574
|
+
resolve(true);
|
|
1575
|
+
});
|
|
1576
|
+
s.on("error", () => {
|
|
1577
|
+
clearTimeout(t);
|
|
1578
|
+
resolve(false);
|
|
1579
|
+
});
|
|
1580
|
+
});
|
|
1472
1581
|
}
|
|
1582
|
+
const alive$2 = (pid) => {
|
|
1583
|
+
try {
|
|
1584
|
+
process.kill(pid, 0);
|
|
1585
|
+
return true;
|
|
1586
|
+
} catch {
|
|
1587
|
+
return false;
|
|
1588
|
+
}
|
|
1589
|
+
};
|
|
1473
1590
|
/**
|
|
1474
|
-
*
|
|
1475
|
-
*
|
|
1476
|
-
*
|
|
1477
|
-
*
|
|
1478
|
-
*
|
|
1591
|
+
* Become the one broker for this directory, or learn that another one is. Two
|
|
1592
|
+
* `launch` runs at once (two tabs both finding no browser) each start a broker,
|
|
1593
|
+
* and before either listens, the socket check below passes for both: both then
|
|
1594
|
+
* spawn Chrome on the same profile, one Chrome hands off to the other through
|
|
1595
|
+
* the profile lock and exits, and one broker's listen fails. An O_EXCL pid file
|
|
1596
|
+
* taken before Chrome is spawned leaves exactly one. A lock whose pid is gone
|
|
1597
|
+
* was left by a broker that died, and is taken over.
|
|
1479
1598
|
*
|
|
1480
|
-
* The
|
|
1481
|
-
*
|
|
1482
|
-
*
|
|
1483
|
-
*
|
|
1484
|
-
* been reported as the browser pid, and its absent Mach name read as the
|
|
1485
|
-
* permanent failure. Seen while writing this: a `ugrep` for the flag sat in
|
|
1486
|
-
* `ps` output alongside the real Chrome.
|
|
1599
|
+
* The pid is written to a file of our own first and linked into place, so the
|
|
1600
|
+
* lock never exists without it. Created empty and written after, a broker that
|
|
1601
|
+
* read it in between found no pid, took it for a dead broker's, and took the
|
|
1602
|
+
* lock as well: two brokers, and the second one's listen failed.
|
|
1487
1603
|
*/
|
|
1488
|
-
function
|
|
1489
|
-
const
|
|
1490
|
-
|
|
1491
|
-
let out;
|
|
1604
|
+
function takeLock(lock) {
|
|
1605
|
+
const mine = `${lock}.${process.pid}`;
|
|
1606
|
+
writeFileSync(mine, `${process.pid}\n`, { mode: 384 });
|
|
1492
1607
|
try {
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
|
|
1608
|
+
for (let attempt = 0; attempt < 2; attempt++) try {
|
|
1609
|
+
linkSync(mine, lock);
|
|
1610
|
+
return true;
|
|
1611
|
+
} catch (e) {
|
|
1612
|
+
if (e.code !== "EEXIST") throw e;
|
|
1613
|
+
let pid = NaN;
|
|
1614
|
+
try {
|
|
1615
|
+
pid = Number.parseInt(readFileSync(lock, "utf8"), 10);
|
|
1616
|
+
} catch (r) {
|
|
1617
|
+
if (r.code !== "ENOENT") throw r;
|
|
1618
|
+
}
|
|
1619
|
+
if (Number.isInteger(pid) && pid > 0 && alive$2(pid)) return false;
|
|
1620
|
+
rmSync(lock, { force: true });
|
|
1621
|
+
}
|
|
1622
|
+
return false;
|
|
1623
|
+
} finally {
|
|
1624
|
+
rmSync(mine, { force: true });
|
|
1625
|
+
}
|
|
1626
|
+
}
|
|
1627
|
+
const sleep$5 = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
1628
|
+
async function runBroker(o) {
|
|
1629
|
+
process.umask(63);
|
|
1630
|
+
const dir = o.dir;
|
|
1631
|
+
for (const d of windows ? [dir] : [dir, dirname(o.socket)]) {
|
|
1632
|
+
mkdirSync(d, {
|
|
1633
|
+
recursive: true,
|
|
1634
|
+
mode: 448
|
|
1501
1635
|
});
|
|
1502
|
-
|
|
1503
|
-
return {
|
|
1504
|
-
browser: null,
|
|
1505
|
-
renderers: null
|
|
1506
|
-
};
|
|
1636
|
+
chmodSync(d, 448);
|
|
1507
1637
|
}
|
|
1508
|
-
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
|
|
1516
|
-
if (/--type=renderer\b/.test(cmd)) renderers++;
|
|
1517
|
-
else if (!cmd.includes("--type=")) browser = Number(pid);
|
|
1638
|
+
const lock = join(dir, "broker.lock");
|
|
1639
|
+
if (!takeLock(lock)) {
|
|
1640
|
+
for (let i = 0; i < 240; i++) {
|
|
1641
|
+
const theirs = windows ? servedSocket(dir) : o.socket;
|
|
1642
|
+
if (theirs && await socketAnswers(theirs)) return;
|
|
1643
|
+
await sleep$5(250);
|
|
1644
|
+
}
|
|
1645
|
+
throw new Error(`another broker holds ${lock}, but nothing answered on ${o.socket} within 60s`);
|
|
1518
1646
|
}
|
|
1519
|
-
|
|
1520
|
-
|
|
1521
|
-
|
|
1647
|
+
const releaseLock = () => {
|
|
1648
|
+
try {
|
|
1649
|
+
if (readFileSync(lock, "utf8").trim() === String(process.pid)) rmSync(lock, { force: true });
|
|
1650
|
+
} catch {}
|
|
1651
|
+
};
|
|
1652
|
+
try {
|
|
1653
|
+
await serve(o, releaseLock);
|
|
1654
|
+
} finally {
|
|
1655
|
+
releaseLock();
|
|
1656
|
+
}
|
|
1657
|
+
}
|
|
1658
|
+
async function serve(o, releaseLock) {
|
|
1659
|
+
const dir = o.dir;
|
|
1660
|
+
if (!windows && existsSync(o.socket)) {
|
|
1661
|
+
if (await socketAnswers(o.socket)) throw new Error(`a broker is already serving ${o.socket}`);
|
|
1662
|
+
rmSync(o.socket, { force: true });
|
|
1663
|
+
}
|
|
1664
|
+
const logFd = openSync(o.log, "a", 384);
|
|
1665
|
+
const chrome = spawn(o.chrome, chromeArgs(o.profile, o.extraArgs), { stdio: [
|
|
1666
|
+
"ignore",
|
|
1667
|
+
logFd,
|
|
1668
|
+
logFd,
|
|
1669
|
+
"pipe",
|
|
1670
|
+
"pipe"
|
|
1671
|
+
] });
|
|
1672
|
+
closeSync(logFd);
|
|
1673
|
+
const toChrome = chrome.stdio[3];
|
|
1674
|
+
const fromChrome = chrome.stdio[4];
|
|
1675
|
+
let nextId = 1;
|
|
1676
|
+
const relayed = /* @__PURE__ */ new Map();
|
|
1677
|
+
const own = /* @__PURE__ */ new Map();
|
|
1678
|
+
const bySession = /* @__PURE__ */ new Map();
|
|
1679
|
+
const clients = /* @__PURE__ */ new Set();
|
|
1680
|
+
const socks = /* @__PURE__ */ new Set();
|
|
1681
|
+
const toPipe = (msg) => toChrome.write(JSON.stringify(msg) + "\0");
|
|
1682
|
+
const ask = (method, params) => new Promise((resolve) => {
|
|
1683
|
+
const id = nextId++;
|
|
1684
|
+
own.set(id, resolve);
|
|
1685
|
+
toPipe({
|
|
1686
|
+
id,
|
|
1687
|
+
method,
|
|
1688
|
+
params
|
|
1689
|
+
});
|
|
1690
|
+
});
|
|
1691
|
+
const tell = (c, msg) => {
|
|
1692
|
+
if (!c.sock.destroyed) c.sock.write(JSON.stringify(msg) + "\n");
|
|
1693
|
+
};
|
|
1694
|
+
let buf = "";
|
|
1695
|
+
fromChrome.setEncoding("utf8");
|
|
1696
|
+
fromChrome.on("data", (chunk) => {
|
|
1697
|
+
buf += chunk;
|
|
1698
|
+
let end;
|
|
1699
|
+
while ((end = buf.indexOf("\0")) >= 0) {
|
|
1700
|
+
const raw = buf.slice(0, end);
|
|
1701
|
+
buf = buf.slice(end + 1);
|
|
1702
|
+
let msg;
|
|
1703
|
+
try {
|
|
1704
|
+
msg = JSON.parse(raw);
|
|
1705
|
+
} catch {
|
|
1706
|
+
continue;
|
|
1707
|
+
}
|
|
1708
|
+
if (typeof msg.id === "number") {
|
|
1709
|
+
const mine = own.get(msg.id);
|
|
1710
|
+
if (mine) {
|
|
1711
|
+
own.delete(msg.id);
|
|
1712
|
+
mine(msg);
|
|
1713
|
+
continue;
|
|
1714
|
+
}
|
|
1715
|
+
const r = relayed.get(msg.id);
|
|
1716
|
+
if (!r) continue;
|
|
1717
|
+
relayed.delete(msg.id);
|
|
1718
|
+
const { sessionId: _drop, ...rest } = msg;
|
|
1719
|
+
tell(r.client, {
|
|
1720
|
+
...rest,
|
|
1721
|
+
id: r.id
|
|
1722
|
+
});
|
|
1723
|
+
continue;
|
|
1724
|
+
}
|
|
1725
|
+
if (msg.sessionId) {
|
|
1726
|
+
const c = bySession.get(msg.sessionId);
|
|
1727
|
+
if (c) tell(c, {
|
|
1728
|
+
method: msg.method,
|
|
1729
|
+
params: msg.params
|
|
1730
|
+
});
|
|
1731
|
+
continue;
|
|
1732
|
+
}
|
|
1733
|
+
if (msg.method === "Target.detachedFromTarget") {
|
|
1734
|
+
const c = bySession.get(msg.params?.sessionId);
|
|
1735
|
+
if (c) {
|
|
1736
|
+
bySession.delete(msg.params.sessionId);
|
|
1737
|
+
c.sessionId = null;
|
|
1738
|
+
c.sock.end();
|
|
1739
|
+
}
|
|
1740
|
+
}
|
|
1741
|
+
for (const c of clients) if (c.browser) tell(c, {
|
|
1742
|
+
method: msg.method,
|
|
1743
|
+
params: msg.params
|
|
1744
|
+
});
|
|
1745
|
+
}
|
|
1746
|
+
});
|
|
1747
|
+
const server = createServer((sock) => {
|
|
1748
|
+
socks.add(sock);
|
|
1749
|
+
sock.on("close", () => socks.delete(sock));
|
|
1750
|
+
const c = {
|
|
1751
|
+
sock,
|
|
1752
|
+
sessionId: null,
|
|
1753
|
+
browser: false
|
|
1754
|
+
};
|
|
1755
|
+
let attached = false;
|
|
1756
|
+
let pending = "";
|
|
1757
|
+
sock.setEncoding("utf8");
|
|
1758
|
+
sock.on("data", async (chunk) => {
|
|
1759
|
+
pending += chunk;
|
|
1760
|
+
let nl;
|
|
1761
|
+
while ((nl = pending.indexOf("\n")) >= 0) {
|
|
1762
|
+
const line = pending.slice(0, nl);
|
|
1763
|
+
pending = pending.slice(nl + 1);
|
|
1764
|
+
let msg;
|
|
1765
|
+
try {
|
|
1766
|
+
msg = JSON.parse(line);
|
|
1767
|
+
} catch {
|
|
1768
|
+
sock.destroy();
|
|
1769
|
+
return;
|
|
1770
|
+
}
|
|
1771
|
+
if (!attached) {
|
|
1772
|
+
attached = true;
|
|
1773
|
+
sock.pause();
|
|
1774
|
+
if (msg.attach === "browser") c.browser = true;
|
|
1775
|
+
else if (msg.attach === "target" && typeof msg.targetId === "string") {
|
|
1776
|
+
const r = await ask("Target.attachToTarget", {
|
|
1777
|
+
targetId: msg.targetId,
|
|
1778
|
+
flatten: true
|
|
1779
|
+
});
|
|
1780
|
+
if (sock.destroyed) {
|
|
1781
|
+
if (!r.error) toPipe({
|
|
1782
|
+
id: nextId++,
|
|
1783
|
+
method: "Target.detachFromTarget",
|
|
1784
|
+
params: { sessionId: r.result.sessionId }
|
|
1785
|
+
});
|
|
1786
|
+
return;
|
|
1787
|
+
}
|
|
1788
|
+
if (r.error) {
|
|
1789
|
+
tell(c, { error: `target ${msg.targetId}: ${r.error.message}` });
|
|
1790
|
+
sock.end();
|
|
1791
|
+
return;
|
|
1792
|
+
}
|
|
1793
|
+
c.sessionId = r.result.sessionId;
|
|
1794
|
+
bySession.set(c.sessionId, c);
|
|
1795
|
+
} else {
|
|
1796
|
+
tell(c, { error: "first line must be {\"attach\":\"browser\"} or {\"attach\":\"target\",\"targetId\":…}" });
|
|
1797
|
+
sock.end();
|
|
1798
|
+
return;
|
|
1799
|
+
}
|
|
1800
|
+
clients.add(c);
|
|
1801
|
+
tell(c, { attached: true });
|
|
1802
|
+
sock.resume();
|
|
1803
|
+
continue;
|
|
1804
|
+
}
|
|
1805
|
+
if (typeof msg.id !== "number" || typeof msg.method !== "string") continue;
|
|
1806
|
+
const id = nextId++;
|
|
1807
|
+
relayed.set(id, {
|
|
1808
|
+
client: c,
|
|
1809
|
+
id: msg.id
|
|
1810
|
+
});
|
|
1811
|
+
toPipe({
|
|
1812
|
+
id,
|
|
1813
|
+
method: msg.method,
|
|
1814
|
+
params: msg.params ?? {},
|
|
1815
|
+
...c.sessionId ? { sessionId: c.sessionId } : {}
|
|
1816
|
+
});
|
|
1817
|
+
}
|
|
1818
|
+
});
|
|
1819
|
+
const gone = () => {
|
|
1820
|
+
if (!clients.delete(c)) return;
|
|
1821
|
+
for (const [id, r] of relayed) if (r.client === c) relayed.delete(id);
|
|
1822
|
+
if (c.sessionId) {
|
|
1823
|
+
bySession.delete(c.sessionId);
|
|
1824
|
+
toPipe({
|
|
1825
|
+
id: nextId++,
|
|
1826
|
+
method: "Target.detachFromTarget",
|
|
1827
|
+
params: { sessionId: c.sessionId }
|
|
1828
|
+
});
|
|
1829
|
+
}
|
|
1830
|
+
};
|
|
1831
|
+
sock.on("close", gone);
|
|
1832
|
+
sock.on("error", gone);
|
|
1833
|
+
});
|
|
1834
|
+
await new Promise((resolve, reject) => {
|
|
1835
|
+
server.once("error", reject);
|
|
1836
|
+
server.listen(o.socket, () => resolve());
|
|
1837
|
+
});
|
|
1838
|
+
if (!windows) chmodSync(o.socket, 384);
|
|
1839
|
+
const state = {
|
|
1840
|
+
brokerPid: process.pid,
|
|
1841
|
+
chromePid: chrome.pid ?? -1,
|
|
1842
|
+
profile: o.profile,
|
|
1843
|
+
socket: o.socket,
|
|
1844
|
+
startedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
1845
|
+
};
|
|
1846
|
+
writeFileSync(statePath(dir), JSON.stringify(state, null, 2) + "\n", { mode: 384 });
|
|
1847
|
+
const cleanup = () => {
|
|
1848
|
+
server.close();
|
|
1849
|
+
for (const s of socks) s.destroy();
|
|
1850
|
+
if (!windows) rmSync(o.socket, { force: true });
|
|
1851
|
+
rmSync(statePath(dir), { force: true });
|
|
1852
|
+
releaseLock();
|
|
1853
|
+
};
|
|
1854
|
+
const stop = () => {
|
|
1855
|
+
toPipe({
|
|
1856
|
+
id: nextId++,
|
|
1857
|
+
method: "Browser.close",
|
|
1858
|
+
params: {}
|
|
1859
|
+
});
|
|
1860
|
+
setTimeout(() => toChrome.end(), 1e4).unref();
|
|
1861
|
+
setTimeout(() => chrome.kill("SIGKILL"), 2e4).unref();
|
|
1862
|
+
};
|
|
1863
|
+
process.on("SIGTERM", stop);
|
|
1864
|
+
process.on("SIGINT", stop);
|
|
1865
|
+
await new Promise((resolve) => {
|
|
1866
|
+
chrome.on("exit", () => resolve());
|
|
1867
|
+
chrome.on("error", (e) => {
|
|
1868
|
+
appendFileSync(o.log, `browser-automation broker: could not start ${o.chrome}: ${e.message}\n`);
|
|
1869
|
+
resolve();
|
|
1870
|
+
});
|
|
1871
|
+
});
|
|
1872
|
+
cleanup();
|
|
1873
|
+
}
|
|
1874
|
+
//#endregion
|
|
1875
|
+
//#region src/core/chrome-path.ts
|
|
1876
|
+
function executable(p) {
|
|
1877
|
+
try {
|
|
1878
|
+
if (!statSync(p).isFile()) return false;
|
|
1879
|
+
if (process.platform === "win32") return true;
|
|
1880
|
+
accessSync(p, constants.X_OK);
|
|
1881
|
+
return true;
|
|
1882
|
+
} catch {
|
|
1883
|
+
return false;
|
|
1884
|
+
}
|
|
1885
|
+
}
|
|
1886
|
+
const MAC_BINARY = join("Google Chrome.app", "Contents", "MacOS", "Google Chrome");
|
|
1887
|
+
function platformCandidates() {
|
|
1888
|
+
if (process.platform === "darwin") return [{
|
|
1889
|
+
path: join(process.env.BROWSER_AUTOMATION_TEST_SYSTEM_APPS || "/Applications", MAC_BINARY),
|
|
1890
|
+
source: "/Applications"
|
|
1891
|
+
}, {
|
|
1892
|
+
path: join(homedir(), "Applications", MAC_BINARY),
|
|
1893
|
+
source: "~/Applications"
|
|
1894
|
+
}];
|
|
1895
|
+
if (process.platform === "win32") {
|
|
1896
|
+
const out = [];
|
|
1897
|
+
const exe = join("Google", "Chrome", "Application", "chrome.exe");
|
|
1898
|
+
if (process.env.PROGRAMFILES) out.push({
|
|
1899
|
+
path: join(process.env.PROGRAMFILES, exe),
|
|
1900
|
+
source: "Program Files"
|
|
1901
|
+
});
|
|
1902
|
+
if (process.env["PROGRAMFILES(X86)"]) out.push({
|
|
1903
|
+
path: join(process.env["PROGRAMFILES(X86)"], exe),
|
|
1904
|
+
source: "Program Files (x86)"
|
|
1905
|
+
});
|
|
1906
|
+
if (process.env.LOCALAPPDATA) out.push({
|
|
1907
|
+
path: join(process.env.LOCALAPPDATA, exe),
|
|
1908
|
+
source: "%LOCALAPPDATA%"
|
|
1909
|
+
});
|
|
1910
|
+
return out;
|
|
1911
|
+
}
|
|
1912
|
+
const dirs = (process.env.PATH ?? "").split(delimiter).filter(Boolean);
|
|
1913
|
+
return [
|
|
1914
|
+
"google-chrome",
|
|
1915
|
+
"google-chrome-stable",
|
|
1916
|
+
"chromium",
|
|
1917
|
+
"chromium-browser"
|
|
1918
|
+
].flatMap((name) => dirs.map((d) => ({
|
|
1919
|
+
path: join(d, name),
|
|
1920
|
+
source: `PATH (${name})`
|
|
1921
|
+
})));
|
|
1922
|
+
}
|
|
1923
|
+
function chromeExecutable() {
|
|
1924
|
+
let ignored;
|
|
1925
|
+
for (const name of ["BROWSER_AUTOMATION_CHROME", "CHROME"]) {
|
|
1926
|
+
const v = process.env[name];
|
|
1927
|
+
if (!v) continue;
|
|
1928
|
+
if (executable(v)) return {
|
|
1929
|
+
path: v,
|
|
1930
|
+
source: name
|
|
1931
|
+
};
|
|
1932
|
+
ignored ??= `${name}=${v} is not an executable file`;
|
|
1933
|
+
}
|
|
1934
|
+
const hit = platformCandidates().find((c) => executable(c.path));
|
|
1935
|
+
return hit ? {
|
|
1936
|
+
path: hit.path,
|
|
1937
|
+
source: hit.source,
|
|
1938
|
+
ignored
|
|
1939
|
+
} : {
|
|
1940
|
+
path: null,
|
|
1941
|
+
source: "not found",
|
|
1942
|
+
ignored
|
|
1943
|
+
};
|
|
1944
|
+
}
|
|
1945
|
+
/** Where we looked, for a "not found" message. */
|
|
1946
|
+
function chromeSearchDescription() {
|
|
1947
|
+
if (process.platform === "darwin") return "/Applications and ~/Applications";
|
|
1948
|
+
if (process.platform === "win32") return "Program Files, Program Files (x86) and %LOCALAPPDATA%";
|
|
1949
|
+
return "google-chrome, google-chrome-stable, chromium and chromium-browser on PATH";
|
|
1950
|
+
}
|
|
1951
|
+
//#endregion
|
|
1952
|
+
//#region src/core/launch-windows.ts
|
|
1953
|
+
const sleep$4 = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
1954
|
+
/** chrome.exe — decided in one place for every platform (core/chrome-path.ts). */
|
|
1955
|
+
function windowsChromeExe() {
|
|
1956
|
+
return chromeExecutable().path;
|
|
1957
|
+
}
|
|
1958
|
+
/** Is anything answering CDP on this port? (The script's `is_up`.) */
|
|
1959
|
+
async function cdpUp(port) {
|
|
1960
|
+
try {
|
|
1961
|
+
return (await fetch(`http://127.0.0.1:${port}/json/version`, { signal: AbortSignal.timeout(2e3) })).ok;
|
|
1962
|
+
} catch {
|
|
1963
|
+
return false;
|
|
1964
|
+
}
|
|
1965
|
+
}
|
|
1966
|
+
/**
|
|
1967
|
+
* pid of OUR automation Chrome's browser process on this port, or 0.
|
|
1968
|
+
*
|
|
1969
|
+
* PowerShell for the command lines: Node cannot read another process's command
|
|
1970
|
+
* line on Windows, and `wmic` is gone from Windows 11 25H2.
|
|
1971
|
+
*/
|
|
1972
|
+
function ourChromePid(port) {
|
|
1973
|
+
return ourChromeProcess(port)?.pid ?? 0;
|
|
1974
|
+
}
|
|
1975
|
+
/**
|
|
1976
|
+
* OUR Chrome's browser process on this port, with the profile it was started
|
|
1977
|
+
* on, or null. The command line comes back base64'd, so a profile path with
|
|
1978
|
+
* spaces or non-ASCII characters survives the console's code page.
|
|
1979
|
+
*/
|
|
1980
|
+
function ourChromeProcess(port) {
|
|
1981
|
+
const script = [
|
|
1982
|
+
"$ProgressPreference = 'SilentlyContinue'",
|
|
1983
|
+
`$re = '--remote-debugging-port=${port}(\\s|"|$)'`,
|
|
1984
|
+
"$sid = [System.Diagnostics.Process]::GetCurrentProcess().SessionId",
|
|
1985
|
+
"$b = Get-CimInstance Win32_Process -Filter \"Name = 'chrome.exe'\" |",
|
|
1986
|
+
" Where-Object { $_.SessionId -eq $sid -and $_.CommandLine -and $_.CommandLine -match $re -and $_.CommandLine -notmatch '--type=' } |",
|
|
1987
|
+
" Select-Object -First 1",
|
|
1988
|
+
"if ($b) { Write-Output ('BA-PID ' + [int]$b.ProcessId + ' ' + [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($b.CommandLine))) } else { Write-Output 'BA-PID 0' }"
|
|
1989
|
+
].join("\n");
|
|
1990
|
+
try {
|
|
1991
|
+
const out = execFileSync("powershell.exe", [
|
|
1992
|
+
"-NoProfile",
|
|
1993
|
+
"-NonInteractive",
|
|
1994
|
+
"-ExecutionPolicy",
|
|
1995
|
+
"Bypass",
|
|
1996
|
+
"-EncodedCommand",
|
|
1997
|
+
Buffer.from(script, "utf16le").toString("base64")
|
|
1998
|
+
], {
|
|
1999
|
+
encoding: "utf8",
|
|
2000
|
+
stdio: [
|
|
2001
|
+
"ignore",
|
|
2002
|
+
"pipe",
|
|
2003
|
+
"ignore"
|
|
2004
|
+
],
|
|
2005
|
+
timeout: 2e4,
|
|
2006
|
+
windowsHide: true
|
|
2007
|
+
});
|
|
2008
|
+
const m = /^BA-PID (\d+)(?: (\S+))?\s*$/m.exec(out);
|
|
2009
|
+
const pid = Number(m?.[1] ?? 0);
|
|
2010
|
+
if (!pid) return null;
|
|
2011
|
+
return {
|
|
2012
|
+
pid,
|
|
2013
|
+
profile: userDataDir(m?.[2] ? Buffer.from(m[2], "base64").toString("utf8") : "")
|
|
2014
|
+
};
|
|
2015
|
+
} catch {
|
|
2016
|
+
return null;
|
|
2017
|
+
}
|
|
2018
|
+
}
|
|
2019
|
+
/** --user-data-dir from a Windows command line, quoted ("--user-data-dir=C:\a b") or not. Pure. */
|
|
2020
|
+
function userDataDir(cmd) {
|
|
2021
|
+
const quoted = /"--user-data-dir=([^"]+)"/.exec(cmd) ?? /--user-data-dir="([^"]+)"/.exec(cmd);
|
|
2022
|
+
if (quoted) return quoted[1];
|
|
2023
|
+
return /--user-data-dir=(\S+)/.exec(cmd)?.[1] ?? null;
|
|
2024
|
+
}
|
|
2025
|
+
/**
|
|
2026
|
+
* Quit OUR Chrome on this port, from before the move to the pipe, through the
|
|
2027
|
+
* PORT (never closeBrowser(), which would address the pipe browser), and wait
|
|
2028
|
+
* for it to exit. taskkill only if it will not go.
|
|
2029
|
+
*/
|
|
2030
|
+
async function stopPortChrome(port, quit, say) {
|
|
2031
|
+
const pid = ourChromePid(port);
|
|
2032
|
+
if (!pid) return;
|
|
2033
|
+
await quit().catch(() => {});
|
|
2034
|
+
for (let i = 0; i < 60 && alive$1(pid); i++) await sleep$4(250);
|
|
2035
|
+
if (alive$1(pid)) {
|
|
2036
|
+
say(`Chrome (pid ${pid}) did not exit within 15s of being asked to quit; ending it.`);
|
|
2037
|
+
try {
|
|
2038
|
+
execFileSync("taskkill", [
|
|
2039
|
+
"/PID",
|
|
2040
|
+
String(pid),
|
|
2041
|
+
"/T",
|
|
2042
|
+
"/F"
|
|
2043
|
+
], { stdio: "ignore" });
|
|
2044
|
+
} catch {}
|
|
2045
|
+
for (let i = 0; i < 20 && alive$1(pid); i++) await sleep$4(250);
|
|
2046
|
+
}
|
|
2047
|
+
if (alive$1(pid)) throw new Error(`Chrome on :${port} (pid ${pid}) would not exit. Not starting another on its profile.`);
|
|
2048
|
+
}
|
|
2049
|
+
function alive$1(pid) {
|
|
2050
|
+
try {
|
|
2051
|
+
process.kill(pid, 0);
|
|
2052
|
+
return true;
|
|
2053
|
+
} catch {
|
|
2054
|
+
return false;
|
|
2055
|
+
}
|
|
2056
|
+
}
|
|
2057
|
+
/**
|
|
2058
|
+
* Quit OUR Chrome on this port and wait until it has really exited.
|
|
2059
|
+
*
|
|
2060
|
+
* CDP Browser.close first — Chrome's own quit, which flushes the profile that
|
|
2061
|
+
* holds the logins. On Windows the process does exit after it (unlike macOS,
|
|
2062
|
+
* where it lingers windowless). taskkill /F only if it will not go.
|
|
2063
|
+
*/
|
|
2064
|
+
async function stopOurChrome(port, say) {
|
|
2065
|
+
const pid = ourChromePid(port);
|
|
2066
|
+
if (!pid) return await cdpUp(port) ? "not-ours" : "none";
|
|
2067
|
+
await closeBrowser().catch(() => {});
|
|
2068
|
+
for (let i = 0; i < 40 && alive$1(pid); i++) await sleep$4(250);
|
|
2069
|
+
if (alive$1(pid)) {
|
|
2070
|
+
say(`Chrome (pid ${pid}) did not exit within 10s of being asked to quit; ending it.`);
|
|
2071
|
+
try {
|
|
2072
|
+
execFileSync("taskkill", [
|
|
2073
|
+
"/PID",
|
|
2074
|
+
String(pid),
|
|
2075
|
+
"/T",
|
|
2076
|
+
"/F"
|
|
2077
|
+
], { stdio: "ignore" });
|
|
2078
|
+
} catch {}
|
|
2079
|
+
for (let i = 0; i < 20 && alive$1(pid); i++) await sleep$4(250);
|
|
2080
|
+
}
|
|
2081
|
+
if (alive$1(pid)) throw new Error(`Chrome on :${port} (pid ${pid}) would not exit. Not relaunching on top of it.`);
|
|
2082
|
+
for (let i = 0; i < 20 && await cdpUp(port); i++) await sleep$4(250);
|
|
2083
|
+
return "stopped";
|
|
2084
|
+
}
|
|
2085
|
+
/** Start the automation Chrome unless ours is already serving the port. */
|
|
2086
|
+
async function startChrome(port, profile, log) {
|
|
2087
|
+
if (await cdpUp(port)) return ourChromePid(port) ? { outcome: "already-running" } : { outcome: "not-ours" };
|
|
2088
|
+
const exe = windowsChromeExe();
|
|
2089
|
+
if (!exe) return { outcome: "no-chrome" };
|
|
2090
|
+
mkdirSync(profile, { recursive: true });
|
|
2091
|
+
mkdirSync(dirname(log), { recursive: true });
|
|
2092
|
+
try {
|
|
2093
|
+
if (statSync(log).size > 0) renameSync(log, `${log}.prev`);
|
|
2094
|
+
} catch {}
|
|
2095
|
+
const fd = openSync(log, "a");
|
|
2096
|
+
spawn(exe, [
|
|
2097
|
+
`--remote-debugging-port=${port}`,
|
|
2098
|
+
`--user-data-dir=${profile}`,
|
|
2099
|
+
"--no-first-run",
|
|
2100
|
+
"--no-default-browser-check",
|
|
2101
|
+
"about:blank"
|
|
2102
|
+
], {
|
|
2103
|
+
detached: true,
|
|
2104
|
+
stdio: [
|
|
2105
|
+
"ignore",
|
|
2106
|
+
fd,
|
|
2107
|
+
fd
|
|
2108
|
+
]
|
|
2109
|
+
}).unref();
|
|
2110
|
+
const started = Date.now();
|
|
2111
|
+
for (let i = 0; i < 240; i++) {
|
|
2112
|
+
if (await cdpUp(port)) return {
|
|
2113
|
+
outcome: "launched",
|
|
2114
|
+
seconds: Math.round((Date.now() - started) / 1e3)
|
|
2115
|
+
};
|
|
2116
|
+
await sleep$4(250);
|
|
2117
|
+
}
|
|
2118
|
+
return {
|
|
2119
|
+
outcome: "timeout",
|
|
2120
|
+
log
|
|
2121
|
+
};
|
|
2122
|
+
}
|
|
2123
|
+
//#endregion
|
|
2124
|
+
//#region src/core/launch-pipe.ts
|
|
2125
|
+
const sleep$3 = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
2126
|
+
function brokerLogPath() {
|
|
2127
|
+
return join(brokerDir(), "broker.log");
|
|
2128
|
+
}
|
|
2129
|
+
function brokerState() {
|
|
2130
|
+
try {
|
|
2131
|
+
return JSON.parse(readFileSync(brokerStatePath(), "utf8"));
|
|
2132
|
+
} catch {
|
|
2133
|
+
return null;
|
|
2134
|
+
}
|
|
2135
|
+
}
|
|
2136
|
+
function alive(pid) {
|
|
2137
|
+
if (!pid || pid < 1) return false;
|
|
2138
|
+
try {
|
|
2139
|
+
process.kill(pid, 0);
|
|
2140
|
+
return true;
|
|
2141
|
+
} catch {
|
|
2142
|
+
return false;
|
|
2143
|
+
}
|
|
2144
|
+
}
|
|
2145
|
+
/** A browser answers on the socket: the broker is there AND Chrome replies. */
|
|
2146
|
+
async function pipeUp(timeout = 3e3) {
|
|
2147
|
+
if (!await socketAnswers(socketPath(), timeout)) return false;
|
|
2148
|
+
return browserVersion(timeout).then(() => true, () => false);
|
|
2149
|
+
}
|
|
2150
|
+
/**
|
|
2151
|
+
* Is this user's Chrome from before the move still running on the port?
|
|
2152
|
+
*
|
|
2153
|
+
* It holds the profile, so a pipe Chrome cannot open it alongside — and it is
|
|
2154
|
+
* the very exposure the move exists to close. `launch` says so and stops;
|
|
2155
|
+
* `launch --restart` quits it.
|
|
2156
|
+
*/
|
|
2157
|
+
function portChromeRunning() {
|
|
2158
|
+
if (process.platform === "win32") return ourChromeProcess(cdpPort()) !== null;
|
|
2159
|
+
try {
|
|
2160
|
+
execFileSync("pgrep", [
|
|
2161
|
+
"-u",
|
|
2162
|
+
String(process.getuid?.() ?? -1),
|
|
2163
|
+
"-f",
|
|
2164
|
+
"--",
|
|
2165
|
+
`--remote-debugging-port=${cdpPort()}`
|
|
2166
|
+
], { stdio: "ignore" });
|
|
2167
|
+
return true;
|
|
2168
|
+
} catch {
|
|
2169
|
+
return false;
|
|
2170
|
+
}
|
|
2171
|
+
}
|
|
2172
|
+
/**
|
|
2173
|
+
* The --user-data-dir of this user's browser on the port, read off its command
|
|
2174
|
+
* line. The launch script's `--stop` waits for THAT profile's lock to go before
|
|
2175
|
+
* it escalates; given the wrong one it sees no lock, decides the profile is
|
|
2176
|
+
* released, and SIGKILLs a browser mid-flush.
|
|
2177
|
+
*/
|
|
2178
|
+
function portChromeProfile() {
|
|
2179
|
+
if (process.platform === "win32") return ourChromeProcess(cdpPort())?.profile ?? null;
|
|
2180
|
+
let out;
|
|
2181
|
+
try {
|
|
2182
|
+
out = execFileSync("ps", ["-Ao", "uid=,command="], {
|
|
2183
|
+
encoding: "utf8",
|
|
2184
|
+
maxBuffer: 64 * 1024 * 1024,
|
|
2185
|
+
stdio: [
|
|
2186
|
+
"ignore",
|
|
2187
|
+
"pipe",
|
|
2188
|
+
"ignore"
|
|
2189
|
+
]
|
|
2190
|
+
});
|
|
2191
|
+
} catch {
|
|
2192
|
+
return null;
|
|
2193
|
+
}
|
|
2194
|
+
const uid = String(process.getuid?.() ?? -1);
|
|
2195
|
+
for (const line of out.split("\n")) {
|
|
2196
|
+
const m = /^\s*(\d+)\s+(.*)$/.exec(line);
|
|
2197
|
+
if (!m || m[1] !== uid) continue;
|
|
2198
|
+
const cmd = m[2];
|
|
2199
|
+
if (!cmd.includes(`--remote-debugging-port=${cdpPort()}`) || cmd.includes("--type=")) continue;
|
|
2200
|
+
const d = /--user-data-dir=(.+?)(?= --|$)/.exec(cmd);
|
|
2201
|
+
if (d) return d[1];
|
|
2202
|
+
}
|
|
2203
|
+
return null;
|
|
2204
|
+
}
|
|
2205
|
+
/** Ask the browser on the port to quit the way its menu does, so it flushes its profile. */
|
|
2206
|
+
async function quitPortChrome() {
|
|
2207
|
+
const ws = (await (await fetch(`http://127.0.0.1:${cdpPort()}/json/version`, { signal: AbortSignal.timeout(2e3) })).json()).webSocketDebuggerUrl;
|
|
2208
|
+
const s = await connect(ws, { timeout: 3e3 });
|
|
2209
|
+
try {
|
|
2210
|
+
await s.send("Browser.close", {}, 3e3).catch(() => {});
|
|
2211
|
+
} finally {
|
|
2212
|
+
s.close();
|
|
2213
|
+
}
|
|
2214
|
+
}
|
|
2215
|
+
/** Start the broker detached, and wait until Chrome answers through it. */
|
|
2216
|
+
async function startBroker(chrome, profile, chromeLog) {
|
|
2217
|
+
const start = Date.now();
|
|
2218
|
+
mkdirSync(brokerDir(), {
|
|
2219
|
+
recursive: true,
|
|
2220
|
+
mode: 448
|
|
2221
|
+
});
|
|
2222
|
+
const logFd = openSync(brokerLogPath(), "a", 384);
|
|
2223
|
+
const ctx = activeContextName();
|
|
2224
|
+
const { BAC_CONTEXT: _project, ...env } = process.env;
|
|
2225
|
+
const child = spawn(process.execPath, [
|
|
2226
|
+
process.argv[1],
|
|
2227
|
+
"broker",
|
|
2228
|
+
"--chrome",
|
|
2229
|
+
chrome,
|
|
2230
|
+
"--profile",
|
|
2231
|
+
profile,
|
|
2232
|
+
"--log",
|
|
2233
|
+
chromeLog,
|
|
2234
|
+
...ctx ? ["--context", ctx] : []
|
|
2235
|
+
], {
|
|
2236
|
+
detached: true,
|
|
2237
|
+
stdio: [
|
|
2238
|
+
"ignore",
|
|
2239
|
+
logFd,
|
|
2240
|
+
logFd
|
|
2241
|
+
],
|
|
2242
|
+
windowsHide: true,
|
|
2243
|
+
env
|
|
2244
|
+
});
|
|
2245
|
+
child.unref();
|
|
2246
|
+
for (let i = 0; i < 240; i++) {
|
|
2247
|
+
if (await pipeUp(1e3)) return {
|
|
2248
|
+
ok: true,
|
|
2249
|
+
seconds: Math.round((Date.now() - start) / 1e3)
|
|
2250
|
+
};
|
|
2251
|
+
if (child.exitCode !== null) break;
|
|
2252
|
+
await sleep$3(250);
|
|
2253
|
+
}
|
|
2254
|
+
return {
|
|
2255
|
+
ok: false,
|
|
2256
|
+
reason: `Chrome did not answer on ${socketPath()} within 60s.${refusedDevTools(chromeLog)} Broker log: ${brokerLogPath()}; Chrome's log: ${chromeLog}`
|
|
2257
|
+
};
|
|
2258
|
+
}
|
|
2259
|
+
/**
|
|
2260
|
+
* Chrome runs, but refused DevTools on the pipe, and says why only in its log.
|
|
2261
|
+
* It refuses remote debugging on its DEFAULT profile, and decides which that is
|
|
2262
|
+
* from its app-data folder: on Windows with USERPROFILE pointed elsewhere it
|
|
2263
|
+
* could not find that folder, took our profile for its default, and the launch
|
|
2264
|
+
* timed out with nothing else to go on (2026-10-27).
|
|
2265
|
+
*/
|
|
2266
|
+
function refusedDevTools(chromeLog) {
|
|
2267
|
+
let tail = "";
|
|
2268
|
+
try {
|
|
2269
|
+
tail = readFileSync(chromeLog, "utf8").slice(-16384);
|
|
2270
|
+
} catch {
|
|
2271
|
+
return "";
|
|
2272
|
+
}
|
|
2273
|
+
if (!tail.includes("requires a non-default data directory")) return "";
|
|
2274
|
+
return ` Chrome refused DevTools: it took this profile for its default one ("DevTools remote debugging requires a non-default data directory"). It decides that from its own app-data folder, so this happens when it cannot find that folder: check that ${process.platform === "win32" ? "USERPROFILE and LOCALAPPDATA are" : "HOME is"} this account's own.`;
|
|
2275
|
+
}
|
|
2276
|
+
/**
|
|
2277
|
+
* Quit the pipe Chrome and wait for the broker to go, which is when Chrome has
|
|
2278
|
+
* exited and released the profile. Browser.close first, so the profile is
|
|
2279
|
+
* flushed; the broker's own SIGTERM path next; SIGKILL only after that.
|
|
2280
|
+
*/
|
|
2281
|
+
async function stopBroker(log) {
|
|
2282
|
+
const st = brokerState();
|
|
2283
|
+
await closeBrowser().catch(() => {});
|
|
2284
|
+
const gone = () => !alive(st?.brokerPid) && !alive(st?.chromePid) && !existsSync(brokerStatePath());
|
|
2285
|
+
for (let i = 0; i < 60 && !gone(); i++) await sleep$3(250);
|
|
2286
|
+
if (gone()) return;
|
|
2287
|
+
if (alive(st?.brokerPid)) {
|
|
2288
|
+
log("Chrome did not quit within 15s of being asked; asking the broker to stop it.");
|
|
2289
|
+
process.kill(st.brokerPid, "SIGTERM");
|
|
2290
|
+
for (let i = 0; i < 100 && !gone(); i++) await sleep$3(250);
|
|
2291
|
+
}
|
|
2292
|
+
if (gone()) return;
|
|
2293
|
+
log("Still running after 40s; sending SIGKILL.");
|
|
2294
|
+
for (const pid of [st?.chromePid, st?.brokerPid]) if (alive(pid)) process.kill(pid, "SIGKILL");
|
|
2295
|
+
for (let i = 0; i < 20 && (alive(st?.chromePid) || alive(st?.brokerPid)); i++) await sleep$3(250);
|
|
2296
|
+
if (alive(st?.chromePid)) throw new Error(`Chrome (pid ${st?.chromePid}) would not exit, even on SIGKILL. Not relaunching on top of it.`);
|
|
2297
|
+
}
|
|
2298
|
+
//#endregion
|
|
2299
|
+
//#region src/core/renderer-health.ts
|
|
2300
|
+
/** First attempt's budget. Later attempts double it. */
|
|
2301
|
+
const DEFAULT_TIMEOUT = 5e3;
|
|
2302
|
+
/** How many times we ask before we are willing to call a browser broken. */
|
|
2303
|
+
const DEFAULT_ATTEMPTS = 3;
|
|
2304
|
+
/** Breathing room between attempts — a browser mid-GC deserves a second look. */
|
|
2305
|
+
const RETRY_PAUSE = 400;
|
|
2306
|
+
/**
|
|
2307
|
+
* The verdict, from the probe and the corroborations — and from nothing else.
|
|
2308
|
+
*
|
|
2309
|
+
* Pure, and separate from the probing, because this is the decision that was
|
|
2310
|
+
* wrong: every failure used to become 'wedged' by default. Now 'wedged'
|
|
2311
|
+
* requires `rendezvous === false`, which is the only thing that has ever
|
|
2312
|
+
* actually meant it.
|
|
2313
|
+
*/
|
|
2314
|
+
function rendererVerdict(outcome, e) {
|
|
2315
|
+
if (outcome === "ok") return "healthy";
|
|
2316
|
+
if (e?.rendezvous === false) return "wedged";
|
|
2317
|
+
if (e?.rendezvous === true && (e.renderers ?? 0) > 0) return "busy";
|
|
2318
|
+
return "unknown";
|
|
2319
|
+
}
|
|
2320
|
+
/**
|
|
2321
|
+
* Create a throwaway tab, make its renderer prove it is alive, close it.
|
|
2322
|
+
*
|
|
2323
|
+
* Three things changed after 2026-09-11, and each of them is load-bearing:
|
|
2324
|
+
*
|
|
2325
|
+
* 1. It goes through `ensureRenderer`, so the probe opens its tab the way the
|
|
2326
|
+
* tool opens tabs AND gets the same wake treatment. A probe that is harsher
|
|
2327
|
+
* on itself than `goto` is on a real tab reports failures `goto` would not
|
|
2328
|
+
* have had.
|
|
2329
|
+
* 2. It retries with a doubling budget. One 5s timeout is not evidence of a
|
|
2330
|
+
* permanent condition; it is evidence of 5 seconds.
|
|
2331
|
+
* 3. It stops early when the Mach name is ABSENT — the one state where more
|
|
2332
|
+
* waiting is genuinely pointless — so the real failure is still reported
|
|
2333
|
+
* fast while a slow browser gets the benefit of the doubt.
|
|
2334
|
+
*/
|
|
2335
|
+
async function probeRenderer({ timeout, attempts } = {}) {
|
|
2336
|
+
const base = timeout ?? envInt("BROWSER_AUTOMATION_PROBE_TIMEOUT", DEFAULT_TIMEOUT);
|
|
2337
|
+
const maxAttempts = Math.max(1, attempts ?? envInt("BROWSER_AUTOMATION_PROBE_ATTEMPTS", DEFAULT_ATTEMPTS));
|
|
2338
|
+
const started = Date.now();
|
|
2339
|
+
let pageTargets = 0;
|
|
2340
|
+
try {
|
|
2341
|
+
pageTargets = (await listPageTargets()).length;
|
|
2342
|
+
} catch {}
|
|
2343
|
+
const tries = [];
|
|
2344
|
+
let evidence;
|
|
2345
|
+
for (let i = 0; i < maxAttempts; i++) {
|
|
2346
|
+
const budget = base * 2 ** i;
|
|
2347
|
+
tries.push(await probeOnce(budget));
|
|
2348
|
+
if (tries[tries.length - 1].outcome === "ok") return finish({
|
|
2349
|
+
ok: true,
|
|
2350
|
+
started,
|
|
2351
|
+
pageTargets,
|
|
2352
|
+
tries,
|
|
2353
|
+
evidence
|
|
2354
|
+
});
|
|
2355
|
+
evidence ??= gatherEvidence();
|
|
2356
|
+
if (evidence.rendezvous === false) break;
|
|
2357
|
+
if (i + 1 < maxAttempts) await new Promise((r) => setTimeout(r, RETRY_PAUSE));
|
|
2358
|
+
}
|
|
2359
|
+
return finish({
|
|
2360
|
+
ok: false,
|
|
2361
|
+
started,
|
|
2362
|
+
pageTargets,
|
|
2363
|
+
tries,
|
|
2364
|
+
evidence
|
|
2365
|
+
});
|
|
2366
|
+
}
|
|
2367
|
+
function finish({ ok, started, pageTargets, tries, evidence }) {
|
|
2368
|
+
const last = tries[tries.length - 1];
|
|
2369
|
+
const health = {
|
|
2370
|
+
ok,
|
|
2371
|
+
ms: Date.now() - started,
|
|
2372
|
+
pageTargets,
|
|
2373
|
+
reason: last?.reason,
|
|
2374
|
+
outcome: last?.outcome ?? "error",
|
|
2375
|
+
verdict: rendererVerdict(last?.outcome ?? "error", evidence),
|
|
2376
|
+
attempts: tries,
|
|
2377
|
+
evidence
|
|
2378
|
+
};
|
|
2379
|
+
recordProbe(health);
|
|
2380
|
+
return health;
|
|
2381
|
+
}
|
|
2382
|
+
/** One create -> ensure -> close cycle. */
|
|
2383
|
+
async function probeOnce(budget) {
|
|
2384
|
+
const started = Date.now();
|
|
2385
|
+
let targetId;
|
|
2386
|
+
try {
|
|
2387
|
+
targetId = await createTab("about:blank", { timeout: budget });
|
|
2388
|
+
} catch (e) {
|
|
2389
|
+
return {
|
|
2390
|
+
outcome: "error",
|
|
2391
|
+
budget,
|
|
2392
|
+
ms: Date.now() - started,
|
|
2393
|
+
woke: false,
|
|
2394
|
+
reason: `could not create a target at all: ${e?.message ?? e}`
|
|
2395
|
+
};
|
|
2396
|
+
}
|
|
2397
|
+
try {
|
|
2398
|
+
const r = await ensureRenderer(targetId, {
|
|
2399
|
+
grace: budget,
|
|
2400
|
+
budget
|
|
2401
|
+
});
|
|
2402
|
+
return {
|
|
2403
|
+
outcome: r.outcome,
|
|
2404
|
+
budget,
|
|
2405
|
+
ms: Date.now() - started,
|
|
2406
|
+
woke: r.woke,
|
|
2407
|
+
reason: r.reason
|
|
2408
|
+
};
|
|
2409
|
+
} finally {
|
|
2410
|
+
if (targetId) await closeTab(targetId).catch(() => {});
|
|
2411
|
+
}
|
|
2412
|
+
}
|
|
2413
|
+
/**
|
|
2414
|
+
* Ask an EXISTING target's renderer to prove it is alive.
|
|
2415
|
+
*
|
|
2416
|
+
* Kept returning `string | null` because that is what `gc` wants (a reason to
|
|
2417
|
+
* print beside a tab it is about to close). New callers should prefer
|
|
2418
|
+
* `askRenderer`, which says WHICH failure it was.
|
|
2419
|
+
*/
|
|
2420
|
+
async function renderersAnswer(targetId, timeout = DEFAULT_TIMEOUT) {
|
|
2421
|
+
const r = await askRenderer(targetId, timeout);
|
|
2422
|
+
return r.outcome === "ok" ? null : r.reason ?? r.outcome;
|
|
2423
|
+
}
|
|
2424
|
+
/**
|
|
2425
|
+
* The port we are actually talking to.
|
|
2426
|
+
*
|
|
2427
|
+
* NOT always `cdpPort()`: `BROWSER_AUTOMATION_CDP` points the CLI at an
|
|
2428
|
+
* arbitrary host:port, and everything here that shells out to `ps` or
|
|
2429
|
+
* `launchctl` has to ask about THAT browser. Using the uid-derived port instead
|
|
2430
|
+
* finds the user's default Chrome and cheerfully reports its health as if it
|
|
2431
|
+
* were the one being driven — caught while testing this module against a second
|
|
2432
|
+
* Chrome, where a perfectly healthy browser was accused of having lost a
|
|
2433
|
+
* bootstrap name that in fact belonged to a different pid.
|
|
2434
|
+
*/
|
|
2435
|
+
function targetPort() {
|
|
2436
|
+
const explicit = process.env.BROWSER_AUTOMATION_CDP;
|
|
2437
|
+
if (explicit) try {
|
|
2438
|
+
const p = Number(new URL(explicit).port);
|
|
2439
|
+
if (Number.isInteger(p) && p > 0) return p;
|
|
2440
|
+
} catch {}
|
|
2441
|
+
return cdpPort();
|
|
2442
|
+
}
|
|
2443
|
+
/**
|
|
2444
|
+
* The browser process serving our port, and how many renderers it has.
|
|
2445
|
+
*
|
|
2446
|
+
* One `ps`, not one `pgrep` plus one `ps` per hit: on a Chrome with 40 children
|
|
2447
|
+
* that was 41 forks to answer two questions, and it ran on the error path of a
|
|
2448
|
+
* browser already thought to be struggling.
|
|
2449
|
+
*
|
|
2450
|
+
* The executable check is not decoration. Matching on the command line alone
|
|
2451
|
+
* (as `pgrep -f` does) hits any process that merely CONTAINS the debugging-port
|
|
2452
|
+
* flag — the `grep` looking for it, or a shell running `browser-automation`
|
|
2453
|
+
* with the flag as an argument. One of those, having no `--type=`, would have
|
|
2454
|
+
* been reported as the browser pid, and its absent Mach name read as the
|
|
2455
|
+
* permanent failure. Seen while writing this: a `ugrep` for the flag sat in
|
|
2456
|
+
* `ps` output alongside the real Chrome.
|
|
2457
|
+
*/
|
|
2458
|
+
function chromeProcesses() {
|
|
2459
|
+
const flag = `--remote-debugging-port=${targetPort()}`;
|
|
2460
|
+
const uid = String(process.getuid?.() ?? -1);
|
|
2461
|
+
let out;
|
|
2462
|
+
try {
|
|
2463
|
+
out = execFileSync("ps", ["-Ao", "pid=,ppid=,uid=,command="], {
|
|
2464
|
+
encoding: "utf8",
|
|
2465
|
+
maxBuffer: 64 * 1024 * 1024,
|
|
2466
|
+
stdio: [
|
|
2467
|
+
"ignore",
|
|
2468
|
+
"pipe",
|
|
2469
|
+
"ignore"
|
|
2470
|
+
]
|
|
2471
|
+
});
|
|
2472
|
+
} catch {
|
|
2473
|
+
return {
|
|
2474
|
+
browser: null,
|
|
2475
|
+
renderers: null
|
|
2476
|
+
};
|
|
2477
|
+
}
|
|
2478
|
+
if (usesPipe()) {
|
|
2479
|
+
const st = brokerState();
|
|
2480
|
+
const browser = st && out.split("\n").some((l) => new RegExp(`^\\s*${st.chromePid}\\s`).test(l)) ? st.chromePid : null;
|
|
2481
|
+
if (browser === null) return {
|
|
2482
|
+
browser: null,
|
|
2483
|
+
renderers: null
|
|
2484
|
+
};
|
|
2485
|
+
let renderers = 0;
|
|
2486
|
+
for (const line of out.split("\n")) {
|
|
2487
|
+
const m = /^\s*(\d+)\s+(\d+)\s+(\d+)\s+(.*)$/.exec(line);
|
|
2488
|
+
if (!m || m[3] !== uid || !/--type=renderer\b/.test(m[4])) continue;
|
|
2489
|
+
if (Number(m[2]) === browser || m[4].includes(`--user-data-dir=${st.profile}`)) renderers++;
|
|
2490
|
+
}
|
|
2491
|
+
return {
|
|
2492
|
+
browser,
|
|
2493
|
+
renderers
|
|
2494
|
+
};
|
|
2495
|
+
}
|
|
2496
|
+
let browser = null;
|
|
2497
|
+
let renderers = 0;
|
|
2498
|
+
for (const line of out.split("\n")) {
|
|
2499
|
+
const m = /^\s*(\d+)\s+\d+\s+(\d+)\s+(.*)$/.exec(line);
|
|
2500
|
+
if (!m) continue;
|
|
2501
|
+
const [, pid, u, cmd] = m;
|
|
2502
|
+
if (u !== uid || !cmd.includes(flag)) continue;
|
|
2503
|
+
if (!/chrome|chromium|brave|msedge|thorium/i.test(cmd.split(" --")[0])) continue;
|
|
2504
|
+
if (/--type=renderer\b/.test(cmd)) renderers++;
|
|
2505
|
+
else if (!cmd.includes("--type=")) browser = Number(pid);
|
|
2506
|
+
}
|
|
2507
|
+
return {
|
|
2508
|
+
browser,
|
|
2509
|
+
renderers
|
|
1522
2510
|
};
|
|
1523
2511
|
}
|
|
1524
2512
|
/** The pid of the browser process serving the port we are driving, if visible. */
|
|
@@ -1561,7 +2549,9 @@ function gatherEvidence() {
|
|
|
1561
2549
|
/** Where `launch` writes Chrome's stdout/stderr — Chrome logs the real reason there. */
|
|
1562
2550
|
function chromeLogPath() {
|
|
1563
2551
|
const tmp = process.platform === "win32" ? tmpdir() : process.env.TMPDIR?.replace(/\/$/, "") || "/tmp";
|
|
1564
|
-
|
|
2552
|
+
if (process.env.BROWSER_AUTOMATION_LOG) return process.env.BROWSER_AUTOMATION_LOG;
|
|
2553
|
+
if (usesPipe()) return join(brokerDir(), "chrome.log");
|
|
2554
|
+
return `${tmp}/chrome-${targetPort()}.log`;
|
|
1565
2555
|
}
|
|
1566
2556
|
function probeLogPath() {
|
|
1567
2557
|
return process.env.BROWSER_AUTOMATION_PROBE_LOG || join(homedir(), ".browser-automation", "renderer-probes.jsonl");
|
|
@@ -1832,16 +2822,12 @@ function describeNotShown(outcome) {
|
|
|
1832
2822
|
//#endregion
|
|
1833
2823
|
//#region src/core/context-launch.ts
|
|
1834
2824
|
async function reachable() {
|
|
1835
|
-
|
|
1836
|
-
return (await fetch(`${cdpHost()}/json/version`, { signal: AbortSignal.timeout(1500) })).ok;
|
|
1837
|
-
} catch {
|
|
1838
|
-
return false;
|
|
1839
|
-
}
|
|
2825
|
+
return pipeUp(1500);
|
|
1840
2826
|
}
|
|
1841
2827
|
async function ensureContextChrome() {
|
|
1842
2828
|
const ctx = activeContext();
|
|
1843
2829
|
if (!ctx || await reachable()) return;
|
|
1844
|
-
consola$1.info(`Starting the Chrome for context "${ctx.name}": its own window and profile
|
|
2830
|
+
consola$1.info(`Starting the Chrome for context "${ctx.name}": its own window and profile. Whatever you sign in to or install there is kept.`);
|
|
1845
2831
|
if (spawnSync(process.execPath, [
|
|
1846
2832
|
process.argv[1],
|
|
1847
2833
|
"launch",
|
|
@@ -2166,7 +3152,67 @@ function clickExpr(ref) {
|
|
|
2166
3152
|
const el=__baFind(${r});
|
|
2167
3153
|
if(!el)return {err:'ref not found: '+${r}+' (re-run snapshot)'};
|
|
2168
3154
|
el.scrollIntoView({block:'center',inline:'center'});
|
|
3155
|
+
const tag=el.tagName.toLowerCase();
|
|
3156
|
+
if(el.getAttribute('role')==='option'&&el.closest('[data-radix-select-viewport]')){
|
|
3157
|
+
el.focus({preventScroll:true});
|
|
3158
|
+
const k={key:'Enter',code:'Enter',keyCode:13,which:13,bubbles:true,cancelable:true,composed:true,view:window};
|
|
3159
|
+
el.dispatchEvent(new KeyboardEvent('keydown',k));
|
|
3160
|
+
el.dispatchEvent(new KeyboardEvent('keyup',k));
|
|
3161
|
+
return {ok:true,tag,via:'keyboard'};
|
|
3162
|
+
}
|
|
3163
|
+
const b=el.getBoundingClientRect();
|
|
3164
|
+
const x=b.left+b.width/2,y=b.top+b.height/2;
|
|
3165
|
+
const o={bubbles:true,cancelable:true,composed:true,view:window,clientX:x,clientY:y,screenX:x,screenY:y,button:0,buttons:1,detail:1,pointerId:1,pointerType:'mouse',isPrimary:true};
|
|
3166
|
+
const up={...o,buttons:0};
|
|
3167
|
+
el.dispatchEvent(new PointerEvent('pointerover',o));
|
|
3168
|
+
el.dispatchEvent(new PointerEvent('pointerenter',{...o,bubbles:false,cancelable:false}));
|
|
3169
|
+
el.dispatchEvent(new MouseEvent('mouseover',o));
|
|
3170
|
+
const down=el.dispatchEvent(new PointerEvent('pointerdown',o));
|
|
3171
|
+
if(down&&el.dispatchEvent(new MouseEvent('mousedown',o))&&typeof el.focus==='function')el.focus({preventScroll:true});
|
|
3172
|
+
el.dispatchEvent(new PointerEvent('pointerup',up));
|
|
3173
|
+
if(down)el.dispatchEvent(new MouseEvent('mouseup',up));
|
|
2169
3174
|
el.click();
|
|
3175
|
+
return {ok:true,tag};
|
|
3176
|
+
})()`;
|
|
3177
|
+
}
|
|
3178
|
+
const KEY_CODES = {
|
|
3179
|
+
Enter: 13,
|
|
3180
|
+
Escape: 27,
|
|
3181
|
+
Tab: 9,
|
|
3182
|
+
" ": 32,
|
|
3183
|
+
Backspace: 8,
|
|
3184
|
+
Delete: 46,
|
|
3185
|
+
ArrowUp: 38,
|
|
3186
|
+
ArrowDown: 40,
|
|
3187
|
+
ArrowLeft: 37,
|
|
3188
|
+
ArrowRight: 39,
|
|
3189
|
+
Home: 36,
|
|
3190
|
+
End: 35,
|
|
3191
|
+
PageUp: 33,
|
|
3192
|
+
PageDown: 34
|
|
3193
|
+
};
|
|
3194
|
+
function keyExpr(ref, key) {
|
|
3195
|
+
const r = JSON.stringify(ref);
|
|
3196
|
+
const name = key === "Space" ? " " : key;
|
|
3197
|
+
const keyCode = KEY_CODES[name] ?? (name.length === 1 ? name.toUpperCase().charCodeAt(0) : 0);
|
|
3198
|
+
const code = name === " " ? "Space" : /^[a-z]$/i.test(name) ? `Key${name.toUpperCase()}` : /^[0-9]$/.test(name) ? `Digit${name}` : name;
|
|
3199
|
+
return WALK + `(() => {
|
|
3200
|
+
const el=__baFind(${r});
|
|
3201
|
+
if(!el)return {err:'ref not found: '+${r}+' (re-run snapshot)'};
|
|
3202
|
+
el.scrollIntoView({block:'center',inline:'center'});
|
|
3203
|
+
if(typeof el.focus==='function')el.focus({preventScroll:true});
|
|
3204
|
+
const t=document.activeElement&&el.contains(document.activeElement)?document.activeElement:el;
|
|
3205
|
+
const k={...${JSON.stringify({
|
|
3206
|
+
key: name,
|
|
3207
|
+
code,
|
|
3208
|
+
keyCode,
|
|
3209
|
+
which: keyCode,
|
|
3210
|
+
bubbles: true,
|
|
3211
|
+
cancelable: true,
|
|
3212
|
+
composed: true
|
|
3213
|
+
})},view:window};
|
|
3214
|
+
t.dispatchEvent(new KeyboardEvent('keydown',k));
|
|
3215
|
+
t.dispatchEvent(new KeyboardEvent('keyup',k));
|
|
2170
3216
|
return {ok:true,tag:el.tagName.toLowerCase()};
|
|
2171
3217
|
})()`;
|
|
2172
3218
|
}
|
|
@@ -2336,7 +3382,7 @@ const snapshotCommand = define({
|
|
|
2336
3382
|
});
|
|
2337
3383
|
//#endregion
|
|
2338
3384
|
//#region src/commands/click.ts
|
|
2339
|
-
const sleep$
|
|
3385
|
+
const sleep$2 = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
2340
3386
|
const clickCommand = define({
|
|
2341
3387
|
name: "click",
|
|
2342
3388
|
description: "Click an element by ref (from the latest snapshot)",
|
|
@@ -2348,7 +3394,7 @@ const clickCommand = define({
|
|
|
2348
3394
|
},
|
|
2349
3395
|
trusted: {
|
|
2350
3396
|
type: "boolean",
|
|
2351
|
-
description: "Dispatch a real, genuinely-trusted CDP mouse click (Input.dispatchMouseEvent) at the element instead of the default JS-dispatched el.click(). Makes the renderer treat the tab as focused+visible and WAITS until it reports so (CDP input no-ops on a backgrounded tab) — without selecting the tab in its window, so the person's own tab keeps their typing, then waits for the element to be actionable (stable position + unoccluded hit-test) before pressing — mirroring Playwright.
|
|
3397
|
+
description: "Dispatch a real, genuinely-trusted CDP mouse click (Input.dispatchMouseEvent) at the element instead of the default JS-dispatched pointer + mouse sequence and el.click(). The default needs no focus and already drives Radix/headless-UI triggers and items; use this only for widgets that check isTrusted. Makes the renderer treat the tab as focused+visible and WAITS until it reports so (CDP input no-ops on a backgrounded tab) — without selecting the tab in its window, so the person's own tab keeps their typing, then waits for the element to be actionable (stable position + unoccluded hit-test) before pressing — mirroring Playwright. Canonical case: artdeco dropdown menu items (LinkedIn More→Connect), which demand isTrusted and animate in, so a default click, or an immediate trusted click on stale coordinates, only highlights them without firing."
|
|
2352
3398
|
}
|
|
2353
3399
|
},
|
|
2354
3400
|
async run(ctx) {
|
|
@@ -2377,7 +3423,7 @@ const clickCommand = define({
|
|
|
2377
3423
|
while (Date.now() < focusDeadline) {
|
|
2378
3424
|
const f = await evalIn(`({f:document.hasFocus(),v:document.visibilityState})`);
|
|
2379
3425
|
if (f && f.f && f.v === "visible") break;
|
|
2380
|
-
await sleep$
|
|
3426
|
+
await sleep$2(50);
|
|
2381
3427
|
}
|
|
2382
3428
|
let prev = null;
|
|
2383
3429
|
let point = null;
|
|
@@ -2403,7 +3449,7 @@ const clickCommand = define({
|
|
|
2403
3449
|
x: a.x,
|
|
2404
3450
|
y: a.y
|
|
2405
3451
|
};
|
|
2406
|
-
await sleep$
|
|
3452
|
+
await sleep$2(60);
|
|
2407
3453
|
}
|
|
2408
3454
|
if (!point) {
|
|
2409
3455
|
consola$1.error(`<${ref}> not actionable for a trusted click: ${lastReason}`);
|
|
@@ -2418,7 +3464,7 @@ const clickCommand = define({
|
|
|
2418
3464
|
buttons: 0,
|
|
2419
3465
|
pointerType: "mouse"
|
|
2420
3466
|
});
|
|
2421
|
-
await sleep$
|
|
3467
|
+
await sleep$2(20);
|
|
2422
3468
|
await s.send("Input.dispatchMouseEvent", {
|
|
2423
3469
|
type: "mousePressed",
|
|
2424
3470
|
x,
|
|
@@ -2448,7 +3494,42 @@ const clickCommand = define({
|
|
|
2448
3494
|
consola$1.error(r.err);
|
|
2449
3495
|
process.exit(1);
|
|
2450
3496
|
}
|
|
2451
|
-
consola$1.success(`clicked ${ref} <${r.tag}
|
|
3497
|
+
consola$1.success(`clicked ${ref} <${r.tag}>${r.via ? ` (${r.via})` : ""}`);
|
|
3498
|
+
}
|
|
3499
|
+
});
|
|
3500
|
+
//#endregion
|
|
3501
|
+
//#region src/commands/key.ts
|
|
3502
|
+
const keyCommand = define({
|
|
3503
|
+
name: "key",
|
|
3504
|
+
description: "Press one key on an element by ref: focus it, then dispatch keydown + keyup (Enter, Escape, ArrowDown, Space, a character…), without bringing the tab to the front",
|
|
3505
|
+
args: {
|
|
3506
|
+
...targetArgs,
|
|
3507
|
+
ref: {
|
|
3508
|
+
type: "positional",
|
|
3509
|
+
description: "Element ref, e.g. e7"
|
|
3510
|
+
},
|
|
3511
|
+
key: {
|
|
3512
|
+
type: "positional",
|
|
3513
|
+
description: "An event.key name: Enter, Escape, Tab, ArrowDown, Space, or one character"
|
|
3514
|
+
}
|
|
3515
|
+
},
|
|
3516
|
+
async run(ctx) {
|
|
3517
|
+
const ref = ctx.positionals[1];
|
|
3518
|
+
const key = ctx.positionals[2];
|
|
3519
|
+
if (!ref || !isValidRef(ref)) {
|
|
3520
|
+
consola$1.error("A ref like \"e7\" is required (run `browser-automation snapshot` first)");
|
|
3521
|
+
process.exit(1);
|
|
3522
|
+
}
|
|
3523
|
+
if (!key) {
|
|
3524
|
+
consola$1.error("A key is required, e.g. `browser-automation key e7 Enter`");
|
|
3525
|
+
process.exit(1);
|
|
3526
|
+
}
|
|
3527
|
+
const r = await evaluate(await resolveExistingTargetId(targetOpts(ctx.values)), keyExpr(ref, key));
|
|
3528
|
+
if (r.err) {
|
|
3529
|
+
consola$1.error(r.err);
|
|
3530
|
+
process.exit(1);
|
|
3531
|
+
}
|
|
3532
|
+
consola$1.success(`pressed ${key} on ${ref} <${r.tag}>`);
|
|
2452
3533
|
}
|
|
2453
3534
|
});
|
|
2454
3535
|
//#endregion
|
|
@@ -2552,7 +3633,7 @@ const readCommand = define({
|
|
|
2552
3633
|
});
|
|
2553
3634
|
//#endregion
|
|
2554
3635
|
//#region src/commands/focus.ts
|
|
2555
|
-
const sleep$
|
|
3636
|
+
const sleep$1 = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
2556
3637
|
/**
|
|
2557
3638
|
* Make a tab believe it is the visible one.
|
|
2558
3639
|
*
|
|
@@ -2622,7 +3703,7 @@ const focusCommand = define({
|
|
|
2622
3703
|
returnByValue: true
|
|
2623
3704
|
})).result?.value ?? last;
|
|
2624
3705
|
if (last.focused && last.visibility === "visible") break;
|
|
2625
|
-
await sleep$
|
|
3706
|
+
await sleep$1(50);
|
|
2626
3707
|
}
|
|
2627
3708
|
return last;
|
|
2628
3709
|
});
|
|
@@ -2988,7 +4069,7 @@ const uploadCommand = define({
|
|
|
2988
4069
|
});
|
|
2989
4070
|
//#endregion
|
|
2990
4071
|
//#region src/commands/drop.ts
|
|
2991
|
-
const sleep
|
|
4072
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
2992
4073
|
/** Resolve each path to absolute and verify it's an existing file. */
|
|
2993
4074
|
function absFiles(paths) {
|
|
2994
4075
|
return paths.map((p) => {
|
|
@@ -3090,7 +4171,7 @@ const dropCommand = define({
|
|
|
3090
4171
|
while (Date.now() < focusDeadline) {
|
|
3091
4172
|
const f = await evalIn(`({f:document.hasFocus(),v:document.visibilityState})`);
|
|
3092
4173
|
if (f && f.f && f.v === "visible") break;
|
|
3093
|
-
await sleep
|
|
4174
|
+
await sleep(50);
|
|
3094
4175
|
}
|
|
3095
4176
|
let prev = null;
|
|
3096
4177
|
let point = null;
|
|
@@ -3116,7 +4197,7 @@ const dropCommand = define({
|
|
|
3116
4197
|
x: a.x,
|
|
3117
4198
|
y: a.y
|
|
3118
4199
|
};
|
|
3119
|
-
await sleep
|
|
4200
|
+
await sleep(60);
|
|
3120
4201
|
}
|
|
3121
4202
|
if (!point) {
|
|
3122
4203
|
consola$1.error(`<${ref}> not actionable for a drop: ${lastReason}`);
|
|
@@ -3140,7 +4221,7 @@ const dropCommand = define({
|
|
|
3140
4221
|
y,
|
|
3141
4222
|
data
|
|
3142
4223
|
});
|
|
3143
|
-
await sleep
|
|
4224
|
+
await sleep(20);
|
|
3144
4225
|
await s.send("Input.dispatchDragEvent", {
|
|
3145
4226
|
type: "drop",
|
|
3146
4227
|
x,
|
|
@@ -3364,7 +4445,7 @@ const listCommand = define({
|
|
|
3364
4445
|
if (stale.length && !ctx.values.all) consola$1.log(` + ${stale.length} stale bookmark(s) whose tab is gone — \`list --all\` to see them, \`gc --sessions\` to clear them`);
|
|
3365
4446
|
if (sessions.length) consola$1.log("");
|
|
3366
4447
|
const ctxName = activeContextName();
|
|
3367
|
-
consola$1.log(`# open tabs (${targets.length}) in ${ctxName ? `context "${ctxName}"'s Chrome` : "your automation Chrome"} (:${cdpPort()}) — address with -t <id> or -m <substr>`);
|
|
4448
|
+
consola$1.log(`# open tabs (${targets.length}) in ${ctxName ? `context "${ctxName}"'s Chrome` : "your automation Chrome"} ${usesPipe() ? "" : ` (:${cdpPort()})`} — address with -t <id> or -m <substr>`);
|
|
3368
4449
|
for (const t of targets) {
|
|
3369
4450
|
const owner = sessions.find((s) => s.targetId === t.id);
|
|
3370
4451
|
const title = (t.title ?? "").replace(/\s+/g, " ").slice(0, 28);
|
|
@@ -3463,211 +4544,6 @@ function launchScriptPath() {
|
|
|
3463
4544
|
return join(packageRoot(), "scripts", "launch-chrome.sh");
|
|
3464
4545
|
}
|
|
3465
4546
|
//#endregion
|
|
3466
|
-
//#region src/core/chrome-path.ts
|
|
3467
|
-
function executable(p) {
|
|
3468
|
-
try {
|
|
3469
|
-
if (!statSync(p).isFile()) return false;
|
|
3470
|
-
if (process.platform === "win32") return true;
|
|
3471
|
-
accessSync(p, constants.X_OK);
|
|
3472
|
-
return true;
|
|
3473
|
-
} catch {
|
|
3474
|
-
return false;
|
|
3475
|
-
}
|
|
3476
|
-
}
|
|
3477
|
-
const MAC_BINARY = join("Google Chrome.app", "Contents", "MacOS", "Google Chrome");
|
|
3478
|
-
function platformCandidates() {
|
|
3479
|
-
if (process.platform === "darwin") return [{
|
|
3480
|
-
path: join(process.env.BROWSER_AUTOMATION_TEST_SYSTEM_APPS || "/Applications", MAC_BINARY),
|
|
3481
|
-
source: "/Applications"
|
|
3482
|
-
}, {
|
|
3483
|
-
path: join(homedir(), "Applications", MAC_BINARY),
|
|
3484
|
-
source: "~/Applications"
|
|
3485
|
-
}];
|
|
3486
|
-
if (process.platform === "win32") {
|
|
3487
|
-
const out = [];
|
|
3488
|
-
const exe = join("Google", "Chrome", "Application", "chrome.exe");
|
|
3489
|
-
if (process.env.PROGRAMFILES) out.push({
|
|
3490
|
-
path: join(process.env.PROGRAMFILES, exe),
|
|
3491
|
-
source: "Program Files"
|
|
3492
|
-
});
|
|
3493
|
-
if (process.env["PROGRAMFILES(X86)"]) out.push({
|
|
3494
|
-
path: join(process.env["PROGRAMFILES(X86)"], exe),
|
|
3495
|
-
source: "Program Files (x86)"
|
|
3496
|
-
});
|
|
3497
|
-
if (process.env.LOCALAPPDATA) out.push({
|
|
3498
|
-
path: join(process.env.LOCALAPPDATA, exe),
|
|
3499
|
-
source: "%LOCALAPPDATA%"
|
|
3500
|
-
});
|
|
3501
|
-
return out;
|
|
3502
|
-
}
|
|
3503
|
-
const dirs = (process.env.PATH ?? "").split(delimiter).filter(Boolean);
|
|
3504
|
-
return [
|
|
3505
|
-
"google-chrome",
|
|
3506
|
-
"google-chrome-stable",
|
|
3507
|
-
"chromium",
|
|
3508
|
-
"chromium-browser"
|
|
3509
|
-
].flatMap((name) => dirs.map((d) => ({
|
|
3510
|
-
path: join(d, name),
|
|
3511
|
-
source: `PATH (${name})`
|
|
3512
|
-
})));
|
|
3513
|
-
}
|
|
3514
|
-
function chromeExecutable() {
|
|
3515
|
-
let ignored;
|
|
3516
|
-
for (const name of ["BROWSER_AUTOMATION_CHROME", "CHROME"]) {
|
|
3517
|
-
const v = process.env[name];
|
|
3518
|
-
if (!v) continue;
|
|
3519
|
-
if (executable(v)) return {
|
|
3520
|
-
path: v,
|
|
3521
|
-
source: name
|
|
3522
|
-
};
|
|
3523
|
-
ignored ??= `${name}=${v} is not an executable file`;
|
|
3524
|
-
}
|
|
3525
|
-
const hit = platformCandidates().find((c) => executable(c.path));
|
|
3526
|
-
return hit ? {
|
|
3527
|
-
path: hit.path,
|
|
3528
|
-
source: hit.source,
|
|
3529
|
-
ignored
|
|
3530
|
-
} : {
|
|
3531
|
-
path: null,
|
|
3532
|
-
source: "not found",
|
|
3533
|
-
ignored
|
|
3534
|
-
};
|
|
3535
|
-
}
|
|
3536
|
-
/** Where we looked, for a "not found" message. */
|
|
3537
|
-
function chromeSearchDescription() {
|
|
3538
|
-
if (process.platform === "darwin") return "/Applications and ~/Applications";
|
|
3539
|
-
if (process.platform === "win32") return "Program Files, Program Files (x86) and %LOCALAPPDATA%";
|
|
3540
|
-
return "google-chrome, google-chrome-stable, chromium and chromium-browser on PATH";
|
|
3541
|
-
}
|
|
3542
|
-
//#endregion
|
|
3543
|
-
//#region src/core/launch-windows.ts
|
|
3544
|
-
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
3545
|
-
/** chrome.exe — decided in one place for every platform (core/chrome-path.ts). */
|
|
3546
|
-
function windowsChromeExe() {
|
|
3547
|
-
return chromeExecutable().path;
|
|
3548
|
-
}
|
|
3549
|
-
/** Is anything answering CDP on this port? (The script's `is_up`.) */
|
|
3550
|
-
async function cdpUp(port) {
|
|
3551
|
-
try {
|
|
3552
|
-
return (await fetch(`http://127.0.0.1:${port}/json/version`, { signal: AbortSignal.timeout(2e3) })).ok;
|
|
3553
|
-
} catch {
|
|
3554
|
-
return false;
|
|
3555
|
-
}
|
|
3556
|
-
}
|
|
3557
|
-
/**
|
|
3558
|
-
* pid of OUR automation Chrome's browser process on this port, or 0.
|
|
3559
|
-
*
|
|
3560
|
-
* PowerShell for the command lines: Node cannot read another process's command
|
|
3561
|
-
* line on Windows, and `wmic` is gone from Windows 11 25H2.
|
|
3562
|
-
*/
|
|
3563
|
-
function ourChromePid(port) {
|
|
3564
|
-
const script = [
|
|
3565
|
-
"$ProgressPreference = 'SilentlyContinue'",
|
|
3566
|
-
`$re = '--remote-debugging-port=${port}(\\s|"|$)'`,
|
|
3567
|
-
"$sid = [System.Diagnostics.Process]::GetCurrentProcess().SessionId",
|
|
3568
|
-
"$b = Get-CimInstance Win32_Process -Filter \"Name = 'chrome.exe'\" |",
|
|
3569
|
-
" Where-Object { $_.SessionId -eq $sid -and $_.CommandLine -and $_.CommandLine -match $re -and $_.CommandLine -notmatch '--type=' } |",
|
|
3570
|
-
" Select-Object -First 1 -ExpandProperty ProcessId",
|
|
3571
|
-
"Write-Output ('BA-PID ' + [int]$b)"
|
|
3572
|
-
].join("\n");
|
|
3573
|
-
try {
|
|
3574
|
-
const out = execFileSync("powershell.exe", [
|
|
3575
|
-
"-NoProfile",
|
|
3576
|
-
"-NonInteractive",
|
|
3577
|
-
"-ExecutionPolicy",
|
|
3578
|
-
"Bypass",
|
|
3579
|
-
"-EncodedCommand",
|
|
3580
|
-
Buffer.from(script, "utf16le").toString("base64")
|
|
3581
|
-
], {
|
|
3582
|
-
encoding: "utf8",
|
|
3583
|
-
stdio: [
|
|
3584
|
-
"ignore",
|
|
3585
|
-
"pipe",
|
|
3586
|
-
"ignore"
|
|
3587
|
-
],
|
|
3588
|
-
timeout: 2e4,
|
|
3589
|
-
windowsHide: true
|
|
3590
|
-
});
|
|
3591
|
-
return Number(/^BA-PID (\d+)\s*$/m.exec(out)?.[1] ?? 0);
|
|
3592
|
-
} catch {
|
|
3593
|
-
return 0;
|
|
3594
|
-
}
|
|
3595
|
-
}
|
|
3596
|
-
function alive(pid) {
|
|
3597
|
-
try {
|
|
3598
|
-
process.kill(pid, 0);
|
|
3599
|
-
return true;
|
|
3600
|
-
} catch {
|
|
3601
|
-
return false;
|
|
3602
|
-
}
|
|
3603
|
-
}
|
|
3604
|
-
/**
|
|
3605
|
-
* Quit OUR Chrome on this port and wait until it has really exited.
|
|
3606
|
-
*
|
|
3607
|
-
* CDP Browser.close first — Chrome's own quit, which flushes the profile that
|
|
3608
|
-
* holds the logins. On Windows the process does exit after it (unlike macOS,
|
|
3609
|
-
* where it lingers windowless). taskkill /F only if it will not go.
|
|
3610
|
-
*/
|
|
3611
|
-
async function stopOurChrome(port, say) {
|
|
3612
|
-
const pid = ourChromePid(port);
|
|
3613
|
-
if (!pid) return await cdpUp(port) ? "not-ours" : "none";
|
|
3614
|
-
await closeBrowser().catch(() => {});
|
|
3615
|
-
for (let i = 0; i < 40 && alive(pid); i++) await sleep(250);
|
|
3616
|
-
if (alive(pid)) {
|
|
3617
|
-
say(`Chrome (pid ${pid}) did not exit within 10s of being asked to quit; ending it.`);
|
|
3618
|
-
try {
|
|
3619
|
-
execFileSync("taskkill", [
|
|
3620
|
-
"/PID",
|
|
3621
|
-
String(pid),
|
|
3622
|
-
"/T",
|
|
3623
|
-
"/F"
|
|
3624
|
-
], { stdio: "ignore" });
|
|
3625
|
-
} catch {}
|
|
3626
|
-
for (let i = 0; i < 20 && alive(pid); i++) await sleep(250);
|
|
3627
|
-
}
|
|
3628
|
-
if (alive(pid)) throw new Error(`Chrome on :${port} (pid ${pid}) would not exit. Not relaunching on top of it.`);
|
|
3629
|
-
for (let i = 0; i < 20 && await cdpUp(port); i++) await sleep(250);
|
|
3630
|
-
return "stopped";
|
|
3631
|
-
}
|
|
3632
|
-
/** Start the automation Chrome unless ours is already serving the port. */
|
|
3633
|
-
async function startChrome(port, profile, log) {
|
|
3634
|
-
if (await cdpUp(port)) return ourChromePid(port) ? { outcome: "already-running" } : { outcome: "not-ours" };
|
|
3635
|
-
const exe = windowsChromeExe();
|
|
3636
|
-
if (!exe) return { outcome: "no-chrome" };
|
|
3637
|
-
mkdirSync(profile, { recursive: true });
|
|
3638
|
-
mkdirSync(dirname(log), { recursive: true });
|
|
3639
|
-
try {
|
|
3640
|
-
if (statSync(log).size > 0) renameSync(log, `${log}.prev`);
|
|
3641
|
-
} catch {}
|
|
3642
|
-
const fd = openSync(log, "a");
|
|
3643
|
-
spawn(exe, [
|
|
3644
|
-
`--remote-debugging-port=${port}`,
|
|
3645
|
-
`--user-data-dir=${profile}`,
|
|
3646
|
-
"--no-first-run",
|
|
3647
|
-
"--no-default-browser-check",
|
|
3648
|
-
"about:blank"
|
|
3649
|
-
], {
|
|
3650
|
-
detached: true,
|
|
3651
|
-
stdio: [
|
|
3652
|
-
"ignore",
|
|
3653
|
-
fd,
|
|
3654
|
-
fd
|
|
3655
|
-
]
|
|
3656
|
-
}).unref();
|
|
3657
|
-
const started = Date.now();
|
|
3658
|
-
for (let i = 0; i < 240; i++) {
|
|
3659
|
-
if (await cdpUp(port)) return {
|
|
3660
|
-
outcome: "launched",
|
|
3661
|
-
seconds: Math.round((Date.now() - started) / 1e3)
|
|
3662
|
-
};
|
|
3663
|
-
await sleep(250);
|
|
3664
|
-
}
|
|
3665
|
-
return {
|
|
3666
|
-
outcome: "timeout",
|
|
3667
|
-
log
|
|
3668
|
-
};
|
|
3669
|
-
}
|
|
3670
|
-
//#endregion
|
|
3671
4547
|
//#region src/commands/launch.ts
|
|
3672
4548
|
const launchCommand = define({
|
|
3673
4549
|
name: "launch",
|
|
@@ -3683,7 +4559,10 @@ const launchCommand = define({
|
|
|
3683
4559
|
}
|
|
3684
4560
|
},
|
|
3685
4561
|
async run(ctx) {
|
|
3686
|
-
if (
|
|
4562
|
+
if (usesPipe()) {
|
|
4563
|
+
if (!await launchPipe(ctx.values.status === true, ctx.values.restart === true)) process.exit(1);
|
|
4564
|
+
if (ctx.values.status) return;
|
|
4565
|
+
} else if (process.platform === "win32") {
|
|
3687
4566
|
if (!await launchWindows(ctx.values.status === true, ctx.values.restart === true)) process.exit(1);
|
|
3688
4567
|
if (ctx.values.status) return;
|
|
3689
4568
|
} else {
|
|
@@ -3802,6 +4681,94 @@ async function launchWindows(statusOnly, restart) {
|
|
|
3802
4681
|
return false;
|
|
3803
4682
|
}
|
|
3804
4683
|
}
|
|
4684
|
+
/** Two profile paths are the same folder (Windows paths ignore case and slash direction). */
|
|
4685
|
+
function sameDir(a, b) {
|
|
4686
|
+
if (process.platform !== "win32") return a === b;
|
|
4687
|
+
const n = (p) => resolve(p).toLowerCase();
|
|
4688
|
+
return n(a) === n(b);
|
|
4689
|
+
}
|
|
4690
|
+
/**
|
|
4691
|
+
* Chrome on the DevTools pipe, behind the broker: every platform, and every
|
|
4692
|
+
* login context (its own broker). Returns false on a failure that must stop
|
|
4693
|
+
* `launch` before the health check.
|
|
4694
|
+
*/
|
|
4695
|
+
async function launchPipe(statusOnly, restart) {
|
|
4696
|
+
const sock = () => socketPath();
|
|
4697
|
+
const ctxName = activeContextName();
|
|
4698
|
+
const driveIt = `Drive it with: browser-automation goto -s <session>${ctxName ? ` --context ${ctxName} <url> (a session opened in it follows it; later commands need no --context)` : " <url>"}`;
|
|
4699
|
+
if (statusOnly) {
|
|
4700
|
+
const up = await pipeUp();
|
|
4701
|
+
consola$1.log(up ? `Chrome is up on the pipe (${sock()})` : `Chrome is NOT running (nothing answers on ${sock()})`);
|
|
4702
|
+
return up;
|
|
4703
|
+
}
|
|
4704
|
+
if (portChromeRunning()) {
|
|
4705
|
+
const theirs = portChromeProfile();
|
|
4706
|
+
const mine = resolveProfile().dir;
|
|
4707
|
+
const where = `port ${cdpPort()}${theirs ? ` (profile ${theirs})` : ""}`;
|
|
4708
|
+
if (!theirs || !sameDir(theirs, mine)) consola$1.warn(`This account also has a browser listening on ${where}; anything on this computer can drive it. It is not this one, so it is left alone.`);
|
|
4709
|
+
else if (!restart) {
|
|
4710
|
+
consola$1.error(`This browser is still running on ${where}, from before the move to the pipe, and anything on this computer can drive it. Switch it over:\n browser-automation launch --restart\nThat quits it (closing its tabs; logins are kept) and starts it again on the pipe.`);
|
|
4711
|
+
return false;
|
|
4712
|
+
} else {
|
|
4713
|
+
consola$1.info(`Quitting this browser on ${where} to start it again on the pipe.`);
|
|
4714
|
+
if (process.platform === "win32") try {
|
|
4715
|
+
await stopPortChrome(cdpPort(), quitPortChrome, (s) => consola$1.warn(s));
|
|
4716
|
+
} catch (e) {
|
|
4717
|
+
consola$1.error(String(e?.message ?? e));
|
|
4718
|
+
return false;
|
|
4719
|
+
}
|
|
4720
|
+
else {
|
|
4721
|
+
await quitPortChrome().catch(() => {});
|
|
4722
|
+
if (spawnSync("bash", [
|
|
4723
|
+
launchScriptPath(),
|
|
4724
|
+
"--port",
|
|
4725
|
+
String(cdpPort()),
|
|
4726
|
+
"--stop",
|
|
4727
|
+
"--profile",
|
|
4728
|
+
theirs
|
|
4729
|
+
], { stdio: "inherit" }).status !== 0) return false;
|
|
4730
|
+
}
|
|
4731
|
+
}
|
|
4732
|
+
}
|
|
4733
|
+
if (await pipeUp()) {
|
|
4734
|
+
if (!restart) {
|
|
4735
|
+
consola$1.log(`Already running on the pipe (${sock()}).`);
|
|
4736
|
+
consola$1.log(driveIt);
|
|
4737
|
+
return true;
|
|
4738
|
+
}
|
|
4739
|
+
const tabs = await listPageTargets().then((t) => t.length).catch(() => null);
|
|
4740
|
+
consola$1.info(`Restarting Chrome — closing ${tabs ?? "?"} open tab(s).`);
|
|
4741
|
+
try {
|
|
4742
|
+
await stopBroker((s) => consola$1.warn(s));
|
|
4743
|
+
} catch (e) {
|
|
4744
|
+
consola$1.error(String(e?.message ?? e));
|
|
4745
|
+
return false;
|
|
4746
|
+
}
|
|
4747
|
+
}
|
|
4748
|
+
const m = migrateProfile();
|
|
4749
|
+
if (m.outcome === "moved") consola$1.success(`Profile ${m.detail} — logins travel with it.`);
|
|
4750
|
+
else if (m.outcome === "refused" || m.outcome === "failed") consola$1.warn(`Profile not moved: ${m.detail}`);
|
|
4751
|
+
await personalizeIfNeeded();
|
|
4752
|
+
if (process.platform === "darwin" && m.dir === legacyProfileDir()) {
|
|
4753
|
+
consola$1.error(`The profile is still inside Chrome's own folder (${m.dir}), where macOS refuses a Chrome started with the DevTools pipe.${m.detail ? ` ${m.detail}` : ""}`);
|
|
4754
|
+
return false;
|
|
4755
|
+
}
|
|
4756
|
+
const chrome = chromeExecutable();
|
|
4757
|
+
if (chrome.ignored) consola$1.warn(`Ignoring ${chrome.ignored}.`);
|
|
4758
|
+
if (!chrome.path) {
|
|
4759
|
+
consola$1.error("Chrome not found. Install it, or set BROWSER_AUTOMATION_CHROME to its binary.");
|
|
4760
|
+
return false;
|
|
4761
|
+
}
|
|
4762
|
+
const r = await startBroker(chrome.path, m.dir, chromeLogPath());
|
|
4763
|
+
if (!r.ok) {
|
|
4764
|
+
consola$1.error(r.reason);
|
|
4765
|
+
return false;
|
|
4766
|
+
}
|
|
4767
|
+
consola$1.log(`Chrome launched on the pipe in ${r.seconds}s (profile: ${m.dir}, ${process.platform === "win32" ? "pipe" : "socket"}: ${sock()}, log: ${chromeLogPath()})`);
|
|
4768
|
+
consola$1.log(`No debugging port is open: only this account can reach it, through the ${process.platform === "win32" ? "named pipe" : "socket"}.`);
|
|
4769
|
+
consola$1.log(driveIt);
|
|
4770
|
+
return true;
|
|
4771
|
+
}
|
|
3805
4772
|
//#endregion
|
|
3806
4773
|
//#region src/commands/doctor.ts
|
|
3807
4774
|
/**
|
|
@@ -3838,7 +4805,10 @@ const doctorCommand = define({
|
|
|
3838
4805
|
const bad = (m) => consola$1.log(` ✗ ${m}`);
|
|
3839
4806
|
if (Number(process.versions.node.split(".")[0]) >= 22) ok(`Node ${process.versions.node} (global WebSocket available)`);
|
|
3840
4807
|
else bad(`Node ${process.versions.node} — need >= 22 for the global WebSocket CDP client`);
|
|
3841
|
-
|
|
4808
|
+
if (usesPipe()) {
|
|
4809
|
+
consola$1.log(` • Transport: DevTools pipe, served on ${socketPath()} — no debugging port open`);
|
|
4810
|
+
if (portChromeRunning()) bad(`a Chrome of yours is still listening on port ${cdpPort()} (from before the pipe): anything on this computer can drive it. Switch it over: browser-automation launch --restart`);
|
|
4811
|
+
} else consola$1.log(` • CDP host: ${cdpHost()} (port ${cdpPort()} — derived from uid ${process.getuid?.() ?? "?"})`);
|
|
3842
4812
|
const profile = resolveProfile();
|
|
3843
4813
|
consola$1.log(` • Profile: ${profile.dir}`);
|
|
3844
4814
|
if (profile.source === "legacy") {
|
|
@@ -3850,7 +4820,13 @@ const doctorCommand = define({
|
|
|
3850
4820
|
else bad(`Chrome binary: not found (looked in ${chromeSearchDescription()}) — \`launch\` cannot start one. Install Chrome, or set CHROME.`);
|
|
3851
4821
|
if (chrome.ignored) consola$1.log(` ⚠ ignoring ${chrome.ignored}`);
|
|
3852
4822
|
let version;
|
|
3853
|
-
try {
|
|
4823
|
+
if (usesPipe()) try {
|
|
4824
|
+
ok(`Chrome reachable: ${(await browserVersion()).product}`);
|
|
4825
|
+
} catch {
|
|
4826
|
+
bad(`No browser on ${socketPath()} — run: browser-automation launch`);
|
|
4827
|
+
return;
|
|
4828
|
+
}
|
|
4829
|
+
else try {
|
|
3854
4830
|
version = await (await fetch(`${cdpHost()}/json/version`)).json();
|
|
3855
4831
|
if (!portIsOurs()) {
|
|
3856
4832
|
bad(`something on port ${cdpPort()} is serving CDP (${version.Browser}) but this account did not start it — it is another user's Chrome, and anything you drive would happen in their browser. Quit Chrome in that account, or set BROWSER_AUTOMATION_PORT to a free port.`);
|
|
@@ -4045,6 +5021,38 @@ const profileCommand = define({
|
|
|
4045
5021
|
}
|
|
4046
5022
|
});
|
|
4047
5023
|
//#endregion
|
|
5024
|
+
//#region src/commands/broker.ts
|
|
5025
|
+
const brokerCommand = define({
|
|
5026
|
+
name: "broker",
|
|
5027
|
+
description: "Internal: hold Chrome's DevTools pipe and serve it on this user's socket. `launch` starts it.",
|
|
5028
|
+
args: {
|
|
5029
|
+
chrome: {
|
|
5030
|
+
type: "string",
|
|
5031
|
+
description: "Chrome binary",
|
|
5032
|
+
required: true
|
|
5033
|
+
},
|
|
5034
|
+
profile: {
|
|
5035
|
+
type: "string",
|
|
5036
|
+
description: "--user-data-dir",
|
|
5037
|
+
required: true
|
|
5038
|
+
},
|
|
5039
|
+
log: {
|
|
5040
|
+
type: "string",
|
|
5041
|
+
description: "Chrome's stdout/stderr",
|
|
5042
|
+
required: true
|
|
5043
|
+
}
|
|
5044
|
+
},
|
|
5045
|
+
async run(ctx) {
|
|
5046
|
+
await runBroker({
|
|
5047
|
+
chrome: ctx.values.chrome,
|
|
5048
|
+
profile: ctx.values.profile,
|
|
5049
|
+
log: ctx.values.log,
|
|
5050
|
+
dir: brokerDir(),
|
|
5051
|
+
socket: process.platform === "win32" ? windowsPipeName() : socketPath()
|
|
5052
|
+
});
|
|
5053
|
+
}
|
|
5054
|
+
});
|
|
5055
|
+
//#endregion
|
|
4048
5056
|
//#region src/commands/context.ts
|
|
4049
5057
|
/** Run `fn` as if `name` (or, when undefined, the user's own automation Chrome) were the active context. */
|
|
4050
5058
|
async function asChrome(name, fn) {
|
|
@@ -4058,7 +5066,9 @@ async function asChrome(name, fn) {
|
|
|
4058
5066
|
else process.env.BROWSER_AUTOMATION_CONTEXT = saved;
|
|
4059
5067
|
}
|
|
4060
5068
|
}
|
|
5069
|
+
/** Is the active Chrome up? Over its pipe, or, for the person's own with BROWSER_AUTOMATION_CDP set, its port. */
|
|
4061
5070
|
async function up() {
|
|
5071
|
+
if (usesPipe()) return pipeUp(1500);
|
|
4062
5072
|
try {
|
|
4063
5073
|
return (await fetch(`${cdpHost()}/json/version`, { signal: AbortSignal.timeout(1500) })).ok;
|
|
4064
5074
|
} catch {
|
|
@@ -4066,11 +5076,7 @@ async function up() {
|
|
|
4066
5076
|
}
|
|
4067
5077
|
}
|
|
4068
5078
|
async function running(r) {
|
|
4069
|
-
|
|
4070
|
-
return (await fetch(`http://localhost:${r.port}/json/version`, { signal: AbortSignal.timeout(1500) })).ok;
|
|
4071
|
-
} catch {
|
|
4072
|
-
return false;
|
|
4073
|
-
}
|
|
5079
|
+
return asChrome(r.name, up);
|
|
4074
5080
|
}
|
|
4075
5081
|
/**
|
|
4076
5082
|
* Login contexts (core/context-store.ts): a separate Chrome per extra account,
|
|
@@ -4078,7 +5084,7 @@ async function running(r) {
|
|
|
4078
5084
|
*/
|
|
4079
5085
|
const contextCommand = define({
|
|
4080
5086
|
name: "context",
|
|
4081
|
-
description: "Login contexts — a separate Chrome (own profile, own
|
|
5087
|
+
description: "Login contexts — a separate Chrome (own profile, own pipe, own window) per extra account, so a second login sits next to your own; opened by `new`/`goto --context <name>`, which start it on demand. `context` lists them; `context stop <name>` quits one; `context forget <name>` removes it (its sessions too), keeping its profile unless --delete-profile.",
|
|
4082
5088
|
args: { "delete-profile": {
|
|
4083
5089
|
type: "boolean",
|
|
4084
5090
|
description: "With forget: also delete the context's Chrome profile — its logins and extensions. Not undoable."
|
|
@@ -4094,9 +5100,9 @@ const contextCommand = define({
|
|
|
4094
5100
|
const on = await up();
|
|
4095
5101
|
const pid = on ? browserPid() : null;
|
|
4096
5102
|
const users = sessions.filter((s) => (s.context ?? void 0) === name).map((s) => s.name);
|
|
4097
|
-
return ` ${label.padEnd(22)}
|
|
5103
|
+
return ` ${label.padEnd(22)} [${on ? "running" : "stopped"}]${pid ? ` pid ${pid}` : ""}${color ? ` ${color} window` : ""}${name && name === project ? " ← BAC_CONTEXT" : ""}${users.length > 6 ? ` ${users.length} sessions` : users.length ? ` sessions: ${users.join(", ")}` : ""}`;
|
|
4098
5104
|
});
|
|
4099
|
-
consola$1.log(`# Chromes driven by browser-automation — login contexts' profiles under ${contextsDir()}`);
|
|
5105
|
+
consola$1.log(`# Chromes driven by browser-automation, each on its own pipe — login contexts' profiles under ${contextsDir()}`);
|
|
4100
5106
|
consola$1.log(await row("(your automation Chrome)", void 0, void 0));
|
|
4101
5107
|
for (const r of all) consola$1.log(await row(r.name, r.name, r.color));
|
|
4102
5108
|
if (!all.length) consola$1.log(" No login contexts yet. Open one with: browser-automation new -s <session> --context <name> <url>");
|
|
@@ -4153,6 +5159,7 @@ const subCommands = new Map([
|
|
|
4153
5159
|
["snapshot", snapshotCommand],
|
|
4154
5160
|
["snap", snapshotCommand],
|
|
4155
5161
|
["click", clickCommand],
|
|
5162
|
+
["key", keyCommand],
|
|
4156
5163
|
["fill", fillCommand],
|
|
4157
5164
|
["read", readCommand],
|
|
4158
5165
|
["focus", focusCommand],
|
|
@@ -4174,6 +5181,7 @@ const subCommands = new Map([
|
|
|
4174
5181
|
["prune", gcCommand],
|
|
4175
5182
|
["port", portCommand],
|
|
4176
5183
|
["profile", profileCommand],
|
|
5184
|
+
["broker", brokerCommand],
|
|
4177
5185
|
["context", contextCommand]
|
|
4178
5186
|
]);
|
|
4179
5187
|
function withRealPositionals(cmd, real) {
|