@generativereality/browser-automation 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/plugin.json +9 -0
- package/README.md +127 -0
- package/dist/index.js +916 -0
- package/package.json +56 -0
- package/scripts/launch-chrome.sh +79 -0
- package/scripts/sync-plugin.sh +68 -0
- package/skills/browser/SKILL.md +201 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,916 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { cli, define } from "gunshi";
|
|
3
|
+
import { consola } from "consola";
|
|
4
|
+
import { homedir } from "node:os";
|
|
5
|
+
import { dirname, join } from "node:path";
|
|
6
|
+
import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
7
|
+
import { spawnSync } from "node:child_process";
|
|
8
|
+
import { fileURLToPath } from "node:url";
|
|
9
|
+
//#region package.json
|
|
10
|
+
var version = "0.3.0";
|
|
11
|
+
var description = "Daemonless, per-tab-isolated browser automation CLI for Claude Code. Drives one shared headed Chrome (persistent profile + extensions) over per-target CDP — many parallel sessions, no focus stealing, nothing long-lived to crash.";
|
|
12
|
+
//#endregion
|
|
13
|
+
//#region src/core/session.ts
|
|
14
|
+
const DIR = join(homedir(), ".browser-automation", "sessions");
|
|
15
|
+
function file(name) {
|
|
16
|
+
return join(DIR, `${encodeURIComponent(name)}.json`);
|
|
17
|
+
}
|
|
18
|
+
function defaultSessionName() {
|
|
19
|
+
return process.env.BAC_SESSION || "default";
|
|
20
|
+
}
|
|
21
|
+
function saveSession(s) {
|
|
22
|
+
mkdirSync(DIR, { recursive: true });
|
|
23
|
+
writeFileSync(file(s.name), JSON.stringify(s, null, 2));
|
|
24
|
+
}
|
|
25
|
+
function loadSession(name) {
|
|
26
|
+
const f = file(name);
|
|
27
|
+
return existsSync(f) ? JSON.parse(readFileSync(f, "utf8")) : null;
|
|
28
|
+
}
|
|
29
|
+
function deleteSession(name) {
|
|
30
|
+
const f = file(name);
|
|
31
|
+
if (existsSync(f)) rmSync(f);
|
|
32
|
+
}
|
|
33
|
+
function listSessions() {
|
|
34
|
+
if (!existsSync(DIR)) return [];
|
|
35
|
+
return readdirSync(DIR).filter((f) => f.endsWith(".json")).map((f) => JSON.parse(readFileSync(join(DIR, f), "utf8")));
|
|
36
|
+
}
|
|
37
|
+
//#endregion
|
|
38
|
+
//#region src/core/cdp.ts
|
|
39
|
+
const DEFAULT_HOST = "http://localhost:9223";
|
|
40
|
+
function cdpHost() {
|
|
41
|
+
return process.env.BROWSER_AUTOMATION_CDP || DEFAULT_HOST;
|
|
42
|
+
}
|
|
43
|
+
/** A target has gone away (tab closed, or Chrome restarted -> new targetIds). */
|
|
44
|
+
var TargetGoneError = class extends Error {
|
|
45
|
+
targetId;
|
|
46
|
+
constructor(targetId) {
|
|
47
|
+
super(`target ${targetId} not found on ${cdpHost()} (tab closed or Chrome restarted)`);
|
|
48
|
+
this.targetId = targetId;
|
|
49
|
+
this.name = "TargetGoneError";
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
async function httpJson(path) {
|
|
53
|
+
const res = await fetch(`${cdpHost()}${path}`);
|
|
54
|
+
if (!res.ok) throw new Error(`CDP HTTP ${res.status} for ${path} — is Chrome running with --remote-debugging-port? (${cdpHost()})`);
|
|
55
|
+
return await res.json();
|
|
56
|
+
}
|
|
57
|
+
async function browserWsUrl() {
|
|
58
|
+
return (await httpJson("/json/version")).webSocketDebuggerUrl;
|
|
59
|
+
}
|
|
60
|
+
async function listTargets() {
|
|
61
|
+
return httpJson("/json/list");
|
|
62
|
+
}
|
|
63
|
+
async function listPageTargets() {
|
|
64
|
+
return (await listTargets()).filter((t) => t.type === "page");
|
|
65
|
+
}
|
|
66
|
+
/** webSocketDebuggerUrl for a targetId, or null if it no longer exists. */
|
|
67
|
+
async function targetWsUrl(targetId) {
|
|
68
|
+
return (await listTargets()).find((t) => t.id === targetId)?.webSocketDebuggerUrl ?? null;
|
|
69
|
+
}
|
|
70
|
+
/** Open a CDP session to an arbitrary webSocketDebuggerUrl (page or browser). */
|
|
71
|
+
function connect(wsUrl, { timeout = 15e3 } = {}) {
|
|
72
|
+
return new Promise((resolve, reject) => {
|
|
73
|
+
const ws = new WebSocket(wsUrl);
|
|
74
|
+
let nextId = 1;
|
|
75
|
+
const pending = /* @__PURE__ */ new Map();
|
|
76
|
+
const listeners = /* @__PURE__ */ new Map();
|
|
77
|
+
const openTimer = setTimeout(() => {
|
|
78
|
+
try {
|
|
79
|
+
ws.close();
|
|
80
|
+
} catch {}
|
|
81
|
+
reject(/* @__PURE__ */ new Error(`CDP connect timeout ${timeout}ms to ${wsUrl}`));
|
|
82
|
+
}, timeout);
|
|
83
|
+
ws.addEventListener("open", () => {
|
|
84
|
+
clearTimeout(openTimer);
|
|
85
|
+
resolve({
|
|
86
|
+
send(method, params = {}, timeoutMs = 3e4) {
|
|
87
|
+
return new Promise((res, rej) => {
|
|
88
|
+
const id = nextId++;
|
|
89
|
+
const t = setTimeout(() => {
|
|
90
|
+
if (pending.delete(id)) rej(/* @__PURE__ */ new Error(`CDP ${method} timed out after ${timeoutMs}ms`));
|
|
91
|
+
}, timeoutMs);
|
|
92
|
+
pending.set(id, {
|
|
93
|
+
resolve: (v) => {
|
|
94
|
+
clearTimeout(t);
|
|
95
|
+
res(v);
|
|
96
|
+
},
|
|
97
|
+
reject: (e) => {
|
|
98
|
+
clearTimeout(t);
|
|
99
|
+
rej(e);
|
|
100
|
+
},
|
|
101
|
+
method
|
|
102
|
+
});
|
|
103
|
+
ws.send(JSON.stringify({
|
|
104
|
+
id,
|
|
105
|
+
method,
|
|
106
|
+
params
|
|
107
|
+
}));
|
|
108
|
+
});
|
|
109
|
+
},
|
|
110
|
+
on(method, cb) {
|
|
111
|
+
const arr = listeners.get(method) ?? [];
|
|
112
|
+
arr.push(cb);
|
|
113
|
+
listeners.set(method, arr);
|
|
114
|
+
},
|
|
115
|
+
close() {
|
|
116
|
+
try {
|
|
117
|
+
ws.close();
|
|
118
|
+
} catch {}
|
|
119
|
+
}
|
|
120
|
+
});
|
|
121
|
+
});
|
|
122
|
+
ws.addEventListener("message", (ev) => {
|
|
123
|
+
let msg;
|
|
124
|
+
try {
|
|
125
|
+
msg = JSON.parse(String(ev.data));
|
|
126
|
+
} catch {
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
if (typeof msg.id === "number" && pending.has(msg.id)) {
|
|
130
|
+
const p = pending.get(msg.id);
|
|
131
|
+
pending.delete(msg.id);
|
|
132
|
+
if (msg.error) p.reject(/* @__PURE__ */ new Error(`${p.method}: ${msg.error.message ?? JSON.stringify(msg.error)}`));
|
|
133
|
+
else p.resolve(msg.result);
|
|
134
|
+
} else if (msg.method) for (const cb of listeners.get(msg.method) ?? []) cb(msg.params);
|
|
135
|
+
});
|
|
136
|
+
ws.addEventListener("error", () => {
|
|
137
|
+
clearTimeout(openTimer);
|
|
138
|
+
reject(/* @__PURE__ */ new Error(`WebSocket error connecting to ${wsUrl}`));
|
|
139
|
+
});
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
/** Run `fn` against a session bound to a single page target, then close it. */
|
|
143
|
+
async function withPage(targetId, fn) {
|
|
144
|
+
const wsUrl = await targetWsUrl(targetId);
|
|
145
|
+
if (!wsUrl) throw new TargetGoneError(targetId);
|
|
146
|
+
const s = await connect(wsUrl);
|
|
147
|
+
try {
|
|
148
|
+
return await fn(s);
|
|
149
|
+
} finally {
|
|
150
|
+
s.close();
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
/** Run `fn` against the browser-level endpoint (Target.* commands), then close. */
|
|
154
|
+
async function withBrowser(fn) {
|
|
155
|
+
const s = await connect(await browserWsUrl());
|
|
156
|
+
try {
|
|
157
|
+
return await fn(s);
|
|
158
|
+
} finally {
|
|
159
|
+
s.close();
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
/** Create a new tab in the BACKGROUND (never steals focus) -> returns targetId. */
|
|
163
|
+
async function createTab(url = "about:blank") {
|
|
164
|
+
return withBrowser(async (s) => {
|
|
165
|
+
return (await s.send("Target.createTarget", {
|
|
166
|
+
url,
|
|
167
|
+
background: true
|
|
168
|
+
})).targetId;
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
async function closeTab(targetId) {
|
|
172
|
+
return withBrowser(async (s) => {
|
|
173
|
+
return !!(await s.send("Target.closeTarget", { targetId })).success;
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
/** Evaluate a JS expression in a page target and return its value by-value.
|
|
177
|
+
* Set userGesture for actions that require user activation (e.g. downloads). */
|
|
178
|
+
async function evaluate(targetId, expression, { userGesture = false } = {}) {
|
|
179
|
+
return withPage(targetId, async (s) => {
|
|
180
|
+
const res = await s.send("Runtime.evaluate", {
|
|
181
|
+
expression,
|
|
182
|
+
returnByValue: true,
|
|
183
|
+
awaitPromise: true,
|
|
184
|
+
userGesture
|
|
185
|
+
});
|
|
186
|
+
if (res.exceptionDetails) {
|
|
187
|
+
const e = res.exceptionDetails;
|
|
188
|
+
throw new Error("page JS exception: " + (e.exception?.description || e.text || "unknown"));
|
|
189
|
+
}
|
|
190
|
+
return res.result?.value;
|
|
191
|
+
});
|
|
192
|
+
}
|
|
193
|
+
/** Re-evaluate until `ready(value)` is true or the timeout elapses (Playwright-
|
|
194
|
+
* style auto-wait for SPA content that renders after load). Returns the last
|
|
195
|
+
* value regardless, so callers can still handle a genuinely-empty page. */
|
|
196
|
+
async function evaluateUntil(targetId, expression, ready, { timeout = 5e3, interval = 250 } = {}) {
|
|
197
|
+
const deadline = Date.now() + timeout;
|
|
198
|
+
let last = await evaluate(targetId, expression);
|
|
199
|
+
while (!ready(last) && Date.now() < deadline) {
|
|
200
|
+
await new Promise((r) => setTimeout(r, interval));
|
|
201
|
+
last = await evaluate(targetId, expression);
|
|
202
|
+
}
|
|
203
|
+
return last;
|
|
204
|
+
}
|
|
205
|
+
/** Navigate a page target and wait for load (or timeout). */
|
|
206
|
+
async function navigate(targetId, url, { timeout = 3e4 } = {}) {
|
|
207
|
+
return withPage(targetId, async (s) => {
|
|
208
|
+
await s.send("Page.enable");
|
|
209
|
+
const loaded = new Promise((resolve) => s.on("Page.loadEventFired", () => resolve()));
|
|
210
|
+
const r = await s.send("Page.navigate", { url });
|
|
211
|
+
if (r.errorText) throw new Error(`navigate failed: ${r.errorText}`);
|
|
212
|
+
await Promise.race([loaded, new Promise((res) => setTimeout(res, timeout))]);
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
//#endregion
|
|
216
|
+
//#region src/core/target.ts
|
|
217
|
+
async function resolveLiveTarget(name, { create = true } = {}) {
|
|
218
|
+
const st = loadSession(name);
|
|
219
|
+
if (st) {
|
|
220
|
+
if (await targetWsUrl(st.targetId)) return {
|
|
221
|
+
targetId: st.targetId,
|
|
222
|
+
created: false
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
if (!create) throw new Error(`session "${name}" has no live tab — run: browser-automation goto -s ${name} <url>`);
|
|
226
|
+
const targetId = await createTab("about:blank");
|
|
227
|
+
saveSession({
|
|
228
|
+
name,
|
|
229
|
+
targetId,
|
|
230
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
231
|
+
url: st?.url
|
|
232
|
+
});
|
|
233
|
+
return {
|
|
234
|
+
targetId,
|
|
235
|
+
created: true
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
function isValidRef(ref) {
|
|
239
|
+
return /^e\d+$/.test(ref);
|
|
240
|
+
}
|
|
241
|
+
const NO_SLASH_SCHEMES = /^(data|about|blob|file|chrome|view-source|javascript):/i;
|
|
242
|
+
/** Add https:// to a bare host/path; leave full URLs and schemeless schemes alone. */
|
|
243
|
+
function normalizeUrl(input) {
|
|
244
|
+
if (input.includes("://") || NO_SLASH_SCHEMES.test(input)) return input;
|
|
245
|
+
return `https://${input}`;
|
|
246
|
+
}
|
|
247
|
+
//#endregion
|
|
248
|
+
//#region src/commands/new.ts
|
|
249
|
+
const newCommand = define({
|
|
250
|
+
name: "new",
|
|
251
|
+
description: "Open a fresh background tab for a session (does not steal focus). Optional positional: URL (default: about:blank)",
|
|
252
|
+
args: {
|
|
253
|
+
session: {
|
|
254
|
+
type: "string",
|
|
255
|
+
short: "s",
|
|
256
|
+
description: "Session name (default: $BAC_SESSION or \"default\")"
|
|
257
|
+
},
|
|
258
|
+
force: {
|
|
259
|
+
type: "boolean",
|
|
260
|
+
short: "f",
|
|
261
|
+
description: "Open a new tab even if the session already has one"
|
|
262
|
+
}
|
|
263
|
+
},
|
|
264
|
+
async run(ctx) {
|
|
265
|
+
const name = ctx.values.session || defaultSessionName();
|
|
266
|
+
const url = ctx.positionals[1] ? normalizeUrl(ctx.positionals[1]) : "about:blank";
|
|
267
|
+
if (loadSession(name) && !ctx.values.force) consola.warn(`Session "${name}" already maps to a tab. Use --force to open another, or just \`browser-automation goto -s ${name} <url>\`.`);
|
|
268
|
+
const targetId = await createTab(url);
|
|
269
|
+
saveSession({
|
|
270
|
+
name,
|
|
271
|
+
targetId,
|
|
272
|
+
url,
|
|
273
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
274
|
+
});
|
|
275
|
+
consola.success(`[${name}] opened background tab ${targetId.slice(0, 12)}… → ${url}`);
|
|
276
|
+
}
|
|
277
|
+
});
|
|
278
|
+
//#endregion
|
|
279
|
+
//#region src/core/resolve.ts
|
|
280
|
+
/** Resolve a -t value: exact targetId, or a unique prefix (so the truncated id
|
|
281
|
+
* shown by `list` is directly usable). Searches ALL targets (incl. iframes). */
|
|
282
|
+
async function resolveTargetIdArg(idOrPrefix) {
|
|
283
|
+
const targets = await listTargets();
|
|
284
|
+
const exact = targets.find((t) => t.id === idOrPrefix);
|
|
285
|
+
if (exact) return exact.id;
|
|
286
|
+
const pre = targets.filter((t) => t.id.startsWith(idOrPrefix));
|
|
287
|
+
if (pre.length === 1) return pre[0].id;
|
|
288
|
+
if (pre.length === 0) throw new Error(`no live tab with targetId ${idOrPrefix}`);
|
|
289
|
+
throw new Error(`targetId prefix "${idOrPrefix}" matches ${pre.length} tabs — use more characters`);
|
|
290
|
+
}
|
|
291
|
+
async function matchOne(match, first) {
|
|
292
|
+
const pages = await listPageTargets();
|
|
293
|
+
const m = match.toLowerCase();
|
|
294
|
+
const hits = pages.filter((p) => (p.url ?? "").toLowerCase().includes(m) || (p.title ?? "").toLowerCase().includes(m));
|
|
295
|
+
if (hits.length === 0) throw new Error(`no open tab matches "${match}" — try \`browser-automation list\``);
|
|
296
|
+
if (hits.length > 1 && !first) throw new Error(`"${match}" matches ${hits.length} tabs — narrow it or pass --first:\n` + hits.map((h) => ` ${(h.title ?? "").slice(0, 30)} ${h.url}`).join("\n"));
|
|
297
|
+
return hits[0];
|
|
298
|
+
}
|
|
299
|
+
/** Resolve to an EXISTING live tab. Never creates. For read/snapshot/click/fill/close. */
|
|
300
|
+
async function resolveExistingTargetId(opts) {
|
|
301
|
+
if (opts.target) return resolveTargetIdArg(opts.target);
|
|
302
|
+
if (opts.match) return (await matchOne(opts.match, opts.first)).id;
|
|
303
|
+
const name = opts.session || defaultSessionName();
|
|
304
|
+
const st = loadSession(name);
|
|
305
|
+
if (st) {
|
|
306
|
+
if (await targetWsUrl(st.targetId)) return st.targetId;
|
|
307
|
+
}
|
|
308
|
+
throw new Error(`session "${name}" has no live tab. Open one with \`browser-automation goto -s ${name} <url>\`, target an existing tab with \`-m <url-or-title-substr>\`, or run \`browser-automation list\`.`);
|
|
309
|
+
}
|
|
310
|
+
/** Resolve, creating+binding a session tab only in pure session mode. For goto. */
|
|
311
|
+
async function resolveOrCreateTargetId(opts) {
|
|
312
|
+
if (opts.target || opts.match) return {
|
|
313
|
+
targetId: await resolveExistingTargetId(opts),
|
|
314
|
+
created: false
|
|
315
|
+
};
|
|
316
|
+
return resolveLiveTarget(opts.session || defaultSessionName());
|
|
317
|
+
}
|
|
318
|
+
//#endregion
|
|
319
|
+
//#region src/core/args.ts
|
|
320
|
+
const targetArgs = {
|
|
321
|
+
session: {
|
|
322
|
+
type: "string",
|
|
323
|
+
short: "s",
|
|
324
|
+
description: "Saved session name (default: $BAC_SESSION or \"default\")"
|
|
325
|
+
},
|
|
326
|
+
match: {
|
|
327
|
+
type: "string",
|
|
328
|
+
short: "m",
|
|
329
|
+
description: "Target an existing tab whose URL or title contains this substring"
|
|
330
|
+
},
|
|
331
|
+
target: {
|
|
332
|
+
type: "string",
|
|
333
|
+
short: "t",
|
|
334
|
+
description: "Target an exact tab by CDP targetId"
|
|
335
|
+
},
|
|
336
|
+
first: {
|
|
337
|
+
type: "boolean",
|
|
338
|
+
description: "If --match is ambiguous, use the first match instead of erroring"
|
|
339
|
+
}
|
|
340
|
+
};
|
|
341
|
+
function targetOpts(values) {
|
|
342
|
+
return {
|
|
343
|
+
session: values.session,
|
|
344
|
+
match: values.match,
|
|
345
|
+
target: values.target,
|
|
346
|
+
first: values.first
|
|
347
|
+
};
|
|
348
|
+
}
|
|
349
|
+
//#endregion
|
|
350
|
+
//#region src/commands/goto.ts
|
|
351
|
+
const gotoCommand = define({
|
|
352
|
+
name: "goto",
|
|
353
|
+
description: "Navigate a tab to a URL. Targets a session tab (created if needed), or an existing tab via -m/-t",
|
|
354
|
+
args: {
|
|
355
|
+
...targetArgs,
|
|
356
|
+
url: {
|
|
357
|
+
type: "positional",
|
|
358
|
+
description: "URL to navigate to"
|
|
359
|
+
}
|
|
360
|
+
},
|
|
361
|
+
async run(ctx) {
|
|
362
|
+
const url = ctx.positionals[1];
|
|
363
|
+
if (!url) {
|
|
364
|
+
consola.error("URL is required");
|
|
365
|
+
process.exit(1);
|
|
366
|
+
}
|
|
367
|
+
const target = normalizeUrl(url);
|
|
368
|
+
const opts = targetOpts(ctx.values);
|
|
369
|
+
const { targetId, created } = await resolveOrCreateTargetId(opts);
|
|
370
|
+
await navigate(targetId, target);
|
|
371
|
+
if (!opts.match && !opts.target) {
|
|
372
|
+
const name = opts.session || defaultSessionName();
|
|
373
|
+
saveSession({
|
|
374
|
+
name,
|
|
375
|
+
targetId,
|
|
376
|
+
url: target,
|
|
377
|
+
createdAt: loadSession(name)?.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
|
|
378
|
+
});
|
|
379
|
+
consola.success(`[${name}] ${created ? "opened tab + " : ""}navigated → ${target}`);
|
|
380
|
+
} else consola.success(`[${targetId.slice(0, 12)}…] navigated → ${target}`);
|
|
381
|
+
}
|
|
382
|
+
});
|
|
383
|
+
//#endregion
|
|
384
|
+
//#region src/core/dom.ts
|
|
385
|
+
const WALK = `
|
|
386
|
+
function __baSkip(t){return t==='SCRIPT'||t==='STYLE'||t==='NOSCRIPT'||t==='TEMPLATE';}
|
|
387
|
+
function __baVisible(el){try{const s=getComputedStyle(el);if(s.display==='none'||s.visibility==='hidden'||s.opacity==='0')return false;const r=el.getBoundingClientRect();return r.width>0||r.height>0;}catch(e){return true;}}
|
|
388
|
+
function __baEachEl(visit){
|
|
389
|
+
function rec(node){
|
|
390
|
+
if(node.nodeType!==1)return;
|
|
391
|
+
const tag=node.tagName;
|
|
392
|
+
if(__baSkip(tag))return;
|
|
393
|
+
visit(node);
|
|
394
|
+
if(node.shadowRoot){for(const c of node.shadowRoot.children)rec(c);}
|
|
395
|
+
if(tag==='IFRAME'){try{const d=node.contentDocument;if(d&&d.body){for(const c of d.body.children)rec(c);}}catch(e){}return;}
|
|
396
|
+
for(const c of node.children)rec(c);
|
|
397
|
+
}
|
|
398
|
+
if(document.body){for(const c of document.body.children)rec(c);}
|
|
399
|
+
}
|
|
400
|
+
function __baFind(ref){let f=null;__baEachEl((el)=>{if(!f&&el.getAttribute&&el.getAttribute('data-ba-ref')===ref)f=el;});return f;}
|
|
401
|
+
function __baQuery(sel){let f=null;__baEachEl((el)=>{if(!f){try{if(el.matches&&el.matches(sel))f=el;}catch(e){}}});return f;}
|
|
402
|
+
function __baText(root){
|
|
403
|
+
let parts=[];
|
|
404
|
+
function rec(node){
|
|
405
|
+
if(node.nodeType===3){const t=node.textContent;if(t&&t.trim())parts.push(t.trim());return;}
|
|
406
|
+
if(node.nodeType!==1)return;
|
|
407
|
+
const el=node,tag=el.tagName;
|
|
408
|
+
if(__baSkip(tag))return;
|
|
409
|
+
try{const s=getComputedStyle(el);if(s.display==='none'||s.visibility==='hidden')return;}catch(e){}
|
|
410
|
+
if(el.shadowRoot){for(const c of el.shadowRoot.childNodes)rec(c);}
|
|
411
|
+
if(tag==='IFRAME'){try{const d=el.contentDocument;if(d&&d.body)rec(d.body);}catch(e){}return;}
|
|
412
|
+
for(const c of el.childNodes)rec(c);
|
|
413
|
+
}
|
|
414
|
+
if(root)rec(root);
|
|
415
|
+
return parts.join(' ').replace(/\\s+/g,' ').trim();
|
|
416
|
+
}
|
|
417
|
+
`;
|
|
418
|
+
const SNAPSHOT_EXPR = WALK + `(() => {
|
|
419
|
+
__baEachEl((el)=>{ if(el.getAttribute && el.getAttribute('data-ba-ref')) el.removeAttribute('data-ba-ref'); });
|
|
420
|
+
const isInteractive=(el)=>{try{return el.matches('a,button,input,select,textarea,summary,[role=button],[role=link],[role=tab],[role=checkbox],[role=radio],[role=menuitem],[role=switch],[onclick],[contenteditable=""],[contenteditable=true]');}catch(e){return false;}};
|
|
421
|
+
const out=[]; let i=1;
|
|
422
|
+
__baEachEl((el)=>{
|
|
423
|
+
if(!isInteractive(el)||!__baVisible(el))return;
|
|
424
|
+
const ref='e'+(i++);
|
|
425
|
+
el.setAttribute('data-ba-ref',ref);
|
|
426
|
+
const tag=el.tagName.toLowerCase();
|
|
427
|
+
const role=el.getAttribute('role')||tag;
|
|
428
|
+
const type=el.getAttribute('type')||'';
|
|
429
|
+
let name=(el.getAttribute('aria-label')||el.getAttribute('placeholder')||(el.value||'')||el.innerText||el.getAttribute('title')||el.getAttribute('name')||'').toString().trim().replace(/\\s+/g,' ').slice(0,80);
|
|
430
|
+
out.push({ref,role,tag,type,name});
|
|
431
|
+
});
|
|
432
|
+
return {url:location.href,title:document.title,count:out.length,elements:out};
|
|
433
|
+
})()`;
|
|
434
|
+
function clickExpr(ref) {
|
|
435
|
+
const r = JSON.stringify(ref);
|
|
436
|
+
return WALK + `(() => {
|
|
437
|
+
const el=__baFind(${r});
|
|
438
|
+
if(!el)return {err:'ref not found: '+${r}+' (re-run snapshot)'};
|
|
439
|
+
el.scrollIntoView({block:'center',inline:'center'});
|
|
440
|
+
el.click();
|
|
441
|
+
return {ok:true,tag:el.tagName.toLowerCase()};
|
|
442
|
+
})()`;
|
|
443
|
+
}
|
|
444
|
+
function fillExpr(ref, value, submit) {
|
|
445
|
+
const r = JSON.stringify(ref);
|
|
446
|
+
const v = JSON.stringify(value);
|
|
447
|
+
return WALK + `(() => {
|
|
448
|
+
const el=__baFind(${r});
|
|
449
|
+
if(!el)return {err:'ref not found: '+${r}+' (re-run snapshot)'};
|
|
450
|
+
el.scrollIntoView({block:'center',inline:'center'});
|
|
451
|
+
el.focus();
|
|
452
|
+
if(el.isContentEditable){
|
|
453
|
+
el.textContent=${v};
|
|
454
|
+
el.dispatchEvent(new InputEvent('input',{bubbles:true}));
|
|
455
|
+
} else {
|
|
456
|
+
const proto=el instanceof HTMLTextAreaElement?HTMLTextAreaElement.prototype:HTMLInputElement.prototype;
|
|
457
|
+
const setter=Object.getOwnPropertyDescriptor(proto,'value')&&Object.getOwnPropertyDescriptor(proto,'value').set;
|
|
458
|
+
if(setter)setter.call(el,${v});else el.value=${v};
|
|
459
|
+
el.dispatchEvent(new Event('input',{bubbles:true}));
|
|
460
|
+
el.dispatchEvent(new Event('change',{bubbles:true}));
|
|
461
|
+
}
|
|
462
|
+
if(${submit ? "true" : "false"}){
|
|
463
|
+
const form=el.form||el.closest('form');
|
|
464
|
+
if(form&&form.requestSubmit)form.requestSubmit();
|
|
465
|
+
else if(form)form.submit();
|
|
466
|
+
else{
|
|
467
|
+
el.dispatchEvent(new KeyboardEvent('keydown',{key:'Enter',keyCode:13,bubbles:true}));
|
|
468
|
+
el.dispatchEvent(new KeyboardEvent('keyup',{key:'Enter',keyCode:13,bubbles:true}));
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
return {ok:true,value:el.value!==undefined?String(el.value).slice(0,80):${v}};
|
|
472
|
+
})()`;
|
|
473
|
+
}
|
|
474
|
+
function readExpr(selector) {
|
|
475
|
+
return WALK + `(() => { const r=${selector ? `__baQuery(${JSON.stringify(selector)})` : `document.body`}; return r ? __baText(r) : ${selector ? `'(no element matches ' + ${JSON.stringify(selector)} + ')'` : `''`}; })()`;
|
|
476
|
+
}
|
|
477
|
+
//#endregion
|
|
478
|
+
//#region src/commands/snapshot.ts
|
|
479
|
+
const snapshotCommand = define({
|
|
480
|
+
name: "snapshot",
|
|
481
|
+
description: "List interactive elements with refs (e1, e2, …) for click/fill",
|
|
482
|
+
args: {
|
|
483
|
+
...targetArgs,
|
|
484
|
+
json: {
|
|
485
|
+
type: "boolean",
|
|
486
|
+
description: "Output raw JSON"
|
|
487
|
+
}
|
|
488
|
+
},
|
|
489
|
+
async run(ctx) {
|
|
490
|
+
const snap = await evaluateUntil(await resolveExistingTargetId(targetOpts(ctx.values)), SNAPSHOT_EXPR, (s) => !!s && s.count > 0);
|
|
491
|
+
if (ctx.values.json) {
|
|
492
|
+
process.stdout.write(JSON.stringify(snap, null, 2) + "\n");
|
|
493
|
+
return;
|
|
494
|
+
}
|
|
495
|
+
consola.log(`# ${snap.title}\n# ${snap.url}\n# ${snap.count} interactive elements`);
|
|
496
|
+
for (const el of snap.elements) {
|
|
497
|
+
const label = el.type ? `${el.role}[${el.type}]` : el.role;
|
|
498
|
+
consola.log(`${el.ref.padEnd(5)} ${label.padEnd(18)} ${el.name}`);
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
});
|
|
502
|
+
//#endregion
|
|
503
|
+
//#region src/commands/click.ts
|
|
504
|
+
const clickCommand = define({
|
|
505
|
+
name: "click",
|
|
506
|
+
description: "Click an element by ref (from the latest snapshot)",
|
|
507
|
+
args: {
|
|
508
|
+
...targetArgs,
|
|
509
|
+
ref: {
|
|
510
|
+
type: "positional",
|
|
511
|
+
description: "Element ref, e.g. e7"
|
|
512
|
+
}
|
|
513
|
+
},
|
|
514
|
+
async run(ctx) {
|
|
515
|
+
const ref = ctx.positionals[1];
|
|
516
|
+
if (!ref || !isValidRef(ref)) {
|
|
517
|
+
consola.error("A ref like \"e7\" is required (run `browser-automation snapshot` first)");
|
|
518
|
+
process.exit(1);
|
|
519
|
+
}
|
|
520
|
+
const r = await evaluate(await resolveExistingTargetId(targetOpts(ctx.values)), clickExpr(ref));
|
|
521
|
+
if (r.err) {
|
|
522
|
+
consola.error(r.err);
|
|
523
|
+
process.exit(1);
|
|
524
|
+
}
|
|
525
|
+
consola.success(`clicked ${ref} <${r.tag}>`);
|
|
526
|
+
}
|
|
527
|
+
});
|
|
528
|
+
//#endregion
|
|
529
|
+
//#region src/commands/fill.ts
|
|
530
|
+
const fillCommand = define({
|
|
531
|
+
name: "fill",
|
|
532
|
+
description: "Type a value into an input/textarea/contenteditable by ref",
|
|
533
|
+
args: {
|
|
534
|
+
...targetArgs,
|
|
535
|
+
submit: {
|
|
536
|
+
type: "boolean",
|
|
537
|
+
description: "Submit the form after filling (requestSubmit / Enter)"
|
|
538
|
+
},
|
|
539
|
+
ref: {
|
|
540
|
+
type: "positional",
|
|
541
|
+
description: "Element ref, e.g. e3"
|
|
542
|
+
},
|
|
543
|
+
value: {
|
|
544
|
+
type: "positional",
|
|
545
|
+
description: "Value to type"
|
|
546
|
+
}
|
|
547
|
+
},
|
|
548
|
+
async run(ctx) {
|
|
549
|
+
const ref = ctx.positionals[1];
|
|
550
|
+
const value = ctx.positionals[2];
|
|
551
|
+
if (!ref || !isValidRef(ref)) {
|
|
552
|
+
consola.error("A ref like \"e3\" is required (run `browser-automation snapshot` first)");
|
|
553
|
+
process.exit(1);
|
|
554
|
+
}
|
|
555
|
+
if (value === void 0) {
|
|
556
|
+
consola.error("A value is required");
|
|
557
|
+
process.exit(1);
|
|
558
|
+
}
|
|
559
|
+
const r = await evaluate(await resolveExistingTargetId(targetOpts(ctx.values)), fillExpr(ref, value, ctx.values.submit ?? false));
|
|
560
|
+
if (r.err) {
|
|
561
|
+
consola.error(r.err);
|
|
562
|
+
process.exit(1);
|
|
563
|
+
}
|
|
564
|
+
consola.success(`filled ${ref} = "${r.value}"${ctx.values.submit ? " + submitted" : ""}`);
|
|
565
|
+
}
|
|
566
|
+
});
|
|
567
|
+
//#endregion
|
|
568
|
+
//#region src/commands/read.ts
|
|
569
|
+
const readCommand = define({
|
|
570
|
+
name: "read",
|
|
571
|
+
description: "Print visible text of the page. Optional positional: a CSS selector (default: whole body)",
|
|
572
|
+
args: { ...targetArgs },
|
|
573
|
+
async run(ctx) {
|
|
574
|
+
const selector = ctx.positionals[1];
|
|
575
|
+
const text = await evaluateUntil(await resolveExistingTargetId(targetOpts(ctx.values)), readExpr(selector), (t) => typeof t === "string" && t.trim().length > 0);
|
|
576
|
+
process.stdout.write((text ?? "") + "\n");
|
|
577
|
+
}
|
|
578
|
+
});
|
|
579
|
+
//#endregion
|
|
580
|
+
//#region src/commands/eval.ts
|
|
581
|
+
const evalCommand = define({
|
|
582
|
+
name: "eval",
|
|
583
|
+
description: "Evaluate a JS expression in the tab and print the result (power-user escape hatch)",
|
|
584
|
+
args: {
|
|
585
|
+
...targetArgs,
|
|
586
|
+
expr: {
|
|
587
|
+
type: "positional",
|
|
588
|
+
description: "JS expression to evaluate"
|
|
589
|
+
}
|
|
590
|
+
},
|
|
591
|
+
async run(ctx) {
|
|
592
|
+
const expr = ctx.positionals[1];
|
|
593
|
+
if (!expr) {
|
|
594
|
+
consola.error("A JS expression is required");
|
|
595
|
+
process.exit(1);
|
|
596
|
+
}
|
|
597
|
+
const v = await evaluate(await resolveExistingTargetId(targetOpts(ctx.values)), expr);
|
|
598
|
+
process.stdout.write((typeof v === "string" ? v : JSON.stringify(v, null, 2)) + "\n");
|
|
599
|
+
}
|
|
600
|
+
});
|
|
601
|
+
//#endregion
|
|
602
|
+
//#region src/core/download.ts
|
|
603
|
+
async function captureDownload(targetId, dir, triggerExpr, timeout = 3e4) {
|
|
604
|
+
mkdirSync(dir, { recursive: true });
|
|
605
|
+
const browser = await connect(await browserWsUrl());
|
|
606
|
+
try {
|
|
607
|
+
await browser.send("Browser.setDownloadBehavior", {
|
|
608
|
+
behavior: "allowAndName",
|
|
609
|
+
downloadPath: dir,
|
|
610
|
+
eventsEnabled: true
|
|
611
|
+
});
|
|
612
|
+
const names = /* @__PURE__ */ new Map();
|
|
613
|
+
const done = new Promise((resolve, reject) => {
|
|
614
|
+
const timer = setTimeout(() => reject(/* @__PURE__ */ new Error(`download did not complete within ${timeout}ms`)), timeout);
|
|
615
|
+
browser.on("Browser.downloadWillBegin", (p) => {
|
|
616
|
+
if (p?.guid) names.set(p.guid, p.suggestedFilename || p.guid);
|
|
617
|
+
});
|
|
618
|
+
browser.on("Browser.downloadProgress", (p) => {
|
|
619
|
+
if (p?.state === "completed") {
|
|
620
|
+
clearTimeout(timer);
|
|
621
|
+
const guidPath = join(dir, p.guid);
|
|
622
|
+
const name = names.get(p.guid) || p.guid;
|
|
623
|
+
let finalPath = guidPath;
|
|
624
|
+
try {
|
|
625
|
+
if (name !== p.guid && existsSync(guidPath)) {
|
|
626
|
+
renameSync(guidPath, join(dir, name));
|
|
627
|
+
finalPath = join(dir, name);
|
|
628
|
+
}
|
|
629
|
+
} catch {}
|
|
630
|
+
let bytes = p.receivedBytes ?? 0;
|
|
631
|
+
try {
|
|
632
|
+
bytes = statSync(finalPath).size;
|
|
633
|
+
} catch {}
|
|
634
|
+
resolve({
|
|
635
|
+
path: finalPath,
|
|
636
|
+
filename: name,
|
|
637
|
+
bytes
|
|
638
|
+
});
|
|
639
|
+
} else if (p?.state === "canceled") {
|
|
640
|
+
clearTimeout(timer);
|
|
641
|
+
reject(/* @__PURE__ */ new Error("download was canceled"));
|
|
642
|
+
}
|
|
643
|
+
});
|
|
644
|
+
});
|
|
645
|
+
await evaluate(targetId, triggerExpr, { userGesture: true });
|
|
646
|
+
return await done;
|
|
647
|
+
} finally {
|
|
648
|
+
browser.close();
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
function clickTriggerExpr(ref) {
|
|
652
|
+
return clickExpr(ref);
|
|
653
|
+
}
|
|
654
|
+
function urlTriggerExpr(url) {
|
|
655
|
+
return `(() => { const a=document.createElement('a'); a.href=${JSON.stringify(url)}; a.download=''; document.body.appendChild(a); a.click(); a.remove(); return true; })()`;
|
|
656
|
+
}
|
|
657
|
+
//#endregion
|
|
658
|
+
//#region src/commands/download.ts
|
|
659
|
+
const DEFAULT_DIR = join(homedir(), ".browser-automation", "downloads");
|
|
660
|
+
const downloadCommand = define({
|
|
661
|
+
name: "download",
|
|
662
|
+
description: "Capture a file download (e.g. a CSV export): trigger it with --click <ref> or --url, wait for completion",
|
|
663
|
+
args: {
|
|
664
|
+
...targetArgs,
|
|
665
|
+
click: {
|
|
666
|
+
type: "string",
|
|
667
|
+
description: "Ref of the element to click to start the download (e.g. e42)"
|
|
668
|
+
},
|
|
669
|
+
url: {
|
|
670
|
+
type: "string",
|
|
671
|
+
description: "Direct download URL to fetch (via an <a download> click in the page)"
|
|
672
|
+
},
|
|
673
|
+
dir: {
|
|
674
|
+
type: "string",
|
|
675
|
+
short: "d",
|
|
676
|
+
description: `Directory to save into (default: ${DEFAULT_DIR})`
|
|
677
|
+
},
|
|
678
|
+
timeout: {
|
|
679
|
+
type: "number",
|
|
680
|
+
description: "Max ms to wait for completion (default 30000)"
|
|
681
|
+
}
|
|
682
|
+
},
|
|
683
|
+
async run(ctx) {
|
|
684
|
+
const click = ctx.values.click;
|
|
685
|
+
const url = ctx.values.url;
|
|
686
|
+
if (!click && !url) {
|
|
687
|
+
consola.error("Provide --click <ref> or --url <url> to trigger the download");
|
|
688
|
+
process.exit(1);
|
|
689
|
+
}
|
|
690
|
+
if (click && !isValidRef(click)) {
|
|
691
|
+
consola.error(`--click expects a ref like e42 (run snapshot first)`);
|
|
692
|
+
process.exit(1);
|
|
693
|
+
}
|
|
694
|
+
const r = await captureDownload(await resolveExistingTargetId(targetOpts(ctx.values)), ctx.values.dir || DEFAULT_DIR, click ? clickTriggerExpr(click) : urlTriggerExpr(url), ctx.values.timeout ?? 3e4);
|
|
695
|
+
consola.success(`Downloaded ${r.filename} (${r.bytes} bytes)`);
|
|
696
|
+
process.stdout.write(r.path + "\n");
|
|
697
|
+
}
|
|
698
|
+
});
|
|
699
|
+
//#endregion
|
|
700
|
+
//#region src/commands/list.ts
|
|
701
|
+
const listCommand = define({
|
|
702
|
+
name: "list",
|
|
703
|
+
description: "List sessions and every open tab (with targetId + title) so you can pick -m/-t",
|
|
704
|
+
args: { json: {
|
|
705
|
+
type: "boolean",
|
|
706
|
+
description: "Output raw JSON"
|
|
707
|
+
} },
|
|
708
|
+
async run(ctx) {
|
|
709
|
+
const sessions = listSessions();
|
|
710
|
+
const targets = await listPageTargets().catch(() => []);
|
|
711
|
+
if (ctx.values.json) {
|
|
712
|
+
process.stdout.write(JSON.stringify({
|
|
713
|
+
sessions,
|
|
714
|
+
targets
|
|
715
|
+
}, null, 2) + "\n");
|
|
716
|
+
return;
|
|
717
|
+
}
|
|
718
|
+
const liveIds = new Set(targets.map((t) => t.id));
|
|
719
|
+
if (sessions.length) {
|
|
720
|
+
consola.log(`# sessions (${sessions.length})`);
|
|
721
|
+
for (const s of sessions) consola.log(` ${s.name.padEnd(16)} [${liveIds.has(s.targetId) ? "live" : "stale"}] ${s.url ?? ""}`);
|
|
722
|
+
consola.log("");
|
|
723
|
+
}
|
|
724
|
+
consola.log(`# open tabs (${targets.length}) — address with -t <id> or -m <substr>`);
|
|
725
|
+
for (const t of targets) {
|
|
726
|
+
const owner = sessions.find((s) => s.targetId === t.id);
|
|
727
|
+
const title = (t.title ?? "").replace(/\s+/g, " ").slice(0, 28);
|
|
728
|
+
consola.log(` ${t.id.slice(0, 12)} ${owner ? `(${owner.name}) ` : ""}${title.padEnd(28)} ${(t.url ?? "").slice(0, 70)}`);
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
});
|
|
732
|
+
//#endregion
|
|
733
|
+
//#region src/commands/close.ts
|
|
734
|
+
const closeCommand = define({
|
|
735
|
+
name: "close",
|
|
736
|
+
description: "Forget a session binding (tab stays open by default). Pass --tab to also close the browser tab",
|
|
737
|
+
args: {
|
|
738
|
+
...targetArgs,
|
|
739
|
+
tab: {
|
|
740
|
+
type: "boolean",
|
|
741
|
+
description: "Also close the actual browser tab (destructive; off by default)"
|
|
742
|
+
}
|
|
743
|
+
},
|
|
744
|
+
async run(ctx) {
|
|
745
|
+
const opts = targetOpts(ctx.values);
|
|
746
|
+
let targetId;
|
|
747
|
+
try {
|
|
748
|
+
targetId = await resolveExistingTargetId(opts);
|
|
749
|
+
} catch (e) {
|
|
750
|
+
consola.warn(e instanceof Error ? e.message : String(e));
|
|
751
|
+
return;
|
|
752
|
+
}
|
|
753
|
+
if (ctx.values.tab) {
|
|
754
|
+
const ok = await closeTab(targetId).catch(() => false);
|
|
755
|
+
consola.log(ok ? `Closed tab ${targetId.slice(0, 12)}….` : `Tab ${targetId.slice(0, 12)}… was already gone.`);
|
|
756
|
+
}
|
|
757
|
+
const forgotten = [];
|
|
758
|
+
for (const s of listSessions()) if (s.targetId === targetId) {
|
|
759
|
+
deleteSession(s.name);
|
|
760
|
+
forgotten.push(s.name);
|
|
761
|
+
}
|
|
762
|
+
if (!opts.match && !opts.target) {
|
|
763
|
+
const name = opts.session || defaultSessionName();
|
|
764
|
+
if (!forgotten.includes(name)) {
|
|
765
|
+
deleteSession(name);
|
|
766
|
+
forgotten.push(name);
|
|
767
|
+
}
|
|
768
|
+
}
|
|
769
|
+
if (forgotten.length) consola.success(`Forgot session(s): ${forgotten.join(", ")}.`);
|
|
770
|
+
else if (!ctx.values.tab) consola.info("No session bound to that tab and --tab not given — nothing to do.");
|
|
771
|
+
}
|
|
772
|
+
});
|
|
773
|
+
//#endregion
|
|
774
|
+
//#region src/commands/bind.ts
|
|
775
|
+
const bindCommand = define({
|
|
776
|
+
name: "bind",
|
|
777
|
+
description: "Adopt an already-open tab into a session name (pick it with -m <substr> or -t <id>)",
|
|
778
|
+
args: { ...targetArgs },
|
|
779
|
+
async run(ctx) {
|
|
780
|
+
const name = ctx.values.session || defaultSessionName();
|
|
781
|
+
const match = ctx.values.match;
|
|
782
|
+
const target = ctx.values.target;
|
|
783
|
+
if (!match && !target) {
|
|
784
|
+
consola.error("Pick the tab to adopt with -m <url/title substr> or -t <targetId>. See `browser-automation list`.");
|
|
785
|
+
process.exit(1);
|
|
786
|
+
}
|
|
787
|
+
let targetId;
|
|
788
|
+
let url;
|
|
789
|
+
if (target) {
|
|
790
|
+
targetId = await resolveTargetIdArg(target);
|
|
791
|
+
url = (await listPageTargets()).find((p) => p.id === targetId)?.url;
|
|
792
|
+
} else {
|
|
793
|
+
const hit = await matchOne(match, ctx.values.first);
|
|
794
|
+
targetId = hit.id;
|
|
795
|
+
url = hit.url;
|
|
796
|
+
}
|
|
797
|
+
saveSession({
|
|
798
|
+
name,
|
|
799
|
+
targetId,
|
|
800
|
+
url,
|
|
801
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
802
|
+
});
|
|
803
|
+
consola.success(`Bound session "${name}" → ${url ?? targetId}`);
|
|
804
|
+
}
|
|
805
|
+
});
|
|
806
|
+
//#endregion
|
|
807
|
+
//#region src/core/paths.ts
|
|
808
|
+
function packageRoot() {
|
|
809
|
+
return dirname(dirname(fileURLToPath(import.meta.url)));
|
|
810
|
+
}
|
|
811
|
+
function launchScriptPath() {
|
|
812
|
+
return join(packageRoot(), "scripts", "launch-chrome.sh");
|
|
813
|
+
}
|
|
814
|
+
//#endregion
|
|
815
|
+
//#region src/commands/launch.ts
|
|
816
|
+
const launchCommand = define({
|
|
817
|
+
name: "launch",
|
|
818
|
+
description: "Start (idempotent) the canonical headed Chrome on :9223 with the persistent profile",
|
|
819
|
+
args: { status: {
|
|
820
|
+
type: "boolean",
|
|
821
|
+
description: "Only report whether the CDP browser is up (exit 0/1)"
|
|
822
|
+
} },
|
|
823
|
+
async run(ctx) {
|
|
824
|
+
const script = launchScriptPath();
|
|
825
|
+
if (!existsSync(script)) {
|
|
826
|
+
consola.error(`launch-chrome.sh not found at ${script}. Reinstall the package.`);
|
|
827
|
+
process.exit(1);
|
|
828
|
+
}
|
|
829
|
+
const r = spawnSync("bash", [script, ...ctx.values.status ? ["--status"] : []], { stdio: "inherit" });
|
|
830
|
+
process.exit(r.status ?? 1);
|
|
831
|
+
}
|
|
832
|
+
});
|
|
833
|
+
//#endregion
|
|
834
|
+
//#region src/commands/doctor.ts
|
|
835
|
+
const PROFILE = process.env.BROWSER_AUTOMATION_PROFILE || `${homedir()}/Library/Application Support/Google/Chrome/browser-automation`;
|
|
836
|
+
const doctorCommand = define({
|
|
837
|
+
name: "doctor",
|
|
838
|
+
description: "Diagnose the setup: Node, Chrome on :9223, targets, sessions",
|
|
839
|
+
args: {},
|
|
840
|
+
async run() {
|
|
841
|
+
const ok = (m) => consola.log(` ✓ ${m}`);
|
|
842
|
+
const bad = (m) => consola.log(` ✗ ${m}`);
|
|
843
|
+
if (Number(process.versions.node.split(".")[0]) >= 22) ok(`Node ${process.versions.node} (global WebSocket available)`);
|
|
844
|
+
else bad(`Node ${process.versions.node} — need >= 22 for the global WebSocket CDP client`);
|
|
845
|
+
consola.log(` • CDP host: ${cdpHost()}`);
|
|
846
|
+
consola.log(` • Profile: ${PROFILE}`);
|
|
847
|
+
let version;
|
|
848
|
+
try {
|
|
849
|
+
version = await (await fetch(`${cdpHost()}/json/version`)).json();
|
|
850
|
+
ok(`Chrome reachable: ${version.Browser}`);
|
|
851
|
+
} catch {
|
|
852
|
+
bad(`No CDP browser on ${cdpHost()} — run: browser-automation launch`);
|
|
853
|
+
return;
|
|
854
|
+
}
|
|
855
|
+
try {
|
|
856
|
+
const targets = await listTargets();
|
|
857
|
+
const byType = {};
|
|
858
|
+
for (const t of targets) byType[t.type] = (byType[t.type] ?? 0) + 1;
|
|
859
|
+
const summary = Object.entries(byType).map(([k, v]) => `${v} ${k}`).join(", ");
|
|
860
|
+
ok(`${targets.length} targets (${summary})`);
|
|
861
|
+
consola.log(` (per-target CDP — target count never wedges this CLI)`);
|
|
862
|
+
} catch {
|
|
863
|
+
bad("Could not enumerate targets");
|
|
864
|
+
}
|
|
865
|
+
const sessions = listSessions();
|
|
866
|
+
consola.log(` • ${sessions.length} known session(s): ${sessions.map((s) => s.name).join(", ") || "(none)"}`);
|
|
867
|
+
}
|
|
868
|
+
});
|
|
869
|
+
//#endregion
|
|
870
|
+
//#region src/commands/index.ts
|
|
871
|
+
const defaultCommand = define({
|
|
872
|
+
name: "browser-automation",
|
|
873
|
+
description,
|
|
874
|
+
args: {},
|
|
875
|
+
async run() {
|
|
876
|
+
await listCommand.run?.call(this, { values: {} });
|
|
877
|
+
}
|
|
878
|
+
});
|
|
879
|
+
const subCommands = new Map([
|
|
880
|
+
["new", newCommand],
|
|
881
|
+
["goto", gotoCommand],
|
|
882
|
+
["snapshot", snapshotCommand],
|
|
883
|
+
["snap", snapshotCommand],
|
|
884
|
+
["click", clickCommand],
|
|
885
|
+
["fill", fillCommand],
|
|
886
|
+
["read", readCommand],
|
|
887
|
+
["eval", evalCommand],
|
|
888
|
+
["download", downloadCommand],
|
|
889
|
+
["list", listCommand],
|
|
890
|
+
["ls", listCommand],
|
|
891
|
+
["close", closeCommand],
|
|
892
|
+
["bind", bindCommand],
|
|
893
|
+
["launch", launchCommand],
|
|
894
|
+
["doctor", doctorCommand]
|
|
895
|
+
]);
|
|
896
|
+
async function run() {
|
|
897
|
+
await cli(process.argv.slice(2), defaultCommand, {
|
|
898
|
+
name: "browser-automation",
|
|
899
|
+
version,
|
|
900
|
+
description,
|
|
901
|
+
subCommands,
|
|
902
|
+
renderHeader: null
|
|
903
|
+
});
|
|
904
|
+
}
|
|
905
|
+
//#endregion
|
|
906
|
+
//#region src/index.ts
|
|
907
|
+
process.stdout.on("error", (err) => {
|
|
908
|
+
if (err.code === "EPIPE") process.exit(0);
|
|
909
|
+
throw err;
|
|
910
|
+
});
|
|
911
|
+
run().catch((err) => {
|
|
912
|
+
console.error(err instanceof Error ? err.message : String(err));
|
|
913
|
+
process.exit(1);
|
|
914
|
+
});
|
|
915
|
+
//#endregion
|
|
916
|
+
export {};
|