@open-take/runtime 0.5.3 → 0.6.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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cdp-capture-DfJeA-uY.js","names":["sleep","ms: number","explicit?: string","candidates: string[]","buildId: string","downloaded: number","total: number","method: string","params: Record<string, unknown>","base?: number","message: string","reason: \"timeout\" | \"closed\" | \"crashed\"","e: unknown","ws: WebSocket","timeoutMs?: number","ev: MessageEvent","msg: {\n id?: number;\n error?: unknown;\n result?: unknown;\n method?: string;\n params?: unknown;\n }","wsUrl: string","opts: { timeoutMs?: number }","resolve","opts: CdpSendOptions","p: Pending","fn: (params: T) => void","why: string","reason: \"closed\" | \"crashed\"","opts: {\n width: number;\n height: number;\n chromePath?: string;\n /** Physical pixels per CSS px (Retina density). A whole-browser launch flag,\n * NOT a per-page metrics override, so frame/viewport/event-space stay\n * consistent: events remain CSS px, the window surface (what the\n * screencast captures) is exactly `deviceScaleFactor`× that. */\n deviceScaleFactor?: number;\n /** Persistent profile dir (an authenticated capture — see `open-take auth`).\n * Kept on close, unlike the default throwaway temp profile. The SAME\n * keychain flags are used for auth and capture (mock keychain), so cookies\n * written during a headed login decrypt in the later headless capture. */\n userDataDir?: string;\n /** false ⇒ launch a visible (headed) window. Default true (headless).\n * The screencast records either way — headed is the escape hatch for\n * sites that gate on a real window. */\n headless?: boolean;\n}","proc: ChildProcess","userDir: string","pid: number","port: number","cdp: CDP","targetId: string","vw: number","vh: number","win: { windowId: number; bounds: { width: number; height: number } } | null","frames: Frame[]","n: number","path: DragPt[]","u: number","ease: \"smooth\" | \"linear\"","events: {\n kind?: string;\n tMs: number;\n durationMs?: number | null;\n x?: number;\n y?: number;\n to?: DragPt;\n path?: DragPt[];\n ease?: string;\n }[]","frameOffsetsMs: number[]","arrivalOffsetsMs?: number[]","out: DragCadence[]","worstHole: DragCadence[\"worstHole\"]","t: number","deliveryMs: number | undefined","dir: string","t0: number","opts: { maxWidth: number; maxHeight: number; quality?: number }","p: { data: string; sessionId: number; metadata?: { timestamp?: number } }","screencast: Pick<Screencast, \"idleForMs\">","active: () => boolean","paused: () => boolean","endMs: number","fps: number","timeline: TimedFrame[]","outPath: string","ffmpegBin?: string","feedErr: Error | undefined","e: Error","stdin: Writable","chunks: AsyncIterable<Buffer>","ready: () => boolean","timeoutMs: number","sleep","ms: number","o: unknown","s: unknown","raw: string","top: unknown","text: string","selector: string","target: { text?: string; selector?: string }","resolve","pts: { x: number; y: number }[]","u: number","seg: number[]","path: string","plan: TakePlan","opts: CaptureOpts","url: string","opts: InspectOpts","expr: string","elements: InspectElement[]","target: { selector?: string; text?: string }","value: string","bin: string","args: string[]","chunks: Buffer[]","d: Buffer","sleep","ms: number","text: string","headers: Record<string, string>","out: number[]","raw: Buffer | string","parts: MhtmlPart[]","body: Buffer","EXT_BY_TYPE: Record<string, string>","part: MhtmlPart","u: string","ENTITY: Record<string, string>","s: string","e: string","html: string","pos: number","attrs: Attr[]","value: string | null","css: string","resolve: (ref: string) => string | null","ref: string","quote: string","d?: string","s?: string","b?: string","value: string","out: { url: string; descriptor: string }[]","URL_ATTRS: Record<string, Set<string>>","ctx: RewriteCtx","resolve","out: string[]","end","kept: Attr[]","rewritten: string | null","probe: DomStateProbe","opts: {\n assetsDir: string;\n /** parts fetched apart from the snapshot (the web fonts it leaves out —\n * `fetchFontFiles`), found by their location like its own parts; a part\n * of the snapshot wins over one here */\n extra?: MhtmlPart[];\n }","bytes: Buffer","ext: string","base: string","ref: string | null","html","docUrl: string","cdp: CDP","urls: string[]","state: FontFetchState","opts: { concurrency?: number }","frameId: string","url: string","chunks: Buffer[]","got: MhtmlPart | string","states: DomStateRaw[]","warn: (l: string) => void","wanted: string[]","parts","a: Uint8Array","b: Uint8Array","mask?: PixelMask","mask: PixelMask","pixels: number","png: Buffer","ffmpeg: string","file: string","w: number","h: number","flags: \"neighbor\" | \"area\"","png: string","box: [number, number, number, number]","livePng: string","statePng: string","moving: [number, number, number, number][]","box: { x: number; y: number; w: number; h: number }","elements: StateElement[]","best: string | undefined","vw: number","vh: number","jpegs: Buffer[]","a: DecodedImage","b: DecodedImage","boxes: [number, number, number, number][]","margin: number","args: {\n statesDir: string;\n id: string;\n tMs: number;\n step?: number;\n vw: number;\n vh: number;\n dpr: number;\n }","raw: DomStateRaw","args: {\n browser: Browser;\n statesDir: string;\n states: DomStateRaw[];\n vw: number;\n vh: number;\n /** measure each state's parts in the same page (parts.json + crisp\n * pictures in states/assets/) — default true; false skips it */\n parts?: boolean;\n /** run on each state's restored page once it is checked and measured\n * (the shoot's full-page sheet); what it throws is a line, not a failure */\n afterRender?: (cdp: CDP, raw: DomStateRaw) => Promise<void>;\n}","l: string","items: DomStateItem[]","converted: { raw: DomStateRaw; index: StateIndex }[]","ffmpeg: string | undefined","fonts: MhtmlPart[]","id: string","e: unknown","fidelity: StateFidelity","browser: Browser","page: { cdp: CDP; targetId: string }","cdp: CDP | undefined","stateHtml: string","timer: ReturnType<typeof setTimeout> | undefined","opts: {\n dir: string;\n index: StateIndex;\n assetsDir: string;\n pictures?: boolean;\n /** keep each part's elements for its file (parts-dom.json) — default true */\n dom?: boolean;\n minArea?: number;\n }","file: PartsFile","expression: string","dir: string","parts: PartsFile","file: PartDomFile","args: {\n browser: Browser;\n dirs: string[];\n pictures?: boolean;\n minArea?: number;\n}","measured: { dir: string; parts: PartsFile }[]","failed: { dir: string; why: string }[]","page: { cdp: CDP; targetId: string } | null","t: NavigateTarget","raw: string","base?: URL","message: string","issues: PrecheckIssue[]","FIELD_ORDER: Record<string, string[]>","steps: TakePlan[\"steps\"]","out: TargetSpec[]","f: string","order: string[]","field: string","kind: \"selector\" | \"text\"","revealOnly?: boolean","action: string","value: string","p: Probe","evalJson: (js: string) => Promise<unknown>","opts?: { retryMs?: number; sleep?: (ms: number) => Promise<void> }","sleep","ms: number","t: TargetSpec","lateMisses: TargetSpec[]","cdp: CDP","notes: string[]","blocks: Block[]","lost: Array<{ producedMs: number; ms: number }>","audio: ProductSoundReport[\"audio\"]","report: ProductSoundReport","n: number","responses: Map<string, FetchedSound>","finished: Set<string>","dir: string","out: FetchedSound[]","body: Buffer | null","r","url: string","used: Set<string>","path: string","blocks: Array<{ src: SourceKey; producedMs: number; ctxFrame?: number; samples: Float32Array }>","sources: Map<SourceKey, { sampleRate: number }>","t0: number","endMs: number","spans: Array<[number, number]>","soundAt: Array<[number, number]>","blocks: B[]","b: B","run: B[]","sources: Map<SourceKey, Source>","pcm: Float32Array","sampleRate: number","channels: number","sleep","ms: number","cdp: CDP","heldMs: number","opts: { budgetMs?: number }","budgetMs: number","reason: SettleOutcome[\"reason\"]","ms: number","u: number","cdp: CDP","js: string","timer: ReturnType<typeof setTimeout> | undefined","b: Box","type: \"mousePressed\" | \"mouseReleased\" | \"mouseMoved\"","x: number","y: number","MOD: Record<string, number>","NAMED: Record<string, KeyInfo>","MOD_KEY: Record<number, KeyInfo>","keys: string","info: KeyInfo","type: \"keyDown\" | \"keyUp\"","mods: number","plan: TakePlan","opts: CaptureOpts","browser: Browser | null","productAudio: ProductAudioRecorder | null","spec: {\n point?: Pt;\n selector?: string;\n text?: string;\n }","events: CaptureLog[\"events\"]","skipped: NonNullable<CaptureLog[\"skipped\"]>","settleWaits: NonNullable<CaptureLog[\"settleWaits\"]>","states: DomStateRaw[]","movingStates: { id: string; tMs: number; step?: number }[]","lastState: DomStateRaw | null","step: number | undefined","mayMove: boolean","target: DomStateRaw | null","action: string","target: string | undefined","reason: string","defaultMs: number","href: string | null","label","tMs","box","pt","pathPts: Pt[]","path: Pt[]","to: Pt","from: Pt","type: \"dragEnter\" | \"dragOver\" | \"drop\"","p: Pt","carriedMs: number","dy: number","box: Box | null","stateItems: DomStateItem[] | undefined","r: ProductSoundReport","lines: string[]","url: string"],"sources":["../src/cdp.ts","../src/capture.ts","../src/tool.ts","../src/dom-state.ts","../src/nav.ts","../src/precheck.ts","../src/product-audio.ts","../src/settle.ts","../src/cdp-capture.ts"],"sourcesContent":["// Minimal Chrome DevTools Protocol toolkit for the high-fps capture path.\n//\n// Why this exists: agent-browser's `record` wraps Playwright recordVideo,\n// hard-throttled to ~10fps (no fps flag — native binary). The fps spike\n// (spike-revideo/fps/VERDICT.md) proved a direct CDP `Page.startScreencast`\n// delivers ~60fps, and that driving the drag via CDP `Input` at ~16ms steps\n// keeps the captured ink in lockstep with the synthetic cursor. So the\n// hi-fps path drives AND captures over one CDP page session: one owner, one\n// clock, no per-step agent-browser process spawn.\n//\n// No deps — Node 22's global `WebSocket`/`fetch` carry the protocol.\n\nimport { type ChildProcess, spawn } from \"node:child_process\";\nimport { once } from \"node:events\";\nimport {\n existsSync,\n mkdirSync,\n mkdtempSync,\n readdirSync,\n readFileSync,\n readlinkSync,\n rmSync,\n writeFileSync,\n} from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { homedir, tmpdir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport type { Writable } from \"node:stream\";\nimport { mjpegMatroska, resolveFfmpeg, type TimedFrame } from \"@open-take/compositor\";\n\nconst sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));\nconst require = createRequire(import.meta.url);\n\n// Where we cache an auto-downloaded Chrome-for-Testing + the resolved buildId.\nconst CHROME_CACHE = join(homedir(), \".open-take\", \"browsers\");\nconst BUILDID_FILE = join(homedir(), \".open-take\", \"chrome-build.json\");\n\n// --- locate a launchable Chrome ----------------------------------------\n// Resolution order: explicit/env → a Chrome-for-Testing we downloaded → a\n// CfT an agent-browser install left behind (legacy). Returns null if none\n// (→ ensureChrome downloads CfT). We deliberately do NOT auto-pick the user's\n// *system* Chrome: launching the same binary while Chrome is already running\n// hands off to the existing instance and never opens the debug port (proven).\n// CfT is the isolated, automation-stable browser Playwright/Puppeteer use too.\n// Point OPEN_TAKE_CHROME at a system Chrome if you really want one (close it\n// first).\nexport function resolveChrome(explicit?: string): string | null {\n const candidates: string[] = [];\n if (explicit) candidates.push(explicit);\n if (process.env.OPEN_TAKE_CHROME) candidates.push(process.env.OPEN_TAKE_CHROME);\n\n // a Chrome-for-Testing we downloaded earlier (offline: derived from the\n // saved buildId, no network)\n if (existsSync(BUILDID_FILE)) {\n try {\n const exe = computeChromePathSync(JSON.parse(readFileSync(BUILDID_FILE, \"utf8\")).buildId);\n if (exe) candidates.push(exe);\n } catch {\n /* ignore a corrupt cache marker */\n }\n }\n\n // legacy: a CfT an older agent-browser install left behind (also isolated)\n const abBrowsers = join(homedir(), \".agent-browser\", \"browsers\");\n if (existsSync(abBrowsers)) {\n for (const d of readdirSync(abBrowsers)\n .filter((n) => n.startsWith(\"chrome-\"))\n .sort()\n .reverse()) {\n candidates.push(\n join(\n abBrowsers,\n d,\n \"Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing\",\n ),\n join(abBrowsers, d, \"chrome-linux64\", \"chrome\"),\n join(abBrowsers, d, \"chrome\"),\n );\n }\n }\n\n return candidates.find((c) => c && existsSync(c)) ?? null;\n}\n\n// Best-effort sync path to a cached CfT build (lazy-loads the helper; returns\n// null if @puppeteer/browsers isn't resolvable for any reason).\nfunction computeChromePathSync(buildId: string): string | null {\n try {\n // require keeps this synchronous inside the sync resolver\n const { computeExecutablePath, Browser } = require(\"@puppeteer/browsers\");\n return computeExecutablePath({ browser: Browser.CHROME, buildId, cacheDir: CHROME_CACHE });\n } catch {\n return null;\n }\n}\n\n// Resolve a Chrome, downloading Chrome-for-Testing on first use if the machine\n// has none. The download is a one-time, cached fetch via @puppeteer/browsers\n// (Chrome-team-maintained pure downloader) — this is what keeps install\n// zero-config without binding us to agent-browser.\nexport async function ensureChrome(explicit?: string): Promise<string> {\n const found = resolveChrome(explicit);\n if (found) return found;\n try {\n const { install, resolveBuildId, detectBrowserPlatform, computeExecutablePath, Browser } =\n await import(\"@puppeteer/browsers\");\n const platform = detectBrowserPlatform();\n if (!platform) throw new Error(\"unsupported platform\");\n const buildId = await resolveBuildId(Browser.CHROME, platform, \"stable\");\n const exe = computeExecutablePath({ browser: Browser.CHROME, buildId, cacheDir: CHROME_CACHE });\n if (!existsSync(exe)) {\n mkdirSync(CHROME_CACHE, { recursive: true });\n // First run on this machine: a one-time ~150MB fetch. Say so (and show\n // coarse progress) so `make` doesn't look like a silent stall.\n process.stderr.write(\n `open-take: downloading Chrome for Testing (${buildId}, one-time) → ${CHROME_CACHE}\\n`,\n );\n let lastPct = -1;\n await install({\n browser: Browser.CHROME,\n buildId,\n cacheDir: CHROME_CACHE,\n downloadProgressCallback: (downloaded: number, total: number) => {\n if (!total) return;\n const pct = Math.floor((downloaded / total) * 100);\n // throttle to whole-ten-percent steps to keep the log quiet\n if (pct >= lastPct + 10 || pct === 100) {\n lastPct = pct;\n process.stderr.write(`open-take: …Chrome download ${pct}%\\n`);\n }\n },\n });\n process.stderr.write(\"open-take: Chrome ready.\\n\");\n }\n mkdirSync(dirname(BUILDID_FILE), { recursive: true });\n writeFileSync(BUILDID_FILE, JSON.stringify({ buildId }));\n return exe;\n } catch (e) {\n throw new Error(\n `open-take: no Chrome found and auto-download failed (${(e as Error).message}). ` +\n \"Install Chrome/Chromium, or set OPEN_TAKE_CHROME to a Chrome binary.\",\n );\n }\n}\n\n// --- minimal CDP client over a page-target websocket -------------------\n\n/** How long a request waits for Chrome's answer before it is given up. Most\n * commands answer in milliseconds; a page whose renderer is stuck (or a\n * Chrome that went quiet) never answers at all, and without a bound the take\n * waits forever with Chrome idle — seen in 2 of 6 multi-screen shoots. */\nexport const CDP_TIMEOUT_MS = 30_000;\n/** The budget of the commands that legitimately take long on a big page —\n * a full screenshot, an MHTML snapshot, a navigation that has to commit, a\n * response body, and any evaluate that awaits the page's own promise. */\nexport const CDP_SLOW_TIMEOUT_MS = 120_000;\nconst SLOW_METHODS = new Set([\n \"Page.captureScreenshot\",\n \"Page.captureSnapshot\",\n \"Page.printToPDF\",\n \"Page.navigate\",\n \"Page.reload\",\n \"Network.getResponseBody\",\n \"Target.createTarget\",\n]);\n\n/** OPEN_TAKE_CDP_TIMEOUT_MS (a very slow machine, a test): the ordinary\n * budget; slow commands get 4× it */\nfunction envBudget(): number | undefined {\n const v = Number(process.env.OPEN_TAKE_CDP_TIMEOUT_MS);\n return Number.isFinite(v) && v > 0 ? v : undefined;\n}\n\n/** The default budget of one request: `base` (the connection's own, else\n * OPEN_TAKE_CDP_TIMEOUT_MS, else CDP_TIMEOUT_MS) — or, for the slow\n * commands and promise-awaiting evaluates, 4× it (CDP_SLOW_TIMEOUT_MS by\n * default). */\nexport function cdpTimeoutFor(\n method: string,\n params: Record<string, unknown>,\n base?: number,\n): number {\n const b = base ?? envBudget() ?? CDP_TIMEOUT_MS;\n const slow =\n SLOW_METHODS.has(method) ||\n ((method === \"Runtime.evaluate\" || method === \"Runtime.callFunctionOn\") &&\n params.awaitPromise === true);\n return slow ? b * (CDP_SLOW_TIMEOUT_MS / CDP_TIMEOUT_MS) : b;\n}\n\n/** A request Chrome did not answer: it timed out, or the connection closed /\n * the page crashed while it waited. `reason` tells which. */\nexport class CdpError extends Error {\n constructor(\n message: string,\n readonly method: string,\n readonly reason: \"timeout\" | \"closed\" | \"crashed\",\n ) {\n super(message);\n this.name = \"CdpError\";\n }\n}\n\n/** true for a request that got no answer (timeout, closed, crashed) — the\n * page behind it may be stuck; a protocol error answer is not one */\nexport const isCdpStall = (e: unknown): e is CdpError => e instanceof CdpError;\n\nexport type CdpSendOptions = {\n /** this request's budget in ms; 0 or Infinity waits as long as it takes */\n timeoutMs?: number;\n};\n\ntype Pending = {\n method: string;\n resolve: (value: unknown) => void;\n reject: (error: Error) => void;\n timer?: ReturnType<typeof setTimeout>;\n};\n\nexport class CDP {\n private ws: WebSocket;\n private id = 0;\n private pending = new Map<number, Pending>();\n private handlers = new Map<string, (params: unknown) => void>();\n /** why the connection is gone, once it is — later sends fail at once */\n private closedWhy: string | null = null;\n private readonly timeoutMs: number | undefined;\n\n private constructor(ws: WebSocket, timeoutMs?: number) {\n this.ws = ws;\n this.timeoutMs = timeoutMs;\n ws.addEventListener(\"message\", (ev: MessageEvent) => {\n let msg: {\n id?: number;\n error?: unknown;\n result?: unknown;\n method?: string;\n params?: unknown;\n };\n try {\n msg = JSON.parse(ev.data as string);\n } catch {\n return;\n }\n if (msg.id != null) {\n const p = this.pending.get(msg.id);\n if (!p) return; // answered after its timeout: nobody waits for it now\n this.pending.delete(msg.id);\n clearTimeout(p.timer);\n if (msg.error) p.reject(new Error(JSON.stringify(msg.error)));\n else p.resolve(msg.result);\n } else if (msg.method) {\n // a crashed renderer never answers what was sent to it\n if (msg.method === \"Inspector.targetCrashed\")\n this.failAll(\"crashed\", \"the page crashed (its renderer died)\");\n // a detached page answers nothing more: later sends fail at once\n else if (msg.method === \"Inspector.detached\")\n this.gone(\n `the page detached (${(msg.params as { reason?: string })?.reason ?? \"no reason given\"})`,\n );\n this.handlers.get(msg.method)?.(msg.params);\n }\n });\n ws.addEventListener(\"close\", () => this.gone(\"the DevTools connection closed\"));\n ws.addEventListener(\"error\", () => this.gone(\"the DevTools connection failed\"));\n }\n\n /** Open a session on `wsUrl`. `timeoutMs` replaces the per-request default\n * base (see cdpTimeoutFor; slow commands get 4× it). */\n static connect(wsUrl: string, opts: { timeoutMs?: number } = {}): Promise<CDP> {\n return new Promise((resolve, reject) => {\n const ws = new WebSocket(wsUrl);\n // a socket that neither opens nor fails would be the same endless wait\n const timer = setTimeout(() => {\n reject(new Error(`CDP connect failed: ${wsUrl} did not open within 15 s`));\n try {\n ws.close();\n } catch {\n /* never opened */\n }\n }, 15_000);\n timer.unref?.();\n ws.addEventListener(\"open\", () => {\n clearTimeout(timer);\n resolve(new CDP(ws, opts.timeoutMs));\n });\n ws.addEventListener(\"error\", () => {\n clearTimeout(timer);\n reject(new Error(`CDP connect failed: ${wsUrl}`));\n });\n });\n }\n\n /** Send one command. Rejects with a CdpError if no answer arrives within its\n * budget (`opts.timeoutMs`, else cdpTimeoutFor), or the connection closes /\n * the page crashes first — it never waits forever. */\n send<T = unknown>(\n method: string,\n params: Record<string, unknown> = {},\n opts: CdpSendOptions = {},\n ): Promise<T> {\n if (this.closedWhy != null)\n return Promise.reject(new CdpError(`CDP ${method}: ${this.closedWhy}`, method, \"closed\"));\n const id = ++this.id;\n const budget = opts.timeoutMs ?? cdpTimeoutFor(method, params, this.timeoutMs);\n return new Promise<T>((resolve, reject) => {\n const p: Pending = { method, resolve: (value) => resolve(value as T), reject };\n if (budget > 0 && Number.isFinite(budget)) {\n p.timer = setTimeout(() => {\n if (!this.pending.delete(id)) return;\n reject(\n new CdpError(\n `CDP ${method}: no answer within ${Math.round(budget / 100) / 10} s — the page (or Chrome) is not responding`,\n method,\n \"timeout\",\n ),\n );\n }, budget);\n // a request still waiting must not be what keeps the process alive\n p.timer.unref?.();\n }\n this.pending.set(id, p);\n try {\n this.ws.send(JSON.stringify({ id, method, params }));\n } catch (e) {\n this.pending.delete(id);\n clearTimeout(p.timer);\n reject(\n new CdpError(`CDP ${method}: could not send (${(e as Error).message})`, method, \"closed\"),\n );\n }\n });\n }\n\n on<T = unknown>(method: string, fn: (params: T) => void): void {\n this.handlers.set(method, (params) => fn(params as T));\n }\n\n /** requests still waiting for an answer */\n get waiting(): number {\n return this.pending.size;\n }\n\n /** whether the connection is gone (closed, failed) */\n get closed(): boolean {\n return this.closedWhy != null;\n }\n\n close(): void {\n this.gone(\"the DevTools connection was closed\");\n try {\n this.ws.close();\n } catch {\n /* already closed */\n }\n }\n\n private gone(why: string): void {\n if (this.closedWhy == null) this.closedWhy = why;\n this.failAll(\"closed\", this.closedWhy);\n }\n\n private failAll(reason: \"closed\" | \"crashed\", why: string): void {\n const all = [...this.pending.values()];\n this.pending.clear();\n for (const p of all) {\n clearTimeout(p.timer);\n p.reject(new CdpError(`CDP ${p.method}: ${why}`, p.method, reason));\n }\n }\n}\n\n// --- launch + page-target discovery ------------------------------------\nexport type Browser = {\n cdp: CDP;\n /** the page target's id (for browser-level window commands) */\n targetId: string;\n /** the DevTools port this Chrome listens on — a second page target created\n * with `Target.createTarget` is reached at\n * `ws://127.0.0.1:<port>/devtools/page/<targetId>` (dom-state fidelity). */\n port: number;\n /** kill the browser process and remove its temp profile */\n close: () => Promise<void>;\n};\n\n/** Launch headless Chrome, return a CDP session bound to its page target. */\nexport async function launchBrowser(opts: {\n width: number;\n height: number;\n chromePath?: string;\n /** Physical pixels per CSS px (Retina density). A whole-browser launch flag,\n * NOT a per-page metrics override, so frame/viewport/event-space stay\n * consistent: events remain CSS px, the window surface (what the\n * screencast captures) is exactly `deviceScaleFactor`× that. */\n deviceScaleFactor?: number;\n /** Persistent profile dir (an authenticated capture — see `open-take auth`).\n * Kept on close, unlike the default throwaway temp profile. The SAME\n * keychain flags are used for auth and capture (mock keychain), so cookies\n * written during a headed login decrypt in the later headless capture. */\n userDataDir?: string;\n /** false ⇒ launch a visible (headed) window. Default true (headless).\n * The screencast records either way — headed is the escape hatch for\n * sites that gate on a real window. */\n headless?: boolean;\n}): Promise<Browser> {\n const chrome = await ensureChrome(opts.chromePath);\n const ephemeral = !opts.userDataDir;\n if (opts.userDataDir) mkdirSync(opts.userDataDir, { recursive: true });\n const userDir = opts.userDataDir ?? mkdtempSync(join(tmpdir(), \"open-take-cdp-\"));\n // A REUSED profile keeps the previous session's DevToolsActivePort on disk;\n // readDevtoolsPort would trust that stale (dead) port on its first poll and\n // then time out on \"no page target appeared\". Clear it so the only port we\n // can ever read is the one THIS launch writes. (Fresh temp profiles have\n // nothing to clear.)\n if (!ephemeral) rmSync(join(userDir, \"DevToolsActivePort\"), { force: true });\n // ProcessSingleton preflight for a reused profile: if a LIVE Chrome holds it\n // (the auth window still open, or a concurrent capture), our spawn would hand\n // off to that instance and never open a debug port — fail with the real story\n // instead. A DEAD holder (SIGKILLed capture, crashed auth) leaves stale lock\n // files behind; clear them so Chrome doesn't stall on takeover.\n if (!ephemeral) {\n const holder = singletonHolderPid(userDir);\n if (holder != null && pidAlive(holder))\n throw new Error(\n `profile in use: a Chrome (pid ${holder}) is already running on ${userDir} — ` +\n `quit it first (e.g. the \\`open-take auth\\` window)`,\n );\n for (const f of [\"SingletonLock\", \"SingletonCookie\", \"SingletonSocket\"])\n rmSync(join(userDir, f), { force: true });\n }\n const dsf = opts.deviceScaleFactor ?? 1;\n const proc: ChildProcess = spawn(\n chrome,\n [\n \"--remote-debugging-port=0\", // pick a free port; read it back from DevToolsActivePort\n `--user-data-dir=${userDir}`,\n `--window-size=${opts.width},${opts.height}`,\n ...(dsf !== 1 ? [`--force-device-scale-factor=${dsf}`] : []),\n ...(opts.headless === false ? [] : [\"--headless=new\"]),\n // automation browser (throwaway profile, loads the user's own target app);\n // without this the launch hangs — never writes DevToolsActivePort — in\n // sandboxed/containerised/CI contexts where Chrome's own sandbox can't init.\n \"--no-sandbox\",\n // never touch the OS keychain (macOS would pop a \"Chrome for Testing wants\n // to use Chromium Safe Storage\" password prompt every capture); use an\n // in-process store instead. These are puppeteer/playwright defaults.\n \"--password-store=basic\",\n \"--use-mock-keychain\",\n \"--no-first-run\",\n \"--no-default-browser-check\",\n \"--hide-scrollbars\",\n \"--disable-extensions\",\n \"--disable-background-networking\",\n \"--disable-features=Translate,AcceptCHFrame,MediaRouter,OptimizationHints\",\n \"--mute-audio\",\n // Audio renders to a fake, timer-driven output, never the machine's own\n // speakers. Every AudioContext's clock (and every playing media\n // element's) is paced by the output device; when the host's device\n // stops pulling — a stalled CoreAudio output (seen on a Mac whose\n // default output is a DisplayPort monitor: afplay hung too), a CI box\n // with no sound card — each context sits \"running\" at\n // currentTime ≈ 0.005 forever, the page plays nothing and the take\n // loses ALL product audio (product-audio.ts). The fake output always runs.\n \"--disable-audio-output\",\n \"about:blank\",\n ],\n { stdio: [\"ignore\", \"ignore\", \"pipe\"] },\n );\n let stderr = \"\";\n proc.stderr?.on(\"data\", (d) => {\n stderr += d;\n });\n\n const close = async () => {\n // Throwaway profile: SIGKILL is fine (the dir is deleted anyway). A\n // PERSISTENT profile needs a graceful shutdown first — Chrome flushes\n // cookies/localStorage (session tokens refreshed DURING the capture) and\n // records a clean exit only then; a bare SIGKILL would slowly log the\n // saved profile out and leave crash-restore state behind.\n const exitWithin = (ms: number) =>\n new Promise<boolean>((res) => {\n if (proc.exitCode != null) return res(true);\n const tm = setTimeout(() => res(false), ms);\n proc.once(\"exit\", () => {\n clearTimeout(tm);\n res(true);\n });\n });\n try {\n if (!ephemeral) {\n proc.kill(\"SIGTERM\");\n if (!(await exitWithin(4000))) proc.kill(\"SIGKILL\");\n } else {\n proc.kill(\"SIGKILL\");\n }\n } catch {\n /* already gone */\n }\n await exitWithin(2000); // don't hang if exit never fires\n // Chrome's helper processes (GPU, network, a second tab's renderer) can\n // outlive the killed browser by a few seconds and keep writing into the\n // profile, so the rm is retried patiently — and a leftover temp dir is\n // only a warning: it must never fail the take that just finished.\n // A user-supplied (persistent, authenticated) profile is KEPT.\n if (ephemeral)\n try {\n rmSync(userDir, { recursive: true, force: true, maxRetries: 12, retryDelay: 250 });\n } catch (e) {\n console.error(\n `open-take: could not remove Chrome's temporary profile ${userDir} (${(e as Error).message}) — safe to delete by hand`,\n );\n }\n };\n\n try {\n const port = await readDevtoolsPort(userDir, proc);\n const target = await pageTargetWs(port);\n const cdp = await CDP.connect(target.wsUrl);\n return { cdp, targetId: target.id, port, close };\n } catch (e) {\n await close();\n throw new Error(\n `open-take(hi-fps): browser launch failed: ${(e as Error).message}\\n${stderr.slice(-600)}`,\n );\n }\n}\n\n// Chrome's ProcessSingleton lock is a symlink named SingletonLock pointing at\n// \"<hostname>-<pid>\". Resolve the holder's pid (null when absent/unreadable).\nfunction singletonHolderPid(userDir: string): number | null {\n try {\n const target = readlinkSync(join(userDir, \"SingletonLock\"));\n const pid = Number(target.split(\"-\").pop());\n return Number.isFinite(pid) && pid > 0 ? pid : null;\n } catch {\n return null; // no lock, or not a symlink (non-POSIX layout)\n }\n}\n\nfunction pidAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch {\n return false;\n }\n}\n\n// Chrome writes the chosen debugging port to <user-data-dir>/DevToolsActivePort\n// (line 1) once the listener is up. Polling that file is the race-free way to\n// learn a port-0 launch's actual port.\n//\n// How long to wait: a Chrome that has run before is up in well under a second,\n// but the FIRST launch of a freshly downloaded bundle is not — macOS validates\n// the whole bundle's code signature before it runs (measured 4.5 s on a fast\n// M-series Mac for Chrome for Testing 153; slower machines take longer), and\n// that is exactly the launch a new install's first `make` performs, right\n// after ensureChrome. A 5 s window turned that first run into a coin flip\n// (\"timed out waiting for DevToolsActivePort\", then the retry works). A\n// crashed Chrome still fails fast through exitCode; only a slow start waits.\nconst DEVTOOLS_PORT_WAIT_MS = 30_000;\nasync function readDevtoolsPort(userDir: string, proc: ChildProcess): Promise<number> {\n const file = join(userDir, \"DevToolsActivePort\");\n for (let i = 0; i < DEVTOOLS_PORT_WAIT_MS / 50; i++) {\n if (proc.exitCode != null) throw new Error(`chrome exited early (${proc.exitCode})`);\n if (existsSync(file)) {\n const line = readFileSync(file, \"utf8\").split(\"\\n\")[0]?.trim();\n const port = Number(line);\n if (Number.isFinite(port) && port > 0) return port;\n }\n await sleep(50);\n }\n throw new Error(`timed out waiting for DevToolsActivePort (${DEVTOOLS_PORT_WAIT_MS / 1000}s)`);\n}\n\nasync function pageTargetWs(port: number): Promise<{ wsUrl: string; id: string }> {\n for (let i = 0; i < 60; i++) {\n try {\n const list = (await (await fetch(`http://localhost:${port}/json`)).json()) as Array<{\n type: string;\n id: string;\n webSocketDebuggerUrl?: string;\n }>;\n const page = list.find((t) => t.type === \"page\");\n if (page?.webSocketDebuggerUrl) return { wsUrl: page.webSocketDebuggerUrl, id: page.id };\n } catch {\n /* browser not ready yet */\n }\n await sleep(100);\n }\n throw new Error(\"no page target appeared\");\n}\n\n// Grow the window so the *natural* layout viewport matches the requested size.\n// Headless reserves window chrome (~140px), so a 1280x800 window yields a\n// ~1280x657 viewport. `Page.startScreencast` captures the window surface, NOT\n// the layout viewport — so a device-metrics override would desync the captured\n// frame from the coordinate space events are measured in. Resizing the real\n// window keeps frame == viewport == event space, exactly. Returns the achieved\n// inner size; on a browser that won't resize (remote/CDP service) it falls back\n// to whatever the natural inner is — still self-consistent, just maybe smaller.\nexport async function fitViewport(\n cdp: CDP,\n targetId: string,\n vw: number,\n vh: number,\n): Promise<[number, number]> {\n const readInner = async (): Promise<[number, number]> => {\n const r = await cdp.send<{ result?: { value?: string } }>(\"Runtime.evaluate\", {\n expression: \"JSON.stringify([window.innerWidth, window.innerHeight])\",\n returnByValue: true,\n });\n const v = JSON.parse(r.result?.value ?? \"[0,0]\");\n return [Number(v[0]), Number(v[1])];\n };\n let win: { windowId: number; bounds: { width: number; height: number } } | null = null;\n try {\n win = await cdp.send<{ windowId: number; bounds: { width: number; height: number } }>(\n \"Browser.getWindowForTarget\",\n { targetId },\n );\n } catch {\n return readInner(); // can't resize — use the natural viewport\n }\n if (!win?.windowId) return readInner();\n let { width, height } = win.bounds;\n let inner = await readInner();\n for (let i = 0; i < 4; i++) {\n const dw = vw - inner[0];\n const dh = vh - inner[1];\n if (Math.abs(dw) <= 1 && Math.abs(dh) <= 1) break;\n width += dw;\n height += dh;\n await cdp.send(\"Browser.setWindowBounds\", {\n windowId: win.windowId,\n bounds: { width, height },\n });\n await sleep(120);\n inner = await readInner();\n }\n return inner;\n}\n\n// --- screencast recorder ------------------------------------------------\n// Frames stream in only when the page surface changes; each is written to\n// disk immediately. Chrome's frame-swap time, not delayed JPEG delivery, is\n// the image's position on the action clock.\nexport type Frame = {\n file: string;\n offMs: number;\n arrivalMs?: number;\n timestampSource?: \"frame-swap\" | \"arrival\";\n};\n\nexport function captureCadence(frames: Frame[]) {\n const ordered = [...frames].sort((a, b) => a.offMs - b.offMs);\n const intervals = ordered\n .slice(1)\n .map((frame, i) => frame.offMs - ordered[i]!.offMs)\n .sort((a, b) => a - b);\n const rounded = (n: number) => Math.round(n * 1000) / 1000;\n const sources = new Set(frames.map((frame) => frame.timestampSource ?? \"arrival\"));\n return {\n frameCount: frames.length,\n timestampSource:\n sources.size > 1\n ? (\"mixed\" as const)\n : sources.has(\"frame-swap\")\n ? (\"frame-swap\" as const)\n : (\"arrival\" as const),\n frameOffsetsMs: ordered.map((frame) => rounded(frame.offMs)),\n arrivalOffsetsMs: ordered.map((frame) => rounded(frame.arrivalMs ?? frame.offMs)),\n medianIntervalMs: rounded(intervals[Math.floor(intervals.length / 2)] ?? 0),\n p95IntervalMs: rounded(intervals[Math.max(0, Math.ceil(intervals.length * 0.95) - 1)] ?? 0),\n maxIntervalMs: rounded(intervals.at(-1) ?? 0),\n maxArrivalDelayMs: rounded(\n frames.reduce(\n (max, frame) => Math.max(max, (frame.arrivalMs ?? frame.offMs) - frame.offMs),\n 0,\n ),\n ),\n outOfOrderFrames: frames.filter((frame, i) => i > 0 && frame.offMs < frames[i - 1]!.offMs)\n .length,\n note: \"Delivered-frame timing, not unique image content or a smoothness score. Static pages may send no frames; inspect image changes within active action windows. Encoded fps is separate.\",\n };\n}\n\n/** What the capture got during each drag: the pictures the page sent while\n * the button was down, how many a second, and the longest gap between two.\n * A drag the page draws all the way (a stroke, a moved shape) sends a picture\n * per frame on a quiet machine; a few a second there means the capture fell\n * behind (another render or capture running at the same time is the usual\n * cause, 6.6 a second against 54 for the same drag re-made alone) and the\n * film replays those few.\n *\n * A gap alone is not a loss: a page sends nothing while nothing changes, and\n * every eased stroke has a slow start and end, so a drag whose pointer barely\n * moves for 100 ms (a canvas app waiting out its drag threshold) is right to\n * send nothing. `holes` counts only the gaps that ARE losses: between two\n * pictures, longer than 40 ms (two frames at 60 fps), while the pointer moved\n * at least 16 px along the drag's own eased path. Measured on tldraw: a quiet\n * machine had none in 18 drags; the same plan under a saturated CPU had 22,\n * the pointer moving up to 74 px through one. `deliveryMs` is the median time\n * from Chrome drawing a picture to the recorder receiving it, the busy-machine\n * evidence: ~30 ms quiet, 45 saturated, 134 in a take whose drags lost up to\n * 118 px at a time. */\nexport type DragCadence = {\n /** index in the log's events */\n event: number;\n tMs: number;\n durationMs: number;\n frames: number;\n perSecond: number;\n maxGapMs: number;\n /** gaps that lost moving pictures (see above); 0 when the drag has no path */\n holes: number;\n /** the hole the pointer moved furthest through */\n worstHole?: { atMs: number; gapMs: number; movedPx: number };\n /** median ms from drawn to received, over this drag's pictures */\n deliveryMs?: number;\n};\n\nconst HOLE_GAP_MS = 40;\nconst HOLE_MOVE_PX = 16;\n\ntype DragPt = { x: number; y: number };\n\n// the same eased arc-length walk the capture drives the mouse along\n// (cdp-capture.ts smoother + capture.ts sampleAlong), kept here to avoid an\n// import cycle with capture.ts\nfunction easedPoint(path: DragPt[], u: number, ease: \"smooth\" | \"linear\"): DragPt {\n const c = Math.max(0, Math.min(1, u));\n const k = ease === \"linear\" ? c : c * c * c * (c * (c * 6 - 15) + 10);\n if (path.length === 1) return path[0]!;\n const seg = path.slice(1).map((q, i) => Math.hypot(q.x - path[i]!.x, q.y - path[i]!.y));\n let left = k * seg.reduce((t, d) => t + d, 0);\n for (let i = 0; i < seg.length; i++) {\n if (left <= seg[i]! || i === seg.length - 1) {\n const f = seg[i]! > 0 ? left / seg[i]! : 0;\n return {\n x: path[i]!.x + (path[i + 1]!.x - path[i]!.x) * f,\n y: path[i]!.y + (path[i + 1]!.y - path[i]!.y) * f,\n };\n }\n left -= seg[i]!;\n }\n return path[path.length - 1]!;\n}\n\nexport function dragCadence(\n events: {\n kind?: string;\n tMs: number;\n durationMs?: number | null;\n x?: number;\n y?: number;\n to?: DragPt;\n path?: DragPt[];\n ease?: string;\n }[],\n frameOffsetsMs: number[],\n arrivalOffsetsMs?: number[],\n): DragCadence[] {\n const out: DragCadence[] = [];\n events.forEach((e, event) => {\n if (e.kind !== \"drag\" || !e.durationMs || e.durationMs < 200) return;\n const start = e.tMs;\n const dur = e.durationMs;\n const end = start + dur;\n const inside = frameOffsetsMs.filter((t) => t >= start && t <= end).sort((a, b) => a - b);\n // the gap from the press to the first picture and from the last to the\n // release counts too: a stroke that shows nothing for half a second is that\n const marks = [start, ...inside, end];\n const maxGapMs = Math.max(...marks.slice(1).map((t, i) => t - marks[i]!));\n const path =\n e.path?.length\n ? e.path\n : e.x != null && e.y != null && e.to\n ? [{ x: e.x, y: e.y }, e.to]\n : null;\n let holes = 0;\n let worstHole: DragCadence[\"worstHole\"];\n if (path) {\n const ease = e.ease === \"linear\" ? \"linear\" : \"smooth\";\n const at = (t: number) => easedPoint(path, (t - start) / dur, ease);\n // between two pictures only: before the first one the page may not have\n // started drawing yet (a drag threshold), and that is not a loss\n for (let i = 1; i < inside.length; i++) {\n const gapMs = inside[i]! - inside[i - 1]!;\n if (gapMs <= HOLE_GAP_MS) continue;\n const p = at(inside[i - 1]!);\n const q = at(inside[i]!);\n const movedPx = Math.hypot(q.x - p.x, q.y - p.y);\n if (movedPx < HOLE_MOVE_PX) continue;\n holes++;\n if (!worstHole || movedPx > worstHole.movedPx)\n worstHole = {\n atMs: Math.round(inside[i - 1]!),\n gapMs: Math.round(gapMs),\n movedPx: Math.round(movedPx),\n };\n }\n }\n let deliveryMs: number | undefined;\n if (arrivalOffsetsMs && arrivalOffsetsMs.length === frameOffsetsMs.length) {\n const delays = frameOffsetsMs\n .map((t, i) => (t >= start && t <= end ? arrivalOffsetsMs[i]! - t : null))\n .filter((d): d is number => d != null)\n .sort((a, b) => a - b);\n if (delays.length) deliveryMs = Math.round(delays[Math.floor(delays.length / 2)]!);\n }\n out.push({\n event,\n tMs: start,\n durationMs: dur,\n frames: inside.length,\n perSecond: Math.round((inside.length / dur) * 10000) / 10,\n maxGapMs: Math.round(maxGapMs),\n holes,\n ...(worstHole ? { worstHole } : {}),\n ...(deliveryMs != null ? { deliveryMs } : {}),\n });\n });\n return out;\n}\n\nexport class Screencast {\n private cdp: CDP;\n private dir: string;\n private t0 = 0;\n private n = 0;\n private lastArrivalAt = 0;\n readonly frames: Frame[] = [];\n\n get idleForMs(): number {\n return Date.now() - this.lastArrivalAt;\n }\n\n constructor(cdp: CDP, dir: string) {\n this.cdp = cdp;\n this.dir = dir;\n }\n\n /** Begin capture. `t0` (Date.now) anchors every frame + event onto one clock. */\n async start(\n t0: number,\n opts: { maxWidth: number; maxHeight: number; quality?: number },\n ): Promise<void> {\n this.t0 = t0;\n this.lastArrivalAt = t0;\n this.cdp.on(\n \"Page.screencastFrame\",\n (p: { data: string; sessionId: number; metadata?: { timestamp?: number } }) => {\n const arrived = Date.now();\n this.lastArrivalAt = arrived;\n const swap = p.metadata?.timestamp;\n const hasSwap = typeof swap === \"number\" && Number.isFinite(swap);\n const off = Math.max(0, hasSwap ? swap * 1000 - this.t0 : arrived - this.t0);\n const file = join(this.dir, `f-${String(this.n++).padStart(5, \"0\")}.jpg`);\n // Release Chrome before local disk work; late delivery must not become\n // late presentation. encodeFrames orders occasional out-of-order swaps.\n this.cdp.send(\"Page.screencastFrameAck\", { sessionId: p.sessionId }).catch(() => {});\n writeFileSync(file, Buffer.from(p.data, \"base64\"));\n this.frames.push({\n file,\n offMs: off,\n arrivalMs: arrived - this.t0,\n timestampSource: hasSwap ? \"frame-swap\" : \"arrival\",\n });\n },\n );\n await this.cdp.send(\"Page.startScreencast\", {\n format: \"jpeg\",\n quality: opts.quality ?? 90,\n maxWidth: opts.maxWidth,\n maxHeight: opts.maxHeight,\n everyNthFrame: 1,\n });\n }\n\n async stop(): Promise<void> {\n await this.cdp.send(\"Page.stopScreencast\").catch(() => {});\n }\n}\n\n/** Refresh idle surfaces without interrupting pages already producing frames.\n * Never queue another expensive screenshot behind a slow/in-flight request. */\nexport async function pumpIdleRaster(\n cdp: CDP,\n screencast: Pick<Screencast, \"idleForMs\">,\n active: () => boolean,\n paused: () => boolean,\n): Promise<void> {\n let pending = false;\n while (active()) {\n if (!paused() && !pending && screencast.idleForMs >= 200) {\n pending = true;\n void cdp\n .send(\"Page.captureScreenshot\", { format: \"jpeg\", quality: 1 })\n .catch(() => {})\n .finally(() => {\n pending = false;\n });\n }\n await sleep(45);\n }\n}\n\n// --- encode timestamped frames -> video --------------------------------\n// The frames go to ffmpeg as an MJPEG Matroska stream over stdin, each block\n// stamped with the millisecond Chrome swapped it (the compositor's mjpeg-matroska.ts explains\n// why not a concat list). `-fps_mode cfr -r <fps>` then resamples that real\n// wall-clock pacing onto a constant grid the web/MP4 decoders downstream read\n// cleanly (static stretches naturally hold one frame). Codec follows the\n// output extension so the file stays honest (.webm→vp9, else h264).\n//\n// Every flag here must clear FFMPEG_FLOOR *and* the newest release: `-vsync`\n// (deprecated 5.1) is gone in 9.0, and the scale filter's colour-matrix names\n// became an enum in 7.0 that knows `bt601` but not the `bt470bg` alias the\n// older string matcher accepted — both found by the managed-build test leg.\n\n/** Where each frame sits on the video's clock, in whole milliseconds. The\n * first frame is pulled back to 0 so the video timeline starts where event\n * timestamps do; later frames keep their observed offset, nudged forward by\n * 1 ms when two swaps round onto the same millisecond so no frame vanishes\n * under its neighbour. The last frame is repeated at the end time (at least\n * one frame period after it was shown) to give it a duration. */\nexport function frameTimeline(frames: Frame[], endMs: number, fps: number): TimedFrame[] {\n const ordered = [...frames].sort((a, b) => a.offMs - b.offMs);\n const timeline: TimedFrame[] = [];\n let tMs = 0;\n for (let i = 0; i < ordered.length; i++) {\n if (i > 0) tMs = Math.max(tMs + 1, Math.round(ordered[i]!.offMs));\n timeline.push({ file: ordered[i]!.file, tMs });\n }\n const last = ordered[ordered.length - 1]!;\n timeline.push({\n file: last.file,\n tMs: Math.max(tMs + 1, Math.round(endMs), Math.round(last.offMs + 1000 / fps)),\n });\n return timeline;\n}\n\nexport async function encodeFrames(\n frames: Frame[],\n endMs: number,\n outPath: string,\n fps: number,\n ffmpegBin?: string,\n): Promise<void> {\n if (frames.length === 0) throw new Error(\"open-take(hi-fps): no frames captured\");\n const timeline = frameTimeline(frames, endMs, fps);\n const bin = ffmpegBin ?? (await resolveFfmpeg());\n\n const isWebm = /\\.webm$/i.test(outPath);\n const codec = isWebm\n ? [\"-c:v\", \"libvpx-vp9\", \"-b:v\", \"0\", \"-crf\", \"28\", \"-deadline\", \"good\", \"-cpu-used\", \"4\"]\n : [\"-c:v\", \"libx264\", \"-preset\", \"veryfast\", \"-crf\", \"18\"];\n\n // Color: the screencast frames are full-range JPEGs (601). For h264, convert\n // to STANDARD limited-range bt709 and label all four fields (range/matrix/\n // primaries/transfer) so every downstream decoder agrees: the revideo render,\n // end-user players, AND any browser <video>→canvas consumer.\n // Without tags ffmpeg stamped yuvj420p/pc/bt470bg, which Chrome's canvas\n // mis-decodes as limited and over-brightens (~20 levels) → washed-out colors in\n // a canvas preview, while ffmpeg/revideo honored the full-range tag and stayed\n // faithful. `scale` converts (and sets range+matrix); `setparams` adds the\n // primaries+transfer labels scale leaves unspecified, so all four are explicit.\n // The transfer is sRGB's (iec61966-2-1), not BT.709's: the screenshots are\n // sRGB pictures and the encode keeps their values. Chrome on macOS shows a\n // video that names BT.709's curve through Apple's gamma (1.961), not as it\n // decodes — #1d4d3c came out as 30,87,67 beside the same page's 29,77,60 —\n // and a film that cuts from the recording to the page itself showed the\n // jump. Named sRGB, Chrome shows the values as they decode. (Takes\n // recorded with BT.709's label are read as sRGB by the film's frames.)\n // swscale's fast path rounds the range and matrix conversion down — grey\n // 128 came back 125, #f4f1ea 242,240,229 — so it rounds exactly, with\n // chroma at full resolution in between (within 1 of the screenshot).\n const colorConvert = isWebm\n ? \"\"\n : \":in_range=full:in_color_matrix=bt601:out_range=tv:out_color_matrix=bt709:flags=bicubic+accurate_rnd+full_chroma_int\";\n const colorLabel = isWebm\n ? \"\"\n : \",setparams=range=tv:colorspace=bt709:color_primaries=bt709:color_trc=iec61966-2-1\";\n\n return new Promise((resolve, reject) => {\n const args = [\n \"-y\",\n \"-loglevel\",\n \"error\",\n \"-f\",\n \"matroska\",\n \"-i\",\n \"pipe:0\",\n \"-fps_mode\",\n \"cfr\",\n \"-r\",\n String(fps),\n // screencast frames can be odd-sized (e.g. 1280x657); yuv420p needs\n // even dims, so round down to the nearest even before pixel-format.\n \"-vf\",\n `scale=trunc(iw/2)*2:trunc(ih/2)*2${colorConvert},format=yuv420p${colorLabel}`,\n ...codec,\n outPath,\n ];\n const c = spawn(bin, args, { stdio: [\"pipe\", \"ignore\", \"pipe\"] });\n let err = \"\";\n let feedErr: Error | undefined;\n c.stderr.on(\"data\", (d) => {\n err += d;\n });\n c.on(\"error\", reject);\n c.on(\"close\", (code) => {\n // ffmpeg's own words first: when it failed, its stderr says why (a bad\n // output path, a full disk) and the pipe closing under the feeder is\n // only the consequence. feedErr speaks when the feeder was the one that\n // stopped things (a frame we could not read) and ffmpeg was killed.\n if (code !== 0 && code !== null)\n reject(new Error(`ffmpeg encode exited ${code}: ${err.slice(-800)}`));\n else if (feedErr) reject(feedErr);\n else if (code === 0) resolve();\n else reject(new Error(`ffmpeg encode killed: ${err.slice(-800)}`));\n });\n // ffmpeg quitting early surfaces as EPIPE on the pipe; nothing to do here\n // beyond keeping it from throwing — `close` above reports the cause.\n c.stdin.on(\"error\", () => {});\n feedStdin(c.stdin, mjpegMatroska(timeline)).then(\n () => c.stdin.end(),\n (e: Error) => {\n // A frame we could not read or parse: stop ffmpeg rather than leave it\n // waiting on a stream that will never finish.\n feedErr = e;\n c.kill(\"SIGKILL\");\n },\n );\n });\n}\n\n/** Write chunks respecting backpressure. The pipe dying underneath us (ffmpeg\n * exited) simply ends the feed — the process exit explains itself; only the\n * source throwing (a frame that cannot be read) rejects. */\nasync function feedStdin(stdin: Writable, chunks: AsyncIterable<Buffer>): Promise<void> {\n for await (const chunk of chunks) {\n if (stdin.destroyed || stdin.writableEnded) return;\n try {\n if (!stdin.write(chunk)) await once(stdin, \"drain\");\n } catch {\n return; // EPIPE / stream error: ffmpeg is gone\n }\n }\n}\n\n/** A throwaway temp dir for the screencast's per-frame JPEGs. */\nexport const makeFrameDir = (): string => mkdtempSync(join(tmpdir(), \"open-take-frames-\"));\n\n/** Poll `ready` every few milliseconds until it is true or `timeoutMs` has passed.\n * Resolves true when the condition was met, false on timeout. Used to pace work\n * by something the page did (a painted frame) instead of by a blind timer. */\nexport async function waitUntil(\n ready: () => boolean,\n timeoutMs: number,\n stepMs = 4,\n): Promise<boolean> {\n const deadline = Date.now() + timeoutMs;\n while (!ready()) {\n if (Date.now() >= deadline) return false;\n await new Promise((r) => setTimeout(r, stepMs));\n }\n return true;\n}\n","// captureTake / inspectPage — drive the real app over the Chrome DevTools\n// Protocol (pure CDP — no agent-browser) and emit the ground-truth event log.\n// The exact bbox coords + measured timings are why the compositor never has\n// to *infer* zoom intent — the moat. All driving + recording lives in\n// cdp-capture.ts (captureTakeCDP); this module owns the element-locator JS\n// (shared by both paths) + the planning aid, and captureTake just delegates.\n\nimport { spawn } from \"node:child_process\";\nimport { type CaptureLog, resolveFfprobe } from \"@open-take/compositor\";\nimport { fitViewport, launchBrowser } from \"./cdp\";\nimport type { TakePlan } from \"./types\";\n\nconst sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));\n\nexport type Box = { x: number; y: number; w: number; h: number };\n\n// Recursively find a {x,y,w/width,h/height} rect in a parsed value. Exported\n// so the CDP capture path can robustly extract a bbox from any eval shape.\nexport function findBox(o: unknown): Box | null {\n if (!o || typeof o !== \"object\") return null;\n const r = o as Record<string, unknown>;\n if (\n typeof r.x === \"number\" &&\n typeof r.y === \"number\" &&\n (typeof r.width === \"number\" || typeof r.w === \"number\")\n )\n return { x: r.x, y: r.y, w: (r.width ?? r.w) as number, h: (r.height ?? r.h) as number };\n for (const k of Object.keys(r)) {\n const hit = findBox(r[k]);\n if (hit) return hit;\n }\n return null;\n}\n\n// Repeatedly JSON.parse while the value is still a string (handles double-\n// encoding).\nfunction deepParse(s: unknown): unknown {\n let cur = s;\n for (let i = 0; i < 5 && typeof cur === \"string\"; i++) {\n try {\n cur = JSON.parse(cur as string);\n } catch {\n break;\n }\n }\n return cur;\n}\n\n// Extract the actual returned value from agent-browser --json output.\n// eval: {\"success\":true,\"data\":{\"result\":\"<encoded>\"},\"error\":null}\n// get box: similar wrapper around the box. Falls back to deep-parsing raw.\nexport function evalValue(raw: string): unknown {\n let top: unknown;\n try {\n top = JSON.parse(raw);\n } catch {\n return deepParse(raw);\n }\n if (top && typeof top === \"object\") {\n const o = top as Record<string, unknown>;\n const data = o.data as Record<string, unknown> | undefined;\n if (data && \"result\" in data) return deepParse(data.result);\n for (const k of [\"result\", \"output\", \"stdout\", \"value\"]) if (k in o) return deepParse(o[k]);\n }\n return deepParse(top);\n}\n\n// --- one name resolver for every text locator ---------------------------\n// Each locator below used to carry its OWN precedence chain, and they\n// disagreed: `click` matched `aria-label || textContent`, while `drag` /\n// `press` / `scroll` / `hrefFrom` put `title` FIRST, and `inspect` — the\n// planning aid whose output SKILL.md explicitly tells agents to \"target these\n// by `text`\" — used a third chain. So an element with a visible label AND a\n// tooltip was advertised by `inspect` under its label, clicked fine, and then\n// silently failed to resolve for a drag. The editor's own Compare button is a\n// live example: label \"Compare\", title \"Hold to compare against the version\n// you opened\" — `text: \"Compare\"` resolved for a click and NOTFOUND for a drag.\n// Title-only controls (icon buttons, the editor's Look swatches) were worse:\n// `inspect` skipped them entirely, so nothing advertised them at all.\n//\n// Now every locator matches against ALL of an element's names — exact before\n// substring, DOM order. This is strictly more permissive than any of the old\n// chains, so nothing that resolved before stops resolving, and an exact hit\n// anywhere in the document still beats a substring hit that comes earlier.\nexport const NAME_JS =\n `function names(e){var raw=[e.getAttribute('aria-label'),e.textContent,e.getAttribute('title'),e.getAttribute('alt'),e.getAttribute('placeholder')];var out=[];` +\n `for(var i=0;i<raw.length;i++){var s=(raw[i]||'').replace(/\\\\s+/g,' ').trim();if(s&&out.indexOf(s)===-1)out.push(s);}return out;}` +\n // The name to SHOW (inspect). Placeholder is deliberately NOT a display name:\n // inspect renders a placeholder-only field as \"[placeholder]\" so a plan\n // author can see at a glance that the control has no real label.\n `function dispName(e){var a=[e.getAttribute('aria-label'),e.textContent,e.getAttribute('title'),e.getAttribute('alt')];` +\n `for(var i=0;i<a.length;i++){var s=(a[i]||'').replace(/\\\\s+/g,' ').trim();if(s)return s;}return '';}` +\n `function pick(els,t){var i,n,j;` +\n `for(i=0;i<els.length;i++){if(names(els[i]).indexOf(t)!==-1)return els[i];}` +\n `for(i=0;i<els.length;i++){n=names(els[i]);for(j=0;j<n.length;j++){if(n[j].indexOf(t)!==-1)return els[i];}}` +\n `return null;}`;\n\n// Shared tail for both click resolvers: the element is in hand — decide HOW\n// the click gets delivered. `m.click()` fires a lone synthetic `click` event\n// with NO pointerdown/mousedown/pointerup in front of it, and a whole class\n// of real controls listens to exactly those: a Radix DropdownMenuTrigger\n// opens on pointerdown, so a programmatic click was a SILENT no-op — the\n// step \"succeeded\", nothing opened, and every later beat died with \"target\n// not found\" (a measured shoot lost 8 of 10 beats this way). So when the\n// element's centre is actually hittable — elementFromPoint lands on it or on\n// one of its descendants — do NOT click in-page: return the point (`cx`/`cy`)\n// and let the capture driver deliver a trusted CDP press/release there, the\n// full native pipeline `hover` and `drag` already use. The in-page m.click()\n// survives as the fallback for what a coordinate cannot reach: zero-size\n// targets (sr-only), a centre covered by an unrelated overlay,\n// pointer-events:none — everything that resolved before still resolves.\n//\n// Scrolling: m.click() never scrolls, and a below-fold target would advance\n// state off-screen — so scroll into view ONLY when out of frame (in-view\n// beats keep their framing) and re-read the rect so the compositor gets a\n// viewport-relative bbox. behavior:'instant' is load-bearing for the point\n// path: with CSS scroll-behavior:smooth the post-scroll rect is mid-animation\n// and the trusted click would land on yesterday's layout.\n//\n// The hittable test asks BOTH point APIs before giving up on the point path.\n// Chrome's singular elementFromPoint can return an element whose border box\n// does not even contain the point: measured on a 33px-tall heading whose\n// centre sat 16px above a sibling with 164px glyphs on a 157px line-height —\n// the sibling's ink overflow won the singular hit-test at every sample while\n// elementsFromPoint()[0] (per spec, the same answer) named the heading, and a\n// trusted click at that point reached the heading. Treating the singular miss\n// as an occluder silently downgraded the beat to m.click() — which the app\n// ignored, because its edit-mode handler resolves the anchor from the click's\n// clientX/clientY and a programmatic click carries (0,0). The beat died with\n// changeCoverage 0 and every dependent beat skipped. So: a miss from the\n// singular API alone is not occlusion — only when the layered list agrees the\n// centre belongs to someone else does the in-page fallback fire.\nexport const HITTABLE_JS =\n `function hittable(m,r){var cx=Math.round(r.x+r.width/2),cy=Math.round(r.y+r.height/2);` +\n `if(!(r.width>0&&r.height>0&&document.elementFromPoint))return null;` +\n `var hit=document.elementFromPoint(cx,cy);` +\n `var ok=!!hit&&(hit===m||(m.contains&&m.contains(hit)));` +\n `if(!ok&&document.elementsFromPoint){var top=document.elementsFromPoint(cx,cy)[0];` +\n `ok=!!top&&(top===m||(m.contains&&m.contains(top)));}` +\n `return ok?{cx:cx,cy:cy}:null;}`;\n\n// Why a target's centre does not reach it, in words a plan author can act\n// on: the commonest case is not an overlay at all but a field inside a\n// closed <details> (a \"use your phone instead\" disclosure) — its content is\n// laid out but neither painted nor hit-testable until the <summary> is\n// clicked. A field with no size is not shown yet at all; one whose centre\n// lands on its own container is hidden by it; otherwise something covers it.\nexport const UNREACHABLE_JS =\n `function unreachable(m){` +\n `var z=m.getBoundingClientRect();if(!z.width||!z.height)return 'it has no size — not shown yet (display:none?)';` +\n `function d(e){var s=e.tagName.toLowerCase();if(e.id)s+='#'+e.id;` +\n `var c=typeof e.className==='string'?e.className.trim().split(/\\\\s+/).slice(0,2).join('.'):'';if(c)s+='.'+c;` +\n `var t=(e.textContent||'').replace(/\\\\s+/g,' ').trim().slice(0,40);return t?s+' \"'+t+'\"':s;}` +\n `var x=m.closest('details:not([open])');` +\n `if(x){var sm=x.querySelector('summary');if(!sm||!sm.contains(m)){` +\n `var st=sm?(sm.textContent||'').replace(/\\\\s+/g,' ').trim().slice(0,40):'';` +\n `return 'it is inside a closed <details> — open it first: click its summary'+(st?' \"'+st+'\"':'');}}` +\n `var r=m.getBoundingClientRect(),top=document.elementsFromPoint?document.elementsFromPoint(r.x+r.width/2,r.y+r.height/2)[0]:null;` +\n `if(!top)return 'its centre is outside the page';` +\n `if(top.contains(m))return 'its centre reaches only its container ('+d(top)+'), so something there hides it';` +\n `return 'its centre is covered by '+d(top);}`;\n\nconst CLICK_TAIL_JS =\n `if(m.tagName==='SELECT')return 'SELECTINERT';` +\n HITTABLE_JS +\n `var r=m.getBoundingClientRect();` +\n `if(r.top<0||r.bottom>window.innerHeight){m.scrollIntoView({block:'center',behavior:'instant'});r=m.getBoundingClientRect();}` +\n `var b={x:Math.round(r.x),y:Math.round(r.y),w:Math.round(r.width),h:Math.round(r.height)};` +\n `var p=hittable(m,r);` +\n `if(p){b.cx=p.cx;b.cy=p.cy;return JSON.stringify(b);}` +\n `m.click();return JSON.stringify(b);`;\n\n// The candidate sets each by-text locator queries — exported for the\n// pre-capture check (precheck.ts), which must resolve with EXACTLY these:\n// a looser probe set would pass targets the real locator then misses, a\n// tighter one would refuse targets it finds.\nexport const CLICK_CANDIDATES =\n \"button,a,[role=button],[role=link],[role=menuitem],input[type=submit],input[type=button]\";\n/** Clicked by text only when nothing in CLICK_CANDIDATES carries the name, so\n * nothing that resolved before resolves differently: a <label> wrapping a\n * checkbox or a radio — clicking it toggles its control, and its text is\n * the only name such a control has (\"I agree to the terms\"). */\nexport const CLICK_FALLBACK_CANDIDATES =\n \"label:has(input[type=checkbox]),label:has(input[type=radio])\";\nexport const FIELD_CANDIDATES =\n \"input,textarea,[contenteditable],[contenteditable=true],[role=textbox],[role=searchbox]\";\nexport const BOX_CANDIDATES =\n \"button,a,[role=button],[role=link],[role=menuitem],[aria-label],[title],img[alt],li,[draggable=true]\";\nexport const SCROLL_CANDIDATES =\n \"button,a,[role=button],[role=link],[role=heading],[aria-label],[title],h1,h2,h3,li,section,p\";\n\n// Find a clickable by accessible name (aria-label or text), record its\n// rect (ground-truth bbox), and resolve the click — all in one page eval so\n// the bbox and the action refer to the same element. Robust where CSS hooks\n// are unstable. Returns the bbox, plus `cx`/`cy` when the caller should\n// deliver the click as trusted CDP input (see CLICK_TAIL_JS).\nexport function clickByTextJs(text: string): string {\n const t = JSON.stringify(text);\n return (\n `(function(){var t=${t};` +\n `var els=Array.prototype.slice.call(document.querySelectorAll('${CLICK_CANDIDATES}'));` +\n NAME_JS +\n `var m=pick(els,t)||pick(Array.prototype.slice.call(document.querySelectorAll('${CLICK_FALLBACK_CANDIDATES}')),t);` +\n `if(!m)return 'NOTFOUND';` +\n CLICK_TAIL_JS +\n `})()`\n );\n}\n\n// Selector twin of clickByTextJs: resolve the element's rect AND the click in\n// ONE page eval, atomically. The old path made two separate agent-browser\n// round-trips (`get box <sel>` then `click <sel>`); under recording the CDP\n// `get box` call flaked (returned null ~1-in-3) and the beat was silently\n// skipped, gutting the demo. A single eval — the same mechanism the text\n// path already uses reliably — removes that race.\nexport function clickBySelectorJs(selector: string): string {\n const s = JSON.stringify(selector);\n return (\n `(function(){var m=document.querySelector(${s});` +\n `if(!m)return 'NOTFOUND';` +\n CLICK_TAIL_JS +\n `})()`\n );\n}\n\n// --- type/drag resolvers ------------------------------------------------\n// type targets are form fields (input/textarea/contenteditable), which the\n// clickable locator above does NOT match. Resolve the field by accessible\n// name OR placeholder, scroll into view, focus + click (caret), return bbox.\n//\n// Whether focus actually LANDED rides back as `f` — Input.insertText types\n// into the current selection, so when the in-page focus();click();focus()\n// bounces off (a contenteditable that only arms when the app sees a real\n// click's coordinates: measured, activeElement stayed BODY and the whole\n// string went nowhere while the step logged as a success), the driver must\n// know, not guess.\n//\n// The predicate reads the DEEP active element (piercing shadow roots — a web\n// component reports its host as document.activeElement while insertText lands\n// in the shadow's own active element) and calls it focused when it can take\n// an insertion (isContentEditable, or a string .value that is not readOnly/\n// disabled — a readOnly field swallows insertText exactly like body does)\n// AND it belongs to the target: on the composed ancestry (host chain\n// included), or as an editable host wrapping the target. document.body only\n// counts when body itself IS the target (designMode pages).\nconst FOCUS_STATE_JS =\n `function deepActive(){var a=document.activeElement;` +\n `while(a&&a.shadowRoot&&a.shadowRoot.activeElement){a=a.shadowRoot.activeElement;}return a;}` +\n `function editable(a){if(!a)return false;if(a.isContentEditable)return true;` +\n `return typeof a.value==='string'&&!a.readOnly&&!a.disabled;}` +\n `function withinTarget(a){var n=a;while(n){if(n===m||(m.contains&&m.contains(n)))return true;` +\n `var rn=n.getRootNode?n.getRootNode():null;n=n.parentElement||((rn&&rn.host)?rn.host:null);}return false;}` +\n `var ae=deepActive();` +\n `var ok=!!ae&&(ae!==document.body||m===document.body)&&editable(ae)&&` +\n `(withinTarget(ae)||(ae.isContentEditable&&ae.contains&&ae.contains(m)));`;\n\n// behavior:'instant' is load-bearing here too now: the box this returns aims\n// the driver's trusted recovery click, and a smooth scroll mid-flight would\n// hand it yesterday's layout (same reasoning as CLICK_TAIL_JS). When focus\n// bounced, `hit` says whether that recovery click can even reach the field —\n// the same hittable test the click path runs, read AFTER the in-page\n// focus/click so it sees whatever those opened. A covered centre is reported\n// rather than punched: a trusted press through an overlay would land on the\n// overlay as a real click, mutate state on camera, and the beat would still\n// skip.\nconst FOCUS_TAIL_JS =\n HITTABLE_JS +\n UNREACHABLE_JS +\n `var r=m.getBoundingClientRect();` +\n `if(r.top<0||r.bottom>window.innerHeight){m.scrollIntoView({block:'center',behavior:'instant'});r=m.getBoundingClientRect();}` +\n `var b={x:Math.round(r.x),y:Math.round(r.y),w:Math.round(r.width),h:Math.round(r.height)};` +\n `m.focus();m.click();m.focus();` +\n FOCUS_STATE_JS +\n `b.f=ok?1:0;` +\n `if(!ok){b.hit=hittable(m,m.getBoundingClientRect())?1:0;if(!b.hit)b.why=unreachable(m);}` +\n `return JSON.stringify(b);`;\n\nexport function focusFieldByTextJs(text: string): string {\n const t = JSON.stringify(text);\n return (\n `(function(){var t=${t};` +\n `var els=Array.prototype.slice.call(document.querySelectorAll('${FIELD_CANDIDATES}'));` +\n NAME_JS +\n `var m=pick(els,t);` +\n `if(!m)return 'NOTFOUND';` +\n FOCUS_TAIL_JS +\n `})()`\n );\n}\n\nexport function focusSelectorJs(selector: string): string {\n const s = JSON.stringify(selector);\n return (\n `(function(){var m=document.querySelector(${s});if(!m)return 'NOTFOUND';` +\n FOCUS_TAIL_JS +\n `})()`\n );\n}\n\n// Side-effect-free re-check of the focus predicate, for after the driver has\n// delivered a trusted click at the field's centre (the recovery a real user\n// performs by hand). Resolves the target exactly like the focus builders but\n// never focuses or clicks — a second in-page click here could toggle app\n// state the first one already changed.\n//\n// After that REAL click the ownership test widens: some editors focus a\n// proxy editable OUTSIDE the clicked container (hidden textarea patterns), so\n// post-click, a deep active element that can take the insertion is accepted\n// wherever it lives — that is where a real user's click-then-type would land,\n// and the strict tier already handled the no-click case. What still skips:\n// focus parked on body or a non-editable control (the measured lie).\nexport function verifyFocusJs(target: { text?: string; selector?: string }): string {\n if (!target.text && !target.selector) return `'0'`;\n const resolve = target.text\n ? `var els=Array.prototype.slice.call(document.querySelectorAll('${FIELD_CANDIDATES}'));` +\n NAME_JS +\n `var m=pick(els,${JSON.stringify(target.text)});`\n : `var m=document.querySelector(${JSON.stringify(target.selector ?? \"\")});`;\n return (\n `(function(){${resolve}if(!m)return '0';` +\n FOCUS_STATE_JS +\n `if(ok)return '1';` +\n `return (!!ae&&ae!==document.body&&editable(ae))?'1':'0';})()`\n );\n}\n\n// Select the focused element's ENTIRE current value (input/textarea via\n// select(); contenteditable via a DOM range) so the next Input.insertText\n// REPLACES it — the `type` step's `clear: true`. Chrome's editing commands\n// don't run off dispatched key events (a \"Meta+a\" press registers nothing),\n// so the selection is made in-page instead.\nexport function selectAllInFocusedJs(): string {\n return (\n `(function(){var el=document.activeElement;if(!el)return 'NOFOCUS';` +\n `if(typeof el.select==='function'&&typeof el.value==='string'){el.select();return 'SEL';}` +\n `if(el.isContentEditable){var r=document.createRange();r.selectNodeContents(el);` +\n `var s=window.getSelection();s.removeAllRanges();s.addRange(r);return 'SEL';}` +\n `return 'NOSEL';})()`\n );\n}\n\n// bbox-only resolvers for drag endpoints — never click/focus (a drag must\n// not deselect a tool or shift the canvas before the stroke).\nexport function boxSelectorJs(selector: string): string {\n const s = JSON.stringify(selector);\n return (\n `(function(){var m=document.querySelector(${s});if(!m)return 'NOTFOUND';` +\n `var r=m.getBoundingClientRect();` +\n `if(r.top<0||r.bottom>window.innerHeight){m.scrollIntoView({block:'center'});r=m.getBoundingClientRect();}` +\n `return JSON.stringify({x:Math.round(r.x),y:Math.round(r.y),w:Math.round(r.width),h:Math.round(r.height)});})()`\n );\n}\n\nexport function boxByTextJs(text: string): string {\n const t = JSON.stringify(text);\n return (\n `(function(){var t=${t};` +\n `var els=Array.prototype.slice.call(document.querySelectorAll('${BOX_CANDIDATES}'));` +\n NAME_JS +\n `var m=pick(els,t);` +\n `if(!m)return 'NOTFOUND';var r=m.getBoundingClientRect();` +\n `if(r.top<0||r.bottom>window.innerHeight){m.scrollIntoView({block:'center'});r=m.getBoundingClientRect();}` +\n `return JSON.stringify({x:Math.round(r.x),y:Math.round(r.y),w:Math.round(r.width),h:Math.round(r.height)});})()`\n );\n}\n\n// --- href resolvers -----------------------------------------------------\n// Read a link's DESTINATION without clicking it — the late-bound half of the\n// `navigate` step. Returns the browser-resolved absolute URL (`.href`), never\n// the raw attribute, so a relative or protocol-relative link comes back usable.\n// Neither of these scrolls or clicks: nothing on screen may change, because\n// this runs mid-recording and the beat is the navigation itself.\nconst CLOSEST_ANCHOR_JS =\n // The named element may BE the link or sit inside one — closest() covers both\n // (it tests the element itself first) — or WRAP one, which it does not.\n `var a=m.closest('a[href]')||m.querySelector('a[href]');` +\n `if(!a||!a.href)return 'NOTFOUND';return a.href;`;\n\nexport function hrefSelectorJs(selector: string): string {\n const s = JSON.stringify(selector);\n return `(function(){var m=document.querySelector(${s});if(!m)return 'NOTFOUND';${CLOSEST_ANCHOR_JS}})()`;\n}\n\nexport function hrefByTextJs(text: string): string {\n const t = JSON.stringify(text);\n return (\n `(function(){var t=${t};` +\n `var els=Array.prototype.slice.call(document.querySelectorAll('a,button,[role=link],[role=button],[aria-label],[title]'));` +\n NAME_JS +\n `var m=pick(els,t);` +\n `if(!m)return 'NOTFOUND';${CLOSEST_ANCHOR_JS}})()`\n );\n}\n\n// --- scroll-to-element delta -------------------------------------------\n// How far (signed px, + = down) to scroll so the element's centre lands at\n// viewport centre. Measures the CURRENT rect WITHOUT scrollIntoView (a jump\n// would defeat the smooth wheel ramp). Returns \"NOTFOUND\" or a {dy} JSON.\nexport function scrollDeltaSelectorJs(selector: string): string {\n const s = JSON.stringify(selector);\n return (\n `(function(){var m=document.querySelector(${s});if(!m)return 'NOTFOUND';` +\n `var r=m.getBoundingClientRect();` +\n `return JSON.stringify({dy:Math.round(r.top+r.height/2-window.innerHeight/2)});})()`\n );\n}\n\nexport function scrollDeltaByTextJs(text: string): string {\n const t = JSON.stringify(text);\n return (\n `(function(){var t=${t};` +\n `var els=Array.prototype.slice.call(document.querySelectorAll('${SCROLL_CANDIDATES}'));` +\n NAME_JS +\n `var m=pick(els,t);` +\n `if(!m)return 'NOTFOUND';var r=m.getBoundingClientRect();` +\n `return JSON.stringify({dy:Math.round(r.top+r.height/2-window.innerHeight/2)});})()`\n );\n}\n\n// Sample a viewport-px point a fraction u (0..1) along a polyline by arc\n// length — used to densify a drag into smooth mouse-move steps so canvas\n// drawing libs receive continuous pointermove (and the stroke looks drawn).\nexport function sampleAlong(pts: { x: number; y: number }[], u: number): { x: number; y: number } {\n if (pts.length === 1) return pts[0]!;\n const seg: number[] = [];\n let total = 0;\n for (let i = 0; i < pts.length - 1; i++) {\n const d = Math.hypot(pts[i + 1]!.x - pts[i]!.x, pts[i + 1]!.y - pts[i]!.y);\n seg.push(d);\n total += d;\n }\n if (total === 0) return pts[0]!;\n let target = u * total;\n for (let i = 0; i < seg.length; i++) {\n if (target <= seg[i]! || i === seg.length - 1) {\n const f = seg[i]! > 0 ? target / seg[i]! : 0;\n return {\n x: pts[i]!.x + (pts[i + 1]!.x - pts[i]!.x) * f,\n y: pts[i]!.y + (pts[i + 1]!.y - pts[i]!.y) * f,\n };\n }\n target -= seg[i]!;\n }\n return pts[pts.length - 1]!;\n}\n\nexport async function ffprobe(\n path: string,\n): Promise<{ width?: number; height?: number; fps?: string; durationS?: number }> {\n // resolved binary (PATH or bundled installer); the probe itself stays\n // best-effort — a failed probe resolves {} (callers have fallbacks).\n const bin = await resolveFfprobe().catch(() => null);\n if (!bin) return {};\n return new Promise((res) => {\n const c = spawn(\n bin,\n [\n \"-v\",\n \"error\",\n \"-select_streams\",\n \"v:0\",\n \"-show_entries\",\n \"stream=width,height,r_frame_rate,duration\",\n \"-show_entries\",\n \"format=duration\",\n \"-of\",\n \"json\",\n path,\n ],\n { stdio: [\"ignore\", \"pipe\", \"ignore\"] },\n );\n let out = \"\";\n c.stdout.on(\"data\", (d) => {\n out += d;\n });\n c.on(\"close\", () => {\n try {\n const j = JSON.parse(out);\n const s = j.streams?.[0] ?? {};\n res({\n width: s.width,\n height: s.height,\n fps: s.r_frame_rate,\n durationS: Number(s.duration ?? j.format?.duration ?? 0),\n });\n } catch {\n res({});\n }\n });\n });\n}\n\nexport type CaptureOpts = {\n /** output video path (mp4) */\n videoPath: string;\n /** ms to let the page settle after capture start before the first action */\n warmupMs?: number;\n /**\n * Encode fps. Default 60; this does not guarantee 60 unique captured frames.\n * Capture is a CDP screencast at the browser's\n * native rate; this is the encode grid and the intended render fps. Drop to\n * 30 for fast-draft renders (~½ the render time + file size) while iterating.\n * See cdp-capture.ts.\n */\n fps?: number;\n /**\n * Capture pixel density (device scale factor). Default 2: record at Retina\n * density — 2 physical px per CSS px — so a camera zoom ≤2× always has\n * ≥1:1 source pixels per output pixel and stays sharp (matches how premium\n * screen recorders keep zooms crisp). Coordinates everywhere (events, log,\n * composition) stay in CSS px; only the video bitmap is denser. Drop to 1\n * if a heavy page can't hold the capture fps at 4K screencast.\n */\n captureScale?: number;\n /** Refresh idle raster surfaces with a bounded screenshot request (default\n * \"idle\"). Use \"off\" for verified self-animating pages when screenshot\n * refresh interferes with their native frame delivery. Inspect actual frames\n * and captureCadence for the chosen scale; neither mode guarantees smoothness. */\n rasterRefresh?: \"idle\" | \"off\";\n /** explicit Chrome binary (else auto-resolved system Chrome / auto-download) */\n chromePath?: string;\n /** How a `drag` stroke is paced (and thus baked into the ink): \"smooth\"\n * (accel-in / decel-out — a natural hand-draw, default) or \"linear\"\n * (constant speed). Recorded on each drag event so the compositor cursor\n * replays the same easing and stays locked to the ink. */\n dragEasing?: \"linear\" | \"smooth\";\n /** Persistent Chrome profile dir (an authenticated capture — pair with\n * `open-take auth`). Default: a throwaway temp profile, removed on close. */\n userDataDir?: string;\n /** false ⇒ drive a visible (headed) window instead of headless. The\n * screencast records either way — the escape hatch for sites that gate on\n * a real window. Default true. */\n headless?: boolean;\n /** Extra ms a beat's hold may spend waiting for the PAGE when `settleMs`\n * expires while it is still working (network in flight, DOM mutating, a\n * reveal animating). Never shortens a hold — see runtime/src/settle.ts.\n * Default `DEFAULT_SETTLE_BUDGET_MS`; 0 restores the old fixed sleeps\n * exactly. */\n settleBudgetMs?: number;\n /** DOM STATES: save the page's UI structure at every settled moment (after\n * the warmup, then after each step's final hold) so a launch film can\n * re-render the real interface as live DOM — see runtime/src/dom-state.ts.\n * Read-only on the live page; costs a few hundred ms of take time per\n * state (reported). Lands in `states/` beside the capture video, and on\n * the log as `states` + per-event `state`/`target`. Default false. */\n states?: boolean;\n /** with `states`: measure each saved state's parts in the fidelity page\n * (states/<id>/parts.json + crisp pictures) — `make` then gathers them\n * into <name>.take/components.json. Default true; false skips both. */\n components?: boolean;\n /** PRODUCT AUDIO: record what the page sends to its speakers (every\n * AudioContext and playing media element) onto the capture timeline, and\n * list the audio files it fetched — `product-audio.wav`,\n * `product-sound.json` and `product-sounds/` beside the capture video (see\n * runtime/src/product-audio.ts). Nothing is created on a silent page; a\n * failure is a note, never a failed take. Default true. */\n productAudio?: boolean;\n};\n\n/** Drive `plan` against the live app over CDP, return the ground-truth log. */\nexport async function captureTake(plan: TakePlan, opts: CaptureOpts): Promise<CaptureLog> {\n const { captureTakeCDP } = await import(\"./cdp-capture\");\n return captureTakeCDP(plan, { ...opts, fps: opts.fps ?? 60 });\n}\n\n// --- inspectPage: planning aid -----------------------------------------\n\nexport type InspectElement = {\n name: string;\n tag: string;\n role: string | null;\n href: string | null;\n inView: boolean;\n x: number;\n y: number;\n w: number;\n h: number;\n};\n\nexport type InspectResult = {\n url: string;\n /** where the navigation actually landed (redirects, SPA rewrites) */\n finalUrl: string;\n /** document.title — the one-call check that this is the app you think it is\n * (a stale port number silently serves a different project's dev server) */\n title: string;\n viewport: { w: number; h: number };\n elements: InspectElement[];\n};\n\n// Exported for the locator-name tests: the bug this shares a resolver with\n// lived in the emitted page-JS, so the test evaluates this string directly.\nexport function listInteractiveJs(): string {\n return (\n `(function(){` +\n NAME_JS +\n `var sel='button,a,[role=button],[role=link],[role=menuitem],[role=tab],[role=switch],[role=checkbox],input,select,textarea';` +\n `var els=Array.prototype.slice.call(document.querySelectorAll(sel));var vw=window.innerWidth,vh=window.innerHeight;var out=[];var seen={};` +\n `for(var i=0;i<els.length;i++){var e=els[i];var n=dispName(e);var ph=e.getAttribute('placeholder');var r=e.getBoundingClientRect();` +\n `if(r.width<6||r.height<6)continue;if(!n&&!ph)continue;` +\n `var label=n||('['+(ph||e.tagName.toLowerCase())+']');var key=label+'@'+Math.round(r.x)+','+Math.round(r.y);if(seen[key])continue;seen[key]=1;` +\n `var iv=r.top<vh&&r.bottom>0&&r.left<vw&&r.right>0;` +\n `out.push({name:label,tag:e.tagName.toLowerCase(),role:e.getAttribute('role')||null,href:e.getAttribute('href')||null,inView:iv,x:Math.round(r.x),y:Math.round(r.y),w:Math.round(r.width),h:Math.round(r.height)});}` +\n `out.sort(function(a,b){return (b.inView?1:0)-(a.inView?1:0);});` +\n `return JSON.stringify(out.slice(0,60));})()`\n );\n}\n\nexport type InspectOpts = {\n viewport?: { width: number; height: number };\n warmupMs?: number;\n /** explicit Chrome binary (else auto-resolved / auto-downloaded) */\n chromePath?: string;\n /** persistent Chrome profile dir (inspect an authenticated page) */\n userDataDir?: string;\n /** false ⇒ inspect via a visible (headed) window. Default true. */\n headless?: boolean;\n};\n\n/** Open `url`, return its interactive elements (accessible name + bbox) —\n * what an agent uses to choose a demo flow. Pure CDP, same as capture, so\n * the reported coordinate space matches what capture will drive against. */\nexport async function inspectPage(url: string, opts: InspectOpts = {}): Promise<InspectResult> {\n const vw = opts.viewport?.width ?? 1920;\n const vh = opts.viewport?.height ?? 1080;\n const browser = await launchBrowser({\n width: vw,\n height: vh,\n chromePath: opts.chromePath,\n ...(opts.userDataDir ? { userDataDir: opts.userDataDir } : {}),\n ...(opts.headless === false ? { headless: false } : {}),\n });\n try {\n const { cdp } = browser;\n await cdp.send(\"Page.enable\");\n await cdp.send(\"Runtime.enable\");\n const inner = await fitViewport(cdp, browser.targetId, vw, vh);\n // errorText set ⇒ no server answered (refused/DNS/timeout) and the tab is\n // showing Chrome's own error page — inspecting ITS elements would send an\n // agent planning a demo of ERR_CONNECTION_REFUSED. An HTTP 404/500 has no\n // errorText: the app answered, inspect what it said.\n const nav = await cdp.send<{ errorText?: string }>(\"Page.navigate\", { url });\n if (nav.errorText)\n throw new Error(\n `inspectPage: ${url} did not answer (${nav.errorText}) — is the app running?`,\n );\n await sleep(opts.warmupMs ?? 1500);\n\n const evalRaw = async (expr: string): Promise<string> => {\n const r = await cdp.send<{ result?: { value?: unknown } }>(\"Runtime.evaluate\", {\n expression: expr,\n returnByValue: true,\n });\n return String(r.result?.value ?? \"\");\n };\n\n let elements: InspectElement[] = [];\n try {\n const v = evalValue(await evalRaw(listInteractiveJs()));\n if (Array.isArray(v)) elements = v as InspectElement[];\n } catch {\n /* leave empty */\n }\n const title = await evalRaw(\"document.title\").catch(() => \"\");\n const finalUrl = (await evalRaw(\"location.href\").catch(() => \"\")) || url;\n\n return { url, finalUrl, title, viewport: { w: inner[0], h: inner[1] }, elements };\n } finally {\n await browser.close();\n }\n}\n\n// --- native <select> ----------------------------------------------------\n// A native `<select>` cannot be DRIVEN by clicking it. Measured directly\n// (probe, 2026-08-09): `.click()` on a select returns in ~3ms and changes\n// NOTHING — value stays put, no popup paints, the app receives no event.\n// Headless Chrome has no browser-process popup to open, so the click is a\n// silent no-op: the beat films a cursor landing on a control that does not\n// respond, and any downstream \"the app recomputed\" payoff never happens.\n// (An earlier note here blamed a capture hang on this click; a direct probe\n// disproved that — the click is inert, not blocking.)\n//\n// So we drive it the way the PAGE experiences it: set `value` and dispatch\n// input+change. Same honesty class as `type` (synthesized keystrokes) — the\n// app really receives the event, really recomputes, and the select really\n// shows its new value on camera. Only the OS popup is missing, and that was\n// never filmable.\n//\n// The option is matched by exact value, then exact label, then a trimmed\n// substring of the label — real option text carries thin spaces, units and\n// parenthetical detail (\"Large (30 seats)\") that an author will not\n// reproduce character-perfect.\nexport function selectOptionJs(\n target: { selector?: string; text?: string },\n value: string,\n): string {\n const sel = JSON.stringify(target.selector ?? \"\");\n const name = JSON.stringify(target.text ?? \"\");\n const v = JSON.stringify(value);\n return (\n `(function(){var s=${sel},n=${name},want=${v};` +\n `var m=null;` +\n `if(s){m=document.querySelector(s);}` +\n `else if(n){var els=Array.prototype.slice.call(document.querySelectorAll('select'));` +\n // by accessible name: aria-label, the label element pointing at it, or a\n // wrapping label's text\n `m=els.find(function(e){var a=(e.getAttribute('aria-label')||'').trim();if(a===n)return true;` +\n `var id=e.id;if(id){var l=document.querySelector('label[for=\"'+id+'\"]');if(l&&(l.textContent||'').trim().indexOf(n)>=0)return true;}` +\n `var p=e.closest('label');if(p&&(p.textContent||'').trim().indexOf(n)>=0)return true;return false;})||null;}` +\n `if(!m)return 'NOTFOUND';` +\n `if(m.tagName!=='SELECT')return 'NOTASELECT';` +\n `var opts=Array.prototype.slice.call(m.options);` +\n `var norm=function(x){return (x||'').replace(/\\\\s+/g,'').trim();};` +\n `var o=opts.find(function(x){return x.value===want;})` +\n `||opts.find(function(x){return norm(x.textContent)===norm(want);})` +\n `||opts.find(function(x){return norm(x.textContent).indexOf(norm(want))>=0;});` +\n `if(!o)return 'NOOPTION';` +\n `var r=m.getBoundingClientRect();` +\n `if(r.top<0||r.bottom>window.innerHeight){m.scrollIntoView({block:'center'});r=m.getBoundingClientRect();}` +\n `m.focus();m.value=o.value;` +\n `m.dispatchEvent(new Event('input',{bubbles:true}));` +\n `m.dispatchEvent(new Event('change',{bubbles:true}));` +\n `var b={x:Math.round(r.x),y:Math.round(r.y),w:Math.round(r.width),h:Math.round(r.height)};` +\n `return JSON.stringify(b);})()`\n );\n}\n","// Running a tool and keeping what it writes: stdout as bytes, and when it\n// fails, the end of its stderr in the error.\n\nimport { spawn } from \"node:child_process\";\n\nexport function runBuffer(bin: string, args: string[]): Promise<Buffer> {\n return new Promise((ok, fail) => {\n const p = spawn(bin, args, { stdio: [\"ignore\", \"pipe\", \"pipe\"] });\n const chunks: Buffer[] = [];\n let err = \"\";\n p.stdout.on(\"data\", (d: Buffer) => chunks.push(d));\n p.stderr.on(\"data\", (d: Buffer) => {\n err = (err + d.toString()).slice(-2000);\n });\n p.on(\"error\", fail);\n p.on(\"close\", (code) =>\n code === 0\n ? ok(Buffer.concat(chunks))\n : fail(new Error(`${bin} exited ${code}: ${err.trim().slice(-400)}`)),\n );\n });\n}\n","// DOM states — the page's UI STRUCTURE, saved at every settled moment of a\n// take so a launch film can later re-render the product's real interface as\n// live, vector-crisp DOM (lift the clicked button out of the page, split the\n// page into its regions, zoom without blur) instead of scaling video pixels.\n//\n// Opt-in (`CaptureOpts.states`). Three moving parts, all in this module:\n//\n// 1. DURING the recording (`captureDomState`) — strictly READ-ONLY on the\n// live page: a page-side probe (`DOM_STATE_PROBE_JS`) reads structure,\n// live input values, scroll offsets, canvas/video pixels and the current\n// value of every animated property; a 1× screenshot is the fidelity\n// reference; `Page.captureSnapshot` (MHTML) carries the markup, styles\n// and images — but no web-font file (see `fetchFontFiles`). Raw files\n// land in `states/<id>/`.\n// 2. AFTER the screencast (`finalizeDomStates`) — the MHTML becomes a\n// self-contained `state.html` (`convertMhtml`): parts are written once\n// into a shared `states/assets/` (sha1-named), references are rewritten,\n// every script is made inert IN PLACE (element indices survive), and a\n// restore script re-applies what markup cannot carry. The page's\n// @font-face files, which the snapshot leaves out, are fetched once\n// through the still-open browser and saved beside the other parts. Then\n// a FIDELITY\n// check re-opens the state in the same browser and compares it with the\n// reference screenshot; a state that does not match stays on disk with\n// `fidelity.ok: false` so the film falls back to the video.\n// 3. `index.json` per state is the contract the film side reads\n// (the compositor's `StateIndex` — exactly these keys).\n//\n// Element PATHS. Chrome's MHTML serializer (measured on 149) drops `<script>`,\n// `<noscript>`, `[hidden]` and `<input type=hidden>` outright, so a path is\n// the chain of child indices counted over the siblings that SURVIVE\n// serialization — the probe skips the same elements the serializer skips,\n// and the restore script resolves the same path in the saved document. The\n// serializer also emits shadow roots as legacy `<template shadowmode>`\n// (rewritten to `shadowrootmode` so the parser attaches them, which keeps a\n// host's light children at their indices) and prepends its own `<meta>` +\n// custom-elements shim `<script>` to `<head>` — nothing visible lives in\n// `<head>`, so no path points there.\n\nimport { createHash } from \"node:crypto\";\nimport { existsSync, mkdirSync, writeFileSync } from \"node:fs\";\nimport { mkdtemp, readFile, rm, writeFile } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { extname, join, relative, sep } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport {\n type CaptureLog,\n CLIP_CLEAR_CSS,\n type ComponentProbeResult,\n componentProbeExpression,\n type PartDomFile,\n type PartsFile,\n partDomExpression,\n pictureClip,\n readStateIndex,\n resolveFfmpeg,\n type StateElement,\n type StateIndex,\n} from \"@open-take/compositor\";\nimport { type Browser, CDP, isCdpStall } from \"./cdp\";\nimport { runBuffer } from \"./tool\";\n\nconst sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));\n\n// --- the contract ---------------------------------------------------------\n\ntype StateFidelity = NonNullable<StateIndex[\"fidelity\"]>;\n\n/** What the page-side probe returns (JSON). Everything the markup cannot\n * carry: live `.value`s, scroll offsets, canvas/video pixels, the computed\n * value of every animated property, and the custom-element names to define\n * so `:defined` styling holds. */\nexport type DomStateProbe = {\n url: string;\n title: string;\n viewport: { w: number; h: number; dpr: number };\n scroll: { x: number; y: number };\n elements: StateElement[];\n layers: string[];\n scrolled: { path: number[]; top: number; left: number }[];\n /** `selected`: a <select>'s chosen options, by index (one, or several when multiple) */\n inputs: { path: number[]; value?: string; checked?: boolean; selected?: number[] }[];\n /** `box`: where it is on screen (CSS px); `blank`: its copy came out one colour */\n canvases: {\n path: number[];\n dataUrl: string;\n box?: [number, number, number, number];\n blank?: boolean;\n }[];\n videos: {\n path: number[];\n dataUrl: string;\n box?: [number, number, number, number];\n blank?: boolean;\n }[];\n animated: { path: number[]; styles: Record<string, string> }[];\n custom: { name: string; extends?: string }[];\n /** the focused element (a typed-into field keeps its focus ring), if any */\n focus?: number[];\n};\n\n/** Hard cap on the element index — a page past it is a data table, not a UI. */\nconst DOM_STATE_MAX_ELEMENTS = 3000;\n/** A state whose re-render reaches this PSNR against the live screenshot is\n * trusted; below it the film uses the video. */\nconst DOM_STATE_PSNR_OK = 30;\n\n// --- the page-side probe ----------------------------------------------------\n\n/** Runs in the live page (Runtime.evaluate, returnByValue) and returns the\n * probe as a JSON string. Reads only: no attribute, style or node is touched\n * — the app is being filmed and must behave exactly as without states. */\nconst DOM_STATE_PROBE_JS = `(() => {\n try {\n const vw = innerWidth, vh = innerHeight, dpr = devicePixelRatio || 1;\n const CAP = ${DOM_STATE_MAX_ELEMENTS};\n // never listed (invisible by nature) — but they DO count as siblings when they survive serialization\n const SKIP = { script: 1, style: 1, link: 1, meta: 1, noscript: 1, head: 1, title: 1, template: 1 };\n // what Chrome's MHTML serializer drops: these never count as siblings (see the module header)\n const survives = (el) => {\n const t = el.localName;\n if (t === \"script\" || t === \"noscript\") return false;\n if (el.hasAttribute(\"hidden\")) return false;\n if (t === \"input\" && (el.getAttribute(\"type\") || \"\").toLowerCase() === \"hidden\") return false;\n return true;\n };\n // containers never take their name from content (a page-sized div would name itself after the page)\n const CONTAINER = { div: 1, section: 1, article: 1, main: 1, nav: 1, header: 1, footer: 1, aside: 1, form: 1, ul: 1, ol: 1, table: 1, tbody: 1, thead: 1, tfoot: 1, tr: 1, fieldset: 1, dialog: 1, body: 1, html: 1, figure: 1, details: 1, menu: 1, dl: 1 };\n const HEADING = { h1: 1, h2: 1, h3: 1, h4: 1, h5: 1, h6: 1 };\n const INTERACTIVE_ROLE = { button: 1, link: 1, tab: 1, menuitem: 1, checkbox: 1, switch: 1, radio: 1, option: 1, combobox: 1, textbox: 1, searchbox: 1, slider: 1, spinbutton: 1, menuitemcheckbox: 1, menuitemradio: 1 };\n const collapse = (s) => (s || \"\").replace(/\\\\s+/g, \" \").trim().slice(0, 80);\n const ownText = (el) => { let s = \"\"; for (const n of el.childNodes) if (n.nodeType === 3) s += n.data; return collapse(s); };\n const implicitRole = (el) => {\n const t = el.localName;\n switch (t) {\n case \"a\": case \"area\": return el.hasAttribute(\"href\") ? \"link\" : null;\n case \"button\": case \"summary\": return \"button\";\n case \"input\": {\n const ty = (el.getAttribute(\"type\") || \"text\").toLowerCase();\n if (ty === \"checkbox\") return \"checkbox\";\n if (ty === \"radio\") return \"radio\";\n if (ty === \"range\") return \"slider\";\n if (ty === \"number\") return \"spinbutton\";\n if (ty === \"search\") return \"searchbox\";\n if (ty === \"button\" || ty === \"submit\" || ty === \"reset\" || ty === \"image\") return \"button\";\n return \"textbox\";\n }\n case \"select\": return el.multiple || el.size > 1 ? \"listbox\" : \"combobox\";\n case \"textarea\": return \"textbox\";\n case \"img\": case \"svg\": return \"img\";\n case \"ul\": case \"ol\": case \"menu\": return \"list\";\n case \"li\": return \"listitem\";\n case \"nav\": return \"navigation\";\n case \"main\": return \"main\";\n case \"header\": return \"banner\";\n case \"footer\": return \"contentinfo\";\n case \"aside\": return \"complementary\";\n case \"form\": return \"form\";\n case \"table\": return \"table\";\n case \"tr\": return \"row\";\n case \"td\": return \"cell\";\n case \"th\": return \"columnheader\";\n case \"dialog\": return \"dialog\";\n case \"option\": return \"option\";\n case \"progress\": return \"progressbar\";\n case \"hr\": return \"separator\";\n case \"article\": return \"article\";\n case \"fieldset\": case \"details\": return \"group\";\n case \"output\": return \"status\";\n case \"section\": return el.hasAttribute(\"aria-label\") || el.hasAttribute(\"aria-labelledby\") ? \"region\" : null;\n default: return HEADING[t] ? \"heading\" : null;\n }\n };\n const isInteractive = (el, role) => {\n const t = el.localName;\n if (t === \"a\" || t === \"button\" || t === \"input\" || t === \"select\" || t === \"textarea\" || t === \"summary\") return true;\n if (role && INTERACTIVE_ROLE[role]) return true;\n const ce = el.getAttribute(\"contenteditable\");\n if (ce != null && ce !== \"false\") return true;\n const ti = el.getAttribute(\"tabindex\");\n if (ti != null && Number(ti) >= 0) return true;\n return false;\n };\n const nameOf = (el, interactive) => {\n const al = el.getAttribute(\"aria-label\"); if (al && al.trim()) return collapse(al);\n const lb = el.getAttribute(\"aria-labelledby\");\n if (lb) { let s = \"\"; for (const id of lb.split(/\\\\s+/)) { const r = document.getElementById(id); if (r) s += \" \" + r.textContent; } if (s.trim()) return collapse(s); }\n const alt = el.getAttribute(\"alt\"); if (alt && alt.trim()) return collapse(alt);\n const ti = el.getAttribute(\"title\"); if (ti && ti.trim()) return collapse(ti);\n const ph = el.getAttribute(\"placeholder\"); if (ph && ph.trim()) return collapse(ph);\n if (el.labels && el.labels.length) { const s = collapse(el.labels[0].textContent); if (s) return s; }\n if (el.localName === \"input\") {\n const ty = (el.getAttribute(\"type\") || \"\").toLowerCase();\n if (ty === \"submit\" || ty === \"button\" || ty === \"reset\") { const v = el.getAttribute(\"value\"); if (v) return collapse(v); }\n }\n if (el.localName === \"select\") { const o = el.selectedOptions && el.selectedOptions[0]; return o ? collapse(o.textContent) : \"\"; }\n if (interactive || !CONTAINER[el.localName]) { const s = collapse(el.textContent); if (s) return s; }\n return \"\";\n };\n const elements = [], scrolled = [], inputs = [], canvases = [], videos = [];\n // a copy that came out empty (a WebGL canvas that does not keep its\n // drawing buffer reads back transparent): one colour over 16×16 samples\n const blankImage = (img) => {\n try {\n const c = document.createElement(\"canvas\"); c.width = 16; c.height = 16;\n const x = c.getContext(\"2d\", { willReadFrequently: true }); x.drawImage(img, 0, 0, 16, 16);\n const d = x.getImageData(0, 0, 16, 16).data;\n for (let i = 4; i < d.length; i += 4)\n if (d[i] !== d[0] || d[i + 1] !== d[1] || d[i + 2] !== d[2] || d[i + 3] !== d[3]) return false;\n return true;\n } catch (e) { return false; }\n };\n const custom = new Map();\n const idOf = new Map();\n let count = 0;\n const visit = (el, path) => {\n const t = el.localName;\n if (t === \"head\") return; // nothing visible lives there\n if (t.indexOf(\"-\") > 0 && customElements.get(t)) custom.set(t, \"\");\n const isAttr = el.getAttribute(\"is\");\n if (isAttr && customElements.get(isAttr)) custom.set(isAttr, t);\n if (!SKIP[t]) {\n const cs = getComputedStyle(el);\n if (cs.display === \"none\") return; // no boxes below either\n if (parseFloat(cs.opacity) === 0) return; // subtree invisible\n const r = el.getBoundingClientRect();\n // checkVisibility: content skipped by content-visibility (a closed\n // <details>' rows keep boxes but are not drawn) is not on screen\n const drawn = typeof el.checkVisibility !== \"function\" || el.checkVisibility();\n const onScreen = drawn && cs.visibility === \"visible\" && r.width > 0 && r.height > 0 && r.right > 0 && r.bottom > 0 && r.left < vw && r.top < vh;\n if (count < CAP && onScreen) {\n const role = (el.getAttribute(\"role\") || \"\").trim().split(/\\\\s+/)[0] || implicitRole(el);\n const interactive = isInteractive(el, role);\n const id = \"e\" + count++;\n const item = { id, path, tag: t };\n if (role) item.role = role;\n const name = nameOf(el, interactive); if (name) item.name = name;\n const text = ownText(el); if (text) item.text = text;\n item.box = [Math.round(r.left), Math.round(r.top), Math.round(r.width), Math.round(r.height)];\n if (cs.position === \"fixed\" || cs.position === \"sticky\") item.fixed = true;\n if (interactive) item.interactive = true;\n elements.push(item);\n idOf.set(el, id);\n }\n if ((el.scrollTop || el.scrollLeft) && el !== document.scrollingElement && el !== document.body)\n scrolled.push({ path, top: el.scrollTop, left: el.scrollLeft });\n if (t === \"input\") {\n const ty = (el.getAttribute(\"type\") || \"text\").toLowerCase();\n if (ty === \"checkbox\" || ty === \"radio\") inputs.push({ path, checked: !!el.checked });\n else if (ty !== \"file\") inputs.push({ path, value: ty === \"password\" ? \"x\".repeat(el.value.length) : el.value });\n } else if (t === \"textarea\") inputs.push({ path, value: el.value });\n else if (t === \"select\") {\n const selected = [];\n for (let i = 0; i < el.options.length; i++) if (el.options[i].selected) selected.push(i);\n inputs.push({ path, selected });\n }\n // pixels are copied only for what is on screen, at the size it is\n // shown (× the pixel ratio): encoding runs on the app's main thread,\n // and a hidden 4K <video> behind a canvas stage cost a 5.7 s freeze\n else if (t === \"canvas\") {\n if (onScreen && el.width > 0 && el.height > 0) {\n try {\n const w = Math.min(el.width, Math.ceil(r.width * dpr)), h = Math.min(el.height, Math.ceil(r.height * dpr));\n let src = el;\n if (w < el.width || h < el.height) { src = document.createElement(\"canvas\"); src.width = w; src.height = h; src.getContext(\"2d\").drawImage(el, 0, 0, w, h); }\n canvases.push({ path, dataUrl: src.toDataURL(\"image/png\"), box: [r.left, r.top, r.width, r.height], blank: blankImage(src) });\n } catch (e) {}\n }\n } else if (t === \"video\") {\n try {\n if (onScreen && el.videoWidth > 0 && el.videoHeight > 0) {\n const c = document.createElement(\"canvas\");\n c.width = Math.min(el.videoWidth, Math.ceil(r.width * dpr)); c.height = Math.min(el.videoHeight, Math.ceil(r.height * dpr));\n c.getContext(\"2d\").drawImage(el, 0, 0, c.width, c.height);\n // a frame of video is opaque: JPEG encodes it an order of magnitude faster than PNG\n videos.push({ path, dataUrl: c.toDataURL(\"image/jpeg\", 0.92), box: [r.left, r.top, r.width, r.height], blank: blankImage(c) });\n }\n } catch (e) {}\n }\n }\n if (t === \"svg\") return; // internals are never targets; keeps icon-heavy pages under the cap\n let i = 0;\n for (const c of el.children) { if (!survives(c)) continue; visit(c, path.concat(i)); i++; }\n };\n visit(document.documentElement, []);\n\n // layers: from <body> descend through single big-child wrappers; a container\n // covering > 50% of the viewport is split into its big in-view children;\n // fixed/sticky and higher z-index sort on top\n const areaOf = (el) => { const r = el.getBoundingClientRect(); return Math.max(0, r.width) * Math.max(0, r.height); };\n const big = (el) => !SKIP[el.localName] && survives(el) && areaOf(el) >= 0.03 * vw * vh && getComputedStyle(el).display !== \"none\";\n const bigKids = (n) => Array.from(n.children).filter(big);\n const inView = (el) => { const r = el.getBoundingClientRect(); return r.top < vh && r.bottom > 0 && r.left < vw && r.right > 0; };\n let node = document.body, guard = 0;\n while (node && bigKids(node).length === 1 && guard++ < 8) node = bigKids(node)[0];\n const split = (k, depth) => {\n const cs = getComputedStyle(k);\n if (depth > 4 || cs.position === \"fixed\" || cs.position === \"sticky\" || areaOf(k) <= 0.5 * vw * vh) return [k];\n const sub = bigKids(k).filter(inView);\n if (sub.length >= 2) return sub;\n if (sub.length === 1) return split(sub[0], depth + 1);\n return [k];\n };\n const score = (el) => { const cs = getComputedStyle(el); return (cs.position === \"fixed\" || cs.position === \"sticky\" ? 1000 : 0) + (Number(cs.zIndex) || 0); };\n const kids = node ? bigKids(node).flatMap((k) => split(k, 0)).filter(inView) : [];\n const layers = [];\n for (const { el } of kids.map((el, i) => ({ el, i, s: score(el) })).sort((a, b) => a.s - b.s || a.i - b.i)) {\n const id = idOf.get(el);\n if (id && layers.length < 8) layers.push(id);\n }\n\n // animated: the CURRENT computed value of every property an animation or\n // transition drives — the saved page runs no animations (animation: none),\n // so without this a finished \"fadeIn forwards\" would show its base style\n const pathOf = (el) => {\n const p = [];\n let n = el;\n while (n !== document.documentElement) {\n const par = n.parentElement;\n if (!par || !survives(n)) return null; // detached, hidden, or inside a shadow root\n let i = 0;\n for (const c of par.children) { if (c === n) break; if (survives(c)) i++; }\n p.push(i);\n n = par;\n }\n return p.reverse();\n };\n const animated = [];\n try {\n const byEl = new Map();\n for (const a of document.getAnimations()) {\n const ef = a.effect;\n if (!ef || typeof ef.getKeyframes !== \"function\") continue;\n const target = ef.target;\n if (!(target instanceof Element) || ef.pseudoElement) continue;\n let styles = byEl.get(target);\n if (!styles) { styles = {}; byEl.set(target, styles); }\n const cs = getComputedStyle(target);\n for (const kf of ef.getKeyframes()) for (const k in kf) {\n if (k === \"offset\" || k === \"easing\" || k === \"composite\" || k === \"computedOffset\") continue;\n const prop = k === \"cssFloat\" ? \"float\" : k === \"cssOffset\" ? \"offset\" : k.startsWith(\"--\") ? k : k.replace(/[A-Z]/g, (m) => \"-\" + m.toLowerCase());\n styles[prop] = cs.getPropertyValue(prop);\n }\n }\n for (const [el, styles] of byEl) {\n const path = pathOf(el);\n if (path && Object.keys(styles).length) animated.push({ path, styles });\n }\n } catch (e) {}\n\n const active = document.activeElement;\n const focus = active && active !== document.body && active !== document.documentElement ? pathOf(active) : null;\n return JSON.stringify({\n url: location.href,\n title: document.title,\n viewport: { w: vw, h: vh, dpr: devicePixelRatio },\n scroll: { x: Math.round(scrollX), y: Math.round(scrollY) },\n elements, layers, scrolled, inputs, canvases, videos, animated,\n custom: Array.from(custom, ([name, ext]) => (ext ? { name, extends: ext } : { name })),\n ...(focus ? { focus } : {}),\n });\n } catch (e) {\n return JSON.stringify({ error: String(e && e.message || e) });\n }\n})()`;\n\n// --- MHTML parsing ------------------------------------------------------------\n\nexport type MhtmlPart = {\n /** media type, lowercased, parameters stripped (\"text/html\") */\n contentType: string;\n /** Content-Location as written (Chrome writes absolute URLs, or `cid:…`) */\n location?: string;\n /** Content-ID without its angle brackets */\n id?: string;\n /** the decoded bytes */\n body: Buffer;\n};\n\nfunction parseHeaders(text: string): Record<string, string> {\n const headers: Record<string, string> = {};\n // unfold continuation lines (a leading space/tab continues the previous header)\n const lines = text.replace(/\\r?\\n[ \\t]+/g, \" \").split(/\\r?\\n/);\n for (const line of lines) {\n const c = line.indexOf(\":\");\n if (c <= 0) continue;\n headers[line.slice(0, c).trim().toLowerCase()] = line.slice(c + 1).trim();\n }\n return headers;\n}\n\n/** quoted-printable → bytes (soft line breaks removed, `=XX` decoded) */\nexport function decodeQuotedPrintable(text: string): Buffer {\n const out: number[] = [];\n for (let i = 0; i < text.length; i++) {\n const ch = text.charCodeAt(i);\n if (ch === 0x3d /* = */) {\n const a = text[i + 1];\n const b = text[i + 2];\n if (a === \"\\r\" && b === \"\\n\") {\n i += 2;\n continue;\n }\n if (a === \"\\n\") {\n i += 1;\n continue;\n }\n if (a != null && b != null && /^[0-9A-Fa-f]{2}$/.test(a + b)) {\n out.push(parseInt(a + b, 16));\n i += 2;\n continue;\n }\n }\n out.push(ch & 0xff);\n }\n return Buffer.from(out);\n}\n\n/** Parse a multipart/related MHTML file (what `Page.captureSnapshot` returns). */\nexport function parseMhtml(raw: Buffer | string): MhtmlPart[] {\n // MHTML is 7-bit: a latin1 view keeps byte offsets and byte values intact\n const text = typeof raw === \"string\" ? raw : raw.toString(\"latin1\");\n const headEnd = text.search(/\\r?\\n\\r?\\n/);\n if (headEnd < 0) throw new Error(\"mhtml: no header block\");\n const headers = parseHeaders(text.slice(0, headEnd));\n const ct = headers[\"content-type\"] ?? \"\";\n const bm = /boundary=\"([^\"]+)\"|boundary=([^;\\s]+)/i.exec(ct);\n const boundary = bm?.[1] ?? bm?.[2];\n if (!boundary) throw new Error(\"mhtml: no multipart boundary\");\n const parts: MhtmlPart[] = [];\n const delimiter = `--${boundary}`;\n // every part starts at a delimiter on its own line\n const chunks = text.split(\n new RegExp(`(?:^|\\\\r?\\\\n)${delimiter.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")}`),\n );\n for (const chunk of chunks.slice(1)) {\n if (chunk.startsWith(\"--\")) break; // the closing delimiter\n const body0 = chunk.search(/\\r?\\n\\r?\\n/);\n if (body0 < 0) continue;\n const h = parseHeaders(chunk.slice(0, body0));\n const bodyText = chunk.slice(body0).replace(/^\\r?\\n\\r?\\n/, \"\");\n const encoding = (h[\"content-transfer-encoding\"] ?? \"binary\").toLowerCase();\n let body: Buffer;\n if (encoding === \"quoted-printable\") body = decodeQuotedPrintable(bodyText);\n else if (encoding === \"base64\") body = Buffer.from(bodyText.replace(/\\s+/g, \"\"), \"base64\");\n else body = Buffer.from(bodyText, \"latin1\");\n const idRaw = h[\"content-id\"];\n parts.push({\n contentType: (h[\"content-type\"] ?? \"application/octet-stream\")\n .split(\";\")[0]!\n .trim()\n .toLowerCase(),\n ...(h[\"content-location\"] ? { location: h[\"content-location\"] } : {}),\n ...(idRaw ? { id: idRaw.replace(/^<|>$/g, \"\") } : {}),\n body,\n });\n }\n return parts;\n}\n\n// --- MHTML → state.html -----------------------------------------------------\n\nconst EXT_BY_TYPE: Record<string, string> = {\n \"text/html\": \"html\",\n \"text/css\": \"css\",\n \"image/png\": \"png\",\n \"image/jpeg\": \"jpg\",\n \"image/gif\": \"gif\",\n \"image/webp\": \"webp\",\n \"image/avif\": \"avif\",\n \"image/svg+xml\": \"svg\",\n \"image/x-icon\": \"ico\",\n \"image/vnd.microsoft.icon\": \"ico\",\n \"image/bmp\": \"bmp\",\n \"font/woff2\": \"woff2\",\n \"application/font-woff2\": \"woff2\",\n \"font/woff\": \"woff\",\n \"application/font-woff\": \"woff\",\n \"font/ttf\": \"ttf\",\n \"application/x-font-ttf\": \"ttf\",\n \"font/otf\": \"otf\",\n \"font/collection\": \"ttc\",\n \"application/x-font-opentype\": \"otf\",\n \"video/mp4\": \"mp4\",\n \"video/webm\": \"webm\",\n \"audio/mpeg\": \"mp3\",\n \"application/pdf\": \"pdf\",\n \"text/javascript\": \"js\",\n \"application/javascript\": \"js\",\n \"application/json\": \"json\",\n};\n\nfunction extFor(part: MhtmlPart): string {\n const byType = EXT_BY_TYPE[part.contentType];\n if (byType) return byType;\n if (part.location && !part.location.startsWith(\"cid:\")) {\n try {\n const e = extname(new URL(part.location).pathname).slice(1).toLowerCase();\n if (/^[a-z0-9]{1,5}$/.test(e)) return e;\n } catch {\n /* not a URL */\n }\n }\n return \"bin\";\n}\n\nconst stripFragment = (u: string): string => u.replace(/#.*$/, \"\");\n\n/** The freeze rule: the saved page runs no animation or transition (each\n * animated property's live value is re-applied by the restore script) and\n * shows no caret. Appended at the END of <head>. */\nconst DOM_STATE_FREEZE_CSS =\n \"*,*::before,*::after{animation:none!important;transition:none!important;caret-color:transparent!important}\";\nconst FREEZE_STYLE = `<style data-ot-freeze>${DOM_STATE_FREEZE_CSS}</style>`;\n/** What every `<script>` becomes: same element, same index, no behaviour. */\nexport const INERT_SCRIPT = '<script type=\"application/x-open-take-inert\"></script>';\n\nconst ENTITY: Record<string, string> = {\n amp: \"&\",\n lt: \"<\",\n gt: \">\",\n quot: '\"',\n apos: \"'\",\n nbsp: \" \",\n};\nconst decodeEntities = (s: string): string =>\n s.replace(/&(#x[0-9a-fA-F]+|#\\d+|[a-zA-Z]+);/g, (m, e: string) => {\n if (e[0] === \"#\") {\n const code =\n e[1] === \"x\" || e[1] === \"X\" ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10);\n return Number.isFinite(code) ? String.fromCodePoint(code) : m;\n }\n return ENTITY[e.toLowerCase()] ?? m;\n });\nconst encodeAttr = (s: string): string =>\n s.replace(/&/g, \"&amp;\").replace(/\"/g, \"&quot;\").replace(/</g, \"&lt;\");\n\ntype Attr = { name: string; lower: string; value: string | null; raw: string };\n\n/** Parse the attributes of one start tag from `pos` (just after the tag\n * name) to its `>`. Chrome's serializer emits well-formed, double-quoted\n * markup; unquoted and single-quoted values are handled for safety. */\nfunction parseTag(html: string, pos: number): { attrs: Attr[]; end: number; selfClosing: boolean } {\n const attrs: Attr[] = [];\n let i = pos;\n const n = html.length;\n let selfClosing = false;\n while (i < n) {\n while (i < n && /\\s/.test(html[i]!)) i++;\n if (i >= n) break;\n const c = html[i]!;\n if (c === \">\") return { attrs, end: i + 1, selfClosing };\n if (c === \"/\") {\n if (html[i + 1] === \">\") {\n selfClosing = true;\n return { attrs, end: i + 2, selfClosing };\n }\n i++;\n continue;\n }\n const start = i;\n while (i < n && !/[\\s=>/]/.test(html[i]!)) i++;\n if (i === start) {\n i++;\n continue;\n }\n const name = html.slice(start, i);\n let j = i;\n while (j < n && /\\s/.test(html[j]!)) j++;\n let value: string | null = null;\n if (html[j] === \"=\") {\n j++;\n while (j < n && /\\s/.test(html[j]!)) j++;\n const q = html[j];\n if (q === '\"' || q === \"'\") {\n const close = html.indexOf(q, j + 1);\n const stop = close < 0 ? n : close;\n value = html.slice(j + 1, stop);\n j = stop + 1;\n } else {\n const vs = j;\n while (j < n && !/[\\s>]/.test(html[j]!)) j++;\n value = html.slice(vs, j);\n }\n i = j;\n }\n attrs.push({ name, lower: name.toLowerCase(), value, raw: html.slice(start, i) });\n }\n return { attrs, end: n, selfClosing };\n}\n\n/** Rewrite `url(…)` and `@import \"…\"` references in CSS text. `resolve`\n * returns the local reference, or null to leave the original as is. */\nfunction rewriteCss(css: string, resolve: (ref: string) => string | null): string {\n const url = (ref: string, quote: string): string | null => {\n const r = resolve(ref);\n return r == null ? null : `url(${quote}${r}${quote})`;\n };\n return css\n .replace(\n /url\\(\\s*(?:\"([^\"]*)\"|'([^']*)'|([^)\\s\"']*))\\s*\\)/g,\n (m, d?: string, s?: string, b?: string) => {\n const ref = d ?? s ?? b ?? \"\";\n if (!ref) return m;\n return url(ref, d != null ? '\"' : s != null ? \"'\" : \"\") ?? m;\n },\n )\n .replace(/@import\\s+(?:\"([^\"]*)\"|'([^']*)')/g, (m, d?: string, s?: string) => {\n const ref = d ?? s ?? \"\";\n const r = ref ? resolve(ref) : null;\n return r == null ? m : `@import ${d != null ? '\"' : \"'\"}${r}${d != null ? '\"' : \"'\"}`;\n });\n}\n\n/** Parse a `srcset` value into candidates (url + descriptor), the way the\n * HTML spec does: a URL runs to the next whitespace (so a data URL keeps\n * its commas), trailing commas end the candidate, otherwise the descriptor\n * runs to the next comma. */\nexport function parseSrcset(value: string): { url: string; descriptor: string }[] {\n const out: { url: string; descriptor: string }[] = [];\n const n = value.length;\n let i = 0;\n while (i < n) {\n while (i < n && /[\\s,]/.test(value[i]!)) i++;\n if (i >= n) break;\n const start = i;\n while (i < n && !/\\s/.test(value[i]!)) i++;\n let url = value.slice(start, i);\n let descriptor = \"\";\n if (url.endsWith(\",\")) url = url.replace(/,+$/, \"\");\n else {\n while (i < n && /\\s/.test(value[i]!)) i++;\n const ds = i;\n while (i < n && value[i] !== \",\") i++;\n descriptor = value.slice(ds, i).trim();\n }\n if (url) out.push({ url, descriptor });\n }\n return out;\n}\n\n/** `rel` tokens whose href names a resource the state may hold */\nconst RESOURCE_RELS = new Set([\n \"stylesheet\",\n \"icon\",\n \"preload\",\n \"modulepreload\",\n \"prefetch\",\n \"apple-touch-icon\",\n \"mask-icon\",\n \"manifest\",\n \"shortcut\",\n]);\n/** What a reference the snapshot did not carry becomes: it loads nothing. */\nconst OFFLINE_REF = \"about:blank\";\nconst URL_ATTRS: Record<string, Set<string>> = {\n img: new Set([\"src\"]),\n source: new Set([\"src\"]),\n video: new Set([\"src\", \"poster\"]),\n audio: new Set([\"src\"]),\n track: new Set([\"src\"]),\n embed: new Set([\"src\"]),\n iframe: new Set([\"src\"]),\n frame: new Set([\"src\"]),\n input: new Set([\"src\"]),\n object: new Set([\"data\"]),\n image: new Set([\"href\", \"xlink:href\"]),\n use: new Set([\"href\", \"xlink:href\"]),\n feimage: new Set([\"href\", \"xlink:href\"]),\n body: new Set([\"background\"]),\n table: new Set([\"background\"]),\n td: new Set([\"background\"]),\n};\n\ntype RewriteCtx = {\n /** resolve one reference against `base`; null ⇒ leave it */\n resolve: (ref: string, base: string) => string | null;\n /** the document's URL (the part's Content-Location) */\n docUrl: string;\n};\n\n/** Rewrite one HTML document: scripts inert in place, `on*` gone, refresh /\n * CSP metas neutralised, `<base href>` dropped, legacy shadow templates made\n * declarative, every resource reference resolved to the local asset. Only\n * attributes change — no element is added or removed before an existing\n * one, so child indices survive. */\nfunction rewriteHtml(html: string, ctx: RewriteCtx): string {\n // a <base href> governs relative references (Chrome absolutises most, not\n // inline-style url() or <source srcset>); it is dropped from the output so\n // ../assets/ resolves beside the state\n let base = ctx.docUrl;\n const bm = /<base\\s[^>]*?href\\s*=\\s*\"([^\"]*)\"/i.exec(html);\n if (bm?.[1]) {\n try {\n base = new URL(decodeEntities(bm[1]), ctx.docUrl).href;\n } catch {\n /* keep the document URL */\n }\n }\n const resolve = (ref: string): string | null => ctx.resolve(ref, base);\n const out: string[] = [];\n const n = html.length;\n let i = 0;\n while (i < n) {\n const lt = html.indexOf(\"<\", i);\n if (lt < 0) {\n out.push(html.slice(i));\n break;\n }\n out.push(html.slice(i, lt));\n const next = html[lt + 1];\n if (html.startsWith(\"<!--\", lt)) {\n const end = html.indexOf(\"-->\", lt + 4);\n const e = end < 0 ? n : end + 3;\n out.push(html.slice(lt, e));\n i = e;\n continue;\n }\n if (next === \"!\" || next === \"?\" || next === \"/\") {\n const end = html.indexOf(\">\", lt);\n const e = end < 0 ? n : end + 1;\n out.push(html.slice(lt, e));\n i = e;\n continue;\n }\n if (next == null || !/[a-zA-Z]/.test(next)) {\n out.push(\"<\");\n i = lt + 1;\n continue;\n }\n let j = lt + 1;\n while (j < n && !/[\\s/>]/.test(html[j]!)) j++;\n const tagName = html.slice(lt + 1, j);\n const tag = tagName.toLowerCase();\n const { attrs, end, selfClosing } = parseTag(html, j);\n\n if (tag === \"script\") {\n // the whole element, content included, becomes the inert twin\n const close = /<\\/script\\s*>/gi;\n close.lastIndex = end;\n const m = close.exec(html);\n out.push(INERT_SCRIPT);\n i = m ? m.index + m[0].length : n;\n continue;\n }\n\n let changed = false;\n const kept: Attr[] = [];\n const relTokens =\n tag === \"link\"\n ? new Set(\n (attrs.find((a) => a.lower === \"rel\")?.value ?? \"\")\n .toLowerCase()\n .split(/\\s+/)\n .filter(Boolean),\n )\n : null;\n const wantsRel = relTokens ? [...relTokens].some((r) => RESOURCE_RELS.has(r)) : false;\n for (const a of attrs) {\n if (a.lower.startsWith(\"on\")) {\n changed = true;\n continue;\n }\n if (tag === \"base\" && a.lower === \"href\") {\n changed = true;\n continue;\n }\n if (a.lower === \"crossorigin\" || a.lower === \"integrity\") {\n // every resource is a local file now: a CORS-mode request for a\n // file:// asset is refused outright (Vite marks its stylesheet\n // `crossorigin`, so the page would lose all its CSS), and a\n // rewritten stylesheet no longer matches its SRI hash\n changed = true;\n continue;\n }\n if (tag === \"meta\" && a.lower === \"http-equiv\" && a.value != null) {\n const v = a.value.trim().toLowerCase();\n if (v === \"refresh\" || v === \"content-security-policy\") {\n const name = \"data-ot-stripped-http-equiv\";\n kept.push({ ...a, name, lower: name, raw: `${name}=\"${a.value}\"` });\n changed = true;\n continue;\n }\n }\n if (tag === \"template\" && a.lower === \"shadowmode\") {\n // Chrome's serializer writes the pre-standard attribute; the parser\n // only attaches a declarative shadow root for `shadowrootmode`\n const name = \"shadowrootmode\";\n kept.push({\n ...a,\n name,\n lower: name,\n raw: a.value == null ? name : `${name}=\"${a.value}\"`,\n });\n changed = true;\n continue;\n }\n if (a.value == null) {\n kept.push(a);\n continue;\n }\n const value = decodeEntities(a.value);\n let rewritten: string | null = null;\n if (a.lower === \"style\") {\n const css = rewriteCss(value, resolve);\n if (css !== value) rewritten = css;\n } else if (a.lower === \"srcset\" && (tag === \"img\" || tag === \"source\")) {\n const local = parseSrcset(value)\n .map((c) => ({ ...c, url: resolve(c.url) }))\n .filter((c) => c.url != null && c.url !== OFFLINE_REF);\n if (local.length === 0) {\n // no candidate travelled with the page — let `src` stand\n changed = true;\n continue;\n }\n rewritten = local\n .map((c) => (c.descriptor ? `${c.url} ${c.descriptor}` : c.url!))\n .join(\", \");\n } else if (\n /^cid:/i.test(value) ||\n URL_ATTRS[tag]?.has(a.lower) ||\n (tag === \"link\" && a.lower === \"href\" && wantsRel)\n ) {\n rewritten = resolve(value);\n }\n if (rewritten != null && rewritten !== value) {\n kept.push({ ...a, value: rewritten, raw: `${a.name}=\"${encodeAttr(rewritten)}\"` });\n changed = true;\n } else kept.push(a);\n }\n if (changed) {\n out.push(`<${tagName}${kept.map((a) => ` ${a.raw}`).join(\"\")}${selfClosing ? \" /\" : \"\"}>`);\n } else out.push(html.slice(lt, end));\n i = end;\n\n if (tag === \"style\") {\n const close = /<\\/style\\s*>/gi;\n close.lastIndex = end;\n const m = close.exec(html);\n const stop = m ? m.index : n;\n out.push(rewriteCss(html.slice(end, stop), resolve));\n i = stop;\n }\n }\n return out.join(\"\");\n}\n\n/** The restore script: what markup cannot carry, re-applied when the saved\n * page loads. Plain JS, the only script that runs; the probe data rides\n * inline as JSON. Sets `document.documentElement.dataset.otReady = \"1\"`\n * once fonts and images are in (bounded — a hung image never blocks it). */\nfunction buildRestoreScript(probe: DomStateProbe): string {\n const data = {\n scroll: probe.scroll,\n scrolled: probe.scrolled,\n inputs: probe.inputs,\n canvases: probe.canvases,\n videos: probe.videos,\n animated: probe.animated,\n custom: probe.custom,\n focus: probe.focus ?? null,\n elements: probe.elements.map((e) => ({ id: e.id, path: e.path, tag: e.tag })),\n };\n const json = JSON.stringify(data)\n .replace(/</g, \"\\\\u003c\")\n .replace(/\\u2028/g, \"\\\\u2028\")\n .replace(/\\u2029/g, \"\\\\u2029\");\n return `<script data-ot-restore>(function(){\nvar P=${json};\nvar doc=document;\nfunction resolve(path){var n=doc.documentElement;for(var i=0;i<path.length;i++){n=n.children[path[i]];if(!n)return null;}return n;}\nfunction paint(el,url){return new Promise(function(res){try{var ctx=el.getContext(\"2d\");if(!ctx)return res();var im=new Image();im.onload=function(){try{ctx.clearRect(0,0,el.width,el.height);ctx.drawImage(im,0,0,el.width,el.height);}catch(e){}res();};im.onerror=function(){res();};im.src=url;}catch(e){res();}});}\nfunction run(){\n var misses=0,i,j,el,waits=[];\n for(i=0;i<P.custom.length;i++){var c=P.custom[i];try{if(!customElements.get(c.name)){if(c.extends){var Base=doc.createElement(c.extends).constructor;customElements.define(c.name,class extends Base{},{extends:c.extends});}else customElements.define(c.name,class extends HTMLElement{});}}catch(e){}}\n for(i=0;i<P.elements.length;i++){var e=P.elements[i];el=resolve(e.path);if(el&&el.localName===e.tag)el.setAttribute(\"data-ot-id\",e.id);else misses++;}\n for(i=0;i<P.inputs.length;i++){var x=P.inputs[i];el=resolve(x.path);if(!el)continue;try{if(\"checked\" in x)el.checked=x.checked;if(x.selected)for(var o=0;o<el.options.length;o++)el.options[o].selected=x.selected.indexOf(o)>=0;if(\"value\" in x)el.value=x.value;}catch(e){}}\n for(i=0;i<P.canvases.length;i++){var cv=P.canvases[i];el=resolve(cv.path);if(!el||el.localName!==\"canvas\")continue;waits.push(paint(el,cv.dataUrl));}\n for(i=0;i<P.videos.length;i++){var vd=P.videos[i];el=resolve(vd.path);if(!el||el.localName!==\"video\")continue;try{el.removeAttribute(\"autoplay\");el.removeAttribute(\"src\");var ss=el.querySelectorAll(\"source\");for(j=0;j<ss.length;j++)ss[j].remove();el.setAttribute(\"preload\",\"none\");el.setAttribute(\"poster\",vd.dataUrl);el.load();}catch(e){}}\n for(i=0;i<P.animated.length;i++){var an=P.animated[i];el=resolve(an.path);if(!el)continue;for(var k in an.styles){try{el.style.setProperty(k,an.styles[k],\"important\");}catch(e){}}}\n var lazy=doc.querySelectorAll(\"img[loading=lazy]\");for(i=0;i<lazy.length;i++)lazy[i].loading=\"eager\";\n try{var sheet=new CSSStyleSheet();sheet.replaceSync(${JSON.stringify(DOM_STATE_FREEZE_CSS)});var all=doc.querySelectorAll(\"*\");for(i=0;i<all.length;i++){var sr=all[i].shadowRoot;if(sr)sr.adoptedStyleSheets=sr.adoptedStyleSheets.concat([sheet]);}}catch(e){}\n function applyScroll(){try{window.scrollTo({left:P.scroll.x,top:P.scroll.y,behavior:\"instant\"});}catch(e){window.scrollTo(P.scroll.x,P.scroll.y);}for(var s=0;s<P.scrolled.length;s++){var sc=P.scrolled[s];var se=resolve(sc.path);if(!se)continue;try{se.scrollTo({left:sc.left,top:sc.top,behavior:\"instant\"});}catch(e){se.scrollTop=sc.top;se.scrollLeft=sc.left;}}}\n void doc.body.getBoundingClientRect();\n if(P.focus){el=resolve(P.focus);if(el){try{el.focus({preventScroll:true});}catch(e){}}}\n applyScroll();\n try{waits.push(doc.fonts.ready);}catch(e){}\n var imgs=doc.images;for(i=0;i<imgs.length;i++){try{if(typeof imgs[i].decode===\"function\")waits.push(imgs[i].decode().catch(function(){}));}catch(e){}}\n var done=false;\n function finish(){if(done)return;done=true;applyScroll();doc.documentElement.setAttribute(\"data-ot-misses\",String(misses));doc.documentElement.setAttribute(\"data-ot-ready\",\"1\");}\n Promise.all(waits).then(finish,finish);\n setTimeout(finish,6000);\n}\nif(doc.readyState===\"loading\")doc.addEventListener(\"DOMContentLoaded\",run);else run();\n})();</script>`;\n}\n\ntype ConvertResult = {\n /** the self-contained document (write it as `state.html`) */\n html: string;\n /** asset files this state references, relative to the assets dir */\n assets: string[];\n /** references that resolved to no part and were left pointing at the network */\n unresolved: number;\n};\n\n/**\n * MHTML → state.html. Every part but the document goes to `assetsDir` as\n * `<sha1>.<ext>` (deduped across states); references are rewritten to\n * `../assets/<file>`. Sub-frame documents become `.html` assets, converted\n * the same way (best effort — no restore script for them).\n */\nexport function convertMhtml(\n raw: Buffer | string,\n probe: DomStateProbe,\n opts: {\n assetsDir: string;\n /** parts fetched apart from the snapshot (the web fonts it leaves out —\n * `fetchFontFiles`), found by their location like its own parts; a part\n * of the snapshot wins over one here */\n extra?: MhtmlPart[];\n },\n): ConvertResult {\n const parts = parseMhtml(raw);\n const doc = parts.find((p) => p.contentType === \"text/html\");\n if (!doc) throw new Error(\"mhtml: no text/html part\");\n mkdirSync(opts.assetsDir, { recursive: true });\n\n const byLocation = new Map<string, MhtmlPart>();\n const byCid = new Map<string, MhtmlPart>();\n for (const p of parts) {\n if (p === doc) continue;\n if (p.id) byCid.set(p.id, p);\n if (p.location) {\n if (/^cid:/i.test(p.location)) byCid.set(p.location.slice(4), p);\n else byLocation.set(stripFragment(p.location), p);\n }\n }\n for (const p of opts.extra ?? []) {\n if (!p.location || /^cid:/i.test(p.location)) continue;\n const at = stripFragment(p.location);\n if (!byLocation.has(at)) byLocation.set(at, p);\n }\n const assets = new Set<string>();\n const emitted = new Map<MhtmlPart, string | null>();\n const inProgress = new Set<MhtmlPart>();\n let unresolved = 0;\n\n const write = (bytes: Buffer, ext: string): string => {\n const name = `${createHash(\"sha1\").update(bytes).digest(\"hex\")}.${ext}`;\n const file = join(opts.assetsDir, name);\n if (!existsSync(file)) writeFileSync(file, bytes);\n assets.add(name);\n return `../assets/${name}`;\n };\n\n const lookup = (ref: string, base: string): MhtmlPart | null => {\n if (/^cid:/i.test(ref)) return byCid.get(ref.slice(4)) ?? null;\n if (/^(data|blob|about|javascript|mailto|tel):/i.test(ref) || ref.startsWith(\"#\")) return null;\n try {\n const abs = stripFragment(new URL(ref, base).href);\n return byLocation.get(abs) ?? null;\n } catch {\n return null;\n }\n };\n\n /** the local reference for a part, converting it on first use */\n const emit = (part: MhtmlPart): string | null => {\n if (emitted.has(part)) return emitted.get(part) ?? null;\n if (inProgress.has(part)) return null; // a cycle (a.css → b.css → a.css)\n inProgress.add(part);\n let ref: string | null;\n try {\n const partBase =\n part.location && !/^cid:/i.test(part.location)\n ? part.location\n : (doc.location ?? \"about:blank\");\n if (part.contentType === \"text/css\") {\n const css = rewriteCss(part.body.toString(\"utf8\"), (r) => resolveRef(r, partBase));\n ref = write(Buffer.from(css, \"utf8\"), \"css\");\n } else if (part.contentType === \"text/html\") {\n const html = rewriteHtml(part.body.toString(\"utf8\"), {\n resolve: resolveRef,\n docUrl: partBase,\n });\n ref = write(Buffer.from(withFreeze(html), \"utf8\"), \"html\");\n } else ref = write(part.body, extFor(part));\n } finally {\n inProgress.delete(part);\n }\n emitted.set(part, ref);\n return ref;\n };\n\n const resolveRef = (ref: string, base: string): string | null => {\n // a place in the document itself (url(#clip), <use href=\"#icon\">) stays\n if (ref.startsWith(\"#\")) return null;\n const part = lookup(ref, base);\n if (part) {\n // and a place in another file (icons.svg#check) stays on its copy\n const local = emit(part);\n const place = /#.*$/.exec(ref)?.[0];\n return local && place ? local + place : local;\n }\n // a network reference the snapshot did not carry is cut off: a saved\n // state never reaches the network — the app's server is gone by the time\n // a film renders, and one that happens to be up must not change it. The\n // fidelity check (network blocked too) shows whether it mattered.\n if (/^cid:/i.test(ref)) {\n unresolved++;\n return OFFLINE_REF;\n }\n try {\n const u = new URL(ref, base);\n if (u.protocol === \"http:\" || u.protocol === \"https:\") {\n unresolved++;\n return OFFLINE_REF;\n }\n } catch {\n /* not a URL at all */\n }\n return null;\n };\n\n const docUrl = doc.location && !/^cid:/i.test(doc.location) ? doc.location : probe.url;\n let html = rewriteHtml(doc.body.toString(\"utf8\"), { resolve: resolveRef, docUrl });\n html = withFreeze(html);\n // the restore script goes AFTER everything the page had (the parser folds a\n // script after </body> into the body as its last child)\n const htmlClose = html.search(/<\\/html\\s*>\\s*$/i);\n const restore = buildRestoreScript(probe);\n html =\n htmlClose >= 0\n ? `${html.slice(0, htmlClose)}${restore}\\n${html.slice(htmlClose)}`\n : `${html}${restore}\\n`;\n return { html, assets: [...assets], unresolved };\n}\n\n/** the freeze style at the END of <head> (or before <body>, or first) */\nfunction withFreeze(html: string): string {\n const headClose = /<\\/head\\s*>/i.exec(html);\n if (headClose)\n return `${html.slice(0, headClose.index)}${FREEZE_STYLE}${html.slice(headClose.index)}`;\n const body = /<body[\\s>]/i.exec(html);\n if (body) return `${html.slice(0, body.index)}${FREEZE_STYLE}${html.slice(body.index)}`;\n return `${FREEZE_STYLE}${html}`;\n}\n\n// --- web fonts --------------------------------------------------------------------\n//\n// `Page.captureSnapshot` carries a page's stylesheets but none of the font\n// files their @font-face rules name (measured: an inline face, a linked one\n// and a unicode-range subset, all three loaded, gave no font part; findgym.tw\n// gave 147 faces and no font part) — every face of a saved state pointed at\n// about:blank and fell back to a system font. So after the take, while the\n// browser is still open, each face's file is fetched through the page that\n// was recorded (`Network.loadNetworkResource`: the page's cookies, nothing run\n// in it) and saved with the other parts. The saved state itself still never\n// reaches the network.\n\n/** The most font bytes one take saves (all states together) — a CJK face cut\n * into ~100 unicode-range subsets is ~5–10 MB; faces the page loaded go\n * first, so what falls past the cap is a subset nothing on screen used. */\nexport const FONT_BUDGET_BYTES = 48 * 1024 * 1024;\n/** One file larger than this is not saved (a whole CJK family in one file is\n * under it). */\nconst FONT_FILE_MAX_BYTES = 12 * 1024 * 1024;\n\nconst CSS_URL = /url\\(\\s*(?:\"([^\"]*)\"|'([^']*)'|([^)\\s\"']*))\\s*\\)/g;\n\n/** The file each @font-face rule in the snapshot's stylesheets (linked,\n * inline, sub-frame) names — the first http(s) `url()` of its `src`, the one\n * Chrome tries first — absolute, in order, once each. */\nexport function fontFaceSources(parts: MhtmlPart[], docUrl: string): string[] {\n const out = new Set<string>();\n const doc = parts.find((p) => p.contentType === \"text/html\");\n const docBase = doc?.location && !/^cid:/i.test(doc.location) ? doc.location : docUrl;\n for (const p of parts) {\n if (p.contentType !== \"text/css\" && p.contentType !== \"text/html\") continue;\n const base = p.location && !/^cid:/i.test(p.location) ? p.location : docBase;\n for (const face of p.body.toString(\"utf8\").matchAll(/@font-face\\s*\\{([^}]*)\\}/gi)) {\n const src = /(?:^|[;\\s])src\\s*:([^;]*)/i.exec(face[1]!)?.[1];\n if (!src) continue;\n for (const m of src.matchAll(CSS_URL)) {\n const ref = m[1] ?? m[2] ?? m[3] ?? \"\";\n try {\n const u = new URL(ref, base);\n if (u.protocol !== \"http:\" && u.protocol !== \"https:\") continue;\n out.add(stripFragment(u.href));\n break;\n } catch {\n /* not a URL */\n }\n }\n }\n }\n return [...out];\n}\n\n/** a font file's media type from its first bytes, or null when it is not one\n * (an app that answers every path with its HTML shell) */\nexport function fontType(bytes: Buffer): string | null {\n const sig = bytes.subarray(0, 4).toString(\"latin1\");\n if (sig === \"wOF2\") return \"font/woff2\";\n if (sig === \"wOFF\") return \"font/woff\";\n if (sig === \"OTTO\") return \"font/otf\";\n if (sig === \"true\" || sig === \"\\x00\\x01\\x00\\x00\") return \"font/ttf\";\n if (sig === \"ttcf\") return \"font/collection\";\n return null;\n}\n\n/** What `fetchFontFiles` has done in one take: each URL's part, or why it\n * has none; and the bytes the cap still allows. */\nexport type FontFetchState = { done: Map<string, MhtmlPart | string>; left: number };\n\n/**\n * Fetch font files through the recorded page (`Network.loadNetworkResource`\n * on its main frame: its cookies and referrer, nothing run in the page), at\n * most `concurrency` at a time, in the order given, until the cap in `state`\n * runs out. Results land in `state.done`; a URL already there is skipped.\n */\nexport async function fetchFontFiles(\n cdp: CDP,\n urls: string[],\n state: FontFetchState,\n opts: { concurrency?: number } = {},\n): Promise<void> {\n const todo = urls.filter((u) => !state.done.has(u));\n if (!todo.length) return;\n let frameId: string;\n try {\n const tree = await cdp.send<{ frameTree: { frame: { id: string } } }>(\"Page.getFrameTree\");\n frameId = tree.frameTree.frame.id;\n } catch (e) {\n for (const u of todo) state.done.set(u, `no page to fetch through (${(e as Error).message})`);\n return;\n }\n const one = async (url: string): Promise<MhtmlPart | string> => {\n if (state.left <= 0) return \"over the cap\";\n const r = await cdp.send<{\n resource: {\n success: boolean;\n httpStatusCode?: number;\n netErrorName?: string;\n stream?: string;\n };\n }>(\"Network.loadNetworkResource\", {\n frameId,\n url,\n options: { disableCache: false, includeCredentials: true },\n });\n const { stream } = r.resource;\n try {\n const status = r.resource.httpStatusCode ?? 0;\n if (!r.resource.success || status < 200 || status > 299)\n return r.resource.netErrorName ?? `HTTP ${status}`;\n if (!stream) return \"no body\";\n const chunks: Buffer[] = [];\n let n = 0;\n for (;;) {\n const c = await cdp.send<{ data: string; base64Encoded?: boolean; eof: boolean }>(\n \"IO.read\",\n { handle: stream, size: 1 << 20 },\n );\n const b = Buffer.from(c.data, c.base64Encoded ? \"base64\" : \"latin1\");\n chunks.push(b);\n n += b.length;\n if (n > FONT_FILE_MAX_BYTES) return `larger than ${FONT_FILE_MAX_BYTES >> 20} MB`;\n if (n > state.left) return \"over the cap\";\n if (c.eof) break;\n }\n const body = Buffer.concat(chunks);\n const contentType = fontType(body);\n if (!contentType) return \"not a font file\";\n state.left -= body.length;\n return { contentType, location: url, body };\n } finally {\n if (stream) await cdp.send(\"IO.close\", { handle: stream }).catch(() => {});\n }\n };\n let next = 0;\n const worker = async () => {\n while (next < todo.length) {\n const url = todo[next++]!;\n let got: MhtmlPart | string;\n try {\n got = await one(url);\n } catch (e) {\n got = (e as Error).message;\n }\n state.done.set(url, got);\n }\n };\n await Promise.all(Array.from({ length: Math.max(1, opts.concurrency ?? 6) }, worker));\n}\n\n/** The web-font files the states' snapshots name and do not carry, fetched\n * once for the whole take — the faces the page loaded first (any state),\n * then the rest — as parts `convertMhtml` resolves like its own. */\nasync function fetchStateFonts(\n cdp: CDP,\n states: DomStateRaw[],\n warn: (l: string) => void,\n): Promise<MhtmlPart[]> {\n const loaded = new Set(states.flatMap((s) => (s.loadedFonts ?? []).map(stripFragment)));\n const wanted: string[] = [];\n for (const raw of states) {\n try {\n const parts = parseMhtml(await readFile(join(raw.dir, \"page.mhtml\"), \"latin1\"));\n const carried = new Set(\n parts.flatMap((p) => (p.location ? [stripFragment(p.location)] : [])),\n );\n for (const u of fontFaceSources(parts, raw.probe.url))\n if (!carried.has(u) && !wanted.includes(u)) wanted.push(u);\n } catch {\n /* the conversion says what is wrong with this one */\n }\n }\n if (!wanted.length) return [];\n const order = [...wanted.filter((u) => loaded.has(u)), ...wanted.filter((u) => !loaded.has(u))];\n const state: FontFetchState = { done: new Map(), left: FONT_BUDGET_BYTES };\n const t0 = Date.now();\n await fetchFontFiles(cdp, order, state);\n const parts = order.flatMap((u) => {\n const p = state.done.get(u);\n return p && typeof p !== \"string\" ? [p] : [];\n });\n const bytes = parts.reduce((s, p) => s + p.body.length, 0);\n const why = new Map<string, number>();\n for (const v of state.done.values()) if (typeof v === \"string\") why.set(v, (why.get(v) ?? 0) + 1);\n warn(\n `dom-state: ${parts.length} of ${order.length} web-font file(s) the snapshot left out saved (${(bytes / 1048576).toFixed(1)} MB, ${Date.now() - t0} ms)${\n why.size\n ? ` — not saved: ${[...why]\n .slice(0, 4)\n .map(([w, n]) => `${n} ${w}`)\n .join(\"; \")}`\n : \"\"\n }`,\n );\n return parts;\n}\n\n// --- fidelity -------------------------------------------------------------------\n\n/** Boxes (x, y, w, h — image px) left out of a comparison. */\ntype PixelMask = { width: number; boxes: [number, number, number, number][] };\n\n/** PSNR (dB, capped at 99 for identical images) and the fraction of pixels\n * differing by more than 8 on any channel, over two rgb24 buffers — pixels\n * inside `mask` boxes (what moves on its own: canvases, videos) left out. */\nexport function comparePixels(\n a: Uint8Array,\n b: Uint8Array,\n mask?: PixelMask,\n): { psnr: number; diffFrac: number } {\n const n = Math.min(a.length, b.length) - (Math.min(a.length, b.length) % 3);\n if (n === 0) return { psnr: 0, diffFrac: 1 };\n const masked = mask?.boxes.length ? maskBits(mask, n / 3) : null;\n let se = 0;\n let diff = 0;\n let counted = 0;\n for (let i = 0; i < n; i += 3) {\n if (masked?.[i / 3]) continue;\n counted++;\n const d0 = a[i]! - b[i]!;\n const d1 = a[i + 1]! - b[i + 1]!;\n const d2 = a[i + 2]! - b[i + 2]!;\n se += d0 * d0 + d1 * d1 + d2 * d2;\n if (Math.abs(d0) > 8 || Math.abs(d1) > 8 || Math.abs(d2) > 8) diff++;\n }\n if (counted === 0) return { psnr: 99, diffFrac: 0 };\n const mse = se / (counted * 3);\n const psnr = mse === 0 ? 99 : Math.min(99, 10 * Math.log10((255 * 255) / mse));\n return {\n psnr: Math.round(psnr * 100) / 100,\n diffFrac: Math.round((diff / counted) * 10000) / 10000,\n };\n}\n\nfunction maskBits(mask: PixelMask, pixels: number): Uint8Array {\n const bits = new Uint8Array(pixels);\n const w = mask.width;\n const h = Math.floor(pixels / w);\n for (const [bx, by, bw, bh] of mask.boxes) {\n const x0 = Math.max(0, Math.floor(bx));\n const y0 = Math.max(0, Math.floor(by));\n const x1 = Math.min(w, Math.ceil(bx + bw));\n const y1 = Math.min(h, Math.ceil(by + bh));\n for (let y = y0; y < y1; y++) bits.fill(1, y * w + x0, Math.max(y * w + x0, y * w + x1));\n }\n return bits;\n}\n\n/** width/height from a PNG's IHDR */\nfunction pngSize(png: Buffer): { w: number; h: number } {\n if (png.length < 24 || png.readUInt32BE(12) !== 0x49484452) throw new Error(\"not a PNG\");\n return { w: png.readUInt32BE(16), h: png.readUInt32BE(20) };\n}\n\n/** Decode an image file to raw rgb24 at `w`×`h` through ffmpeg. */\nfunction decodeRgb(\n ffmpeg: string,\n file: string,\n w: number,\n h: number,\n flags: \"neighbor\" | \"area\" = \"neighbor\",\n): Promise<Uint8Array> {\n return runBuffer(ffmpeg, [\n \"-v\",\n \"error\",\n \"-i\",\n file,\n \"-vf\",\n `scale=${w}:${h}:flags=${flags}`,\n \"-f\",\n \"rawvideo\",\n \"-pix_fmt\",\n \"rgb24\",\n \"-\",\n ]).then((buf) => {\n if (buf.length !== w * h * 3)\n throw new Error(`ffmpeg decoded ${file} to ${buf.length} bytes, not ${w}×${h} rgb`);\n return new Uint8Array(buf);\n });\n}\n\n/** `box` (CSS px) of a PNG as a PNG data URL, clamped to the image. */\nasync function cropPng(\n ffmpeg: string,\n png: string,\n box: [number, number, number, number],\n): Promise<string> {\n const { w, h } = pngSize(await readFile(png));\n const x = Math.max(0, Math.floor(box[0]));\n const y = Math.max(0, Math.floor(box[1]));\n const cw = Math.min(w - x, Math.ceil(box[0] + box[2]) - x);\n const ch = Math.min(h - y, Math.ceil(box[1] + box[3]) - y);\n if (cw < 1 || ch < 1) throw new Error(\"the box is off the image\");\n const out = await runBuffer(ffmpeg, [\n \"-v\",\n \"error\",\n \"-i\",\n png,\n \"-vf\",\n `crop=${cw}:${ch}:${x}:${y}`,\n \"-f\",\n \"image2pipe\",\n \"-vcodec\",\n \"png\",\n \"-\",\n ]);\n return `data:image/png;base64,${out.toString(\"base64\")}`;\n}\n\n/** Compare a state's re-render against the live reference, both PNG files. */\nasync function measureFidelity(\n ffmpeg: string,\n livePng: string,\n statePng: string,\n /** CSS-px boxes to leave out: canvases and videos whose moving content the\n * still froze a moment apart from the reference screenshot */\n moving: [number, number, number, number][] = [],\n): Promise<StateFidelity> {\n const { w, h } = pngSize(await readFile(livePng));\n const [a, b] = await Promise.all([\n decodeRgb(ffmpeg, livePng, w, h),\n decodeRgb(ffmpeg, statePng, w, h),\n ]);\n const { psnr, diffFrac } = comparePixels(a, b, { width: w, boxes: moving });\n return { psnr, diffFrac, ok: psnr >= DOM_STATE_PSNR_OK };\n}\n\n// --- event ↔ element matching ------------------------------------------------------\n\n/** The element whose box best matches `box` (IoU ≥ 0.5), or undefined. */\nexport function matchTarget(\n box: { x: number; y: number; w: number; h: number },\n elements: StateElement[],\n): string | undefined {\n let best: string | undefined;\n let bestIou = 0.5;\n const area = Math.max(0, box.w) * Math.max(0, box.h);\n for (const e of elements) {\n const [x, y, w, h] = e.box;\n const ix = Math.max(0, Math.min(box.x + box.w, x + w) - Math.max(box.x, x));\n const iy = Math.max(0, Math.min(box.y + box.h, y + h) - Math.max(box.y, y));\n const inter = ix * iy;\n if (inter <= 0) continue;\n const iou = inter / (area + w * h - inter);\n if (iou > bestIou) {\n bestIou = iou;\n best = e.id;\n }\n }\n return best;\n}\n\n// --- during the take -------------------------------------------------------------------\n\nexport type DomStateRaw = {\n id: string;\n tMs: number;\n step?: number;\n /** `states/<id>/` */\n dir: string;\n probe: DomStateProbe;\n /** files the page had fetched for its fonts by then (its resource timing)\n * — saved first when the snapshot's fonts are fetched */\n loadedFonts?: string[];\n /** what reading it cost the take */\n ms: number;\n};\n\n/** Visible canvases and videos (CSS px): content that moves on its own — a\n * spinning WebGL globe, a looping clip — which a still can only freeze. And\n * the focused text field, whose caret blinks on its own (every half second:\n * two shots 150 ms apart straddled a blink about one time in three). */\nconst LIVING_JS = `(() => {\n const out = [];\n const f = document.activeElement;\n if (f && (f.isContentEditable || /^(input|textarea|select)$/i.test(f.tagName))) {\n const r = f.getBoundingClientRect();\n if (r.width > 0 && r.height > 0) out.push([r.left, r.top, r.width, r.height]);\n }\n for (const el of document.querySelectorAll(\"canvas,video\")) {\n const r = el.getBoundingClientRect();\n if (r.width < 2 || r.height < 2 || r.right <= 0 || r.bottom <= 0 || r.left >= innerWidth || r.top >= innerHeight) continue;\n const cs = getComputedStyle(el);\n if (cs.visibility === \"hidden\" || Number(cs.opacity) === 0) continue;\n out.push([r.left, r.top, r.width, r.height]);\n }\n return out;\n})()`;\n\n/** Is the page visually still? Two screenshots 150 ms apart. They are taken at\n * the page's own scale: a scaled capture re-rasters the page and is not\n * repeatable (a still page gave two different 1/8-scale images in 12 shots;\n * native-scale shots were identical), so identical bytes mean nothing moved.\n * When they differ and the page has content that moves on its own — visible\n * canvases and videos, the focused field's caret — both are decoded small\n * and compared outside those boxes. The settle probe hears a page WORKING —\n * timers, requests, mutations — which a loaded machine stretches past its\n * budget even when nothing on screen moves; only moving pixels make a moment\n * unfit for a still. */\nexport async function visuallyStill(cdp: CDP, vw: number, vh: number): Promise<boolean> {\n const living = await cdp\n .send<{ result?: { value?: [number, number, number, number][] } }>(\"Runtime.evaluate\", {\n expression: LIVING_JS,\n returnByValue: true,\n })\n .then((r) => r.result?.value ?? [])\n .catch(() => [] as [number, number, number, number][]);\n const shot = async () =>\n Buffer.from(\n (\n await cdp.send<{ data: string }>(\"Page.captureScreenshot\", {\n format: \"jpeg\",\n quality: 80,\n optimizeForSpeed: true,\n })\n ).data,\n \"base64\",\n );\n const a = await shot();\n await sleep(150);\n const b = await shot();\n if (a.equals(b)) return true;\n if (!living.length) return false;\n const w = Math.max(1, Math.round(vw / 4));\n const h = Math.max(1, Math.round(vh / 4));\n const [sa, sb] = await decodeSmall(await resolveFfmpeg(), [a, b], w, h);\n // JPEG blocks at a box's edge carry some of what moves inside it: 2 px of margin\n return stillOutside(sa!, sb!, living, vw, 2);\n}\n\n/** JPEG screenshots → w×h rgb24 (area-averaged), one ffmpeg run each. */\nasync function decodeSmall(\n ffmpeg: string,\n jpegs: Buffer[],\n w: number,\n h: number,\n): Promise<DecodedImage[]> {\n const dir = await mkdtemp(join(tmpdir(), \"open-take-still-\"));\n try {\n const files = await Promise.all(\n jpegs.map(async (j, i) => {\n const f = join(dir, `${i}.jpg`);\n await writeFile(f, j);\n return f;\n }),\n );\n const frames = await Promise.all(files.map((f) => decodeRgb(ffmpeg, f, w, h, \"area\")));\n return frames.map((data) => ({ w, h, ch: 3, data }));\n } finally {\n await rm(dir, { recursive: true, force: true });\n }\n}\n\n/** Pixels of the small image that may change without the page moving, and by\n * how much a channel must change to count. */\nconst STILL_TOLERANCE = { pixels: 2, level: 12 };\n\n/** Two decoded screenshots of a `vw`-wide viewport show the same page outside\n * the CSS-px `boxes` (grown by a screenshot pixel for antialiased edges). */\nexport function stillOutside(\n a: DecodedImage,\n b: DecodedImage,\n boxes: [number, number, number, number][],\n vw: number,\n /** image px of margin around each box (antialiased edges, JPEG blocks) */\n margin: number,\n): boolean {\n if (a.w !== b.w || a.h !== b.h || a.ch !== b.ch) return false;\n const k = a.w / vw; // image px per CSS px\n const masked = maskBits(\n {\n width: a.w,\n boxes: boxes.map(([x, y, w, h]) => [\n x * k - margin,\n y * k - margin,\n w * k + 2 * margin,\n h * k + 2 * margin,\n ]),\n },\n a.w * a.h,\n );\n let moved = 0;\n for (let i = 0; i < a.w * a.h; i++) {\n if (masked[i]) continue;\n for (let c = 0; c < a.ch; c++)\n if (Math.abs(a.data[i * a.ch + c]! - b.data[i * a.ch + c]!) > STILL_TOLERANCE.level) {\n if (++moved > STILL_TOLERANCE.pixels) return false;\n break;\n }\n }\n return true;\n}\n\n/** A decoded image: `ch` bytes per pixel, row by row. */\ntype DecodedImage = { w: number; h: number; ch: number; data: Uint8Array };\n\n/** One settled moment: probe, reference screenshot, MHTML — raw files into\n * `<statesDir>/<id>/` (`probe.json`, `live.png`, `page.mhtml`). Read-only on\n * the page. Throws on a CDP failure; the caller decides whether a missing\n * state matters (it never fails a take). */\nexport async function captureDomState(\n cdp: CDP,\n args: {\n statesDir: string;\n id: string;\n tMs: number;\n step?: number;\n vw: number;\n vh: number;\n dpr: number;\n },\n): Promise<DomStateRaw> {\n const t0 = Date.now();\n const dir = join(args.statesDir, args.id);\n mkdirSync(dir, { recursive: true });\n // A screenshot's clip is in DOCUMENT px: on a scrolled page, (0, 0) is the\n // top of the document, not of what is on screen — the reference must start\n // where the page is scrolled to (measured: a page scrolled by 643 px gave a\n // reference of the document's top, blank above the sticky header).\n const at = await cdp\n .send<{ cssVisualViewport?: { pageX?: number; pageY?: number } }>(\"Page.getLayoutMetrics\")\n .then((m) => ({ x: m.cssVisualViewport?.pageX ?? 0, y: m.cssVisualViewport?.pageY ?? 0 }))\n .catch(() => ({ x: 0, y: 0 }));\n // The probe and the reference screenshot go out together: the probe holds\n // the main thread for a few ms and the screenshot's frame commits right\n // after it, so a running animation is read at (nearly) the phase the\n // reference shows. The screenshot is at 1× CSS size — the clip is CSS px\n // and the output is clip × dsf × scale, so 1/dsf undoes a Retina capture.\n const [r, shot] = await Promise.all([\n cdp\n .send<{ result?: { value?: unknown } }>(\"Runtime.evaluate\", {\n expression: DOM_STATE_PROBE_JS,\n returnByValue: true,\n })\n .then((x) => ({ value: x.result?.value })),\n cdp\n .send<{ data: string }>(\"Page.captureScreenshot\", {\n format: \"png\",\n clip: {\n x: at.x,\n y: at.y,\n width: args.vw,\n height: args.vh,\n scale: 1 / Math.max(1, args.dpr),\n },\n })\n .then((s) => ({ data: s.data })),\n ]);\n const v = r.value;\n if (typeof v !== \"string\") throw new Error(\"dom-state probe returned nothing\");\n const probe = JSON.parse(v) as DomStateProbe & { error?: string };\n if (probe.error) throw new Error(`dom-state probe failed in page: ${probe.error}`);\n const snap = await cdp.send<{ data: string }>(\"Page.captureSnapshot\", { format: \"mhtml\" });\n // which font files the page has loaded (read-only: its resource timing) —\n // the snapshot carries none of them; they are fetched after the take\n const loadedFonts = await cdp\n .send<{ result?: { value?: unknown } }>(\"Runtime.evaluate\", {\n expression: `performance.getEntriesByType(\"resource\").filter(function(e){return /\\\\.(woff2?|ttf|otf|ttc)(?:[?#]|$)/i.test(e.name)}).map(function(e){return e.name})`,\n returnByValue: true,\n })\n .then((x) =>\n Array.isArray(x.result?.value)\n ? (x.result.value as unknown[]).filter((u): u is string => typeof u === \"string\")\n : [],\n )\n .catch(() => [] as string[]);\n writeFileSync(join(dir, \"live.png\"), Buffer.from(shot.data, \"base64\"));\n writeFileSync(join(dir, \"page.mhtml\"), snap.data, \"utf8\");\n writeFileSync(join(dir, \"probe.json\"), v, \"utf8\");\n return {\n id: args.id,\n tMs: args.tMs,\n ...(args.step != null ? { step: args.step } : {}),\n dir,\n probe,\n ...(loadedFonts.length ? { loadedFonts } : {}),\n ms: Date.now() - t0,\n };\n}\n\n// --- after the screencast ----------------------------------------------------------------\n\nexport type DomStateItem = NonNullable<CaptureLog[\"states\"]>[\"items\"][number];\n\n/** `states/<id>/index.json` from a raw capture (fidelity filled in later) */\nfunction buildIndex(raw: DomStateRaw): StateIndex {\n return {\n version: 1,\n id: raw.id,\n url: raw.probe.url,\n title: raw.probe.title,\n tMs: raw.tMs,\n ...(raw.step != null ? { step: raw.step } : {}),\n viewport: raw.probe.viewport,\n scroll: raw.probe.scroll,\n elements: raw.probe.elements,\n layers: raw.probe.layers,\n };\n}\n\n/**\n * Convert every raw state to `state.html` + `index.json`, drop the raw\n * MHTML/probe, then re-open each state in a second page of the SAME browser\n * (viewport-sized, deviceScaleFactor 1) and score it against `live.png`.\n * Returns the items for the capture log. A state that fails conversion or\n * the check stays on disk with `fidelity.ok: false`; nothing here throws\n * past a single state.\n */\nexport async function finalizeDomStates(args: {\n browser: Browser;\n statesDir: string;\n states: DomStateRaw[];\n vw: number;\n vh: number;\n /** measure each state's parts in the same page (parts.json + crisp\n * pictures in states/assets/) — default true; false skips it */\n parts?: boolean;\n /** run on each state's restored page once it is checked and measured\n * (the shoot's full-page sheet); what it throws is a line, not a failure */\n afterRender?: (cdp: CDP, raw: DomStateRaw) => Promise<void>;\n}): Promise<DomStateItem[]> {\n const warn = (l: string) => console.error(l);\n const assetsDir = join(args.statesDir, \"assets\");\n const items: DomStateItem[] = [];\n const converted: { raw: DomStateRaw; index: StateIndex }[] = [];\n let ffmpeg: string | undefined;\n try {\n ffmpeg = await resolveFfmpeg();\n } catch (e) {\n warn(`dom-state: no ffmpeg for the fidelity check (${(e as Error).message})`);\n }\n let fonts: MhtmlPart[] = [];\n try {\n fonts = await fetchStateFonts(args.browser.cdp, args.states, warn);\n } catch (e) {\n warn(`dom-state: the page's web fonts were not fetched (${(e as Error).message})`);\n }\n for (const raw of args.states) {\n const index = buildIndex(raw);\n // A canvas that copied out empty (WebGL that clears its buffer) would be a\n // hole in the state: its pixels as shown are in the reference screenshot,\n // taken at the same moment — crop them from there.\n if (ffmpeg)\n for (const cv of raw.probe.canvases) {\n if (!cv.blank || !cv.box) continue;\n try {\n cv.dataUrl = await cropPng(ffmpeg, join(raw.dir, \"live.png\"), cv.box);\n cv.blank = false;\n warn(\n `dom-state ${raw.id}: a canvas read back empty — filled from the screenshot taken with it`,\n );\n } catch (e) {\n warn(\n `dom-state ${raw.id}: an empty canvas could not be filled (${(e as Error).message})`,\n );\n }\n }\n try {\n const mhtml = await readFile(join(raw.dir, \"page.mhtml\"), \"latin1\");\n const { html, unresolved } = convertMhtml(mhtml, raw.probe, { assetsDir, extra: fonts });\n await writeFile(join(raw.dir, \"state.html\"), html, \"utf8\");\n if (unresolved)\n warn(\n `dom-state ${raw.id}: ${unresolved} reference(s) not in the snapshot cut off (the page never loaded them, or loaded them after the snapshot)`,\n );\n converted.push({ raw, index });\n } catch (e) {\n warn(\n `dom-state ${raw.id}: conversion failed (${(e as Error).message}) — the film will use the video here`,\n );\n index.fidelity = { psnr: 0, diffFrac: 1, ok: false };\n }\n await writeFile(join(raw.dir, \"index.json\"), JSON.stringify(index, null, 2));\n await rm(join(raw.dir, \"page.mhtml\"), { force: true });\n await rm(join(raw.dir, \"probe.json\"), { force: true });\n }\n if (converted.length) {\n // (cast, not annotated: openPage/dropPage assign it, and TS would\n // otherwise narrow it to null for the loop below)\n let page = null as { cdp: CDP; targetId: string } | null;\n // A state whose page stops answering (a request timed out, the renderer\n // crashed) leaves that page unusable: it is closed and the next state gets\n // a fresh one. A page that cannot be opened at all — or two states in a\n // row whose pages stall (Chrome itself, not one page, is stuck: each more\n // would wait out its own budgets) — ends the checks; the remaining states\n // keep `ok: false` and the take goes on.\n let noPage = false;\n let stallsInARow = 0;\n const openPage = async () => {\n if (page || noPage || !ffmpeg) return;\n try {\n page = await openFidelityPage(args.browser, args.vw, args.vh);\n } catch (e) {\n noPage = true;\n warn(`dom-state: could not open a page for the fidelity check (${(e as Error).message})`);\n }\n };\n const dropPage = async (id: string, e: unknown) => {\n if (!page || !isCdpStall(e)) return;\n warn(`dom-state ${id}: the check's page stopped answering — the next state gets a new one`);\n await closeFidelityPage(args.browser, page);\n page = null;\n if (++stallsInARow >= 2) {\n noPage = true;\n warn(\n \"dom-state: two checks in a row stopped answering — the remaining states are not checked\",\n );\n }\n };\n for (const { raw, index } of converted) {\n const stallsBefore = stallsInARow;\n let fidelity: StateFidelity = { psnr: 0, diffFrac: 1, ok: false };\n await openPage();\n if (page && ffmpeg) {\n const statePng = join(raw.dir, \"render.png\");\n try {\n const shot = await renderState(page.cdp, join(raw.dir, \"state.html\"), args.vw, args.vh);\n await writeFile(statePng, shot.png);\n // the restored page is open and laid out: measure its parts here,\n // after the fidelity screenshot so nothing it does reaches that\n if (args.parts !== false)\n await measureParts(page.cdp, { dir: raw.dir, index, assetsDir }).catch(async (e) => {\n warn(`dom-state ${raw.id}: parts not measured (${(e as Error).message})`);\n await dropPage(raw.id, e);\n });\n // what moves on its own was frozen a moment apart from the\n // reference; the rest of the page decides whether the state is true\n const moving = [...raw.probe.canvases, ...raw.probe.videos]\n .filter((m) => m.box && !m.blank)\n .map((m) => m.box!);\n fidelity = await measureFidelity(ffmpeg, join(raw.dir, \"live.png\"), statePng, moving);\n if (args.afterRender)\n await args.afterRender(page.cdp, raw).catch(async (e) => {\n warn(`dom-state ${raw.id}: ${(e as Error).message}`);\n await dropPage(raw.id, e);\n });\n if (shot.misses)\n warn(\n `dom-state ${raw.id}: ${shot.misses} element path(s) did not resolve in state.html`,\n );\n } catch (e) {\n warn(`dom-state ${raw.id}: fidelity check failed (${(e as Error).message})`);\n await dropPage(raw.id, e);\n } finally {\n await rm(statePng, { force: true });\n }\n }\n if (page && stallsInARow === stallsBefore) stallsInARow = 0;\n index.fidelity = fidelity;\n await writeFile(join(raw.dir, \"index.json\"), JSON.stringify(index, null, 2));\n }\n if (page) await closeFidelityPage(args.browser, page);\n }\n for (const raw of args.states) {\n const index = converted.find((c) => c.raw === raw)?.index;\n items.push({\n id: raw.id,\n tMs: raw.tMs,\n ...(raw.step != null ? { step: raw.step } : {}),\n ...(index?.fidelity\n ? { fidelity: index.fidelity }\n : { fidelity: { psnr: 0, diffFrac: 1, ok: false } }),\n });\n }\n return items;\n}\n\n/** close a page openFidelityPage opened (never throws, never waits long:\n * its target may be the one that stopped answering) */\nexport async function closeFidelityPage(\n browser: Browser,\n page: { cdp: CDP; targetId: string },\n): Promise<void> {\n page.cdp.close();\n await browser.cdp\n .send(\"Target.closeTarget\", { targetId: page.targetId }, { timeoutMs: 5000 })\n .catch(() => {});\n}\n\n/** a second page target in the same Chrome, emulated at vw×vh @1× */\nexport async function openFidelityPage(\n browser: Browser,\n vw: number,\n vh: number,\n): Promise<{ cdp: CDP; targetId: string }> {\n const { targetId } = await browser.cdp.send<{ targetId: string }>(\"Target.createTarget\", {\n url: \"about:blank\",\n });\n let cdp: CDP | undefined;\n try {\n cdp = await CDP.connect(`ws://127.0.0.1:${browser.port}/devtools/page/${targetId}`);\n await setUpFidelityPage(cdp, vw, vh);\n } catch (e) {\n // a page that could not be set up is not left open behind the error\n cdp?.close();\n await browser.cdp.send(\"Target.closeTarget\", { targetId }, { timeoutMs: 5000 }).catch(() => {});\n throw e;\n }\n return { cdp, targetId };\n}\n\nasync function setUpFidelityPage(cdp: CDP, vw: number, vh: number): Promise<void> {\n await cdp.send(\"Page.enable\");\n await cdp.send(\"Runtime.enable\");\n await cdp.send(\"Emulation.setDeviceMetricsOverride\", {\n width: vw,\n height: vh,\n deviceScaleFactor: 1,\n mobile: false,\n });\n // The check must see what a film render sees later, when the app's server\n // is long gone: only the saved files load. A reference left pointing at the\n // app would otherwise load from it now and pass a state that breaks then.\n await cdp.send(\"Network.enable\");\n await cdp.send(\"Network.setBlockedURLs\", {\n urls: [\"http://*\", \"https://*\", \"ws://*\", \"wss://*\"],\n });\n}\n\n/** Open a state.html (file://), wait for the restore script's ready flag, screenshot at 1×. */\nexport async function renderState(\n cdp: CDP,\n stateHtml: string,\n vw: number,\n vh: number,\n): Promise<{ png: Buffer; misses: number }> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const loaded = new Promise<void>((res) => {\n cdp.on(\"Page.loadEventFired\", () => res());\n timer = setTimeout(res, 15000);\n });\n try {\n await cdp.send(\"Page.navigate\", { url: pathToFileURL(stateHtml).href });\n await loaded;\n } finally {\n // a pending 15 s timer would hold the process open after the last state\n // (also when the navigation itself failed or timed out)\n clearTimeout(timer);\n }\n const deadline = Date.now() + 10000;\n let misses = 0;\n for (;;) {\n const r = await cdp.send<{ result?: { value?: string } }>(\"Runtime.evaluate\", {\n expression:\n 'document.documentElement.dataset.otReady === \"1\" ? (document.documentElement.dataset.otMisses || \"0\") : \"\"',\n returnByValue: true,\n });\n const v = r.result?.value;\n if (v) {\n misses = Number(v) || 0;\n break;\n }\n if (Date.now() > deadline) throw new Error(\"state.html never reported ready\");\n await sleep(50);\n }\n await sleep(60); // two frames for the paint after the last restore step\n // the clip is in document px: start where the restored state is scrolled to\n const at = await cdp\n .send<{ cssVisualViewport?: { pageX?: number; pageY?: number } }>(\"Page.getLayoutMetrics\")\n .then((m) => ({ x: m.cssVisualViewport?.pageX ?? 0, y: m.cssVisualViewport?.pageY ?? 0 }))\n .catch(() => ({ x: 0, y: 0 }));\n const shot = await cdp.send<{ data: string }>(\"Page.captureScreenshot\", {\n format: \"png\",\n clip: { x: at.x, y: at.y, width: vw, height: vh, scale: 1 },\n });\n return { png: Buffer.from(shot.data, \"base64\"), misses };\n}\n\n// --- parts: the component probe, in the restored page --------------------------\n\n/** Most pictures taken per state (each is one clipped screenshot, ~40–80 ms). */\nconst PARTS_MAX_PICTURES = 60;\n\n/**\n * Measure the parts of the saved state open in `cdp` (state.html, ready —\n * renderState has run) with the compositor's component probe, take a crisp\n * picture of each kept part (its ink or box ± pad, 3×, the rest of the page\n * hidden and see-through — what lift(…, { around: \"clear\" }) shows), and\n * write `<dir>/parts.json`. Pictures are content-named files in `assetsDir`\n * (shared with the state's other files), referenced relative to `dir`. The\n * page's look is put back afterwards (the background override persists\n * across navigations in this target).\n */\nexport async function measureParts(\n cdp: CDP,\n opts: {\n dir: string;\n index: StateIndex;\n assetsDir: string;\n pictures?: boolean;\n /** keep each part's elements for its file (parts-dom.json) — default true */\n dom?: boolean;\n minArea?: number;\n },\n): Promise<PartsFile> {\n const r = await cdp.send<{ result?: { value?: string }; exceptionDetails?: { text?: string } }>(\n \"Runtime.evaluate\",\n {\n expression: componentProbeExpression(\n opts.index,\n opts.minArea != null ? { minArea: opts.minArea } : {},\n ),\n returnByValue: true,\n },\n );\n const raw = r.result?.value;\n if (typeof raw !== \"string\")\n throw new Error(`the component probe returned nothing (${r.exceptionDetails?.text ?? \"?\"})`);\n const res = JSON.parse(raw) as ComponentProbeResult;\n if (\"error\" in res) throw new Error(`the component probe failed: ${res.error}`);\n const file: PartsFile = {\n version: 1,\n state: opts.index.id,\n viewport: res.viewport,\n scroll: res.scroll,\n medianTextPx: res.medianTextPx,\n parts: res.parts,\n skipped: res.skipped,\n ms: { measure: res.ms },\n };\n // each part as a file of its own (parts-dom.json): read here, while its\n // computed styles are live and before the pictures restyle the page\n if (opts.dom !== false && file.parts.length) await keepPartDom(cdp, opts.dir, file);\n if (opts.pictures !== false && file.parts.length) {\n const t0 = Date.now();\n mkdirSync(opts.assetsDir, { recursive: true });\n const evaluate = (expression: string) =>\n cdp.send(\"Runtime.evaluate\", { expression, returnByValue: true });\n await cdp.send(\"Emulation.setDefaultBackgroundColorOverride\", {\n color: { r: 0, g: 0, b: 0, a: 0 },\n });\n // a page that stops answering ends the pictures (each would wait out its\n // own timeout) and skips the clean-up: the caller drops that page\n let stalled = false;\n try {\n await evaluate(\n `(() => { const st = document.createElement(\"style\"); st.setAttribute(\"data-ot-clip-css\", \"\"); st.textContent = ${JSON.stringify(CLIP_CLEAR_CSS)}; document.head.appendChild(st); })()`,\n );\n const at = await cdp\n .send<{ cssVisualViewport?: { pageX?: number; pageY?: number } }>(\"Page.getLayoutMetrics\")\n .then((m) => ({ x: m.cssVisualViewport?.pageX ?? 0, y: m.cssVisualViewport?.pageY ?? 0 }))\n .catch(() => ({ x: 0, y: 0 }));\n let taken = 0;\n for (const part of file.parts) {\n const win = pictureClip(part, file.viewport);\n if (!win) {\n part.noPicture = \"nothing of it inside the screen\";\n continue;\n }\n if (taken >= PARTS_MAX_PICTURES) {\n part.noPicture = `not taken: ${PARTS_MAX_PICTURES} pictures already taken in this state`;\n continue;\n }\n const sel = JSON.stringify(`[data-ot-id=\"${part.el}\"]`);\n await evaluate(`document.querySelector(${sel})?.setAttribute(\"data-ot-clip\", \"\")`);\n try {\n const [x, y, w, h] = win.clip;\n const shot = await cdp.send<{ data: string }>(\"Page.captureScreenshot\", {\n format: \"png\",\n clip: { x: x + at.x, y: y + at.y, width: w, height: h, scale: win.scale },\n });\n const png = Buffer.from(shot.data, \"base64\");\n const name = `${createHash(\"sha1\").update(png).digest(\"hex\")}.png`;\n const path = join(opts.assetsDir, name);\n if (!existsSync(path)) writeFileSync(path, png);\n part.picture = relative(opts.dir, path).split(sep).join(\"/\");\n part.clip = win.clip;\n part.clipScale = win.scale;\n taken++;\n } catch (e) {\n if (isCdpStall(e)) {\n stalled = true;\n throw e;\n }\n part.noPicture = `the screenshot failed (${(e as Error).message})`;\n } finally {\n if (!stalled)\n await evaluate(`document.querySelector(${sel})?.removeAttribute(\"data-ot-clip\")`);\n }\n }\n } catch (e) {\n if (isCdpStall(e)) stalled = true;\n throw e;\n } finally {\n if (!stalled) {\n await evaluate('document.querySelector(\"style[data-ot-clip-css]\")?.remove()').catch(\n () => {},\n );\n await cdp.send(\"Emulation.setDefaultBackgroundColorOverride\", {}).catch(() => {});\n }\n }\n file.ms.pictures = Date.now() - t0;\n }\n await writeFile(join(opts.dir, \"parts.json\"), `${JSON.stringify(file, null, 2)}\\n`);\n return file;\n}\n\n/**\n * Each measured part's elements with their computed styles inlined, its\n * fonts' families and its natural size — what `parts/<state>-<el>-<kind>.html`\n * is written from (compositor part-files.ts) — as `<dir>/parts-dom.json`.\n * One that cannot be read is a line, never a failure of the parts; a page\n * that stops answering is passed on (the caller drops it).\n */\nasync function keepPartDom(cdp: CDP, dir: string, parts: PartsFile): Promise<void> {\n const path = join(dir, \"parts-dom.json\");\n try {\n const r = await cdp.send<{ result?: { value?: string }; exceptionDetails?: { text?: string } }>(\n \"Runtime.evaluate\",\n {\n expression: partDomExpression(parts.parts.map((p) => p.el)),\n returnByValue: true,\n },\n { timeoutMs: 30_000 },\n );\n const raw = r.result?.value;\n if (typeof raw !== \"string\")\n throw new Error(`the page returned nothing (${r.exceptionDetails?.text ?? \"?\"})`);\n const res = JSON.parse(raw) as Omit<PartDomFile, \"version\" | \"state\"> | { error: string };\n if (\"error\" in res) throw new Error(res.error.split(\"\\n\")[0]);\n const file: PartDomFile = { version: 1, state: parts.state, ...res };\n await writeFile(path, `${JSON.stringify(file)}\\n`);\n } catch (e) {\n if (isCdpStall(e)) throw e;\n await rm(path, { force: true });\n console.error(`dom-state ${parts.state}: parts not kept as files (${(e as Error).message})`);\n }\n}\n\n/**\n * Measure the parts of saved states that already exist (each a folder with\n * state.html + index.json) — for states saved before parts.json, which\n * `open-take components` meets. One page in `browser`, emulated at each\n * state's own viewport @1×, network blocked, as the fidelity check opens\n * them. A state that cannot be measured is a line in `failed`.\n */\nexport async function measureStateDirs(args: {\n browser: Browser;\n dirs: string[];\n pictures?: boolean;\n minArea?: number;\n}): Promise<{\n measured: { dir: string; parts: PartsFile }[];\n failed: { dir: string; why: string }[];\n}> {\n const measured: { dir: string; parts: PartsFile }[] = [];\n const failed: { dir: string; why: string }[] = [];\n let page: { cdp: CDP; targetId: string } | null = null;\n try {\n for (const dir of args.dirs) {\n const index = readStateIndex(dir);\n if (typeof index === \"string\") {\n failed.push({ dir, why: index });\n continue;\n }\n const { w, h } = index.viewport;\n try {\n if (!page) page = await openFidelityPage(args.browser, w, h);\n else\n await page.cdp.send(\"Emulation.setDeviceMetricsOverride\", {\n width: w,\n height: h,\n deviceScaleFactor: 1,\n mobile: false,\n });\n await renderState(page.cdp, join(dir, \"state.html\"), w, h);\n const parts = await measureParts(page.cdp, {\n dir,\n index,\n assetsDir: join(dir, \"..\", \"assets\"),\n ...(args.pictures != null ? { pictures: args.pictures } : {}),\n ...(args.minArea != null ? { minArea: args.minArea } : {}),\n });\n measured.push({ dir, parts });\n } catch (e) {\n failed.push({ dir, why: (e as Error).message });\n // a page that stopped answering is replaced for the next state\n if (page && isCdpStall(e)) {\n await closeFidelityPage(args.browser, page);\n page = null;\n }\n }\n }\n } finally {\n if (page) await closeFidelityPage(args.browser, page);\n }\n return { measured, failed };\n}\n\n/** One stderr line: what the states cost the take and how they scored. */\nexport function summarizeDomStates(states: DomStateRaw[], items: DomStateItem[]): string {\n const moving = items.filter((i) => i.moving).map((i) => i.id);\n if (!states.length)\n return moving.length\n ? `captureTakeCDP: DOM states — none saved: the page was still moving at ${moving.join(\", \")} (use the recording)`\n : \"captureTakeCDP: DOM states — none captured\";\n const total = states.reduce((s, r) => s + r.ms, 0);\n const each = states.map((r) => `${r.id} ${r.ms}ms`).join(\", \");\n const scored = items.filter((i) => i.fidelity);\n const ok = scored.filter((i) => i.fidelity!.ok).length;\n const worst = scored.reduce<DomStateItem | null>(\n (w, i) => (!w || i.fidelity!.psnr < w.fidelity!.psnr ? i : w),\n null,\n );\n return (\n `captureTakeCDP: DOM states — ${states.length} captured, +${(total / 1000).toFixed(1)}s on the take (${each}); ` +\n (moving.length\n ? `${moving.join(\", \")} not saved — the page was still moving there (use the recording); `\n : \"\") +\n `fidelity ${ok}/${scored.length} ok` +\n (worst\n ? ` (lowest ${worst.id}: psnr ${worst.fidelity!.psnr.toFixed(1)}, ${(worst.fidelity!.diffFrac * 100).toFixed(1)}% px differ)`\n : \"\")\n );\n}\n","// Destination resolution for the `navigate` step.\n//\n// A TakePlan is static JSON authored BEFORE the capture runs, which is why a\n// demo that spans two pages used to be two takes: the second page's URL often\n// does not exist yet when the plan is written (a deploy's generated domain, a\n// created record's permalink, a share link). So a navigate destination is\n// LATE-BOUND — the plan says *where to read it from*, and this resolves it\n// against what the page actually shows at that moment.\n//\n// Pure on purpose: the browser supplies `current`/`href` as strings, so every\n// precedence and merge rule below is unit-testable without launching Chrome.\n\nexport type NavigateTarget = {\n /** the page's URL right now — the base for a relative `url`, and the\n * destination itself when the step only carries `query` */\n current: string;\n /** explicit destination from the plan; absolute, or relative to `current` */\n url?: string;\n /** destination read off the page at capture time (already absolute) */\n href?: string | null;\n /** params merged onto whichever destination won. The reason this exists\n * separately from `url`: the page links to the bare thing, but the demo\n * needs it parameterised (`?speed=3` to compress a long animation into the\n * shot). Clicking the link could never produce that. */\n query?: Record<string, string>;\n};\n\n/**\n * Resolve a navigate step to one absolute URL, or null when it cannot be.\n *\n * Precedence is `href` > `url` > `current`: a destination READ FROM THE PAGE\n * beats one written in the plan, because it is the one that reflects what the\n * app just did. `current` last means `{ query }` on its own is \"reload this\n * same page with these params\" rather than an error.\n */\nexport function resolveNavigateUrl(t: NavigateTarget): string | null {\n const base = safeUrl(t.current);\n const raw = t.href || t.url || t.current;\n if (!raw) return null;\n // A relative `url` (\"/pricing\") needs the current page as its base; an\n // absolute one ignores the base. `href` is already absolute (the DOM\n // resolves it), so this is a no-op for that path.\n const dest = safeUrl(raw, base);\n if (!dest) return null;\n for (const [k, v] of Object.entries(t.query ?? {})) dest.searchParams.set(k, v);\n return dest.toString();\n}\n\nfunction safeUrl(raw: string, base?: URL): URL | undefined {\n try {\n return new URL(raw, base);\n } catch {\n return undefined;\n }\n}\n","// Pre-capture target resolution — the 2-second gate in front of the 60-second\n// shoot. Resolves every plan target against the page AS LOADED with the exact\n// locator semantics the capture will use (same candidate sets, same pick()),\n// so a plan whose opening steps can never resolve is refused BEFORE the\n// screencast exists — the same contract as the dead-URL check in cdp-capture.\n//\n// The page is stateful, so the gate is deliberately state-honest:\n// - steps up to and including the FIRST state-changing action run against\n// the initial DOM by construction — a miss there is a certainty, and an\n// error;\n// - a miss after that point is only \"not in the initial DOM\": a prior step\n// may reveal it (a toolbar that appears once editing starts), so it is a\n// warning, and the capture-time skip (plus the strict default exit) stays\n// the authority.\n// A measured motivator: 12/12 model-repaired plans of one broken take kept a\n// first click that resolves to a sidebar thumbnail instead of the headline —\n// every later beat then dies \"target not found\" after a full minute of\n// capture. The ambiguity/zero-size warnings here are how that reads BEFORE\n// the shoot.\nimport {\n BOX_CANDIDATES,\n CLICK_CANDIDATES,\n CLICK_FALLBACK_CANDIDATES,\n FIELD_CANDIDATES,\n NAME_JS,\n SCROLL_CANDIDATES,\n} from \"./capture\";\nimport type { TakePlan } from \"./types\";\n\nexport type PrecheckIssue = {\n severity: \"error\" | \"warn\";\n /** dotted/indexed field path, e.g. \"steps[3].selector\" */\n path: string;\n message: string;\n /** a concrete suggested correction the author can apply */\n fix?: string;\n};\n\n/** Thrown by the capture when error-severity findings refuse the shoot.\n * Carries the FULL structured findings (warns included) so the CLI can emit\n * the machine-readable defects block and exit 2 like every other gate\n * verdict — the message is only the human rendering of the same facts, and\n * flattening the findings into it is how the measured values used to get\n * lost on the way to the repair loop. */\nexport class PrecheckRefusal extends Error {\n readonly issues: PrecheckIssue[];\n constructor(message: string, issues: PrecheckIssue[]) {\n super(message);\n this.name = \"PrecheckRefusal\";\n this.issues = issues;\n }\n}\n\ntype TargetSpec = {\n step: number;\n action: string;\n field: string; // which plan field named the target (selector/text/toSelector/…)\n kind: \"selector\" | \"text\";\n value: string;\n /** true = runs against the initial DOM by construction (miss ⇒ certainty) */\n cold: boolean;\n /** press reveals are named so the ZOOM can frame them — they exist only\n * AFTER the press by definition, so a miss is never even a warning */\n revealOnly?: boolean;\n /** false = the capture will never consult this field, because the step also\n * carries the one this action resolves first (see FIELD_ORDER) */\n used: boolean;\n};\n\n// Which field the capture actually resolves when a step names more than one.\n// Read off cdp-capture / capture.ts, verb by verb: click, type, look, hover\n// and press try `text` first and do NOT fall back when it misses; `select`\n// (selectOptionJs) and `scroll` (scrollDeltaSelectorJs) try the SELECTOR\n// first; a `drag` endpoint takes a literal point, then `selector`, then\n// `text`. Grading a field the engine never reads would refuse a plan that\n// captures fine.\nconst FIELD_ORDER: Record<string, string[]> = {\n click: [\"text\", \"selector\"],\n type: [\"text\", \"selector\"],\n look: [\"text\", \"selector\"],\n hover: [\"text\", \"selector\"],\n press: [\"text\", \"selector\"],\n select: [\"selector\", \"text\"],\n scroll: [\"toSelector\", \"toText\"],\n drag: [\"selector\", \"text\"],\n};\nconst DRAG_TO_ORDER = [\"toSelector\", \"toText\"];\n\n// Any action that can change what the page shows ends the cold prefix. hover\n// and scroll are included on purpose: a hover can open a menu, a scroll can\n// mount lazy content — after either, absence from the initial DOM proves\n// nothing.\nconst MUTATING = new Set([\n \"click\",\n \"type\",\n \"press\",\n \"select\",\n \"drag\",\n \"dropFiles\",\n \"navigate\",\n \"hover\",\n \"scroll\",\n]);\n\n/** Every named target in the plan, in step order, tagged cold/late. */\nexport function planTargets(steps: TakePlan[\"steps\"]): TargetSpec[] {\n const out: TargetSpec[] = [];\n let cold = true;\n for (let i = 0; i < steps.length; i++) {\n const s = steps[i] as Record<string, unknown>;\n const action = String(s.action ?? \"\");\n const has = (f: string) => typeof s[f] === \"string\" && s[f];\n /** the first field of this group the step actually carries */\n const winner = (order: string[]) => order.find(has);\n const order = FIELD_ORDER[action];\n const dragTo = action === \"drag\" && (s.to as unknown) ? null : winner(DRAG_TO_ORDER);\n const primary = action === \"drag\" && (s.from as unknown) ? null : winner(order ?? []);\n // an action with no precedence entry gets every field checked — a new\n // verb must not silently switch the gate off for itself\n const isUsed = (field: string) => !order || field === primary || field === dragTo;\n const add = (field: string, kind: \"selector\" | \"text\", revealOnly?: boolean) => {\n const v = s[field];\n if (typeof v === \"string\" && v)\n out.push({\n step: i,\n action,\n field,\n kind,\n value: v,\n cold: cold && !revealOnly,\n used: isUsed(field),\n ...(revealOnly ? { revealOnly } : {}),\n });\n };\n switch (action) {\n case \"click\":\n case \"hover\":\n case \"look\":\n case \"type\":\n case \"select\":\n add(\"selector\", \"selector\");\n add(\"text\", \"text\");\n break;\n case \"press\":\n // the reveal target exists only after the press lands\n add(\"selector\", \"selector\", true);\n add(\"text\", \"text\", true);\n break;\n case \"scroll\":\n add(\"toSelector\", \"selector\");\n add(\"toText\", \"text\");\n break;\n case \"drag\": {\n // With a `path`, the stroke is the waypoints and each element endpoint\n // has them as a fallback (resolvePoint(...) ?? pathPts[0]) — a miss\n // costs nothing, so nothing here is load-bearing.\n const hasPath = Array.isArray(s.path) && (s.path as unknown[]).length > 0;\n if (!hasPath) {\n add(\"selector\", \"selector\");\n add(\"text\", \"text\");\n add(\"toSelector\", \"selector\");\n add(\"toText\", \"text\");\n }\n break;\n }\n case \"navigate\": {\n // navigate DOES resolve an in-page target: hrefFrom names the link\n // whose real href the demo follows — selector first, then by-text\n // over the link candidate set (capture.ts hrefSelectorJs/hrefByTextJs).\n // A cold miss here is the worst cascade in the file's header: every\n // later step is excused as \"late\", and the take shoots zero beats.\n const hf = s.hrefFrom as { selector?: string; text?: string } | undefined;\n const hfField = hf?.selector ? \"selector\" : hf?.text ? \"text\" : null;\n for (const [sub, kind] of [\n [\"selector\", \"selector\"],\n [\"text\", \"text\"],\n ] as const) {\n const v = hf?.[sub];\n if (typeof v === \"string\" && v)\n out.push({\n step: i,\n action,\n field: `hrefFrom.${sub}`,\n kind,\n value: v,\n cold,\n used: sub === hfField,\n });\n }\n break;\n }\n default:\n break; // wait names no in-page target to resolve\n }\n if (MUTATING.has(action)) cold = false;\n }\n return out;\n}\n\n/** The candidate set the ENGINE's by-text locator queries for this action —\n * imported from capture.ts so the probe and the real resolver cannot drift. */\nfunction textCandidates(action: string): string {\n switch (action) {\n case \"type\":\n return FIELD_CANDIDATES; // focusFieldByTextJs\n case \"click\":\n return CLICK_CANDIDATES; // clickByTextJs\n case \"scroll\":\n return SCROLL_CANDIDATES; // scrollDeltaByTextJs\n case \"navigate\":\n return \"a,button,[role=link],[role=button],[aria-label],[title]\"; // hrefByTextJs\n default:\n return BOX_CANDIDATES; // hover / look / drag endpoints / press reveals → boxByTextJs\n }\n}\n\n/** One page eval: resolve a target and DESCRIBE the outcome (no side effects). */\nexport function probeJs(kind: \"selector\" | \"text\", value: string, action: string): string {\n const v = JSON.stringify(value);\n const desc =\n `function desc(m){if(!m)return null;var r=m.getBoundingClientRect();` +\n `return {tag:m.tagName,w:Math.round(r.width),h:Math.round(r.height),` +\n `x:Math.round(r.x),y:Math.round(r.y),inMain:!!m.closest('main')};}`;\n if (kind === \"selector\")\n return (\n `(function(){${desc}` +\n `var all;try{all=Array.prototype.slice.call(document.querySelectorAll(${v}));}` +\n `catch(e){return JSON.stringify({err:String(e.message||e)});}` +\n `return JSON.stringify({count:all.length,first:desc(all[0]||null)});})()`\n );\n if (action === \"select\")\n // a <select> is located by its OWN semantics (selectOptionJs): aria-label\n // equal to the name, a label[for] pointing at it, or a wrapping <label> —\n // pick() over form fields would never match one.\n return (\n `(function(){${desc}var n=${v};` +\n `var els=Array.prototype.slice.call(document.querySelectorAll('select'));` +\n `var hits=els.filter(function(e){var a=(e.getAttribute('aria-label')||'').trim();if(a===n)return true;` +\n `var id=e.id;if(id){var l=document.querySelector('label[for=\"'+id+'\"]');if(l&&(l.textContent||'').trim().indexOf(n)>=0)return true;}` +\n `var p=e.closest('label');if(p&&(p.textContent||'').trim().indexOf(n)>=0)return true;return false;});` +\n `return JSON.stringify({count:hits.length?1:0,exact:hits.length,first:desc(hits[0]||null)});})()`\n );\n const set = textCandidates(action);\n // Alongside the pick itself: HOW it matched (an exact name vs a substring\n // buried in some clickable's textContent), and every element inside <main>\n // that actually carries this name — the C3.5 evidence. The intended element\n // (a headline, a paragraph) is typically NOT in the candidate set, which is\n // why a resolving target can still be the wrong node.\n return (\n `(function(){${desc}${NAME_JS}` +\n `var els=Array.prototype.slice.call(document.querySelectorAll('${set}'));` +\n `var m=pick(els,${v});` +\n // when the pick is a label wrapping a checkbox, its peers are what share\n // the name: two \"Notify me\" labels are as ambiguous as two buttons\n (action === \"click\"\n ? `if(!m){var fb=Array.prototype.slice.call(document.querySelectorAll('${CLICK_FALLBACK_CANDIDATES}'));m=pick(fb,${v});if(m)els=fb;}`\n : \"\") +\n `var exact=0;for(var i=0;i<els.length;i++){if(names(els[i]).indexOf(${v})!==-1)exact++;}` +\n `var how=m?(names(m).indexOf(${v})!==-1?'exact':'substring'):'none';` +\n // How much of the pick's own (shortest containing) name the value covers.\n // \"Comments\" naming a button whose name is \"Comments3\", or \"Start free\n // trial\" naming \"Start free trial →\", covers most of it — the author\n // ABBREVIATED the control's label. \"Build slides\" matched inside a\n // 200-char thumbnail blob covers a sliver — the author named something\n // else entirely. This ratio is what separates the two.\n `var share=how==='exact'?1:0,pn=null;` +\n `if(m&&how==='substring'){var mn=names(m);for(var k=0;k<mn.length;k++){` +\n `if(mn[k].indexOf(${v})!==-1&&(pn===null||mn[k].length<pn.length))pn=mn[k];}` +\n `if(pn)share=${v}.length/pn.length;}` +\n // Containment is how a plan names a fragment of a long paragraph, or a\n // headline the session has already edited — but only between names long\n // enough to be distinctive in BOTH directions: a two-letter label\n // \"contained\" in a sentence is a coincidence, not the author's intent.\n `function nm(e){var n=names(e),k;for(k=0;k<n.length;k++){if(n[k]===${v})return 'exact';}` +\n `if(${v}.length>6){for(k=0;k<n.length;k++){if(n[k].length>6&&` +\n `(n[k].indexOf(${v})!==-1||${v}.indexOf(n[k])!==-1))return 'contains';}}` +\n `return null;}` +\n `var inM=[],same=false,am=document.querySelectorAll('main *'),vwA=window.innerWidth*window.innerHeight;` +\n `for(var i=0;i<am.length;i++){var e=am[i],mk=nm(e);if(!mk)continue;` +\n // The pick wraps / sits inside the element that carries the name (a\n // clickable card around its own title, a link inside a heading): the\n // click lands on the thing the author named — no mismatch. The pick\n // MATCHING ITSELF proves nothing under substring semantics (every\n // substring pick's name contains the value by definition), so a self-hit\n // only exonerates on an exact name. Checked over EVERY match, before\n // any capping.\n `if(m&&e===m){if(mk==='exact')same=true;continue;}` +\n `if(m&&(m.contains(e)||e.contains(m))){same=true;continue;}` +\n `var d=desc(e);` +\n // display:none duplicates (responsive markup) and sr-only text measure\n // as nothing — they are not what a demo was aimed at\n `if(d.w<3||d.h<3)continue;` +\n // a containment hit the size of the stage is a container, not the element\n // the author named — every ancestor of the real target would match too\n `if(mk==='contains'&&d.w*d.h>vwA*0.25)continue;d.match=mk;inM.push(d);}` +\n // plausible intent: an exact name beats containment; among peers the\n // tightest box is the named element, its wrappers are noise\n `inM.sort(function(a,b){if(a.match!==b.match)return a.match==='exact'?-1:1;return a.w*a.h-b.w*b.h;});` +\n `return JSON.stringify({count:m?1:0,exact:exact,first:desc(m),how:how,` +\n `pickNameShare:Math.round(share*100)/100,pickName:pn?pn.slice(0,60):null,` +\n `pickIsNamed:same,mainMatches:inM.slice(0,4)});})()`\n );\n}\n\ntype Landed = {\n tag: string;\n w: number;\n h: number;\n x?: number;\n y?: number;\n inMain?: boolean;\n match?: \"exact\" | \"contains\";\n};\ntype Probe = {\n err?: string;\n count?: number;\n exact?: number;\n first?: Landed | null;\n /** how the by-text pick matched: an exact accessible name, or a substring */\n how?: \"exact\" | \"substring\" | \"none\";\n /** fraction of the pick's own (shortest containing) name the value covers:\n * 1 for an exact hit, ~0.9 for an abbreviated label (\"Comments\" naming\n * \"Comments3\"), a sliver for a match inside some blob's textContent */\n pickNameShare?: number;\n /** the pick's shortest name containing the value (substring hits only) */\n pickName?: string | null;\n /** the pick wraps/sits inside an element carrying the name, or IS one exactly */\n pickIsNamed?: boolean;\n /** elements inside <main> that carry the target's name (C3.5 evidence) */\n mainMatches?: Landed[];\n};\n\n/** C3.5 parse-intent mismatch: the pick and the same-named in-main element\n * disagree by more than a step's worth of geometry. Validated against the 36\n * plans of the X5 corpus (23 poisoned targets). A pick that covers most of\n * its own label (share >= 0.5) is the named control, abbreviated — for that\n * shape only an EXACT in-main duplicate is evidence of anything; body copy\n * merely mentioning the phrase is how landing pages talk about their own\n * buttons. */\nconst FAR_PX = 150;\nconst ABBREVIATION_SHARE = 0.5;\nfunction parseIntentMismatch(p: Probe): { pick: Landed; intended: Landed } | null {\n const pick = p.first;\n if (!pick || typeof pick.x !== \"number\" || typeof pick.y !== \"number\") return null;\n if (p.pickIsNamed) return null; // the pick is (or contains) the named element\n let matches = (p.mainMatches ?? []).filter(\n (m) => typeof m.x === \"number\" && typeof m.y === \"number\",\n );\n if ((p.pickNameShare ?? 0) >= ABBREVIATION_SHARE)\n matches = matches.filter((m) => m.match === \"exact\");\n if (!matches.length) return null;\n const cx = pick.x + pick.w / 2;\n const cy = pick.y + pick.h / 2;\n for (const m of matches) {\n // the pick IS one of the named elements — clean\n if (Math.abs(m.x! + m.w / 2 - cx) <= 5 && Math.abs(m.y! + m.h / 2 - cy) <= 5) return null;\n }\n const intended = matches[0]!; // exact-first, tightest-box-first (sorted in-page)\n const far =\n Math.abs(intended.x! + intended.w / 2 - cx) > FAR_PX ||\n Math.abs(intended.y! + intended.h / 2 - cy) > FAR_PX;\n return !pick.inMain || far ? { pick, intended } : null;\n}\n\n/** Resolve every plan target through `evalJson` (a Runtime.evaluate wrapper)\n * and grade the outcomes. Cold-prefix misses get ONE retry after `retryMs` —\n * a hydration-slow page may mount its controls a beat after load. */\nexport async function precheckPlan(\n steps: TakePlan[\"steps\"],\n evalJson: (js: string) => Promise<unknown>,\n opts?: { retryMs?: number; sleep?: (ms: number) => Promise<void> },\n): Promise<PrecheckIssue[]> {\n const sleep = opts?.sleep ?? ((ms: number) => new Promise((r) => setTimeout(r, ms)));\n // A field the capture will never read cannot break the take — probing it\n // would only produce verdicts about a resolution that never happens.\n const targets = planTargets(steps).filter((t) => t.used);\n const probes = new Map<TargetSpec, Probe>();\n const probe = async (t: TargetSpec): Promise<Probe> =>\n ((await evalJson(probeJs(t.kind, t.value, t.action))) ?? {}) as Probe;\n for (const t of targets) probes.set(t, await probe(t));\n\n // One bounded retry for every miss — a hydration-slow page mounts content a\n // beat after load, and a stale first probe would mislabel targets that ARE\n // in the initial DOM (only the cold grading below turns a miss into an\n // error; the retry just keeps both tiers honest).\n const misses = targets.filter((t) => !probes.get(t)?.err && !probes.get(t)?.count);\n if (misses.length) {\n await sleep(opts?.retryMs ?? 1500);\n for (const t of misses) probes.set(t, await probe(t));\n }\n\n const issues: PrecheckIssue[] = [];\n // Late-bound misses are EXPECTED on a healthy plan (every post-reveal step\n // has one), so they aggregate into a single advisory instead of one line\n // per step — per-step warnings on a good plan would train authors to\n // scroll past this section, which is how warnings die.\n const lateMisses: TargetSpec[] = [];\n for (const t of targets) {\n const p = probes.get(t) ?? {};\n const path = `steps[${t.step}].${t.field}`;\n const name = `${t.action} ${JSON.stringify(t.value)}`;\n if (p.err) {\n issues.push({\n severity: \"error\",\n path,\n message: `${name}: invalid selector — the page rejected it (${p.err})`,\n fix: \"fix the selector syntax; the capture would skip every use of it\",\n });\n continue;\n }\n if (!p.count) {\n if (t.revealOnly) continue; // exists only after the press, by design\n if (t.cold) {\n issues.push({\n severity: \"error\",\n path,\n message:\n `${name}: target not found in the page as loaded — this step runs before anything ` +\n `has changed the page, so it is CERTAIN to be skipped. Refusing in seconds what ` +\n `would fail after the full capture.`,\n fix:\n \"point it at an element that exists at load (`open-take inspect <url>` lists them), \" +\n \"or move it after the step that reveals it\",\n });\n } else {\n lateMisses.push(t);\n }\n continue;\n }\n // C3.5 — the target RESOLVES, so the existence check above stays quiet,\n // but it resolves to a different node than the element in <main> that\n // actually carries this name: the by-text lookup only queries the\n // action's clickable candidate set, so a headline's words match whatever\n // clickable merely CONTAINS them (measured: a sidebar page-thumbnail,\n // whose click navigates — the defect that sank a whole take). A cold\n // mismatch is a certainty by construction; a late one is graded on the\n // initial DOM, so it stays a warning. Three more conditions narrow the\n // ERROR tier to the shape that was actually measured — every one of the\n // 23 poisoned targets in the validation corpus is a SUBSTRING pick,\n // landing OUTSIDE <main>, whose value is a sliver of the picked blob's\n // name (share < 0.5) — so requiring all three costs no recall while\n // sparing the realistic look-alikes: a topbar control whose exact label\n // an in-main heading shares, an ABBREVIATED label (\"Comments\" naming the\n // header's \"Comments3\" badge button, \"Start free trial\" naming\n // \"Start free trial →\"), and two in-main elements far apart.\n // A press reveal target names what the ZOOM should frame AFTER the press,\n // so — like the miss above — the initial DOM says nothing about it.\n if (t.kind === \"text\" && !t.revealOnly) {\n const mm = parseIntentMismatch(p);\n if (mm) {\n const certain =\n t.cold &&\n p.how === \"substring\" &&\n !mm.pick.inMain &&\n (p.pickNameShare ?? 0) < ABBREVIATION_SHARE;\n issues.push({\n severity: certain ? \"error\" : \"warn\",\n path,\n message:\n `${name}: resolves to the WRONG element. The by-text lookup for ${t.action} ` +\n `searches only its candidate set and ${p.how === \"substring\" ? \"substring-\" : \"\"}matched a ` +\n `${mm.pick.w}x${mm.pick.h} ${mm.pick.tag.toLowerCase()} at (${mm.pick.x},${mm.pick.y})` +\n `${mm.pick.inMain ? \"\" : \" OUTSIDE <main>\"}` +\n `${p.pickName ? ` (its actual name: ${JSON.stringify(p.pickName)})` : \"\"}, ` +\n `while the element named ` +\n `${JSON.stringify(t.value.slice(0, 40))} is a ${mm.intended.tag.toLowerCase()} at ` +\n `(${mm.intended.x},${mm.intended.y}) inside <main>. The step would land on the impostor.`,\n fix:\n `target the in-main ${mm.intended.tag.toLowerCase()} with a CSS selector scoped to ` +\n \"`main` (`open-take inspect <url>` lists one), or name a real control instead\",\n });\n continue;\n }\n }\n if (t.kind === \"selector\" && (p.count ?? 0) > 1) {\n const z =\n p.first && (p.first.w === 0 || p.first.h === 0)\n ? \" — and the first match is ZERO-SIZE\"\n : \"\";\n issues.push({\n severity: \"warn\",\n path,\n message:\n `${name}: matches ${p.count} nodes; the engine takes the FIRST in document order${z}. ` +\n `A sidebar thumbnail or an off-screen clone outranking the real element is exactly ` +\n `how a whole take dies.`,\n fix: \"qualify the selector until it matches once (e.g. scope it to `main`)\",\n });\n continue;\n }\n if (t.kind === \"text\" && (p.exact ?? 0) > 1) {\n issues.push({\n severity: \"warn\",\n path,\n message: `${name}: ${p.exact} elements carry this exact accessible name; the engine takes the first in document order`,\n fix: \"use a more specific name, or a CSS selector scoped to the intended region\",\n });\n continue;\n }\n if (p.first && (p.first.w === 0 || p.first.h === 0)) {\n // graded on the page as loaded: after a step that changes the page,\n // no size usually means \"hidden until then\" (a later step of a form),\n // which is fine — only a target the page has to show at load is certain\n // to have nowhere to land\n issues.push({\n severity: \"warn\",\n path,\n message: t.cold\n ? `${name}: resolves to a zero-size element — the cursor has nowhere real to land`\n : `${name}: has no size in the page as loaded (hidden until an earlier step shows it?) — fine if one does; if none does, the step lands on nothing`,\n });\n }\n }\n if (lateMisses.length) {\n issues.push({\n severity: \"warn\",\n path: \"steps\",\n message:\n `${lateMisses.length} target${lateMisses.length === 1 ? \" is\" : \"s are\"} not in the initial DOM ` +\n `(${lateMisses.map((t) => `steps[${t.step}] ${JSON.stringify(t.value)}`).join(\", \")}) — ` +\n `fine if earlier steps reveal them; any that never appears is SKIPPED at capture time ` +\n `(and the run exits non-zero)`,\n });\n }\n return issues;\n}\n","// Product audio — the sounds the app itself makes while a take is recorded.\n//\n// The CDP screencast carries pictures only, so a film that wants the\n// product's REAL clicks, chimes and notes had nothing to work with. This\n// module records them in-page and hands them to the runtime:\n//\n// 1. An init script (runs before the page's own scripts, in every document\n// a take visits) wraps AudioNode.prototype.connect/disconnect. Whenever\n// a node is connected to an AudioContext's destination, it is ALSO\n// connected to a private tap in that context; the destination itself is\n// never replaced, so library code that inspects it sees the real node.\n// HTMLMediaElement.play is wrapped the same way: a playing <audio>/<video>\n// is tapped through captureStream(), which does not change its output.\n// 2. Each tap is a ScriptProcessor that forwards only NON-SILENT blocks,\n// stamped with the wall-clock time the page produced them (the browser's\n// AudioContext.getOutputTimestamp, less the capturing device's own output\n// latency) and with their frame on the context's own sample clock,\n// through a CDP binding. Buffers it never got (a busy main thread) are\n// reported as a gap, not hidden.\n// 3. At the end of the take the runtime mixes every block onto the capture\n// timeline — sample 0 is the take's t0, the same zero every event tMs\n// and the capture video use — and writes product-audio.wav (32-bit float,\n// unclipped) plus product-sound.json describing how it was placed.\n//\n// Cost on a silent page: one prototype patch and a CDP binding — no node is\n// created until the page connects something to its speakers, and silent\n// blocks never cross the wire. Every part is guarded: a failure anywhere is a\n// warning and no file, never a failed take.\n//\n// Alongside, the audio files the page FETCHED (audio/* responses, or a URL\n// with an audio extension) are listed in product-sound.json, and small ones\n// are saved to product-sounds/ so a film can load the product's own sound\n// pack directly.\n\nimport { mkdirSync, writeFileSync } from \"node:fs\";\nimport { basename, join } from \"node:path\";\nimport type { CDP } from \"./cdp\";\n\n/** the CDP binding the page posts blocks through */\nexport const PRODUCT_AUDIO_BINDING = \"__openTakeProductAudio\";\n\n/** Saved fetched sound files: per file and in total. Larger ones are only listed. */\nconst MAX_SAVED_FILE_BYTES = 8 * 1024 * 1024;\nconst MAX_SAVED_TOTAL_BYTES = 48 * 1024 * 1024;\nconst MAX_LISTED_FILES = 200;\n\nconst AUDIO_EXT = /\\.(mp3|wav|wave|ogg|oga|opus|m4a|aac|flac|weba|caf|aif|aiff)(?:$|[?#])/i;\n\n// The in-page half. Plain ES2017, no template literals inside (it is itself\n// one). Never throws into the page: every wrapper calls the original FIRST and\n// returns its result, and the tap work after it is try/caught.\nexport const PRODUCT_AUDIO_INIT_JS = `(() => {\n if (window.__openTakeAudioTap || typeof AudioNode === \"undefined\") return;\n window.__openTakeAudioTap = true;\n var NAME = ${JSON.stringify(PRODUCT_AUDIO_BINDING)};\n var post = function (s) { try { var f = window[NAME]; if (typeof f === \"function\") f(s); } catch (e) {} };\n var connect = AudioNode.prototype.connect;\n var disconnect = AudioNode.prototype.disconnect;\n var taps = new WeakMap();\n var nextId = 0;\n var DOC = Math.random().toString(36).slice(2, 10);\n var toB64 = function (f32) {\n var u8 = new Uint8Array(f32.buffer), s = \"\";\n for (var i = 0; i < u8.length; i += 0x8000) s += String.fromCharCode.apply(null, u8.subarray(i, i + 0x8000));\n return btoa(s);\n };\n // Wall-clock ms at which the page's audio graph PRODUCED context time t:\n // the output timestamp pairs a context time with the moment it leaves the\n // speakers, and the output device's own latency (outputLatency) is taken\n // back off — that delay belongs to the capturing browser (its fake output,\n // see launchBrowser, reports ~16 ms), not to the product, and a film's own\n // playback adds its own. Right after a context starts it reports\n // contextTime 0 (not yet paired): then \"now\" plus the base latency.\n var producedAt = function (ctx, t) {\n var o = null;\n try { o = ctx.getOutputTimestamp(); } catch (e) {}\n if (o && o.contextTime > 0 && o.performanceTime > 0)\n return performance.timeOrigin + o.performanceTime + (t - o.contextTime - (ctx.outputLatency || 0)) * 1000;\n return performance.timeOrigin + performance.now() + (t - ctx.currentTime + (ctx.baseLatency || 0)) * 1000;\n };\n var tapFor = function (ctx, kind) {\n if (taps.has(ctx)) return taps.get(ctx);\n var t = null;\n try {\n if (typeof AudioContext !== \"undefined\" && ctx instanceof AudioContext) {\n var bus = ctx.createGain();\n var sp = ctx.createScriptProcessor(4096, 2, 2);\n connect.call(bus, sp);\n connect.call(sp, ctx.destination);\n var id = DOC + \".\" + ++nextId;\n post(\"S \" + id + \" \" + ctx.sampleRate + \" \" + kind + \" \" + (ctx.baseLatency || 0));\n var next = -1;\n sp.onaudioprocess = function (e) {\n try {\n // a buffer the main thread was too busy to take is skipped, and\n // its sound is lost to the tap (the page itself still played it)\n var span = e.inputBuffer.length / ctx.sampleRate;\n if (next >= 0 && e.playbackTime - next > span / 2)\n post(\"G \" + id + \" \" + producedAt(ctx, next - 2 * span).toFixed(3) + \" \" + ((e.playbackTime - next) * 1000).toFixed(0));\n next = e.playbackTime + span;\n var ob = e.outputBuffer;\n for (var c = 0; c < ob.numberOfChannels; c++) ob.getChannelData(c).fill(0);\n var ib = e.inputBuffer, n = ib.length;\n var L = ib.getChannelData(0), R = ib.numberOfChannels > 1 ? ib.getChannelData(1) : L;\n var peak = 0;\n for (var i = 0; i < n; i++) { var a = L[i] < 0 ? -L[i] : L[i], b = R[i] < 0 ? -R[i] : R[i]; if (a > peak) peak = a; if (b > peak) peak = b; }\n if (peak < 1e-5) return;\n var f = new Float32Array(n * 2);\n for (var j = 0; j < n; j++) { f[2 * j] = L[j]; f[2 * j + 1] = R[j]; }\n // a ScriptProcessor hands over its input two buffers before the\n // playbackTime it reports (Chrome double-buffers it): the block's\n // audio is the graph's output at playbackTime - 2 * n / rate. The\n // block's frame on the context's own sample clock goes along, so\n // the runtime can lay consecutive blocks sample-exactly end to end\n // (the wall-clock estimate jitters by a few samples per block).\n var at = e.playbackTime - (2 * n) / ctx.sampleRate;\n post(\"B \" + id + \" \" + producedAt(ctx, at).toFixed(3) + \" \" + ((ctx.outputLatency || 0) * 1000).toFixed(1) + \" \" + Math.round(at * ctx.sampleRate) + \" \" + toB64(f));\n } catch (err) {}\n };\n t = { bus: bus, sp: sp };\n }\n } catch (e) { t = null; }\n taps.set(ctx, t);\n return t;\n };\n AudioNode.prototype.connect = function (dest) {\n var r = connect.apply(this, arguments);\n try {\n if (dest instanceof AudioDestinationNode) {\n var t = tapFor(this.context, \"webaudio\");\n if (t && t.bus !== this) connect.call(this, t.bus, arguments.length > 1 ? arguments[1] : 0);\n }\n } catch (e) {}\n return r;\n };\n AudioNode.prototype.disconnect = function (dest) {\n var r = disconnect.apply(this, arguments);\n try {\n if (dest instanceof AudioDestinationNode) {\n var t = taps.get(this.context);\n if (t) { try { arguments.length > 1 ? disconnect.call(this, t.bus, arguments[1]) : disconnect.call(this, t.bus); } catch (e) {} }\n }\n } catch (e) {}\n return r;\n };\n // <audio>/<video>: captureStream() leaves the element's own output alone —\n // but it also ignores the element's muted/volume, so each element's tap goes\n // through a gain that follows them (a muted hero video stays unheard). An\n // element the page routes into its own graph (createMediaElementSource) is\n // already heard at that graph's speakers, so its stream tap is silenced.\n var mediaCtx = null;\n var tappedMedia = new WeakSet();\n var routed = new WeakSet();\n var mediaGains = new WeakMap();\n var follow = function (el) {\n var g = mediaGains.get(el);\n if (g) { try { g.gain.value = routed.has(el) || el.muted ? 0 : el.volume; } catch (e) {} }\n };\n if (typeof AudioContext !== \"undefined\" && AudioContext.prototype.createMediaElementSource) {\n var cmes = AudioContext.prototype.createMediaElementSource;\n AudioContext.prototype.createMediaElementSource = function (el) {\n var r = cmes.apply(this, arguments);\n try { routed.add(el); follow(el); } catch (e) {}\n return r;\n };\n }\n var tapMedia = function (el) {\n if (!el || tappedMedia.has(el) || routed.has(el) || typeof el.captureStream !== \"function\") return;\n tappedMedia.add(el);\n var stream;\n try { stream = el.captureStream(); } catch (e) { return; }\n var attached = false;\n var attach = function () {\n try {\n if (attached || !stream.getAudioTracks().length) return;\n attached = true;\n stream.getVideoTracks().forEach(function (v) { try { v.stop(); } catch (e) {} });\n if (!mediaCtx) mediaCtx = new AudioContext();\n if (mediaCtx.state === \"suspended\") mediaCtx.resume().catch(function () {});\n var t = tapFor(mediaCtx, \"media\");\n if (!t) return;\n var g = mediaCtx.createGain();\n mediaGains.set(el, g);\n follow(el);\n el.addEventListener(\"volumechange\", function () { follow(el); });\n connect.call(mediaCtx.createMediaStreamSource(stream), g);\n connect.call(g, t.bus);\n } catch (e) {}\n };\n attach();\n try { stream.addEventListener(\"addtrack\", attach); } catch (e) {}\n };\n var play = HTMLMediaElement.prototype.play;\n HTMLMediaElement.prototype.play = function () {\n var r = play.apply(this, arguments);\n try { tapMedia(this); } catch (e) {}\n return r;\n };\n // autoplay (and any play the wrapper above did not see) still fires \"play\"\n try { window.addEventListener(\"play\", function (e) { try { if (e.target instanceof HTMLMediaElement) tapMedia(e.target); } catch (x) {} }, true); } catch (e) {}\n})();`;\n\n/** A source = one AudioContext in one document: \"<document tag>.<n>\", so\n * contexts of a later page (after a navigation) or of an iframe never share\n * a key — each has its own sample clock. */\ntype SourceKey = string | number;\n\n/** One forwarded block: produced at `producedMs` (wall clock), interleaved\n * stereo; `ctxFrame` = its first frame on its source's own sample clock. */\ntype Block = { src: SourceKey; producedMs: number; ctxFrame?: number; samples: Float32Array };\ntype Source = {\n id: SourceKey;\n sampleRate: number;\n kind: \"webaudio\" | \"media\";\n baseLatencyMs: number;\n outputLatencyMs: number;\n};\n\nexport type FetchedSound = {\n url: string;\n mimeType: string;\n status: number;\n /** bytes on the wire, when the response finished loading */\n bytes?: number;\n /** take-relative path of the saved copy (`product-sounds/…`), when saved */\n saved?: string;\n};\n\nexport type ProductSoundReport = {\n /** the mix of everything the page sent to its speakers, or null when the\n * page made no sound the tap could hear */\n audio: null | {\n file: string;\n sampleRate: number;\n channels: 2;\n format: \"float32\";\n /** capture-timeline ms of the WAV's first sample (the take's t0) */\n startMs: number;\n durationMs: number;\n /** capture-timeline ms ranges where the product made sound (blocks of\n * ~85 ms; adjacent blocks merged) */\n soundAt: Array<[number, number]>;\n peakDbfs: number;\n /** how the sound was put on the capture timeline */\n placement: string;\n sources: Array<Omit<Source, \"id\">>;\n };\n /** audio files the page fetched */\n files: FetchedSound[];\n /** what could not be done (the take itself is unaffected) */\n notes: string[];\n};\n\nexport type ProductAudioRecorder = {\n /** stop listening and write what was heard; never throws */\n finish(opts: { t0: number; endMs: number; dir: string }): Promise<ProductSoundReport | null>;\n};\n\n/** Start listening on the capture page. Call BEFORE the first navigation so\n * the init script runs ahead of the page's own scripts. Never throws: a\n * failure to install returns a recorder that reports why. */\nexport async function startProductAudio(cdp: CDP): Promise<ProductAudioRecorder> {\n const notes: string[] = [];\n const sources = new Map<SourceKey, Source>();\n const blocks: Block[] = [];\n const lost: Array<{ producedMs: number; ms: number }> = [];\n let listening = true;\n let installed = false;\n try {\n await cdp.send(\"Runtime.addBinding\", { name: PRODUCT_AUDIO_BINDING });\n cdp.on<{ name: string; payload: string }>(\"Runtime.bindingCalled\", (p) => {\n if (!listening || p.name !== PRODUCT_AUDIO_BINDING) return;\n const s = p.payload;\n const parts = s.split(\" \", 6);\n if (parts[0] === \"S\") {\n sources.set(parts[1]!, {\n id: parts[1]!,\n sampleRate: Number(parts[2]),\n kind: parts[3] === \"media\" ? \"media\" : \"webaudio\",\n baseLatencyMs: round1(Number(parts[4]) * 1000),\n outputLatencyMs: 0,\n });\n } else if (parts[0] === \"G\") {\n // \"G <src> <producedMs> <lostMs>\": buffers the tap never received\n lost.push({ producedMs: Number(parts[2]), ms: Number(parts[3]) });\n } else if (parts[0] === \"B\") {\n // \"B <src> <producedMs> <outputLatencyMs> <ctxFrame> <base64>\"\n const src = parts[1]!;\n const source = sources.get(src);\n if (source)\n source.outputLatencyMs = Math.max(source.outputLatencyMs, round1(Number(parts[3])));\n let at = 0;\n for (let k = 0; k < 5; k++) at = s.indexOf(\" \", at) + 1;\n const buf = Buffer.from(s.slice(at), \"base64\");\n const samples = new Float32Array(Math.floor(buf.length / 8) * 2);\n for (let k = 0; k < samples.length; k++) samples[k] = buf.readFloatLE(k * 4);\n const ctxFrame = Number(parts[4]);\n blocks.push({\n src,\n producedMs: Number(parts[2]),\n ...(Number.isFinite(ctxFrame) ? { ctxFrame } : {}),\n samples,\n });\n }\n });\n await cdp.send(\"Page.addScriptToEvaluateOnNewDocument\", { source: PRODUCT_AUDIO_INIT_JS });\n installed = true;\n } catch (e) {\n notes.push(`product audio tap not installed (${(e as Error).message})`);\n }\n\n // fetched sound files — listed as they arrive; their bodies are read only\n // at the end, so a page that preloads a whole sample library does not put\n // megabytes on the capture's CDP socket while frames are streaming\n const responses = new Map<string, FetchedSound>();\n const finished = new Set<string>();\n try {\n await cdp.send(\"Network.enable\", {});\n cdp.on<{\n requestId: string;\n response: { url: string; mimeType?: string; status: number };\n }>(\"Network.responseReceived\", (p) => {\n if (!listening || responses.size >= MAX_LISTED_FILES) return;\n const { url, mimeType = \"\", status } = p.response;\n if (!/^https?:|^file:/i.test(url)) return;\n if (!/^audio\\//i.test(mimeType) && !AUDIO_EXT.test(url)) return;\n responses.set(p.requestId, { url, mimeType, status });\n });\n cdp.on<{ requestId: string; encodedDataLength?: number }>(\"Network.loadingFinished\", (p) => {\n const r = responses.get(p.requestId);\n if (!r) return;\n if (p.encodedDataLength != null) r.bytes = Math.round(p.encodedDataLength);\n finished.add(p.requestId);\n });\n } catch (e) {\n notes.push(`fetched sound files not listed (${(e as Error).message})`);\n }\n\n return {\n async finish({ t0, endMs, dir }) {\n listening = false;\n try {\n const files = await saveFetched(cdp, responses, finished, dir, notes);\n let audio: ProductSoundReport[\"audio\"] = null;\n const gaps = lost\n .map((g) => ({ at: Math.round(g.producedMs - t0), ms: g.ms }))\n .filter((g) => Number.isFinite(g.at) && g.at < endMs && g.at + g.ms > 0);\n if (blocks.length && gaps.length)\n notes.push(\n `the tap missed ${Math.round(gaps.reduce((a, g) => a + g.ms, 0))} ms of the page's audio while its main thread was busy (any sound there is missing from product-audio.wav; the page itself played it) — at ${gaps\n .slice(0, 8)\n .map((g) => `${g.at}+${g.ms} ms`)\n .join(\", \")}${gaps.length > 8 ? \", …\" : \"\"}`,\n );\n if (installed && blocks.length) {\n try {\n audio = writeMix(blocks, sources, t0, endMs, join(dir, \"product-audio.wav\"));\n } catch (e) {\n notes.push(`product audio not written (${(e as Error).message})`);\n }\n }\n if (!audio && !files.length && !notes.length) return null;\n const report: ProductSoundReport = { audio, files, notes };\n writeFileSync(join(dir, \"product-sound.json\"), `${JSON.stringify(report, null, 2)}\\n`);\n return report;\n } catch (e) {\n console.error(`product audio: nothing written (${(e as Error).message})`);\n return null;\n }\n },\n };\n}\n\nconst round1 = (n: number): number => (Number.isFinite(n) ? Math.round(n * 10) / 10 : 0);\n\nasync function saveFetched(\n cdp: CDP,\n responses: Map<string, FetchedSound>,\n finished: Set<string>,\n dir: string,\n notes: string[],\n): Promise<FetchedSound[]> {\n const out: FetchedSound[] = [];\n const used = new Set<string>();\n const seen = new Set<string>();\n let total = 0;\n let timedOut = false;\n // reading bodies gets a few seconds, never the take's time\n const deadline = Date.now() + 5000;\n for (const [id, r] of responses) {\n if (seen.has(r.url)) continue;\n seen.add(r.url);\n let body: Buffer | null = null;\n if (finished.has(id) && r.status === 200 && (r.bytes ?? 0) <= MAX_SAVED_FILE_BYTES) {\n if (Date.now() > deadline) timedOut = true;\n else\n body = await Promise.race([\n cdp\n .send<{ body: string; base64Encoded: boolean }>(\"Network.getResponseBody\", {\n requestId: id,\n })\n .then((b) => Buffer.from(b.body, b.base64Encoded ? \"base64\" : \"utf8\"))\n .catch(() => null),\n // a body that never comes cannot hold the take up past the deadline\n new Promise<null>((r) =>\n setTimeout(() => r(null), Math.max(0, deadline - Date.now())).unref(),\n ),\n ]);\n }\n if (body?.length && total + body.length <= MAX_SAVED_TOTAL_BYTES) {\n const name = uniqueName(r.url, used);\n mkdirSync(join(dir, \"product-sounds\"), { recursive: true });\n writeFileSync(join(dir, \"product-sounds\", name), body);\n total += body.length;\n out.push({ ...r, bytes: r.bytes ?? body.length, saved: `product-sounds/${name}` });\n } else out.push(r);\n }\n if (timedOut)\n notes.push(\"some fetched sound files are listed but not saved (ran out of time reading them)\");\n return out;\n}\n\n/** `https://x/sounds/click/1.wav?v=3` → `sounds-click-1.wav` (deduped). */\nexport function uniqueName(url: string, used: Set<string>): string {\n let path: string;\n try {\n path = decodeURIComponent(new URL(url).pathname);\n } catch {\n path = url;\n }\n const segs = path.split(\"/\").filter(Boolean).slice(-3);\n let name = (segs.join(\"-\") || \"sound\").replace(/[^A-Za-z0-9._-]+/g, \"_\").slice(-120);\n if (!/\\.[A-Za-z0-9]{2,5}$/.test(name)) name += \".audio\";\n let candidate = name;\n for (let i = 2; used.has(candidate.toLowerCase()); i++) {\n const dot = name.lastIndexOf(\".\");\n candidate = `${name.slice(0, dot)}-${i}${name.slice(dot)}`;\n }\n used.add(candidate.toLowerCase());\n return basename(candidate);\n}\n\n/** Mix the blocks onto the capture timeline and write a float WAV. Exported\n * for the unit test; `producedMs` and `t0` share one wall clock (the page's\n * performance.timeOrigin and the runtime's Date.now are both epoch ms on the\n * same machine). */\nexport function mixBlocks(\n blocks: Array<{ src: SourceKey; producedMs: number; ctxFrame?: number; samples: Float32Array }>,\n sources: Map<SourceKey, { sampleRate: number }>,\n t0: number,\n endMs: number,\n): {\n sampleRate: number;\n pcm: Float32Array;\n soundAt: Array<[number, number]>;\n peak: number;\n} {\n // the rate most of the sound arrived at; anything else is resampled to it\n const weight = new Map<number, number>();\n for (const b of blocks) {\n const sr = sources.get(b.src)?.sampleRate ?? 48000;\n weight.set(sr, (weight.get(sr) ?? 0) + b.samples.length);\n }\n const sampleRate = [...weight.entries()].sort((a, b) => b[1] - a[1])[0]?.[0] ?? 48000;\n const frames = Math.max(1, Math.ceil((Math.max(endMs, 0) / 1000) * sampleRate));\n const pcm = new Float32Array(frames * 2);\n const spans: Array<[number, number]> = [];\n const startOf = placeOnSourceClocks(blocks, sources);\n for (const b of blocks) {\n const sr = sources.get(b.src)?.sampleRate ?? sampleRate;\n const n = b.samples.length / 2;\n const placed = startOf.get(b);\n if (placed === null) continue;\n const startMs = (placed ?? b.producedMs) - t0;\n const durMs = (n / sr) * 1000;\n if (startMs + durMs <= 0 || startMs >= endMs) continue;\n spans.push([startMs, startMs + durMs]);\n const ratio = sr / sampleRate;\n const first = Math.round((startMs / 1000) * sampleRate);\n const count = Math.floor(n / ratio);\n for (let k = 0; k < count; k++) {\n const o = first + k;\n if (o < 0) continue;\n if (o >= frames) break;\n const x = k * ratio;\n const i = Math.floor(x);\n const f = x - i;\n const j = Math.min(i + 1, n - 1);\n pcm[2 * o] = pcm[2 * o]! + b.samples[2 * i]! * (1 - f) + b.samples[2 * j]! * f;\n pcm[2 * o + 1] =\n pcm[2 * o + 1]! + b.samples[2 * i + 1]! * (1 - f) + b.samples[2 * j + 1]! * f;\n }\n }\n let peak = 0;\n for (let i = 0; i < pcm.length; i++) peak = Math.max(peak, Math.abs(pcm[i]!));\n spans.sort((a, b) => a[0] - b[0]);\n const soundAt: Array<[number, number]> = [];\n for (const [a, b] of spans) {\n const last = soundAt[soundAt.length - 1];\n if (last && a <= last[1] + 30) last[1] = Math.max(last[1], b);\n else soundAt.push([a, b]);\n }\n return {\n sampleRate,\n pcm,\n soundAt: soundAt.map(([a, b]) => [Math.max(0, Math.round(a)), Math.min(endMs, Math.round(b))]),\n peak,\n };\n}\n\n/** Wall-clock start of each block that carries its source-clock frame.\n * Each block's own wall-clock estimate jitters by a few samples, which laid\n * end to end leaves 1-2 sample overlaps (spikes) and holes (dropouts) at\n * every ~85 ms boundary. So per source, blocks whose clock offset (wall ms −\n * source-clock ms) agrees within OFFSET_JUMP_MS form a run that shares ONE\n * offset — the run's median — and sit sample-exactly on the source's clock;\n * a larger jump (a suspend/resume, an output restart) starts a new run.\n * After a main-thread stall Chrome hands over a few buffers stamped with one\n * stale playbackTime, overlapping the steady chain that follows; a block that\n * runs into the next one on its own clock is such a stamp and is dropped\n * (null) rather than summed into a spike. */\nconst OFFSET_JUMP_MS = 10;\nfunction placeOnSourceClocks<\n B extends { src: SourceKey; producedMs: number; ctxFrame?: number; samples: Float32Array },\n>(blocks: B[], sources: Map<SourceKey, { sampleRate: number }>): Map<B, number | null> {\n const out = new Map<B, number | null>();\n const bySrc = new Map<SourceKey, B[]>();\n for (const b of blocks) {\n if (b.ctxFrame == null || !sources.get(b.src)) continue;\n const list = bySrc.get(b.src) ?? [];\n list.push(b);\n bySrc.set(b.src, list);\n }\n for (const [src, list] of bySrc) {\n const sr = sources.get(src)!.sampleRate;\n list.sort((a, b) => a.ctxFrame! - b.ctxFrame!);\n const offset = (b: B) => b.producedMs - (b.ctxFrame! / sr) * 1000;\n let run: B[] = [];\n const close = () => {\n if (!run.length) return;\n const offs = run.map(offset).sort((a, b) => a - b);\n // whole source samples, so every block of the run rounds the same way\n const mid = Math.round((offs[Math.floor(offs.length / 2)]! * sr) / 1000);\n for (const b of run) out.set(b, ((mid + b.ctxFrame!) / sr) * 1000);\n run = [];\n };\n for (let i = 0; i < list.length; i++) {\n const b = list[i]!;\n const next = list[i + 1];\n if (next && next.ctxFrame! < b.ctxFrame! + b.samples.length / 2) {\n out.set(b, null);\n continue;\n }\n const last = run[run.length - 1];\n if (last && Math.abs(offset(b) - offset(last)) > OFFSET_JUMP_MS) close();\n run.push(b);\n }\n close();\n }\n return out;\n}\n\nfunction writeMix(\n blocks: Block[],\n sources: Map<SourceKey, Source>,\n t0: number,\n endMs: number,\n path: string,\n): NonNullable<ProductSoundReport[\"audio\"]> {\n const mix = mixBlocks(blocks, sources, t0, endMs);\n writeFileSync(path, floatWav(mix.pcm, mix.sampleRate, 2));\n return {\n file: \"product-audio.wav\",\n sampleRate: mix.sampleRate,\n channels: 2,\n format: \"float32\",\n startMs: 0,\n durationMs: Math.round(endMs),\n soundAt: mix.soundAt,\n peakDbfs: mix.peak > 0 ? Math.round(20 * Math.log10(mix.peak) * 10) / 10 : -Infinity,\n placement:\n \"estimated: each ~85 ms block is placed where the browser's audio clock says the page \" +\n \"produced it (AudioContext.getOutputTimestamp, less the output latency the capturing \" +\n \"browser reports for its own device — see sources[].outputLatencyMs); sample 0 = capture \" +\n \"t0, the zero of every event tMs and of capture.mp4. Blocks of one AudioContext sit \" +\n \"sample-exactly end to end on that context's own clock (one clock offset per run, the \" +\n \"median of its blocks). The product's own delay between an \" +\n \"input and its sound is kept. A context's first sound can come late while the browser \" +\n \"starts its audio output.\",\n sources: [...sources.values()].map(({ id: _id, ...s }) => s),\n };\n}\n\n/** IEEE-float WAV (format 3), interleaved. */\nexport function floatWav(pcm: Float32Array, sampleRate: number, channels: number): Buffer {\n const data = Buffer.from(pcm.buffer, pcm.byteOffset, pcm.byteLength);\n const h = Buffer.alloc(44);\n h.write(\"RIFF\", 0);\n h.writeUInt32LE(36 + data.length, 4);\n h.write(\"WAVE\", 8);\n h.write(\"fmt \", 12);\n h.writeUInt32LE(16, 16);\n h.writeUInt16LE(3, 20);\n h.writeUInt16LE(channels, 22);\n h.writeUInt32LE(sampleRate, 24);\n h.writeUInt32LE(sampleRate * channels * 4, 28);\n h.writeUInt16LE(channels * 4, 32);\n h.writeUInt16LE(32, 34);\n h.write(\"data\", 36);\n h.writeUInt32LE(data.length, 40);\n return Buffer.concat([h, data]);\n}\n","// Capture-side settle: stop BETTING that the page finished inside settleMs.\n//\n// Every hold in cdp-capture.ts used to be `sleep(step.settleMs ?? N)` — a\n// fixed guess authored before the app was ever run. Two different jobs were\n// riding on that one number:\n//\n// 1. the EDITORIAL hold — how long the result stays on screen so a viewer\n// can read it. That is a taste call and belongs in the plan.\n// 2. the bet that the page had actually finished rendering by then. That is\n// not a taste call, it is a fact about the app, and guessing it wrong\n// captures the NEXT beat against a half-built page: a stale bbox, a click\n// into a button that has not mounted, a payoff frame that shows a spinner.\n//\n// This module keeps (1) exactly as it was and MEASURES (2). `settle()` runs\n// the editorial hold in full and only then, if the page is still visibly\n// working, keeps waiting — up to a budget. So a settled app pays one CDP\n// round-trip and nothing changes; a slow app gets the time it actually needs,\n// and the capture REPORTS what it needed so the next plan can stop guessing.\n//\n// It can only ever ADD time, never cut a hold short: a shortened hold would\n// silently degrade the video, which is a worse failure than waiting.\n//\n// WHAT IT SEES: DOM mutations, in-flight fetch/XHR, running finite animations,\n// pending short setTimeouts, and document.readyState. WHAT IT DOES NOT SEE:\n// repaints inside a <canvas> or <video> — no DOM signal exists for those (the\n// same blind spot that made frame-diff.ts a pixel pass).\n//\n// Timers earn their place: the commonest slow beat is not a request in flight,\n// it is \"render a skeleton now, swap in the real thing on a timer\", and DOM /\n// network / animation are all quiet across that gap. Two guards keep the\n// signal from turning into a permanent \"busy\": only timers under\n// TIMER_MAX_MS count (a 5s poll loop is the page's heartbeat, not this beat's\n// work), and infinite-iteration animations (spinners, pulses) are ignored\n// outright — they never end, so counting them would spend the whole budget on\n// every beat of any page that has one.\n\nimport type { CDP } from \"./cdp\";\n\nconst sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));\n\n/** Extra time a hold may spend waiting for a busy page, per beat. Generous\n * enough for a slow round-trip, short enough that a page which NEVER goes\n * quiet (a live clock, a polling dashboard) costs a bounded, reported amount\n * rather than stretching the take without explanation. */\nexport const DEFAULT_SETTLE_BUDGET_MS = 1200;\n/** The page must have been still this long to count as settled — one paint\n * plus slack, so a mutation and the layout it triggers aren't read as two\n * separate quiet periods. */\nconst QUIET_MS = 120;\nconst POLL_MS = 60;\n/** A pending setTimeout longer than this is the page's own heartbeat (a poll\n * loop, a session timer), not this beat finishing. Counting it would make the\n * page look permanently busy. */\nconst TIMER_MAX_MS = 2000;\n/** Grace on a timer's own deadline before it stops counting as pending. Errs\n * SHORT on purpose: expiring early costs the old behaviour (a beat that may\n * be captured a touch soon), expiring late costs dead air in the cut on\n * every remaining beat — a much worse trade. */\nconst TIMER_SLACK_MS = 250;\n/** A <canvas>/<video> covering this much of the frame makes the probe\n * effectively blind for that beat: the element never changes size, position\n * or attributes no matter what is painted inside it, so \"the page is done\"\n * is unanswerable. Set low on purpose — a needless note costs a line of\n * output, a missed one costs an author trusting a quiet run that proved\n * nothing. */\nexport const PAINT_BLIND_FRAC = 0.2;\n\n/** Installed once per document; keeps `t` at the last moment anything moved. */\nconst PROBE_INSTALL_JS = `(() => {\n if (window.__openTakeActivity) return;\n const TIMER_MAX = ${TIMER_MAX_MS}, TIMER_SLACK = ${TIMER_SLACK_MS};\n const A = { t: 0, net: 0, timers: 0 };\n const touch = () => { A.t = performance.now(); };\n touch();\n try {\n new MutationObserver(touch).observe(document, {\n subtree: true, childList: true, attributes: true, characterData: true,\n });\n } catch (e) {}\n try {\n const of = window.fetch;\n if (typeof of === \"function\")\n window.fetch = function () {\n A.net++; touch();\n let p;\n try { p = of.apply(window, arguments); } catch (e) { A.net--; throw e; }\n return Promise.resolve(p).then(\n (r) => { A.net--; touch(); return r; },\n (e) => { A.net--; touch(); throw e; },\n );\n };\n } catch (e) {}\n try {\n const os = XMLHttpRequest.prototype.send;\n if (typeof os === \"function\")\n XMLHttpRequest.prototype.send = function () {\n A.net++; touch();\n // send() throws on API misuse (send before open, send after abort) and\n // then NO request exists, so loadend never fires — without this the\n // increment is permanent and the page reads busy for the rest of the\n // take. Same guard the fetch branch above already has.\n try { this.addEventListener(\"loadend\", () => { A.net--; touch(); }); } catch (e) {}\n try { return os.apply(this, arguments); } catch (e) { A.net--; touch(); throw e; }\n };\n } catch (e) {}\n try {\n const st = window.setTimeout, ct = window.clearTimeout, ci = window.clearInterval;\n // id -> the moment it must have fired by. Counting by DEADLINE rather than\n // by cancellation bookkeeping is what makes this safe: a timer we never see\n // cancelled (clearInterval on a setTimeout id, an id coerced through a\n // dataset attribute, any API we did not wrap) simply expires and stops\n // counting. Chasing every cancellation path would leave one uncounted, and\n // ONE stuck entry means every remaining beat of the take waits the whole\n // budget for nothing.\n const live = new Map();\n const forget = function (id) { live.delete(Number(id)); };\n A.pending = function () {\n const now = performance.now();\n live.forEach(function (due, id) { if (due <= now) live.delete(id); });\n A.timers = live.size;\n return live.size;\n };\n window.setTimeout = function (fn, delay) {\n const d = Number(delay) || 0;\n // a string body keeps the original semantics (wrapping would stop the\n // code ever running), and a long delay is a heartbeat, not this beat\n if (typeof fn !== \"function\" || d > TIMER_MAX) return st.apply(window, arguments);\n const rest = Array.prototype.slice.call(arguments, 2);\n let id;\n const wrapped = function () {\n forget(id); touch();\n return fn.apply(this, arguments);\n };\n id = st.apply(window, [wrapped, d].concat(rest));\n live.set(Number(id), performance.now() + d + TIMER_SLACK);\n touch();\n return id;\n };\n // Both cancellers, and both coerce their argument the way the platform\n // does — clearInterval legally cancels a setTimeout (one timer map), and\n // clearTimeout(String(id)) is what you get back out of a dataset.\n window.clearTimeout = function (id) { forget(id); return ct.apply(window, arguments); };\n window.clearInterval = function (id) { forget(id); return ci.apply(window, arguments); };\n } catch (e) {}\n window.__openTakeActivity = A;\n})()`;\n\n/** Reads the probe. Returns a JSON string so one Runtime.evaluate round-trip\n * carries the whole answer (returnByValue on a plain object also works, but\n * the rest of this package already speaks the JSON-string convention). */\nconst PROBE_READ_JS = `(() => {\n const A = window.__openTakeActivity;\n if (!A) return JSON.stringify({ ok: false });\n let anims = 0;\n try {\n for (const a of document.getAnimations()) {\n if (a.playState !== \"running\") continue;\n let it = 1;\n try { it = a.effect.getTiming().iterations; } catch (e) {}\n if (it === Infinity) continue; // ambient — never settles, never counted\n anims++;\n }\n } catch (e) {}\n // The largest <canvas>/<video> as a fraction of the viewport, clipped to it\n // (an offscreen or scrolled-away surface is not what the viewer is watching).\n let paint = 0;\n try {\n const area = innerWidth * innerHeight;\n if (area > 0)\n for (const el of document.querySelectorAll(\"canvas,video\")) {\n const r = el.getBoundingClientRect();\n const w = Math.max(0, Math.min(r.right, innerWidth) - Math.max(r.left, 0));\n const h = Math.max(0, Math.min(r.bottom, innerHeight) - Math.max(r.top, 0));\n if (w * h > paint * area) paint = (w * h) / area;\n }\n } catch (e) {}\n const timers = typeof A.pending === \"function\" ? A.pending() : (A.timers | 0);\n const busy = A.net > 0 || timers > 0 || anims > 0 || document.readyState !== \"complete\";\n return JSON.stringify({\n ok: true,\n quietMs: busy ? 0 : Math.max(0, performance.now() - A.t),\n net: A.net,\n timers,\n anims,\n paint,\n });\n})()`;\n\nexport type SettleOutcome = {\n /** the editorial hold, run in full and unchanged */\n heldMs: number;\n /** extra time spent waiting for the page AFTER the hold */\n waitedMs: number;\n /** how the wait ended: the page went quiet, the budget ran out, or no probe\n * was installed (an older page context / a navigation in flight) */\n reason: \"idle\" | \"budget\" | \"unavailable\";\n /** biggest share of the frame a <canvas>/<video> held while this beat waited.\n * Past PAINT_BLIND_FRAC the \"idle\" verdict above says nothing about what was\n * painted inside it — see the module header. */\n paintFrac: number;\n /** on \"idle\": how long the page had already been quiet when the wait\n * ended (ms) — so the moment it went quiet is now minus this */\n quietForMs?: number;\n};\n\n/** Install the activity probe for the current document AND every future one\n * (a plan may navigate mid-take). Never throws — a capture must not fail\n * because a diagnostic could not be attached. */\nexport async function installActivityProbe(cdp: CDP): Promise<void> {\n await cdp\n .send(\"Page.addScriptToEvaluateOnNewDocument\", { source: PROBE_INSTALL_JS })\n .catch(() => {});\n await cdp.send(\"Runtime.evaluate\", { expression: PROBE_INSTALL_JS }).catch(() => {});\n}\n\ntype Probe = { quietMs: number; net: number; timers: number; anims: number; paint: number };\n\nasync function readProbe(cdp: CDP): Promise<Probe | null> {\n try {\n const r = await cdp.send<{ result?: { value?: unknown } }>(\"Runtime.evaluate\", {\n expression: PROBE_READ_JS,\n returnByValue: true,\n });\n const v = r.result?.value;\n if (typeof v !== \"string\") return null;\n const p = JSON.parse(v) as Partial<Probe> & { ok?: boolean };\n if (!p.ok) return null;\n return {\n quietMs: p.quietMs ?? 0,\n net: p.net ?? 0,\n timers: p.timers ?? 0,\n anims: p.anims ?? 0,\n paint: p.paint ?? 0,\n };\n } catch {\n return null;\n }\n}\n\n/**\n * Hold for `heldMs` (the editorial beat — always run in full), then keep\n * waiting while the page is still working, up to `budgetMs`.\n *\n * `budgetMs <= 0` reduces this to the old fixed sleep exactly — the escape\n * hatch for a page that never goes quiet (`CaptureOpts.settleBudgetMs: 0`),\n * and what the unit tests use to pin the legacy timing.\n */\nexport async function settle(\n cdp: CDP,\n heldMs: number,\n opts: { budgetMs?: number } = {},\n): Promise<SettleOutcome> {\n const budget = opts.budgetMs ?? DEFAULT_SETTLE_BUDGET_MS;\n await sleep(Math.max(0, heldMs));\n if (!(budget > 0)) return { heldMs, waitedMs: 0, reason: \"budget\", paintFrac: 0 };\n const t0 = Date.now();\n let paintFrac = 0;\n for (;;) {\n const p = await readProbe(cdp);\n const waitedMs = Date.now() - t0;\n if (!p) return { heldMs, waitedMs, reason: \"unavailable\", paintFrac };\n paintFrac = Math.max(paintFrac, p.paint);\n if (p.quietMs >= QUIET_MS)\n return { heldMs, waitedMs, reason: \"idle\", paintFrac, quietForMs: p.quietMs };\n if (waitedMs >= budget) return { heldMs, waitedMs, reason: \"budget\", paintFrac };\n await sleep(POLL_MS);\n }\n}\n\n/** How many beats in a row may spend the WHOLE budget without the page ever\n * settling before the waiting is written off. */\nexport const SETTLE_GIVE_UP_STREAK = 2;\n\n/**\n * Budget policy across one take. Some pages never go quiet — a one-second\n * clock, a poll loop, a streaming widget — and no DOM signal can tell that\n * apart from real work. So do not try: once a run of beats has each spent the\n * entire budget with no result, the waiting is provably not helping, and\n * paying it on every remaining beat would add more dead air than the whole\n * demo is long. Give up once, loudly, and let the author set settleMs by eye.\n */\nexport function makeBudgetGovernor(budgetMs: number, giveUpStreak = SETTLE_GIVE_UP_STREAK) {\n let budget = budgetMs;\n let streak = 0;\n return {\n get budgetMs() {\n return budget;\n },\n get gaveUp() {\n return budget <= 0 && budgetMs > 0;\n },\n /** Feed every outcome back. Returns true on the ONE call that gives up. */\n record(reason: SettleOutcome[\"reason\"]): boolean {\n if (reason === \"idle\") {\n streak = 0;\n return false;\n }\n if (reason !== \"budget\" || budget <= 0) return false;\n if (++streak < giveUpStreak) return false;\n budget = 0;\n return true;\n },\n };\n}\n","// captureTakeCDP — the high-fps capture path (HANDOFF #5).\n//\n// Same contract as captureTake (drive `plan` against the live app, emit the\n// ground-truth CaptureLog + a video at `videoPath`), but it launches its own\n// headless Chrome and drives AND captures over one CDP page session. That\n// removes agent-browser's ~10fps recordVideo ceiling (→ ~60fps screencast)\n// and the per-step process spawn (→ drags driven at ~16ms steps, so the\n// captured ink stays in lockstep with the synthetic cursor). See\n// spike-revideo/fps/VERDICT.md. The ELEMENT-RESOLUTION logic is reused\n// verbatim from capture.ts — same locator JS, run via Runtime.evaluate —\n// so robustness is shared, not re-derived.\n\nimport { existsSync, rmSync, statSync } from \"node:fs\";\nimport { basename, dirname, join, resolve } from \"node:path\";\nimport type { CaptureLog } from \"@open-take/compositor\";\nimport type { CaptureOpts } from \"./capture\";\nimport {\n type Box,\n boxByTextJs,\n boxSelectorJs,\n clickBySelectorJs,\n clickByTextJs,\n evalValue,\n ffprobe,\n findBox,\n focusFieldByTextJs,\n focusSelectorJs,\n hrefByTextJs,\n hrefSelectorJs,\n sampleAlong,\n scrollDeltaByTextJs,\n scrollDeltaSelectorJs,\n selectAllInFocusedJs,\n selectOptionJs,\n verifyFocusJs,\n} from \"./capture\";\nimport {\n type Browser,\n type CDP,\n captureCadence,\n encodeFrames,\n fitViewport,\n launchBrowser,\n makeFrameDir,\n pumpIdleRaster,\n Screencast,\n waitUntil,\n} from \"./cdp\";\nimport {\n captureDomState,\n type DomStateItem,\n type DomStateRaw,\n finalizeDomStates,\n matchTarget,\n summarizeDomStates,\n visuallyStill,\n} from \"./dom-state\";\nimport { resolveNavigateUrl } from \"./nav\";\nimport { PrecheckRefusal, precheckPlan } from \"./precheck\";\nimport {\n type ProductAudioRecorder,\n type ProductSoundReport,\n startProductAudio,\n} from \"./product-audio\";\nimport {\n DEFAULT_SETTLE_BUDGET_MS,\n installActivityProbe,\n makeBudgetGovernor,\n PAINT_BLIND_FRAC,\n settle,\n} from \"./settle\";\nimport type { TakePlan } from \"./types\";\n\nconst sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));\n\n/** Report a settle wait only past this — a couple of polls is the probe\n * confirming quiet, not the page being slow, and a log full of 60ms notes\n * would bury the beat that actually needed a second. */\nconst SETTLE_NOTE_MS = 150;\n\n// smootherstep — ease-in-out. Used to ease a drag along its path (must match\n// the compositor's drag easing in math.ts exactly so the cursor stays locked\n// to the captured ink).\nconst smoother = (u: number) => {\n const clamped = Math.max(0, Math.min(1, u));\n return clamped * clamped * clamped * (clamped * (clamped * 6 - 15) + 10);\n};\n\ntype Pt = { x: number; y: number };\n\n// Run a locator JS string (the same builders capture.ts uses) and parse the\n// box it returns. `returnByValue` hands us the inner JSON string; evalValue\n// unwraps any double-encoding, then findBox extracts the rect.\nasync function evalBox(cdp: CDP, js: string): Promise<Box | null> {\n const r = await cdp.send<{ result?: { value?: unknown } }>(\"Runtime.evaluate\", {\n expression: js,\n returnByValue: true,\n awaitPromise: true,\n });\n const v = r.result?.value;\n if (v == null || v === \"NOTFOUND\") return null;\n return findBox(evalValue(typeof v === \"string\" ? v : JSON.stringify(v)));\n}\n\n// Run a locator JS string and return its parsed value (any shape), or null for\n// a NOTFOUND / empty result. Used by scroll-to-element ({dy} delta).\nasync function evalAny(cdp: CDP, js: string): Promise<unknown> {\n const r = await cdp.send<{ result?: { value?: unknown } }>(\"Runtime.evaluate\", {\n expression: js,\n returnByValue: true,\n awaitPromise: true,\n });\n const v = r.result?.value;\n if (v == null || v === \"NOTFOUND\") return null;\n return evalValue(typeof v === \"string\" ? v : JSON.stringify(v));\n}\n\n// Run a locator JS string and return its STRING result (a URL), or null for a\n// NOTFOUND/empty one. Deliberately NOT evalAny: a URL is not JSON, and the\n// deep-parse that unwraps box payloads would mangle it.\nasync function evalString(cdp: CDP, js: string): Promise<string | null> {\n const r = await cdp.send<{ result?: { value?: unknown } }>(\"Runtime.evaluate\", {\n expression: js,\n returnByValue: true,\n awaitPromise: true,\n });\n const v = r.result?.value;\n return typeof v === \"string\" && v !== \"NOTFOUND\" && v !== \"\" ? v : null;\n}\n\n// Wait (bounded) for the document's webfonts. A capture runs on a fresh temp\n// profile, so the HTTP cache is cold and third-party webfonts otherwise FOUT in\n// the first ~700ms the document is on screen. Runs before the recording clock\n// starts AND after every mid-take `navigate` — the second document is exactly\n// as cold as the first, and a FOUT mid-shot is just as visible as one at the\n// head. A page with no webfonts resolves immediately.\nexport async function awaitFonts(cdp: CDP): Promise<void> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n await Promise.race([\n cdp\n .send(\"Runtime.evaluate\", {\n expression: \"document.fonts.ready.then(() => true)\",\n awaitPromise: true,\n returnByValue: true,\n })\n .catch(() => {}),\n new Promise((r) => {\n timer = setTimeout(r, 3000);\n }),\n ]);\n clearTimeout(timer); // see navigate(): a live timer holds the process open\n}\n\nconst center = (b: Box): Pt => ({ x: Math.round(b.x + b.w / 2), y: Math.round(b.y + b.h / 2) });\n\n// mouse via CDP Input — trusted events, near-zero per-call overhead.\n// `buttons` is the bitmask of *currently-pressed* buttons (1 = left held);\n// `button` names the one this event acts on (\"none\" for a bare move).\nconst mouse = (\n cdp: CDP,\n type: \"mousePressed\" | \"mouseReleased\" | \"mouseMoved\",\n x: number,\n y: number,\n buttons = 0,\n) =>\n cdp.send(\"Input.dispatchMouseEvent\", {\n type,\n x: Math.round(x),\n y: Math.round(y),\n button: type === \"mouseMoved\" ? \"none\" : \"left\",\n buttons,\n ...(type === \"mouseMoved\" ? {} : { clickCount: 1 }),\n });\n\n// --- keyboard ----------------------------------------------------------\n// CDP modifier bitmask: Alt=1, Ctrl=2, Meta(⌘)=4, Shift=8.\nconst MOD: Record<string, number> = {\n alt: 1,\n option: 1,\n ctrl: 2,\n control: 2,\n meta: 4,\n cmd: 4,\n command: 4,\n super: 4,\n win: 4,\n shift: 8,\n};\ntype KeyInfo = { key: string; code: string; vk: number; text?: string };\n// Named non-printable keys an editorial demo reaches for. `text` only where a\n// page expects a character (Enter submits forms via \"\\r\"; Space inserts \" \").\nconst NAMED: Record<string, KeyInfo> = {\n enter: { key: \"Enter\", code: \"Enter\", vk: 13, text: \"\\r\" },\n return: { key: \"Enter\", code: \"Enter\", vk: 13, text: \"\\r\" },\n tab: { key: \"Tab\", code: \"Tab\", vk: 9 },\n escape: { key: \"Escape\", code: \"Escape\", vk: 27 },\n esc: { key: \"Escape\", code: \"Escape\", vk: 27 },\n backspace: { key: \"Backspace\", code: \"Backspace\", vk: 8 },\n delete: { key: \"Delete\", code: \"Delete\", vk: 46 },\n space: { key: \" \", code: \"Space\", vk: 32, text: \" \" },\n arrowup: { key: \"ArrowUp\", code: \"ArrowUp\", vk: 38 },\n arrowdown: { key: \"ArrowDown\", code: \"ArrowDown\", vk: 40 },\n arrowleft: { key: \"ArrowLeft\", code: \"ArrowLeft\", vk: 37 },\n arrowright: { key: \"ArrowRight\", code: \"ArrowRight\", vk: 39 },\n up: { key: \"ArrowUp\", code: \"ArrowUp\", vk: 38 },\n down: { key: \"ArrowDown\", code: \"ArrowDown\", vk: 40 },\n left: { key: \"ArrowLeft\", code: \"ArrowLeft\", vk: 37 },\n right: { key: \"ArrowRight\", code: \"ArrowRight\", vk: 39 },\n home: { key: \"Home\", code: \"Home\", vk: 36 },\n end: { key: \"End\", code: \"End\", vk: 35 },\n pageup: { key: \"PageUp\", code: \"PageUp\", vk: 33 },\n pagedown: { key: \"PageDown\", code: \"PageDown\", vk: 34 },\n};\n\n// VK code for the Left variant of each modifier (dispatched as its own key\n// event so apps that track modifier keydown state see it pressed).\nconst MOD_KEY: Record<number, KeyInfo> = {\n 1: { key: \"Alt\", code: \"AltLeft\", vk: 18 },\n 2: { key: \"Control\", code: \"ControlLeft\", vk: 17 },\n 4: { key: \"Meta\", code: \"MetaLeft\", vk: 91 },\n 8: { key: \"Shift\", code: \"ShiftLeft\", vk: 16 },\n};\n\n// Parse \"Meta+k\" / \"Enter\" / \"Control+Shift+p\" into a modifier bitmask + the\n// main key's CDP fields. The last token is the key; the rest are modifiers.\nfunction parseChord(keys: string): { mods: number; info: KeyInfo } {\n const tokens = keys\n .split(\"+\")\n .map((t) => t.trim())\n .filter(Boolean);\n const main = tokens.pop() ?? \"\";\n let mods = 0;\n for (const t of tokens) mods |= MOD[t.toLowerCase()] ?? 0;\n const named = NAMED[main.toLowerCase()];\n let info: KeyInfo;\n if (named) {\n info = named;\n } else {\n // a single printable character\n const ch = main;\n const code = /^[a-z]$/i.test(ch)\n ? `Key${ch.toUpperCase()}`\n : /^[0-9]$/.test(ch)\n ? `Digit${ch}`\n : \"\";\n info = { key: ch, code, vk: ch.toUpperCase().charCodeAt(0) || 0 };\n // include the character ONLY for a bare key (no Ctrl/Meta/Alt) — a shortcut\n // must not also insert text.\n if (!(mods & (1 | 2 | 4))) info.text = ch;\n }\n return { mods, info };\n}\n\nasync function dispatchKey(\n cdp: CDP,\n type: \"keyDown\" | \"keyUp\",\n info: KeyInfo,\n mods: number,\n): Promise<void> {\n await cdp.send(\"Input.dispatchKeyEvent\", {\n type: info.text && type === \"keyDown\" ? \"keyDown\" : type,\n modifiers: mods,\n key: info.key,\n code: info.code,\n windowsVirtualKeyCode: info.vk,\n nativeVirtualKeyCode: info.vk,\n ...(info.text ? { text: info.text } : {}),\n });\n}\n\n// Press a chord: hold modifiers, tap the key, release in reverse — the order a\n// real keyboard produces, so apps tracking modifier state respond correctly.\nexport async function pressChord(cdp: CDP, keys: string): Promise<void> {\n const { mods, info } = parseChord(keys);\n const active = [1, 2, 4, 8].filter((m) => mods & m);\n for (const m of active) await dispatchKey(cdp, \"keyDown\", MOD_KEY[m]!, mods);\n await dispatchKey(cdp, \"keyDown\", info, mods);\n await sleep(40);\n await dispatchKey(cdp, \"keyUp\", info, mods);\n for (const m of active.reverse()) await dispatchKey(cdp, \"keyUp\", MOD_KEY[m]!, 0);\n}\n\n/** High-fps twin of captureTake. Drives + records via CDP. */\nexport async function captureTakeCDP(plan: TakePlan, opts: CaptureOpts): Promise<CaptureLog> {\n const vw = plan.viewport?.width ?? 1920;\n const vh = plan.viewport?.height ?? 1080;\n const fps = Math.min(60, Math.max(24, Math.round(opts.fps ?? 60)));\n const scale = Math.max(1, opts.captureScale ?? 2);\n const out = resolve(opts.videoPath);\n\n let browser: Browser | null = null;\n const frameDir = makeFrameDir();\n try {\n browser = await launchBrowser({\n width: vw,\n height: vh,\n chromePath: opts.chromePath,\n deviceScaleFactor: scale,\n ...(opts.userDataDir ? { userDataDir: opts.userDataDir } : {}),\n ...(opts.headless === false ? { headless: false } : {}),\n });\n const { cdp } = browser;\n await cdp.send(\"Page.enable\");\n await cdp.send(\"Runtime.enable\");\n // The product's own sound (on unless opted out): taps every AudioContext\n // and playing media element from the first document on — see\n // product-audio.ts. Installing can only fail into a note, never the take.\n const productAudio: ProductAudioRecorder | null =\n opts.productAudio === false ? null : await startProductAudio(cdp);\n // Grow the window so the natural viewport == requested (headless reserves\n // window chrome). This — NOT a metrics override — keeps the captured frame,\n // the viewport, and the event coordinate space all the same size (the\n // frame is exactly `scale`× the CSS event space; see launchBrowser).\n let inner = await fitViewport(cdp, browser.targetId, vw, vh);\n\n // Watch the page for activity from the very first document (and every\n // one a mid-take navigation creates) so a hold can tell \"finished\" from\n // \"still working\" instead of betting on settleMs. Diagnostic only — a\n // failure to install just returns the old fixed-sleep behaviour.\n await installActivityProbe(cdp);\n if (!originAllowed(plan.url))\n throw new Error(\n `captureTakeCDP: plan.url ${plan.url} is outside OPEN_TAKE_ALLOWED_ORIGINS — an unattended run only films the app it was pointed at`,\n );\n // Fail BEFORE the screencast exists: a URL nobody is listening on used to\n // sail through here and produce a polished 4K take of Chrome's\n // ERR_CONNECTION_REFUSED page, minutes after the mistake was made.\n const navError = await navigate(cdp, plan.url);\n if (navError)\n throw new Error(\n `captureTakeCDP: ${plan.url} did not answer (${navError}) — is the app running? ` +\n `Start it (or fix the URL) and re-make; nothing was recorded.`,\n );\n await installActivityProbe(cdp);\n\n // Fonts before frames — the recording's first ~700ms is the one place a\n // viewer's eye is guaranteed to be. Every mid-take `navigate` repeats this.\n await awaitFonts(cdp);\n\n // Re-fit AFTER navigation + font wait: a window manager (cloud/Xvfb) can\n // re-apply its own bounds during those seconds, and a viewport measured\n // before that lie skews EVERY recorded coordinate the same way — a real\n // take shipped with the cursor drawn 13% below every control because the\n // window grew ~1226px tall after the first measure while the screencast\n // stayed capped at the stale 1080. Re-running the fit both retries the\n // requested size and, failing that, adopts what the window truly is.\n inner = await fitViewport(cdp, browser.targetId, vw, vh);\n\n // The 2-second gate in front of the 60-second shoot: resolve every plan\n // target with the exact locator semantics the steps below will use. A\n // cold-prefix miss is a certainty, and fails here — BEFORE the screencast\n // exists — like the dead-URL check above. Warnings ride along on the log.\n const precheck = await precheckPlan(plan.steps, (js) => evalAny(cdp, js));\n const precheckErrors = precheck.filter((p) => p.severity === \"error\");\n if (precheckErrors.length)\n throw new PrecheckRefusal(\n `captureTakeCDP: ${precheckErrors.length} plan target(s) failed the pre-capture check — nothing was recorded:\\n` +\n precheckErrors\n .map((p) => ` ${p.path}: ${p.message}${p.fix ? `\\n fix: ${p.fix}` : \"\"}`)\n .join(\"\\n\"),\n precheck,\n );\n for (const p of precheck)\n console.error(`captureTakeCDP precheck [${p.severity}] ${p.path}: ${p.message}`);\n\n const screencast = new Screencast(cdp, frameDir);\n const t0 = Date.now();\n // max dims in PHYSICAL px — at deviceScaleFactor 2 the surface is 2× the\n // CSS viewport; capping at CSS size would silently downscale back to 1×.\n await screencast.start(t0, {\n maxWidth: inner[0] * scale,\n maxHeight: inner[1] * scale,\n quality: 92,\n });\n\n // Refresh genuinely idle surfaces, not every 45ms: unconditional large\n // screenshots interrupt native animations and can queue behind each other.\n // A held mouse button still pauses the pump because screenshots can stall\n // CDP input mid-drag. The helper never waits indefinitely on a screenshot.\n let pumping = true;\n let pumpPaused = false;\n const pump =\n opts.rasterRefresh === \"off\"\n ? Promise.resolve()\n : pumpIdleRaster(\n cdp,\n screencast,\n () => pumping,\n () => pumpPaused,\n );\n\n await sleep(opts.warmupMs ?? 900);\n\n const resolvePoint = async (spec: {\n point?: Pt;\n selector?: string;\n text?: string;\n }): Promise<Pt | null> => {\n if (spec.point) return { x: Math.round(spec.point.x), y: Math.round(spec.point.y) };\n if (spec.selector) {\n const b = await evalBox(cdp, boxSelectorJs(spec.selector));\n return b ? center(b) : null;\n }\n if (spec.text) {\n const b = await evalBox(cdp, boxByTextJs(spec.text));\n return b ? center(b) : null;\n }\n return null;\n };\n\n const events: CaptureLog[\"events\"] = [];\n // Dropped steps are collected onto the log (and echoed to stderr at the\n // moment they happen) so the end-of-run summary and the strict-by-default\n // exit code can see them\n // — an early stderr line alone gets buried under render progress.\n const skipped: NonNullable<CaptureLog[\"skipped\"]> = [];\n // Beats whose hold was NOT long enough for the page — the measurement that\n // turns `settleMs` from a guess into a number the next plan can copy.\n const settleWaits: NonNullable<CaptureLog[\"settleWaits\"]> = [];\n // Bounds what a page that never goes quiet can cost the take — see\n // makeBudgetGovernor.\n const governor = makeBudgetGovernor(opts.settleBudgetMs ?? DEFAULT_SETTLE_BUDGET_MS);\n // Biggest paint surface seen. Reported ONCE — an author who sees no ⏱\n // lines would otherwise read that as \"my timings were right\", which on a\n // canvas app is exactly the wrong conclusion.\n let paintedFrac = 0;\n let paintNoted = false;\n // DOM states (opt-in): the page's structure at every settled moment — s0\n // now, after the warmup, then one at the end of each step's final hold.\n // The per-step capture lives inside hold() so every branch that settles\n // the page gets one and none of the exit paths has to remember to. Each\n // capture also stamps the events the step produced with the state that\n // followed them and the element (in the state BEFORE) they acted on.\n // Never fails the take: a state that cannot be read is a stderr line.\n const statesDir = opts.states ? join(dirname(out), \"states\") : null;\n const states: DomStateRaw[] = [];\n // moments the page was still moving at: no still to keep there, and\n // reading one (the probe, the snapshot) stalls the app being filmed — a\n // playing video froze, then jumped, in the recording. Logged, not saved.\n const movingStates: { id: string; tMs: number; step?: number }[] = [];\n let statesAnnotated = 0; // events[0..n) already carry their `state`\n let lastState: DomStateRaw | null = null;\n // `mayMove`: the page may still be moving here (no settle said it is quiet):\n // look at the pixels before reading anything\n const captureState = async (step: number | undefined, mayMove: boolean) => {\n if (!statesDir) return;\n // our screenshot and the pump's forced ones would queue behind each other\n pumpPaused = true;\n await sleep(60);\n try {\n const id = `s${states.length + movingStates.length}`;\n const tMs = Date.now() - t0;\n const annotate = (target: DomStateRaw | null) => {\n for (; statesAnnotated < events.length; statesAnnotated++) {\n const ev = events[statesAnnotated]!;\n ev.state = id;\n const hit = ev.box && target ? matchTarget(ev.box, target.probe.elements) : undefined;\n if (hit) ev.target = hit;\n }\n };\n // moving only if the pixels move\n if (mayMove && !(await visuallyStill(cdp, inner[0], inner[1]))) {\n movingStates.push({ id, tMs, ...(step != null ? { step } : {}) });\n annotate(lastState);\n return;\n }\n const raw = await captureDomState(cdp, {\n statesDir,\n id,\n tMs,\n ...(step != null ? { step } : {}),\n vw: inner[0],\n vh: inner[1],\n dpr: scale,\n });\n states.push(raw);\n annotate(lastState);\n lastState = raw;\n } catch (e) {\n console.error(\n `captureTakeCDP: DOM state after ${step == null ? \"the warmup\" : `step ${step}`} not captured (${(e as Error).message})`,\n );\n } finally {\n pumpPaused = false;\n }\n };\n await captureState(undefined, true);\n for (let stepIdx = 0; stepIdx < plan.steps.length; stepIdx++) {\n const step = plan.steps[stepIdx]!;\n const firstEvent = events.length; // this step's events start here\n const skip = (action: string, target: string | undefined, reason: string) => {\n skipped.push({ step: stepIdx, action, ...(target ? { target } : {}), reason });\n console.error(`captureTakeCDP: ${action} ${reason}, skipped: ${JSON.stringify(target)}`);\n };\n // The editorial hold, then — only if the page is still working — the\n // time it actually needs. `defaultMs` stays the per-action default the\n // plan author never has to think about; `step.settleMs` still wins.\n const hold = async (defaultMs: number) => {\n // `step` is the un-narrowed union here (every action calls this), and\n // `wait` is the one variant with no settleMs — it IS a hold.\n const heldMs = (\"settleMs\" in step ? step.settleMs : undefined) ?? defaultMs;\n const budgeted = governor.budgetMs > 0;\n const r = await settle(cdp, heldMs, { budgetMs: governor.budgetMs });\n paintedFrac = Math.max(paintedFrac, r.paintFrac);\n // when the page went quiet after this step's input (an estimate from\n // structure; the frame-diff pass measures when the result SHOWED)\n if (r.quietForMs != null) {\n const quietAt = Math.round(Date.now() - t0 - r.quietForMs);\n for (let i = firstEvent; i < events.length; i++)\n if (quietAt > events[i]!.tMs) events[i]!.settledMs = quietAt;\n }\n if (paintedFrac >= PAINT_BLIND_FRAC && !paintNoted) {\n paintNoted = true;\n console.error(\n `captureTakeCDP: a <canvas>/<video> covers ~${Math.round(paintedFrac * 100)}% of the frame — the settle probe reads page STRUCTURE and cannot see what is painted inside one, so on beats whose payoff is drawn there, settleMs is doing the whole job. Set those by eye and check \\`frames\\`.`,\n );\n }\n if (governor.record(r.reason))\n console.error(\n \"captureTakeCDP: this page never goes quiet (consecutive beats spent the whole settle budget) — settle waiting is OFF for the rest of the take; set each beat's settleMs explicitly instead\",\n );\n // the page is as settled as it gets: the moment a DOM state describes.\n // Unless settling said it went quiet — it stayed busy through the\n // whole budget, or settle waiting is off — it may still be moving, and\n // a moving moment saves nothing (reading it would stall the page)\n await captureState(stepIdx, !budgeted || r.reason === \"budget\");\n if (r.waitedMs < SETTLE_NOTE_MS) return;\n const waitedMs = Math.round(r.waitedMs);\n settleWaits.push({\n step: stepIdx,\n action: step.action,\n heldMs,\n waitedMs,\n reason: r.reason,\n });\n console.error(\n `captureTakeCDP: step ${stepIdx} (${step.action}) held ${heldMs}ms, then waited ${waitedMs}ms more for the page to settle (${r.reason})`,\n );\n };\n if (step.action === \"wait\") {\n await sleep(step.ms);\n await captureState(stepIdx, true); // a wait has no settle; the state follows it\n continue;\n }\n\n if (step.action === \"navigate\") {\n // Late-bind the destination FIRST — reading a link's href is the whole\n // reason this step can reach a page the plan's author could not name\n // (a deploy's generated domain, a permalink the run just created).\n const spec = step.hrefFrom;\n let href: string | null = null;\n if (spec) {\n const target = spec.text ?? spec.selector;\n if (!target) {\n skip(\"navigate\", undefined, \"hrefFrom has neither `selector` nor `text`\");\n continue;\n }\n href = spec.selector\n ? await evalString(cdp, hrefSelectorJs(spec.selector))\n : await evalString(cdp, hrefByTextJs(spec.text!));\n if (!href) {\n skip(\"navigate\", target, \"no link with an href found\");\n continue;\n }\n }\n const current = (await evalString(cdp, \"location.href\")) ?? plan.url;\n const dest = resolveNavigateUrl({ current, url: step.url, href, query: step.query });\n if (!dest) {\n skip(\"navigate\", step.url ?? href ?? current, \"destination is not a resolvable URL\");\n continue;\n }\n if (!originAllowed(dest)) {\n skip(\"navigate\", dest, \"destination is outside OPEN_TAKE_ALLOWED_ORIGINS\");\n continue;\n }\n // Same tab ⇒ same page target ⇒ the screencast never breaks. The\n // activity probe reinstalls itself on the new document (it is an\n // addScriptToEvaluateOnNewDocument), so the hold below can still tell\n // \"finished\" from \"still working\".\n const midNavError = await navigate(cdp, dest);\n if (midNavError) {\n // The failed navigation already replaced the app with Chrome's error\n // page — filming THAT for the remaining beats helps nobody. Going\n // back re-loads the app (SPA state is lost, and steps that depended\n // on it will skip in turn, each with its own reason), which is still\n // strictly more footage than an error page.\n skip(\"navigate\", dest, `destination did not answer (${midNavError})`);\n await navigate(cdp, current);\n await hold(1200);\n continue;\n }\n await awaitFonts(cdp);\n // Then the ordinary settle. A navigate with no hold cuts to a\n // half-painted screen — this is the beat where the new page arrives,\n // even though it emits no event.\n await hold(1200);\n continue;\n }\n\n if (step.action === \"type\") {\n const label = step.text ?? step.selector;\n let tMs = Date.now() - t0;\n const focusRaw = step.text\n ? await evalAny(cdp, focusFieldByTextJs(step.text))\n : step.selector\n ? await evalAny(cdp, focusSelectorJs(step.selector))\n : null;\n const box = focusRaw ? findBox(focusRaw as Record<string, unknown>) : null;\n if (!box) {\n skip(\"type\", label, \"target not found\");\n await hold(600);\n continue;\n }\n // Did focus LAND? Input.insertText types into the current selection —\n // when the in-page focus();click();focus() bounces off (a\n // contenteditable that only arms on a real click's coordinates:\n // measured, activeElement stayed BODY, the string went nowhere, and\n // the beat logged as a success with changeCoverage 0), recover the\n // way a user would: one trusted press/release at the field's centre,\n // then ask again. Still unfocused after that → the beat is a lie the\n // video would tell — skip it and let the post-shoot gate name it.\n let focused = (focusRaw as Record<string, unknown>).f === 1;\n // A covered centre is not recovered: the press would land on whatever\n // covers the field as a REAL click — state mutated on camera — and\n // the beat would skip anyway. Name it and move on.\n if (!focused && (focusRaw as Record<string, unknown>).hit !== 1) {\n const why = (focusRaw as Record<string, unknown>).why;\n skip(\n \"type\",\n label,\n `focus never reached the target — ${typeof why === \"string\" ? why : \"its centre is covered\"}, so no click could arm it`,\n );\n await hold(600);\n continue;\n }\n if (!focused) {\n const pt = center(box);\n pumpPaused = true;\n await sleep(160);\n tMs = Date.now() - t0; // the press, not the eval, is the beat (as click)\n mouse(cdp, \"mouseMoved\", pt.x, pt.y, 0).catch(() => {});\n mouse(cdp, \"mousePressed\", pt.x, pt.y, 1).catch(() => {});\n await sleep(60);\n mouse(cdp, \"mouseReleased\", pt.x, pt.y, 0).catch(() => {});\n await sleep(120);\n pumpPaused = false;\n // the app may arm the editor in a state update — a short bounded\n // poll, not one fixed probe, so a slow arm (loaded CI box) is not a\n // false skip; the failing path costs at most ~750ms extra\n for (let poll = 0; poll < 3 && !focused; poll++) {\n await sleep(250);\n focused =\n (await evalString(\n cdp,\n verifyFocusJs({ text: step.text, selector: step.selector }),\n )) === \"1\";\n }\n }\n if (!focused) {\n skip(\"type\", label, \"focus never reached the target — typing would go nowhere\");\n await hold(600);\n continue;\n }\n // Unattended runs must never film a credential being typed — the plan\n // is agent-written and the mp4 is the one artifact nobody reviews.\n // Focus is verified on the field by now, so ask the page what kind of\n // field it actually is.\n if (\n process.env.OPEN_TAKE_CI &&\n (await evalString(cdp, credentialFieldProbeJs())) === \"secret\"\n ) {\n skip(\"type\", label, \"refusing to type into a credential field (OPEN_TAKE_CI)\");\n await hold(600);\n continue;\n }\n // Replace-not-append: select the field's existing value in-page so the\n // first inserted character replaces it (dispatched \"Meta+a\" key events\n // never run Chrome's editing commands — see selectAllInFocusedJs).\n if (step.clear) await evalAny(cdp, selectAllInFocusedJs());\n // A literal zero requests one real paste-like input event. Otherwise,\n // type progressively so the recording shows the text appear; paced by\n // us (insertText fires `input` events React/inputs honour).\n const chars = [...step.value];\n // ~1.1s per beat, clamped 28–90ms/char. The cap used to be 60ms, which\n // made SHORT strings the FASTEST typing in the video (inverted feel);\n // 90 lets a short hero string read deliberate while long strings keep\n // their genre-normal pace. Mostly-CJK strings slow ~1.4× (every glyph\n // is a word — the viewer reads, not skims). perCharMs overrides.\n const cjk = chars.filter((c) =>\n /[\\u2E80-\\u9FFF\\uAC00-\\uD7AF\\uF900-\\uFAFF\\uFF66-\\uFF9F]/.test(c),\n ).length;\n const auto =\n Math.min(90, Math.max(28, Math.round(1100 / Math.max(1, chars.length)))) *\n (cjk * 2 > chars.length ? 1.4 : 1);\n if (step.perCharMs === 0) {\n await cdp.send(\"Input.insertText\", { text: step.value });\n } else {\n const perChar = Math.round(step.perCharMs ?? auto);\n for (const ch of chars) {\n const painted = screencast.frames.length,\n sentAt = Date.now();\n await cdp.send(\"Input.insertText\", { text: ch });\n // One character per painted frame. A fixed sleep after insertText let a\n // slow re-render batch several characters into one paint and then stall:\n // the recording showed 17–350 ms between visible characters for a 45 ms\n // budget, i.e. typing that stutters. Wait for the page's own swap first,\n // bounded so a surface that stops painting cannot hang the take, then\n // spend whatever is left of the per-character budget.\n await waitUntil(() => screencast.frames.length > painted, Math.max(perChar, 250));\n const rest = perChar - (Date.now() - sentAt);\n if (rest > 0) await sleep(rest);\n }\n }\n events.push({\n kind: \"type\",\n ...center(box),\n box,\n tMs,\n sel: label,\n note: step.note,\n ...(step.caption ? { caption: step.caption } : {}),\n text: step.value,\n // measured from tMs, not from the first keystroke: on the recovery\n // path the beat starts at the assist press, and the frame-diff\n // window + the compositor's dwell must span click-through-typing —\n // a typing-only duration would leave the recovery's ~700ms outside\n // the beat it belongs to\n durationMs: Date.now() - t0 - tMs,\n ...(step.zoom ? { zoom: step.zoom } : {}),\n });\n await hold(900);\n continue;\n }\n\n if (step.action === \"drag\") {\n // A freehand `path` carries its own endpoints — fall back to them so a\n // path-only drag (no addressable element) isn't dropped.\n const pathPts: Pt[] = (step.path ?? []).map((p) => ({\n x: Math.round(p.x),\n y: Math.round(p.y),\n }));\n const from =\n (await resolvePoint({ point: step.from, selector: step.selector, text: step.text })) ??\n pathPts[0] ??\n null;\n const to =\n (await resolvePoint({ point: step.to, selector: step.toSelector, text: step.toText })) ??\n pathPts[pathPts.length - 1] ??\n null;\n const label = step.note ?? step.text ?? step.selector;\n if (!from || !to) {\n skip(\"drag\", label, \"endpoint not found\");\n await hold(600);\n continue;\n }\n const path: Pt[] = pathPts.length ? pathPts : [from, to];\n const target = step.durationMs ?? 1200;\n // Stroke pacing baked into the ink. \"smooth\" (default) accelerates in /\n // decelerates out (a natural hand-draw); \"linear\" is constant speed. The\n // compositor cursor replays the SAME curve (it's recorded on the event)\n // so it stays locked to the ink. Time steps stay uniform; the EASING is\n // applied to the along-path position, so the pen moves slow-fast-slow.\n const dragEase = opts.dragEasing ?? \"smooth\";\n const easeParam = dragEase === \"smooth\" ? smoother : (u: number) => u;\n // ~16ms steps → ~60 distinct frames/sec captured (one redraw per move);\n // this is what keeps the ink from lagging the cursor (spike VERDICT).\n const n = Math.max(12, Math.round(target / 16));\n // Pause the raster pump for the held-button stroke (a stalled\n // captureScreenshot would block the drag's mouse events). Drain any\n // in-flight (button-up) screenshot first.\n pumpPaused = true;\n await sleep(160);\n const tDrag = Date.now();\n // the stroke starts here, after the pause: the event's time is when the\n // button goes down, so a replayed cursor moves with the ink\n const tMs = tDrag - t0;\n // All pointer events are fire-and-forget (see the move loop) — a\n // held-button dispatch withholds its ack ~5s in headless, so awaiting\n // press/release/moves would stall the stroke. Sends stay ordered on the\n // socket, and Chrome processes them promptly (only the ack is delayed).\n mouse(cdp, \"mouseMoved\", path[0]!.x, path[0]!.y, 0).catch(() => {});\n mouse(cdp, \"mousePressed\", path[0]!.x, path[0]!.y, 1).catch(() => {});\n for (let k = 1; k <= n; k++) {\n // Eased along-path position over UNIFORM time steps → the pen draws\n // slow-fast-slow (smooth) or constant (linear). cursorPos replays the\n // same `easeParam`, so cursor and ink stay locked (math.ts).\n const p = sampleAlong(path, easeParam(k / n));\n // FIRE-AND-FORGET the move (don't await its ack). A held-button\n // dispatchMouseEvent that paints nothing withholds its response ~5s in\n // headless (waiting for a frame commit) — awaiting each would stall the\n // whole stroke. Chrome still processes the moves in send order; we pace\n // the stroke by wall-clock below.\n mouse(cdp, \"mouseMoved\", p.x, p.y, 1).catch(() => {});\n // pace by absolute wall-clock so dispatch latency doesn't stretch the\n // stroke past its requested duration (drag stays on its editorial beat).\n const due = tDrag + (target * k) / n;\n const slack = due - Date.now();\n if (slack > 0) await sleep(slack);\n }\n const last = path[path.length - 1]!;\n mouse(cdp, \"mouseReleased\", last.x, last.y, 0).catch(() => {}); // no buttons held after release\n // durationMs is the STROKE window only (loop end ≈ target) — measured\n // before the flush/settle sleeps so the compositor cursor traces exactly\n // the ink's draw window and stays locked to it (not the longer wall time).\n const drawnMs = Date.now() - tDrag;\n await sleep(120); // let the release + last moves flush before resuming\n pumpPaused = false; // button released — safe to resume forced rasters\n events.push({\n kind: \"drag\",\n x: from.x,\n y: from.y,\n to,\n path,\n tMs,\n sel: label,\n note: step.note,\n ...(step.caption ? { caption: step.caption } : {}),\n durationMs: drawnMs,\n ease: dragEase,\n ...(step.zoom ? { zoom: step.zoom } : {}),\n });\n await hold(1100);\n continue;\n }\n\n if (step.action === \"dropFiles\") {\n // Synthesize an OS-level file drag-and-drop: CDP Input.dispatchDragEvent\n // carries REAL file paths, so the page's dragenter/dragover state fires\n // on the way in and the drop delivers actual Files (dataTransfer.files).\n // The DragData must ride EVERY dispatch (enter, each over, drop), not\n // just the drop (spiked: baseline {items:[], files, mask:1} works in\n // --headless=new with no focus requirement).\n const label = step.note ?? step.paths.map((p) => basename(p)).join(\", \");\n if (!step.paths.length) {\n skip(\"dropFiles\", label, \"no files given (empty paths)\");\n await hold(600);\n continue;\n }\n const absPaths = step.paths.map((p) => resolve(p));\n const missing = absPaths.filter((p) => !existsSync(p));\n if (missing.length) {\n skip(\"dropFiles\", label, `file not found: ${missing.join(\", \")}`);\n await hold(600);\n continue;\n }\n const files = absPaths.map((p) => {\n const st = statSync(p);\n return { name: basename(p), size: st.size };\n });\n // Drop target: locator when given (a FAILED lookup skips — dropping real\n // files \"somewhere in the middle\" would fabricate the beat, and Chrome's\n // default drop action could even navigate the tab to the file). The\n // viewport-centre default applies only when the plan names NO target.\n let to: Pt;\n if (step.to || step.toSelector || step.toText) {\n const found = await resolvePoint({\n point: step.to,\n selector: step.toSelector,\n text: step.toText,\n });\n if (!found) {\n skip(\"dropFiles\", label, \"drop target not found\");\n await hold(600);\n continue;\n }\n to = found;\n } else {\n to = { x: Math.round(inner[0] / 2), y: Math.round(inner[1] / 2) };\n }\n // default entry: swing in from the top-right edge, like a file dragged\n // in from the desktop; deterministic so re-makes reproduce the take.\n const from: Pt = step.from\n ? { x: Math.round(step.from.x), y: Math.round(step.from.y) }\n : { x: inner[0] - 28, y: Math.round(inner[1] * 0.18) };\n const pathPts: Pt[] = (step.path ?? []).map((p) => ({\n x: Math.round(p.x),\n y: Math.round(p.y),\n }));\n const path: Pt[] = pathPts.length ? pathPts : [from, to];\n const target = step.durationMs ?? 1400;\n const dragEase = opts.dragEasing ?? \"smooth\";\n const easeParam = dragEase === \"smooth\" ? smoother : (u: number) => u;\n const data = { items: [], files: absPaths, dragOperationsMask: 1 };\n const dragEvt = (type: \"dragEnter\" | \"dragOver\" | \"drop\", p: Pt) =>\n cdp.send(\"Input.dispatchDragEvent\", {\n type,\n x: Math.round(p.x),\n y: Math.round(p.y),\n data,\n });\n const n = Math.max(12, Math.round(target / 16));\n // Pause the raster pump for the carry (mirroring drag): a mid-drag\n // captureScreenshot could stall the CDP session; the page's dragover\n // reaction (dropzone morph) self-rasters, so nothing is lost.\n pumpPaused = true;\n await sleep(160);\n const tCarry = Date.now();\n const tMs = tCarry - t0; // when the carry starts, after the pause (see drag)\n const last = path[path.length - 1]!;\n let carriedMs: number;\n try {\n // dragEnter and the final drop are load-bearing (the page's drag\n // state, then the actual file delivery) — a rejection there means the\n // beat did NOT happen, so it must SKIP, not fabricate a success.\n // The mid-march dragOvers stay fire-and-forget: they only pace the\n // carry, and awaiting each ack would stall the stroke (see drag).\n await dragEvt(\"dragEnter\", path[0]!);\n for (let k = 1; k <= n; k++) {\n const p = sampleAlong(path, easeParam(k / n));\n dragEvt(\"dragOver\", p).catch(() => {});\n const due = tCarry + (target * k) / n;\n const slack = due - Date.now();\n if (slack > 0) await sleep(slack);\n }\n await dragEvt(\"dragOver\", last).catch(() => {});\n await dragEvt(\"drop\", last);\n carriedMs = Date.now() - tCarry;\n } catch (e) {\n pumpPaused = false;\n skip(\"dropFiles\", label, `drag dispatch failed: ${(e as Error).message}`);\n await hold(600);\n continue;\n }\n await sleep(120);\n pumpPaused = false;\n events.push({\n kind: \"dropFiles\",\n x: path[0]!.x,\n y: path[0]!.y,\n to: last,\n path,\n tMs,\n sel: label,\n note: step.note,\n ...(step.caption ? { caption: step.caption } : {}),\n durationMs: carriedMs,\n ease: dragEase,\n files,\n ...(step.zoom ? { zoom: step.zoom } : {}),\n });\n // dropzones usually kick off real work (parse / upload UI) — default a\n // longer settle than a click so the payoff is on screen.\n await hold(1600);\n continue;\n }\n\n if (step.action === \"scroll\") {\n // Resolve the scroll distance: to an element's centre, or a fixed dy\n // (default ~0.8 viewport down). The cursor holds; the content pans.\n const tMs = Date.now() - t0;\n let dy: number;\n if (step.toSelector || step.toText) {\n const r = (await evalAny(\n cdp,\n step.toSelector\n ? scrollDeltaSelectorJs(step.toSelector)\n : scrollDeltaByTextJs(step.toText!),\n )) as { dy?: number } | null;\n if (r && typeof r.dy === \"number\") {\n dy = r.dy;\n } else {\n skip(\"scroll\", step.toText ?? step.toSelector, \"target not found\");\n await hold(600);\n continue;\n }\n } else {\n dy = step.dy ?? Math.round(vh * 0.8);\n }\n const targetMs = step.durationMs ?? 1000;\n const cx = Math.round(inner[0] / 2),\n cy = Math.round(inner[1] / 2);\n // Programmatic window.scrollTo, eased and paced from node. The raster\n // pump (see above) forces the re-raster that makes the screencast\n // actually capture the motion — a bare scrollTo would otherwise freeze\n // the recording on stale tiles. No trusted wheel: it hangs forever in\n // headless if dispatched after an Escape keypress.\n const start = Number(await evalAny(cdp, \"window.scrollY\")) || 0;\n const n = Math.max(12, Math.round(targetMs / 16));\n const tScroll = Date.now();\n for (let k = 1; k <= n; k++) {\n const u = k / n;\n const want = Math.round(dy * (u * u * u * (u * (u * 6 - 15) + 10))); // eased cumulative\n await cdp.send(\"Runtime.evaluate\", { expression: `window.scrollTo(0, ${start + want})` });\n const due = tScroll + (targetMs * k) / n;\n const slack = due - Date.now();\n if (slack > 0) await sleep(slack);\n }\n events.push({\n kind: \"scroll\",\n x: cx,\n y: cy,\n tMs,\n dy,\n durationMs: Date.now() - tScroll,\n note: step.note,\n ...(step.caption ? { caption: step.caption } : {}),\n });\n await hold(800);\n continue;\n }\n\n if (step.action === \"hover\") {\n // Move the real pointer onto the element (triggers :hover / mouseenter)\n // and dwell so the tooltip/menu is visible. No click. The synthetic\n // cursor travels + parks at the same point (compositor).\n const label = step.text ?? step.selector;\n const tMs = Date.now() - t0;\n const box = step.text\n ? await evalBox(cdp, boxByTextJs(step.text))\n : step.selector\n ? await evalBox(cdp, boxSelectorJs(step.selector))\n : null;\n if (!box) {\n skip(\"hover\", label, \"target not found\");\n await hold(600);\n continue;\n }\n const c = center(box);\n const dwell = step.durationMs ?? 1200;\n await mouse(cdp, \"mouseMoved\", c.x, c.y, 0);\n events.push({\n kind: \"hover\",\n ...c,\n box,\n tMs,\n sel: label,\n note: step.note,\n ...(step.caption ? { caption: step.caption } : {}),\n durationMs: dwell,\n ...(step.zoom ? { zoom: step.zoom } : {}),\n });\n await sleep(dwell);\n // A hover DWELLS on its target and the cursor is parked for all of it, so\n // this settle is the ONLY room the next glide has. 300ms could not fit\n // one (travelMaxMs is 850 at the shipped pace) and the cursor darted.\n await hold(900);\n continue;\n }\n\n if (step.action === \"select\") {\n // Native <select>: set value + dispatch input/change (see\n // selectOptionJs — clicking one hangs the capture). Visually this is\n // a click beat: the cursor travels to the control and its value\n // changes under the pointer, which is exactly what a viewer sees a\n // user do, so it enters the log as `click`.\n const label = step.text ?? step.selector;\n const tMs = Date.now() - t0;\n const r = await cdp.send<{ result?: { value?: unknown } }>(\"Runtime.evaluate\", {\n expression: selectOptionJs({ selector: step.selector, text: step.text }, step.value),\n returnByValue: true,\n awaitPromise: true,\n });\n const raw = r.result?.value;\n const str = typeof raw === \"string\" ? raw : raw == null ? \"NOTFOUND\" : JSON.stringify(raw);\n if (str === \"NOTFOUND\" || str === \"NOTASELECT\" || str === \"NOOPTION\") {\n skip(\n \"select\",\n label,\n str === \"NOTASELECT\"\n ? \"target is not a <select> (use click for custom dropdowns)\"\n : str === \"NOOPTION\"\n ? `no option matching ${JSON.stringify(step.value)}`\n : \"target not found\",\n );\n await hold(600);\n continue;\n }\n const box = findBox(evalValue(str));\n if (!box) {\n skip(\"select\", label, \"target not found\");\n await hold(600);\n continue;\n }\n events.push({\n kind: \"click\",\n ...center(box),\n box,\n tMs,\n sel: label,\n note: step.note,\n ...(step.caption ? { caption: step.caption } : {}),\n ...(step.zoom ? { zoom: step.zoom } : {}),\n });\n await hold(1300);\n continue;\n }\n\n if (step.action === \"look\") {\n // CAMERA-only: resolve the target's bbox so the compositor can frame\n // it, then just WAIT out the hold. Nothing is dispatched to the page\n // and the synthetic cursor stays parked (compositor: no travel leg,\n // no ripple) — cursor movement promises an action, and a look makes\n // none. Zoom defaults to \"always\": framing IS this beat's content.\n // (Unrelated to the A/B `look=` knob, which names a backdrop preset.)\n const label = step.text ?? step.selector;\n const tMs = Date.now() - t0;\n const box = step.text\n ? await evalBox(cdp, boxByTextJs(step.text))\n : step.selector\n ? await evalBox(cdp, boxSelectorJs(step.selector))\n : null;\n if (!box) {\n skip(\"look\", label, step.text || step.selector ? \"target not found\" : \"no target given\");\n await hold(600);\n continue;\n }\n const dwell = step.durationMs ?? 1800;\n events.push({\n kind: \"look\",\n ...center(box),\n box,\n tMs,\n sel: label,\n note: step.note,\n ...(step.caption ? { caption: step.caption } : {}),\n durationMs: dwell,\n zoom: step.zoom ?? \"always\",\n });\n await sleep(dwell);\n // The cursor is parked through the hold (like hover/press), so this\n // settle is the entire window the next travel has to glide in.\n await hold(900);\n continue;\n }\n\n if (step.action === \"press\") {\n // Keyboard-driven: dispatch the chord to whatever has focus, then hold\n // while the effect plays out. The cursor does NOT move. If a reveal\n // element is named, locate its bbox AFTER the press so the zoom frames\n // what appeared.\n const tMs = Date.now() - t0;\n try {\n await pressChord(cdp, step.keys);\n } catch (e) {\n console.error(\n `captureTakeCDP: press failed for ${JSON.stringify(step.keys)}: ${(e as Error).message}`,\n );\n }\n const dwell = step.durationMs ?? 1000;\n let box: Box | null = null;\n if (step.selector || step.text) {\n await sleep(250); // let the revealed UI mount before measuring\n box = step.text\n ? await evalBox(cdp, boxByTextJs(step.text))\n : await evalBox(cdp, boxSelectorJs(step.selector!));\n }\n const anchor = box\n ? center(box)\n : { x: Math.round(inner[0] / 2), y: Math.round(inner[1] / 2) };\n events.push({\n kind: \"press\",\n ...anchor,\n ...(box ? { box } : {}),\n tMs,\n keys: step.keys,\n sel: step.text ?? step.selector,\n note: step.note,\n ...(step.caption ? { caption: step.caption } : {}),\n durationMs: dwell,\n ...(step.zoom ? { zoom: step.zoom } : {}),\n });\n await sleep(dwell);\n // Same as hover: the cursor is parked through the reveal, so this settle is\n // the entire window the next travel has to glide in. See hold() above.\n await hold(900);\n continue;\n }\n\n // click: one eval resolves the element and decides delivery. When the\n // centre is hittable the eval returns `cx`/`cy` WITHOUT clicking, and\n // the click is delivered here as trusted CDP input — press + release,\n // the full pointerdown→click pipeline. A programmatic m.click() fires a\n // lone `click` event, and pointer-listening controls (Radix dropdown\n // triggers open on pointerdown) treat that as silence: measured on a\n // real shoot, the step \"succeeded\", nothing opened, and 8 of 10 beats\n // died downstream. The eval keeps m.click() as its own fallback for\n // targets a coordinate cannot reach (zero-size / covered /\n // pointer-events:none), so `cx` missing means \"already clicked in-page\".\n const label = step.text ?? step.selector;\n let tMs = Date.now() - t0; // js-fallback mode: the eval clicks ~now\n // the locators refuse to .click() a <select> (it hangs the capture) and\n // say so with this sentinel — name the real fix instead of \"not found\"\n const clickRaw = step.text\n ? await evalString(cdp, clickByTextJs(step.text))\n : step.selector\n ? await evalString(cdp, clickBySelectorJs(step.selector))\n : null;\n if (clickRaw === \"SELECTINERT\") {\n skip(\n \"click\",\n label,\n \"clicking a native <select> does nothing headless (inert, no popup) — use the `select` action\",\n );\n await hold(600);\n continue;\n }\n const parsed = clickRaw ? (evalValue(clickRaw) as Record<string, unknown> | null) : null;\n const box = parsed ? findBox(parsed) : null;\n const pt =\n parsed && typeof parsed.cx === \"number\" && typeof parsed.cy === \"number\"\n ? { x: parsed.cx, y: parsed.cy }\n : null;\n if (box && pt) {\n // Trusted delivery, mirroring the drag block's proven pattern: pause\n // the forced-raster pump (a stalled captureScreenshot would block the\n // held-button dispatch), drain any in-flight one, then fire-and-forget\n // — a held-button dispatchMouseEvent withholds its ack ~5s in headless,\n // so awaiting press/release would stall the beat. Sends stay ordered\n // on the socket; Chrome processes them promptly.\n pumpPaused = true;\n await sleep(160);\n tMs = Date.now() - t0; // the press, not the eval, is the beat\n mouse(cdp, \"mouseMoved\", pt.x, pt.y, 0).catch(() => {});\n mouse(cdp, \"mousePressed\", pt.x, pt.y, 1).catch(() => {});\n await sleep(60); // a human-scale press→release gap\n mouse(cdp, \"mouseReleased\", pt.x, pt.y, 0).catch(() => {});\n await sleep(120); // let the release flush before resuming rasters\n pumpPaused = false;\n }\n if (box) {\n events.push({\n kind: \"click\",\n ...(pt ?? center(box)),\n box,\n tMs,\n sel: label,\n note: step.note,\n ...(step.caption ? { caption: step.caption } : {}),\n ...(step.zoom ? { zoom: step.zoom } : {}),\n });\n } else {\n skip(\"click\", label, \"target not found\");\n }\n await hold(1300);\n }\n\n const tEndMs = Date.now() - t0;\n await sleep(400);\n pumping = false;\n await pump;\n await screencast.stop();\n // The encode and the states' conversion + fidelity pass are independent\n // (disk + ffmpeg vs. a second page in the still-open browser), so they run\n // side by side. The encode is awaited below; the early catch only keeps\n // a rejection from going unhandled while the states finish.\n const encoded = encodeFrames(screencast.frames, tEndMs + 400, out, fps);\n encoded.catch(() => {});\n const sound = productAudio\n ? productAudio.finish({ t0, endMs: tEndMs + 400, dir: dirname(out) })\n : Promise.resolve(null);\n let stateItems: DomStateItem[] | undefined;\n if (statesDir && (states.length || movingStates.length)) {\n try {\n const saved = states.length\n ? await finalizeDomStates({\n browser,\n statesDir,\n states,\n vw: inner[0],\n vh: inner[1],\n parts: opts.components !== false,\n })\n : [];\n stateItems = [...saved, ...movingStates.map((m) => ({ ...m, moving: true as const }))].sort(\n (a, b) => a.tMs - b.tMs,\n );\n console.error(summarizeDomStates(states, stateItems));\n } catch (e) {\n console.error(`captureTakeCDP: DOM states not finalized (${(e as Error).message})`);\n }\n }\n await encoded;\n const soundReport = await sound;\n if (soundReport) console.error(summarizeProductSound(soundReport));\n\n const probe = await ffprobe(out);\n // Space-integrity check: the whole pipeline maps coordinates viewport →\n // stage 1:1, which is only true while the encoded frame KEEPS the\n // viewport's aspect (uniform scale cancels out downstream; a non-uniform\n // one skews every cursor/zoom point). A window resize mid-capture — after\n // the re-fit above — is the one thing that breaks it: the screencast then\n // uniform-fits a changed surface into the stale cap and the aspects drift\n // apart. Say so loudly; the take will render with visibly misplaced\n // cursors and re-running is the fix.\n if (probe.width && probe.height) {\n const videoAspect = probe.width / probe.height;\n const viewAspect = inner[0] / inner[1];\n if (Math.abs(videoAspect / viewAspect - 1) > 0.01) {\n process.stderr.write(\n `⚠ the browser window resized MID-capture: viewport ${inner[0]}×${inner[1]} but the ` +\n `recording is ${probe.width}×${probe.height} — cursor/zoom coordinates in this take ` +\n `are skewed. Re-run; in a cloud/Xvfb environment give the screen a fixed size at ` +\n `least the requested viewport.\\n`,\n );\n }\n }\n return {\n video: {\n width: probe.width ?? inner[0],\n height: probe.height ?? inner[1],\n fps: probe.fps,\n durationS: probe.durationS,\n },\n viewport: { w: inner[0], h: inner[1] },\n start: plan.startCursor ?? { x: Math.round(inner[0] * 0.25), y: Math.round(inner[1] * 0.9) },\n events,\n tEndMs,\n captureCadence: {\n ...captureCadence(screencast.frames),\n rasterRefresh: opts.rasterRefresh ?? \"idle\",\n },\n // Both of these were collected all along but never reached the caller on\n // this path, so the end-of-run summary and the strict exit saw an empty list and\n // a dropped beat lived only in an early stderr line — exactly what the\n // CaptureLog.skipped contract says must not happen.\n ...(skipped.length ? { skipped } : {}),\n ...(precheck.length ? { precheck } : {}),\n ...(settleWaits.length ? { settleWaits } : {}),\n ...(paintedFrac >= PAINT_BLIND_FRAC\n ? { paintedFrac: Math.round(paintedFrac * 100) / 100 }\n : {}),\n ...(stateItems ? { states: { dir: \"states\", items: stateItems } } : {}),\n };\n } finally {\n await browser?.close();\n rmSync(frameDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });\n }\n}\n\n/** One stderr paragraph on what the product's sound left in the take. */\nfunction summarizeProductSound(r: ProductSoundReport): string {\n const lines: string[] = [];\n if (r.audio)\n lines.push(\n `product audio: ${r.audio.file} — sound at ${r.audio.soundAt.length} moment(s), peak ${r.audio.peakDbfs} dBFS (placement estimated; see product-sound.json)`,\n );\n else lines.push(\"product audio: not detected (the page sent nothing to its speakers)\");\n if (r.files.length) {\n const saved = r.files.filter((f) => f.saved).length;\n lines.push(\n `product sound files: the page fetched ${r.files.length} audio file(s)${saved ? `, ${saved} saved to product-sounds/` : \"\"}`,\n );\n }\n for (const n of r.notes) lines.push(`product audio: ${n}`);\n return lines.join(\"\\n\");\n}\n\n// Navigate and wait for load (bounded) so the first frame isn't a blank page.\n/** CI containment. A plan is agent-written, and the agent reads the very page\n * it films — a hostile string ON that page can talk its way into a plan step.\n * When OPEN_TAKE_ALLOWED_ORIGINS is set (comma-separated origins; `open-take\n * ci` sets it to the app's own origin), any navigation outside the list is a\n * skipped step, never a request. Unset (the interactive default), everything\n * is allowed — a human is watching. */\nexport function originAllowed(url: string): boolean {\n const raw = process.env.OPEN_TAKE_ALLOWED_ORIGINS;\n if (!raw) return true;\n try {\n const origin = new URL(url).origin;\n return raw.split(\",\").some((entry) => entry.trim() === origin);\n } catch {\n return false;\n }\n}\n\n/** Runs in-page AFTER focus landed on the type target: names the field\n * \"secret\" when it is a password input or smells like a credential field.\n * Only consulted under OPEN_TAKE_CI — locally the human sees what is typed. */\nfunction credentialFieldProbeJs(): string {\n return `(() => {\n const el = document.activeElement;\n if (!el) return \"ok\";\n const type = (el.getAttribute(\"type\") || \"\").toLowerCase();\n const smell = [el.getAttribute(\"name\"), el.getAttribute(\"id\"), el.getAttribute(\"autocomplete\"), el.getAttribute(\"placeholder\")]\n .filter(Boolean).join(\" \").toLowerCase();\n return type === \"password\" || /passw|secret|api[-_]?key|access[-_]?token/.test(smell) ? \"secret\" : \"ok\";\n })()`;\n}\n\n/** Returns Chrome's `errorText` (e.g. \"net::ERR_CONNECTION_REFUSED\") when the\n * navigation never reached a server — the tab is then showing Chrome's own\n * error page, which fires load events like any document and would otherwise\n * get filmed as if it were the app. HTTP error PAGES (404/500) carry no\n * errorText: the app answered, and what it said is what an honest take shows. */\nexport async function navigate(cdp: CDP, url: string): Promise<string | undefined> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const loaded = new Promise<void>((res) => {\n cdp.on(\"Page.loadEventFired\", () => res());\n timer = setTimeout(res, 8000); // don't hang on a never-firing load\n });\n const nav = await cdp.send<{ errorText?: string }>(\"Page.navigate\", { url });\n await loaded;\n // a pending timer keeps the process alive: a short `shoot` would sit out\n // the rest of the 8 s before it could exit\n clearTimeout(timer);\n return nav.errorText || undefined;\n}\n"],"mappings":";;;;;;;;;;;;AA8BA,MAAMA,UAAQ,CAACC,OAAe,IAAI,QAAQ,CAAC,MAAM,WAAW,GAAG,GAAG;AAClE,MAAM,UAAU,cAAc,OAAO,KAAK,IAAI;AAG9C,MAAM,eAAe,KAAK,SAAS,EAAE,cAAc,WAAW;AAC9D,MAAM,eAAe,KAAK,SAAS,EAAE,cAAc,oBAAoB;AAWvE,SAAgB,cAAcC,UAAkC;CAC9D,MAAMC,aAAuB,CAAE;AAC/B,KAAI,SAAU,YAAW,KAAK,SAAS;AACvC,KAAI,QAAQ,IAAI,iBAAkB,YAAW,KAAK,QAAQ,IAAI,iBAAiB;AAI/E,KAAI,WAAW,aAAa,CAC1B,KAAI;EACF,MAAM,MAAM,sBAAsB,KAAK,MAAM,aAAa,cAAc,OAAO,CAAC,CAAC,QAAQ;AACzF,MAAI,IAAK,YAAW,KAAK,IAAI;CAC9B,QAAO,CAEP;CAIH,MAAM,aAAa,KAAK,SAAS,EAAE,kBAAkB,WAAW;AAChE,KAAI,WAAW,WAAW,CACxB,MAAK,MAAM,KAAK,YAAY,WAAW,CACpC,OAAO,CAAC,MAAM,EAAE,WAAW,UAAU,CAAC,CACtC,MAAM,CACN,SAAS,CACV,YAAW,KACT,KACE,YACA,GACA,yEACD,EACD,KAAK,YAAY,GAAG,kBAAkB,SAAS,EAC/C,KAAK,YAAY,GAAG,SAAS,CAC9B;AAIL,QAAO,WAAW,KAAK,CAAC,MAAM,KAAK,WAAW,EAAE,CAAC,IAAI;AACtD;AAID,SAAS,sBAAsBC,SAAgC;AAC7D,KAAI;EAEF,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