1 +import { type ChildProcess, execFileSync, spawn }
from "node:child_process";
2 +import { randomUUID }
from "node:crypto";
3 +import { existsSync }
from "node:fs";
14 +}
from "node:fs/promises";
15 +import { tmpdir }
from "node:os";
16 +import { join }
from "node:path";
17 +import type { Diagnostic }
from "./debug.ts";
32 +const COMMAND_MS
= 30_000,
34 + SPOOL_LIMIT
= 16 * 1024 * 1024;
36 + VIDEO_MAX
= 5 * 60_000,
37 + VIDEO_BYTES
= 256 * 1024 * 1024;
38 +const traceCategories
= 39 + "devtools.timeline,blink.user_timing,loading,disabled-by-default-devtools.timeline";
41 +export type Operation = {
63 +export type Options = {
65 + executablePath
?: string;
68 + artifactDir
?: string;
69 + diagnostic?: (entry
: Diagnostic)
=> void;
76 + frame
?: Record<
string,
Json>;
88 + process
: ChildProcess;
92 + droppedFrames
: number;
93 + timer
: NodeJS.
Timeout;
94 + sampleTimer
?: NodeJS.
Timeout;
97 + done
: Promise<
number | null>;
101 + done
: Promise<
Record<
string,
Json>>;
102 + finish: (v
: Record<
string,
Json>)
=> void;
103 + timer
: NodeJS.
Timeout;
106 +function alive(pid
: number)
: boolean {
107 + if (
!Number.
isSafeInteger(pid)
|| pid
<= 0)
return false;
109 + process.
kill(pid,
0);
112 + return (e
as NodeJS.
ErrnoException).
code === "EPERM";
116 +async function markOwned(dir
: string, browserPid
= 0)
: Promise<
void> {
118 + join(dir,
".pi-chrome-cdp-owner.json"),
120 + tag:
"pi-chrome-cdp-v1",
121 + ownerPid:
process.
pid,
128 +async function cleanupStale()
: Promise<
void> {
129 + for (
const name
of await readdir(
tmpdir())) {
130 + if (
!/^pi-chrome-cdp-[A-Za-z0-9_-]+$/.
test(name))
continue;
131 + const path
= join(
tmpdir(), name);
133 + if (
!(
await lstat(path)).
isDirectory())
continue;
134 + const marker
= JSON.
parse(
135 + await readFile(
join(path,
".pi-chrome-cdp-owner.json"),
"utf8"),
136 + )
as { tag
?: string; ownerPid
?: number; browserPid
?: number };
138 + marker.tag
!== "pi-chrome-cdp-v1" || 139 + alive(marker.ownerPid
|| 0)
|| 140 + alive(marker.browserPid
|| 0)
155 +async function saveNew(file
: string, bytes
: Buffer | string)
: Promise<
void> {
156 + const f
= await open(file,
"wx",
0o600);
158 + await f.
writeFile(bytes);
164 +async function waitExit(child
: ChildProcess, ms
= 3000)
: Promise<
boolean> {
165 + if (child.exitCode
!== null || child.signalCode
!== null)
return true;
166 + return new Promise((resolve)
=> {
167 + const t
= setTimeout(()
=> {
168 + child.
off(
"exit", onExit);
171 + const onExit = ()
=> {
175 + child.
once(
"exit", onExit);
179 +export class Browser {
180 + child
!: ChildProcess;
181 + socket
!: WebSocket;
187 + persistent
= false;
189 + lockToken
= randomUUID();
193 + viewport
= "unknown";
194 + observedTargets
: Json[]
= [];
195 + generation
= randomUUID();
196 + initialTarget
= "";
197 + initialSession
= "";
202 + monitor
= new Map<
string,
boolean>();
204 + sessions
= new Map<
string,
string>();
205 + results
= new Map<
string,
Frame>();
206 + pending
= new Map<
number, (f
: Frame)
=> void>();
207 + events
: Event[]
= [];
208 + watchers
: Watcher[]
= [];
209 + lateResponses
: Frame[]
= [];
211 + notices
: string[]
= [];
215 + firstEventSeq
?: number;
216 + lastEventSeq
?: number;
220 + spoolWrites
: Promise<
void>
= Promise.
resolve();
221 + queuedSpoolBytes
= 0;
222 + private protectedSpoolFiles
= new Set<
string>();
223 + private batchSpooling
= false;
225 + videoStopping
?: Promise<
string>;
227 + traceStopping
?: Promise<
string>;
228 + busy
: Promise<
void>
= Promise.
resolve();
230 + diagnostic?: (entry
: Diagnostic)
=> void;
231 + private eventCounts
= new Map<
string,
number>();
232 + private eventCount
= 0;
234 + private flushEventCounts()
: void {
235 + for (
const [method, count]
of this.eventCounts)
236 + this.
diagnostic?.({ event:
"cdp.events", method, count });
237 + this.eventCounts.
clear();
238 + this.eventCount
= 0;
241 + static async launch(opts
: Options)
: Promise<
Browser> {
242 + await cleanupStale();
243 + const b
= new Browser();
244 + b.diagnostic
= opts.diagnostic;
245 + b.
diagnostic?.({ event:
"browser.launch.start" });
246 + b.binary
= findExecutable(opts.executablePath);
247 + b.headed
= opts.headed
?? false;
248 + validateFlags(opts.flags
|| []);
249 + b.artifactDir
= opts.artifactDir
|| downloads();
250 + b.persistent
= !!opts.
profile;
252 + if (opts.
profile) {
253 + const name
= profileName(opts.
profile);
254 + b.profileDir
= join(
dataRoot(),
binaryKey(b.binary), name);
255 + await mkdir(b.profileDir, { recursive:
true, mode:
0o700 });
256 + const marker
= join(b.profileDir,
".pi-chrome-cdp-version");
257 + const lock
= join(b.profileDir,
".pi-chrome-cdp-lock");
258 + if (
existsSync(lock))
259 + throw new Error(
`profile locked: ${name}; close other owner first`);
260 + const version
= await Browser.
binaryMajor(b.binary);
261 + const entries
= await readdir(b.profileDir);
262 + if (
!existsSync(marker)
&& entries.
length)
264 + "profile version marker absent; refusing existing profile",
268 + JSON.
stringify({ pid:
process.
pid, token: b.lockToken }),
270 + b.ownedLock
= true;
271 + if (
existsSync(marker)) {
272 + const previous
= (
await readFile(marker,
"utf8")).
trim();
273 + if (
!/^\d+\.\d+\.\d+\.\d+$/.
test(previous))
274 + throw new Error(
"corrupt profile version marker");
275 + const a
= previous.
split(
".").
map(
Number),
276 + bver
= version.
split(
".").
map(
Number);
280 + n
> bver[i]
&& a.
slice(
0, i).
every((v, j)
=> v
=== bver[j]),
284 + `profile downgrade refused: ${previous} → ${version}`,
287 + const staged
= `${marker}.${randomUUID()}`;
288 + await writeFile(staged, version, { flag:
"wx", mode:
0o600 });
289 + await import(
"node:fs/promises").
then((fs)
=> 290 + fs.
rename(staged, marker),
293 + b.profileDir
= await mkdtemp(TMP_PREFIX);
294 + await markOwned(b.profileDir);
296 + b.spoolDir
= await mkdtemp(TMP_PREFIX);
297 + await markOwned(b.spoolDir);
299 + "--remote-debugging-port=0",
300 + "--remote-debugging-address=127.0.0.1",
301 + `--user-data-dir=${b.profileDir}`,
303 + "--window-size=1280,720",
304 + ...(b.headed
? []
: [
"--headless=new"]),
305 + ...(opts.flags
|| []),
308 + const active
= join(b.profileDir,
"DevToolsActivePort");
309 + await rm(active, { force:
true });
310 + b.child
= spawn(b.binary, args, { stdio:
"ignore" });
311 + let spawnFailure
: Error | undefined;
312 + b.child.
on(
"error", (e)
=> {
315 + if (
!b.persistent)
await markOwned(b.profileDir, b.child.pid);
316 + await markOwned(b.spoolDir, b.child.pid);
318 + for (
let i
= 0; i
< 200; i
++) {
319 + if (
existsSync(active)) {
320 + const [port]
= (
await readFile(active,
"utf8")).
split(
"\n");
321 + b.
port = Number(port);
322 + if (
Number.
isInteger(b.
port)
&& b.
port > 0) {
327 + if (spawnFailure)
throw spawnFailure;
328 + if (b.child.exitCode
!== null || b.child.signalCode
!== null)
330 + `Chrome exited during launch (${b.child.exitCode ?? b.child.signalCode})`,
332 + await new Promise((r)
=> setTimeout(r,
100));
335 + throw new Error(
"Chrome did not publish DevToolsActivePort within 20s");
336 + const address
= `http://127.0.0.1:${b.port}`;
337 + let meta
: { webSocketDebuggerUrl
: string; Browser
: string }
| undefined;
338 + for (
let attempt
= 0; attempt
< 50; attempt
++) {
341 + await fetch(
`${address}/json/version`, {
342 + signal: AbortSignal.
timeout(
1000),
344 + ).
json())
as typeof meta;
347 + if (spawnFailure)
throw spawnFailure;
348 + if (b.child.exitCode
!== null || b.child.signalCode
!== null)
349 + throw new Error(
"Chrome exited before HTTP endpoint became ready");
350 + await new Promise((r)
=> setTimeout(r,
100));
353 + if (
!meta)
throw new Error(
"Chrome HTTP discovery endpoint unavailable");
355 + !meta.webSocketDebuggerUrl?.
startsWith(
356 + `ws://127.0.0.1:${b.port}/devtools/browser/`,
358 + !meta.webSocketDebuggerUrl?.
startsWith(
359 + `ws://localhost:${b.port}/devtools/browser/`,
362 + throw new Error(
"unexpected Chrome debug endpoint");
363 + b.endpoint
= address;
364 + b.
version = meta.Browser;
365 + b.socket
= new WebSocket(meta.webSocketDebuggerUrl);
366 + await new Promise<
void>((resolve, reject)
=> {
367 + const timer
= setTimeout(
368 + ()
=> reject(
new Error(
"Chrome WebSocket timeout")),
371 + b.socket.
onopen = ()
=> {
372 + clearTimeout(timer);
375 + b.socket.
onerror = ()
=> {
376 + clearTimeout(timer);
377 + reject(
new Error(
"Chrome WebSocket failed"));
380 + b.socket.
onmessage = (e)
=> b.
onMessage(
String(e.
data));
381 + b.socket.
onclose = ()
=> {
382 + for (
const [id, pending]
of b.pending)
385 + error: { code:
-1, message:
"Chrome connection closed" },
386 + transportError:
true,
389 + b.uncertain
= true;
391 + const dir
= await mkdtemp(TMP_PREFIX);
393 + await markOwned(dir, b.child.pid);
394 + b.spoolFiles.
push({ file: dir, bytes:
0 });
395 + const download
= await b.
send(
"Browser.setDownloadBehavior", {
398 + eventsEnabled:
true,
400 + if (download.error)
401 + throw new Error(
`cannot contain downloads: ${download.error.message}`);
402 + const auto
= await b.
send(
"Target.setAutoAttach", {
404 + waitForDebuggerOnStart:
false,
408 + throw new Error(
`cannot attach targets: ${auto.error.message}`);
409 + const target
= await b.
send(
"Target.createTarget", {
410 + url:
"about:blank",
412 + if (target.error)
throw new Error(target.error.message);
413 + b.initialTarget
= String(
414 + (target.result
as Record<
string,
Json>).targetId,
416 + const attach
= await b.
send(
"Target.attachToTarget", {
417 + targetId: b.initialTarget,
420 + if (attach.error)
throw new Error(attach.error.message);
421 + b.initialSession
= String(
422 + (attach.result
as Record<
string,
Json>).sessionId,
424 + b.sessions.
set(b.initialSession, b.initialTarget);
425 + for (
const method
of [
"Runtime.enable",
"Log.enable",
"Page.enable"]) {
426 + const result
= await b.
send(method, {}, b.initialSession);
428 + `${b.initialSession}:${method.split(".")[0]}`,
432 + await b.
refreshStatus();
433 + b.
diagnostic?.({ event:
"browser.launch.end", outcome:
"ok" });
436 + b.
diagnostic?.({ event:
"browser.launch.end", outcome:
"error" });
442 + static async binaryMajor(file
: string)
: Promise<
string> {
443 + const text
= execFileSync(file, [
"--version"], {
447 + const version
= text.
match(
/\b(\d+\.\d+\.\d+\.\d+)\b/)?.[
1];
449 + throw new Error(
`cannot parse Chrome version: ${text.trim()}`);
453 + onMessage(text
: string)
: void {
454 + let frame
: Record<
string,
Json>;
456 + frame
= JSON.
parse(text);
460 + if (
typeof frame.
id === "number") {
461 + const callback
= this.pending.
get(frame.
id);
463 + this.pending.
delete(frame.
id);
464 + callback(frame
as Frame);
466 + const size
= Buffer.
byteLength(text);
467 + this.lateResponses.
push(
473 + message:
`late response of ${size} bytes omitted from memory`,
475 + transportError:
true,
477 + : (frame
as Frame),
479 + if (size
> 16384) this.gaps
++;
480 + while (this.lateResponses.
length > 4) this.lateResponses.
shift();
484 + const method
= frame.
method;
485 + const params
= frame.params
as Record<
string,
Json>
| undefined;
486 + if (method
!== "Page.screencastFrame" && this.diagnostic) {
487 + const name
= String(method);
489 + /^(Runtime\.exceptionThrown|Log\.entryAdded|Target\.(attachedToTarget|detachedFromTarget)|Page\.(frameNavigated|loadEventFired)|Network\.loadingFailed|Tracing\.tracingComplete)$/.
test(
494 + event:
"cdp.event",
497 + typeof frame.sessionId
=== "string" ? frame.sessionId
: undefined,
500 + this.eventCounts.
set(name, (this.eventCounts.
get(name)
|| 0)
+ 1);
501 + if (
++this.eventCount
>= 200) this.
flushEventCounts();
505 + method
=== "Page.screencastFrame" && 507 + frame.sessionId
=== this.video.sessionId
&& 510 + const data
= String(params.
data || "");
511 + const bytes
= Buffer.
from(data,
"base64");
512 + this.video.
size += bytes.
length;
513 + const video
= this.video;
514 + if (video.
size > VIDEO_BYTES
&& !this.videoStopping)
515 + void this.
stopVideo().
catch((e)
=> {
516 + this.notices.
push(
`video finalize failed: ${String(e)}`);
518 + else if (
!this.videoStopping) video.lastFrame
= bytes;
519 + if (this.video
=== video)
521 + "Page.screencastFrameAck",
522 + { sessionId: params.sessionId },
527 + if (method
=== "Tracing.tracingComplete" && this.trace
&& params)
528 + this.trace.
finish(params);
529 + if (method
=== "Target.attachedToTarget" && params) {
530 + const sid
= String(params.sessionId
|| "");
531 + const info
= params.targetInfo
as Record<
string,
Json>
| undefined;
532 + if (sid
&& info?.targetId) {
533 + this.sessions.
set(sid,
String(info.targetId));
535 + info.
type === "page" || 536 + info.
type === "worker" || 537 + info.
type === "service_worker" || 538 + info.
type === "iframe" 541 + "Target.setAutoAttach",
542 + { autoAttach:
true, waitForDebuggerOnStart:
false, flatten:
true },
546 + ...(info.
type === "page" ? [
"Page.enable"]
: []),
550 + void this.
send(m, {}, sid)
552 + this.monitor.
set(
`${sid}:${m.split(".")[0]}`,
!r.error),
558 + if (method
=== "Target.detachedFromTarget" && params)
559 + this.sessions.
delete(
String(params.sessionId
|| ""));
560 + if (this.events.
length >= EVENTS) {
561 + const removed
= this.events.
shift();
562 + if (removed) this.
queueEventSpool(removed);
564 + const raw
= JSON.
stringify(frame);
565 + const size
= Buffer.
byteLength(raw);
566 + const event
: Event = {
568 + time:
new Date().
toISOString(),
569 + sessionId: frame.sessionId
as string | undefined,
570 + method:
String(method),
571 + ...(size
> 16384 ? { bytes: size }
: { frame }),
573 + if (size
> 16384) this.
queueEventSpool(
event, frame);
574 + for (
const watcher
of this.watchers)
577 + event.seq
> watcher.since
&& 578 + event.
method === watcher.
method && 579 + event.sessionId
=== watcher.sessionId
581 + watcher.hit
= event;
582 + this.events.
push(
event);
585 + private queueSpool<
T>(
write: ()
=> Promise<
T>)
: Promise<
T> {
586 + const task
= this.spoolWrites.
then(write);
587 + this.spoolWrites
= task.
then(
594 + queueEventSpool(e
: Event, frame
?: Record<
string,
Json>)
: void {
595 + const item
= frame
? {
...e, frame }
: e;
596 + const bytes
= Buffer.
byteLength(
JSON.
stringify(item));
597 + if (this.queuedSpoolBytes
+ bytes
> SPOOL_LIMIT) {
602 + this.queuedSpoolBytes
+= bytes;
603 + void this.
queueSpool(
async ()
=> {
604 + e.spooled
= await this.
writeSpoolEvent(item);
611 + this.queuedSpoolBytes
-= bytes;
615 + beginBatchSpool(startSeq
: number)
: void {
616 + this.protectedSpoolFiles.
clear();
617 + this.batchSpooling
= true;
618 + for (
const event
of this.events)
619 + if (
event.seq
> startSeq
&& event.spooled
&& !event.lost)
620 + this.
protectSpoolFile(
event.spooled);
623 + private async makeSpoolRoom(bytes
: number)
: Promise<
boolean> {
624 + while (this.spoolBytes
+ bytes
> SPOOL_LIMIT) {
625 + const oldest
= this.spoolFiles.
find(
626 + (f)
=> f.bytes
> 0 && !this.protectedSpoolFiles.
has(f.file),
628 + if (
!oldest)
return false;
629 + this.spoolFiles.
splice(this.spoolFiles.
indexOf(oldest),
1);
630 + await rm(oldest.file, { force:
true });
631 + if (oldest.firstEventSeq
!== undefined) {
633 + for (
const event
of this.events)
634 + if (
event.spooled
=== oldest.file) {
635 + delete event.spooled;
639 + this.spoolBytes
-= oldest.bytes;
645 + protectSpoolFile(file
: string)
: void {
646 + if (this.batchSpooling) this.protectedSpoolFiles.
add(file);
649 + private async writeSpoolEvent(e
: Event)
: Promise<
string> {
650 + const bytes
= JSON.
stringify(e)
+ "\n";
651 + const size
= Buffer.
byteLength(bytes);
652 + if (
!(
await this.
makeSpoolRoom(size))) {
659 + `events-${this.generation}-${this.eventChunk}.jsonl`,
661 + await appendFile(path, bytes, { mode:
0o600 });
662 + let entry
= this.spoolFiles.
find((f)
=> f.file
=== path);
667 + firstEventSeq: e.seq,
668 + lastEventSeq: e.seq,
670 + this.spoolFiles.
push(entry);
672 + entry.bytes
+= size;
673 + entry.firstEventSeq
??= e.seq;
674 + entry.lastEventSeq
= e.seq;
675 + this.spoolBytes
+= size;
676 + this.
protectSpoolFile(path);
680 + spoolEvent(e
: Event)
: Promise<
string> {
681 + return this.
queueSpool(()
=> this.
writeSpoolEvent(e));
687 + sessionId
?: string,
688 + signal
?: AbortSignal,
689 + timeoutMs
= COMMAND_MS,
690 + )
: Promise<
Frame> {
691 + if (
!this.socket
|| this.socket.
readyState !== WebSocket.OPEN)
692 + return Promise.
reject(
new Error(
"Chrome socket not open"));
693 + const id
= this.nextId
++;
694 + const started
= Date.
now();
695 + if (method
!== "Page.screencastFrameAck")
696 + this.
diagnostic?.({ event:
"cdp.send", method, wireId: id, sessionId });
697 + return new Promise((resolve)
=> {
699 + const finish = (frame
: Frame)
=> {
702 + clearTimeout(timer);
703 + signal?.
removeEventListener(
"abort", abort);
704 + this.pending.
delete(id);
705 + if (method
!== "Page.screencastFrameAck")
706 + this.
diagnostic?.({
707 + event:
"cdp.reply",
710 + elapsedMs:
Date.
now()
- started,
711 + code: frame.error?.
code,
712 + outcome: frame.transportError
720 + const abort = ()
=> {
721 + this.uncertain
= true;
724 + error: { code:
-2, message:
"canceled; effects may have applied" },
725 + transportError:
true,
728 + const timer
= setTimeout(()
=> {
729 + this.uncertain
= true;
734 + message:
`timeout after ${timeoutMs}ms; effects may have applied`,
736 + transportError:
true,
739 + if (signal?.aborted) {
743 + signal?.
addEventListener(
"abort", abort, { once:
true });
744 + this.pending.
set(id, finish);
751 + ...(sessionId
? { sessionId }
: {}),
757 + error: { code:
-4, message:
String(e) },
758 + transportError:
true,
764 + async refreshStatus()
: Promise<
void> {
765 + const targets
= await this.
send(
"Target.getTargets");
767 + throw new Error(
`status unavailable: ${targets.error.message}`);
768 + this.observedTargets
= 769 + ((targets.result
as Record<
string,
Json>).targetInfos
as Json[])
|| [];
770 + const metrics
= await this.
send(
771 + "Page.getLayoutMetrics",
773 + this.initialSession,
775 + if (
!metrics.error) {
776 + const viewport
= (metrics.result
as Record<
string,
Json>)
777 + .cssVisualViewport
as Record<
string,
Json>
| undefined;
779 + this.viewport
= `${viewport.clientWidth}x${viewport.clientHeight}`;
781 + this.uncertain
= false;
786 + generation: this.generation,
787 + pid: this.child?.pid,
789 + endpoint: this.endpoint,
790 + protocol:
`${this.endpoint}/json/protocol`,
791 + version: this.
version,
792 + binary: this.binary,
793 + headed: this.headed,
794 + viewport: this.viewport,
795 + profile: this.persistent
? "named" : "temporary",
796 + initialTarget: this.initialTarget,
797 + initialSession: this.initialSession,
798 + targets: this.observedTargets,
799 + sessions:
Object.
fromEntries(this.sessions),
800 + monitor:
Object.
fromEntries(this.monitor),
801 + autoAttach: this.autoAttach,
802 + uncertain: this.uncertain,
803 + notices: this.notices.
slice(
-8),
804 + lateResponses: this.lateResponses,
805 + video: this.video?.file,
806 + droppedVideoFrames: this.video?.droppedFrames,
807 + trace: this.trace?.file,
812 + async outputFile(filename
: string | undefined, ext
: string)
: Promise<
string> {
813 + await mkdir(this.artifactDir, { recursive:
true, mode:
0o700 });
816 + `chrome-cdp-${new Date().toISOString().replace(/[:.]/g, "-")}-${randomUUID()}.${ext}`;
817 + const path
= artifactPath(this.artifactDir, name);
818 + if (
existsSync(path))
throw new Error(
`artifact already exists: ${path}`);
826 + )
: Promise<{ file
: string; data
: string }> {
827 + const response
= await this.
send(
828 + "Page.captureScreenshot",
829 + { format:
"png", captureBeyondViewport: fullPage, fromSurface:
true },
832 + if (response.error)
throw new Error(response.error.message);
833 + const data
= String((response.result
as Record<
string,
Json>).
data || "");
834 + const file
= await this.
outputFile(filename,
"png");
835 + await saveNew(file,
Buffer.
from(data,
"base64"));
836 + return { file, data };
839 + async startVideo(sid
: string, filename
?: string)
: Promise<
string> {
840 + if (this.video)
throw new Error(
"video already running");
841 + const file
= await this.
outputFile(filename,
"webm");
842 + if (
!file.
endsWith(
".webm"))
843 + throw new Error(
"video filename must end in .webm");
844 + const ffmpeg
= spawn(
863 + { stdio: [
"pipe",
"ignore",
"pipe"] },
865 + await new Promise<
void>((resolve, reject)
=> {
866 + ffmpeg.
once(
"spawn", ()
=> resolve());
867 + ffmpeg.
once(
"error", reject);
870 + ffmpeg.stderr?.
on(
"data", (data)
=> {
871 + error
= (error
+ String(data)).
slice(
-2048);
873 + ffmpeg.stdin?.
on(
"error", ()
=> {
876 + const done
= new Promise<
number | null>((resolve)
=> 877 + ffmpeg.
once(
"exit", (code)
=> resolve(code)),
879 + const timer
= setTimeout(
881 + void this.
stopVideo().
catch((e)
=> {
882 + this.notices.
push(
`video finalize failed: ${String(e)}`);
886 + const video
: Video = {
895 + this.video
= video;
896 + const r
= await this.
send(
897 + "Page.startScreencast",
898 + { format:
"jpeg", quality:
75, everyNthFrame:
1 },
902 + await this.
stopVideo();
903 + throw new Error(r.error.message);
907 + video.sampleTimer
= setInterval(()
=> {
908 + if (
!video.lastFrame)
return;
910 + video.process.stdin?.writable
&& 911 + video.process.stdin.writableLength
< 2 * 1024 * 1024 913 + video.process.stdin.
write(video.lastFrame);
914 + video.samples
= (video.samples
|| 0)
+ 1;
915 + }
else video.droppedFrames
++;
920 + async stopVideo(issueStop
= true)
: Promise<
string> {
921 + if (this.videoStopping)
return this.videoStopping;
922 + const v
= this.video;
923 + if (
!v)
throw new Error(
"no managed video running");
924 + this.videoStopping
= (
async ()
=> {
925 + clearTimeout(v.timer);
926 + if (v.sampleTimer)
clearInterval(v.sampleTimer);
927 + if (issueStop
&& this.socket?.
readyState === WebSocket.OPEN)
928 + await this.
send(
"Page.stopScreencast", {}, v.sessionId).
catch(()
=> {});
929 + v.process.stdin?.
end();
930 + let guard
: NodeJS.
Timeout | undefined;
931 + const code
= await Promise.
race([
933 + new Promise<
null>((resolve)
=> {
934 + guard
= setTimeout(()
=> resolve(
null),
5000);
937 + if (guard)
clearTimeout(guard);
938 + if (code
=== null) {
939 + v.process.
kill(
"SIGKILL");
942 + if (this.video
=== v) this.video
= undefined;
943 + if (code
!== 0 || !existsSync(v.file))
944 + throw new Error(
`ffmpeg failed (${code ?? "timeout"}); ${v.file}`);
948 + return await this.videoStopping;
950 + this.videoStopping
= undefined;
954 + async startTrace(filename
?: string)
: Promise<
string> {
955 + if (this.trace)
throw new Error(
"trace already running");
956 + const file
= await this.
outputFile(filename,
"json");
957 + let finish!: (v
: Record<
string,
Json>)
=> void;
958 + const done
= new Promise<
Record<
string,
Json>>((resolve)
=> {
961 + const timer
= setTimeout(
963 + void this.
stopTrace().
catch((e)
=> {
964 + this.notices.
push(
`trace finalize failed: ${String(e)}`);
968 + this.trace
= { file, done, finish, timer };
969 + const result
= await this.
send(
"Tracing.start", {
970 + categories: traceCategories,
971 + transferMode:
"ReturnAsStream",
973 + if (result.error) {
974 + clearTimeout(timer);
975 + this.trace
= undefined;
976 + throw new Error(result.error.message);
981 + async stopTrace(issueEnd
= true)
: Promise<
string> {
982 + if (this.traceStopping)
return this.traceStopping;
983 + const trace
= this.trace;
984 + if (
!trace)
throw new Error(
"no managed trace running");
985 + this.traceStopping
= (
async ()
=> {
986 + clearTimeout(trace.timer);
989 + const end
= await this.
send(
"Tracing.end");
990 + if (end.error)
throw new Error(end.error.message);
992 + let guard
: NodeJS.
Timeout | undefined;
993 + const completion
= await Promise.
race([
995 + new Promise<
null>((resolve)
=> {
996 + guard
= setTimeout(()
=> resolve(
null),
15000);
999 + if (guard)
clearTimeout(guard);
1000 + if (
!completion?.stream)
throw new Error(
"trace stream not returned");
1001 + const stream
= String(completion.stream);
1002 + let out
: Awaited<
ReturnType<
typeof open>>
| undefined;
1003 + let finished
= false;
1006 + out
= await open(trace.file,
"wx",
0o600);
1008 + const r
= await this.
send(
"IO.read", {
1010 + size:
1024 * 1024,
1012 + if (r.error)
throw new Error(r.error.message);
1013 + const data
= r.result
as Record<
string,
Json>;
1014 + const chunk
= data.base64Encoded
1015 + ? Buffer.
from(
String(data.
data),
"base64")
1016 + : Buffer.
from(
String(data.
data || ""));
1017 + bytes
+= chunk.
length;
1018 + if (bytes
> VIDEO_BYTES)
1019 + throw new Error(
"trace size limit reached");
1020 + await out.
writeFile(chunk);
1021 + if (data.eof)
break;
1026 + await out?.
close();
1028 + await this.
send(
"IO.close", { handle: stream }).
catch(()
=> {});
1029 + if (out
&& !finished)
await rm(trace.file, { force:
true });
1032 + return trace.file;
1034 + if (this.trace
=== trace) this.trace
= undefined;
1038 + return await this.traceStopping;
1040 + this.traceStopping
= undefined;
1044 + spoolPayload(text
: string)
: Promise<
string> {
1045 + return this.
queueSpool(
async ()
=> {
1046 + const bytes
= Buffer.
byteLength(text);
1047 + if (bytes
> SPOOL_LIMIT)
1048 + throw new Error(
"tool result exceeds spool quota");
1049 + if (
!(
await this.
makeSpoolRoom(bytes)))
1051 + "tool result exceeds available spool quota; current batch files are retained",
1053 + const file
= join(this.spoolDir,
`batch-${randomUUID()}.json`);
1054 + await saveNew(file, text);
1055 + this.spoolFiles.
push({ file, bytes });
1056 + this.spoolBytes
+= bytes;
1057 + this.
protectSpoolFile(file);
1064 + text
= JSON.
stringify(frame),
1065 + )
: Promise<{ path
: string; bytes
: number; preview
: string }
| Frame> {
1066 + return this.
queueSpool(
async ()
=> {
1067 + const bytes
= Buffer.
byteLength(text);
1068 + if (bytes
<= INLINE)
return frame;
1069 + if (bytes
> SPOOL_LIMIT)
1070 + throw new Error(
`response ${bytes} bytes exceeds spool quota`);
1071 + if (
!(
await this.
makeSpoolRoom(bytes)))
1073 + `response ${bytes} bytes exceeds available spool quota; current batch files are retained`,
1075 + const file
= join(
1077 + `response-${frame.id}-${randomUUID()}.json`,
1079 + await saveNew(file, text);
1080 + this.spoolFiles.
push({ file, bytes });
1081 + this.spoolBytes
+= bytes;
1082 + this.
protectSpoolFile(file);
1083 + return { path: file, bytes, preview: text.
slice(
0,
512) };
1087 + async close()
: Promise<
void> {
1088 + if (this.
closed)
return;
1089 + this.
flushEventCounts();
1090 + this.
diagnostic?.({ event:
"browser.close.start" });
1091 + const failed = (type
: string)
=> (e
: unknown)
=> {
1092 + this.notices.
push(
`${type} finalize failed: ${String(e)}`);
1094 + if (this.videoStopping)
await this.videoStopping.
catch(
failed(
"video"));
1095 + else if (this.video)
await this.
stopVideo().
catch(
failed(
"video"));
1096 + if (this.traceStopping)
await this.traceStopping.
catch(
failed(
"trace"));
1097 + else if (this.trace)
await this.
stopTrace().
catch(
failed(
"trace"));
1100 + this.child.exitCode
=== null && 1101 + this.child.signalCode
=== null && 1102 + this.socket?.
readyState === WebSocket.OPEN
1107 + id: this.nextId
++,
1108 + method:
"Browser.close",
1115 + await waitExit(this.child);
1117 + this.socket?.
close();
1120 + this.child.exitCode
=== null && 1121 + this.child.signalCode
=== null 1123 + this.child.
kill(
"SIGTERM");
1124 + if (
!(
await waitExit(this.child))) {
1125 + this.child.
kill(
"SIGKILL");
1126 + if (
!(
await waitExit(this.child)))
1127 + throw new Error(
"Chrome remains alive; profile and lock preserved");
1130 + if (
!this.persistent
&& this.profileDir)
1131 + await rm(this.profileDir, { recursive:
true, force:
true });
1132 + if (this.spoolDir)
1133 + await rm(this.spoolDir, { recursive:
true, force:
true });
1134 + for (
const f
of this.spoolFiles)
1135 + if (
!f.bytes)
await rm(f.file, { recursive:
true, force:
true });
1136 + if (this.persistent
&& this.ownedLock) {
1137 + const lock
= join(this.profileDir,
".pi-chrome-cdp-lock");
1138 + const current
= JSON.
parse(
await readFile(lock,
"utf8"))
as {
1141 + if (current.token
!== this.lockToken)
1142 + throw new Error(
"profile lock ownership changed; refusing release");
1144 + this.ownedLock
= false;
1146 + this.
closed = true;
1147 + this.
diagnostic?.({ event:
"browser.close.end", outcome:
"ok" });
1151 +export async function executeOperations(
1154 + signal
?: AbortSignal,
1155 + replayFrom
?: number,
1156 + onProgress?: (completed
: number, active
: string)
=> void,
1158 + output
: unknown[];
1159 + images
: { data
: string; mimeType
: string }[];
1161 + overflow
: string[];
1162 + status
: ReturnType<
Browser[
"status"]>;
1165 + failedOperation
?: { operation
: number; kind
: Operation[
"kind"] };
1166 + skipped
?: { operation
: number; kind
: Operation[
"kind"] }[];
1168 + const results
: unknown[]
= [],
1169 + images
: { data
: string; mimeType
: string }[]
= [];
1170 + let failure
: string | undefined;
1171 + let failedOperation
: 1172 + | { operation
: number; kind
: Operation[
"kind"] }
1174 + const skipped = (from
: number)
=> 1175 + ops.
slice(from).
map((op, index)
=> ({
1176 + operation: from
+ index,
1179 + const startSeq
= replayFrom
?? b.cursor;
1180 + const closeIndex
= ops.
findIndex((op)
=> op.kind
=== "close");
1181 + if (closeIndex
>= 0 && ops.
length !== 1)
1187 + status: b.
status(),
1189 + failure:
"close must be the only operation in its call",
1190 + failedOperation: { operation: closeIndex, kind:
"close" },
1191 + skipped:
skipped(closeIndex
+ 1),
1193 + const waits
= new Map<
string,
Watcher>();
1194 + const knownLabels
= new Set<
string>();
1195 + for (
const [index, op]
of ops.
entries()) {
1196 + if (op.kind
=== "cdp" && op.
label) knownLabels.
add(op.
label);
1197 + if (op.kind
=== "wait") {
1198 + if (
!op.after
|| !knownLabels.
has(op.after)
|| !op.
event || !op.sessionId)
1204 + status: b.
status(),
1207 + "wait must follow a labeled cdp command in the same batch and include after, event, and sessionId",
1208 + failedOperation: { operation: index, kind:
"wait" },
1209 + skipped:
skipped(index
+ 1),
1211 + if (waits.
has(op.after))
1217 + status: b.
status(),
1219 + failure:
`multiple waits use after label: ${op.after}; use distinct labeled cdp commands`,
1220 + failedOperation: { operation: index, kind:
"wait" },
1221 + skipped:
skipped(index
+ 1),
1223 + waits.
set(op.after, {
1225 + sessionId: op.sessionId,
1230 + b.
beginBatchSpool(startSeq);
1231 + const session = (op
: Operation)
: string | undefined => {
1232 + if (
!op.sessionId)
return undefined;
1233 + const sid
= ref(op.sessionId, b.results);
1234 + if (
typeof sid
!== "string")
1235 + throw new Error(
"sessionId reference must resolve to a string");
1239 + for (
let i
= 0; i
< ops.
length; i
++) {
1240 + const op
= ops[i];
1241 + const started
= Date.
now();
1243 + event:
"operation.start",
1246 + method: op.kind
=== "cdp" ? op.
method : undefined,
1248 + onProgress?.(i, op.kind
=== "cdp" ? `cdp ${op.method ?? ""}` : op.kind);
1250 + if (signal?.aborted) {
1251 + b.uncertain
= true;
1252 + throw new Error(
"canceled before next operation");
1254 + if (b.uncertain
&& op.kind
!== "status" && op.kind
!== "close")
1255 + throw new Error(
"browser state uncertain; call managed status first");
1256 + if (op.kind
=== "cdp") {
1257 + if (
!op.
method)
throw new Error(
"method required");
1258 + const sid
= session(op);
1261 + /^(Page|DOM|Runtime|Log|Network|CSS|Input|Accessibility|Performance|Emulation|Fetch)\./.
test(
1265 + throw new Error(
"page command requires sessionId");
1267 + if (
!/^[a-zA-Z][\w-]*$/.
test(op.
label))
1268 + throw new Error(
"invalid command label");
1269 + if (b.results.
has(op.
label))
1270 + throw new Error(
`duplicate label: ${op.label}`);
1272 + if (op.
label && waits.
has(op.
label)) {
1273 + const watcher
= waits.
get(op.
label);
1274 + if (
!watcher)
throw new Error(
"wait not armed");
1275 + watcher.sessionId
= 1276 + session({
...op, sessionId: watcher.sessionId })
|| "";
1277 + watcher.since
= b.seq;
1278 + b.watchers.
push(watcher);
1280 + const p
= ref(op.params
?? {}, b.results);
1281 + const frame
= await b.
send(
1286 + op.timeoutMs
|| COMMAND_MS,
1288 + const serialized
= 1289 + op.
label && !frame.error
? JSON.
stringify(frame)
: undefined;
1293 + Buffer.
byteLength(serialized)
<= INLINE
1295 + b.results.
set(op.
label, frame);
1296 + if (b.results.
size > 128) {
1297 + const oldest
= b.results.
keys().
next().
value;
1298 + if (oldest
!== undefined) b.results.
delete(oldest);
1303 + /^(Runtime|Log)\.(enable|disable)$/.
test(op.
method)
&& 1307 + `${sid}:${op.method.split(".")[0]}`,
1308 + op.
method.
endsWith(
"enable"),
1310 + const entry
: Record<
string,
unknown>
= {
1312 + command: op.
method,
1313 + ...(frame.transportError
1314 + ? { transport: frame }
1315 + : { raw:
await b.
spoolFrame(frame, serialized) }),
1317 + results.
push(entry);
1318 + if (frame.error)
throw new Error(frame.error.message);
1320 + op.
method === "Target.setAutoAttach" && 1322 + typeof p
=== "object" && 1323 + !Array.
isArray(p)
&& 1324 + p.autoAttach
=== false 1326 + b.autoAttach
= false;
1327 + entry.interference
= "managed descendant monitoring disabled";
1330 + (op.
method === "Page.stopScreencast" || 1331 + op.
method === "Page.startScreencast")
&& 1333 + b.video?.sessionId
=== sid
1335 + entry.interference
= "managed video interrupted";
1336 + entry.partialFile
= await b.
stopVideo(
false);
1338 + if (op.
method === "Tracing.end" && b.trace) {
1339 + entry.interference
= "managed trace ended by raw command";
1340 + entry.partialFile
= await b.
stopTrace(
false);
1342 + }
else if (op.kind
=== "status") {
1343 + await b.
refreshStatus();
1346 + status: b.
status(),
1347 + note:
"observed status; earlier unconfirmed command may still take effect",
1349 + }
else if (op.kind
=== "wait") {
1350 + const watcher
= op.after
? waits.
get(op.after)
: undefined;
1351 + if (
!watcher)
throw new Error(
"wait not armed");
1352 + let hit
= watcher.hit;
1353 + const end
= Date.
now()
+ (op.timeoutMs
|| 5000);
1354 + while (
!hit
&& Date.
now()
< end
&& !signal?.aborted) {
1355 + await new Promise((r)
=> setTimeout(r,
20));
1356 + hit
= watcher.hit;
1358 + if (signal?.aborted) {
1359 + b.uncertain
= true;
1360 + throw new Error(
"wait canceled; command effects uncertain");
1364 + `wait timed out: ${op.event} on ${watcher.sessionId}`,
1366 + results.
push({ operation: i, wait: hit });
1367 + }
else if (op.kind
=== "screenshot") {
1368 + const sid
= session(op);
1369 + if (
!sid)
throw new Error(
"screenshot requires sessionId");
1370 + const image
= await b.
screenshot(sid, op.
filename, op.fullPage);
1371 + images.
push({ data: image.
data, mimeType:
"image/png" });
1372 + results.
push({ operation: i, file: image.file });
1373 + }
else if (op.kind
=== "videoStart") {
1374 + const sid
= session(op);
1375 + if (
!sid)
throw new Error(
"videoStart requires sessionId");
1378 + file:
await b.
startVideo(sid, op.
filename),
1380 + }
else if (op.kind
=== "videoStop")
1381 + results.
push({ operation: i, file:
await b.
stopVideo() });
1382 + else if (op.kind
=== "traceStart")
1383 + results.
push({ operation: i, file:
await b.
startTrace(op.
filename) });
1384 + else if (op.kind
=== "traceStop")
1385 + results.
push({ operation: i, file:
await b.
stopTrace() });
1386 + else if (op.kind
=== "close") {
1388 + results.
push({ operation: i, closed:
true });
1390 + }
else throw new Error(
`unknown operation: ${String(op.kind)}`);
1392 + failure
= error
instanceof Error ? error.message
: String(error);
1393 + failedOperation
= { operation: i, kind: op.kind };
1395 + event:
"operation.end",
1398 + elapsedMs:
Date.
now()
- started,
1404 + event:
"operation.end",
1407 + elapsedMs:
Date.
now()
- started,
1410 + onProgress?.(i
+ 1,
"");
1413 + const owned
= new Set(waits.
values());
1414 + b.watchers
= b.watchers.
filter((w)
=> !owned.
has(w));
1422 + status: b.
status(),
1428 + skipped:
skipped((failedOperation?.operation
|| 0)
+ 1),
1432 + await b.spoolWrites;
1433 + const candidates
= b.events.
filter((e)
=> e.seq
> startSeq);
1434 + const events
: Event[]
= [];
1435 + let eventBytes
= 0;
1436 + for (
let i
= candidates.
length - 1; i
>= 0; i
--) {
1437 + const e
= candidates[i];
1438 + const size
= Buffer.
byteLength(
JSON.
stringify(e));
1439 + if (eventBytes
+ size
<= 65536) {
1440 + events.
unshift(e);
1441 + eventBytes
+= size;
1442 + }
else await b.
spoolEvent(e);
1444 + const overflow
= b.spoolFiles
1448 + f.lastEventSeq
!== undefined && 1449 + f.lastEventSeq
> startSeq,
1452 + b.
protectSpoolFile(f.file);
1461 + status: b.
status(),
1467 + skipped:
skipped((failedOperation?.operation
|| 0)
+ 1),