import { type ChildProcess, execFile, spawn } from "node:child_process"; import { existsSync } from "node:fs"; import { mkdir, mkdtemp, readdir, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { dirname, join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import { promisify } from "node:util"; import { parseArgs } from "../args.js"; import { collectDiff } from "../git.js"; import { startReviewServer } from "../server.js"; const execFileAsync = promisify(execFile); const EXT_DIR = dirname(dirname(fileURLToPath(import.meta.url))); const ROOT = dirname(dirname(EXT_DIR)); const WIDTH = 1400; const HEIGHT = 900; const FPS = 8; const FRAME_DELAY_MS = 100; const CHROME_COMMANDS = [ "google-chrome-stable", "google-chrome", "chromium", "chromium-browser", ]; async function main() { const out = outputPath(); const chrome = process.env.CHROME ?? (await findCommand(CHROME_COMMANDS)); if (!chrome) throw new Error("Chrome/Chromium not found; set CHROME=/path/to/chrome"); if (!(await findCommand(["ffmpeg"]))) throw new Error("ffmpeg not found"); await execFileAsync("bun", ["run", "build"], { cwd: EXT_DIR, maxBuffer: 20 * 1024 * 1024, }); const repo = await mkdtemp(join(tmpdir(), "diff-review-demo-repo-")); const profile = await mkdtemp(join(tmpdir(), "diff-review-demo-chrome-")); const frames = await mkdtemp(join(tmpdir(), "diff-review-demo-frames-")); let browser: ChildProcess | undefined; let server: Awaited> | undefined; try { await prepareRepo(repo); server = await startReviewServer({ diff: await collectDiff(repo, parseArgs("")), state: { round: 0, findings: [], rounds: [] }, round: 1, timeoutMs: 60_000, }); const debugPort = 12_000 + Math.floor(Math.random() * 1000); browser = launchChrome(chrome, profile, debugPort, server.url); const client = await connectCdp( (await waitForTab(debugPort)).webSocketDebuggerUrl, ); try { await client.call("Runtime.enable"); await client.call("Page.enable"); await waitForUi(client); await recordFrames(client, frames); } finally { client.close(); } } finally { server?.close("demo"); browser?.kill("SIGTERM"); await Promise.all([ rm(repo, { recursive: true, force: true }), rm(profile, { recursive: true, force: true }), ]); } await encodeGif(frames, out); const count = (await readdir(frames)).filter((name) => name.endsWith(".png"), ).length; await rm(frames, { recursive: true, force: true }); console.log(`OK browser demo ${out} (${count} frames)`); } function outputPath() { const idx = process.argv.indexOf("--out"); if (idx >= 0 && process.argv[idx + 1]) return resolve(process.argv[idx + 1]); return join(ROOT, ".demo", "diff_review_browser.gif"); } async function prepareRepo(repo: string) { await git(repo, ["init", "-q"]); await git(repo, ["config", "user.email", "demo@example.invalid"]); await git(repo, ["config", "user.name", "Demo"]); await mkdir(join(repo, "src")); await mkdir(join(repo, "test")); await writeFile( join(repo, "src/report.ts"), `export function total(items: number[]) {\n\treturn items.reduce((sum, n) => sum + n, 0);\n}\n\nexport function label(name: string) {\n\treturn name.trim();\n}\n`, ); await writeFile( join(repo, "test/report.test.ts"), `import { total } from '../src/report';\n\nconsole.log(total([1, 2]));\n`, ); await git(repo, ["add", "."]); await git(repo, ["commit", "-qm", "init"]); await writeFile( join(repo, "src/report.ts"), `export function total(items: number[]) {\n\treturn items.reduce((sum, n) => sum - n, 0);\n}\n\nexport function label(name: string) {\n\treturn name.trim().toUpperCase();\n}\n`, ); await writeFile( join(repo, "test/report.test.ts"), `import { total } from '../src/report';\n\nconsole.log(total([1, 2, 3]));\n`, ); } async function git(cwd: string, args: string[]) { await execFileAsync("git", args, { cwd, maxBuffer: 20 * 1024 * 1024 }); } function launchChrome( chrome: string, profile: string, debugPort: number, url: string, ) { return spawn( chrome, [ "--headless=new", "--disable-gpu", "--no-sandbox", "--disable-dev-shm-usage", `--remote-debugging-port=${debugPort}`, `--user-data-dir=${profile}`, `--window-size=${WIDTH},${HEIGHT}`, url, ], { stdio: "ignore" }, ); } async function recordFrames(client: CdpClient, frames: string) { let frame = 0; const snap = async (count: number) => { for (let i = 0; i < count; i++) { const result = await client.call("Page.captureScreenshot", { format: "png", fromSurface: true, }); const data = result.result?.data; if (typeof data !== "string") throw new Error("screenshot failed"); await writeFile( join(frames, `${String(frame++).padStart(4, "0")}.png`), Buffer.from(data, "base64"), ); await sleep(FRAME_DELAY_MS); } }; await snap(8); await client.eval(` document.querySelector('#theme-mode').value = 'dark'; document.querySelector('#theme-mode').dispatchEvent(new Event('change', { bubbles: true })); `); await snap(8); await client.eval(` document.querySelector('#search').value = 'total'; document.querySelector('#search').dispatchEvent(new Event('input', { bubbles: true })); `); await sleep(300); await snap(10); await client.eval(` document.querySelector('#search').dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true })); `); await sleep(300); await snap(8); await client.eval(` const root = document.querySelector('diffs-container')?.shadowRoot; const line = root?.querySelector('[data-additions] [data-line]'); const rect = line?.getBoundingClientRect(); line?.dispatchEvent(new MouseEvent('click', { bubbles: true, composed: true, clientX: (rect?.left ?? 300) + 24, clientY: (rect?.top ?? 300) + 10, })); `); await sleep(500); await snap(8); await client.eval(` document.querySelector('#comment').value = 'Demo finding: validate changed total.'; document.querySelector('#comment').dispatchEvent(new Event('input', { bubbles: true })); `); await snap(10); } async function encodeGif(frames: string, out: string) { const palette = join(frames, "palette.png"); await execFileAsync( "ffmpeg", [ "-y", "-framerate", String(FPS), "-i", join(frames, "%04d.png"), "-vf", "scale=1000:-1:flags=lanczos,palettegen", palette, ], { maxBuffer: 20 * 1024 * 1024 }, ); await execFileAsync( "ffmpeg", [ "-y", "-framerate", String(FPS), "-i", join(frames, "%04d.png"), "-i", palette, "-lavfi", "scale=1000:-1:flags=lanczos[x];[x][1:v]paletteuse", out, ], { maxBuffer: 20 * 1024 * 1024 }, ); } async function waitForUi(client: CdpClient) { await sleep(1000); for (let i = 0; i < 80; i++) { const ok = await client.eval(` document.querySelector('diffs-container')?.shadowRoot?.querySelector('[data-additions] [data-line]') !== null `); if (ok === true) return; await sleep(100); } throw new Error("diff-review UI not ready"); } async function waitForTab( port: number, ): Promise<{ webSocketDebuggerUrl: string }> { for (let i = 0; i < 80; i++) { const tab = await fetch(`http://127.0.0.1:${port}/json/list`) .then((res) => res.json() as Promise>>) .catch(() => undefined); const page = tab?.find( (item) => item.type === "page" && item.webSocketDebuggerUrl && item.url?.startsWith("http://127.0.0.1"), ); if (page?.webSocketDebuggerUrl) { return { webSocketDebuggerUrl: page.webSocketDebuggerUrl }; } await sleep(250); } throw new Error("Chrome CDP tab not found"); } type CdpResponse = { result?: { data?: unknown; result?: { value?: unknown }; exceptionDetails?: { text?: string }; }; error?: { message?: string }; }; type CdpClient = { call(method: string, params?: Record): Promise; eval(expression: string): Promise; close(): void; }; async function connectCdp(url: string): Promise { let id = 0; const ws = new WebSocket(url); const pending = new Map void>(); ws.onmessage = (event) => { const msg = JSON.parse(String(event.data)); if (typeof msg.id !== "number") return; const resolve = pending.get(msg.id); if (!resolve) return; pending.delete(msg.id); resolve(msg); }; await new Promise((resolve, reject) => { ws.onopen = () => resolve(); ws.onerror = reject; }); return { call(method: string, params: Record = {}) { return new Promise((resolve) => { const callId = ++id; pending.set(callId, resolve); ws.send(JSON.stringify({ id: callId, method, params })); }); }, async eval(expression: string) { const response = await this.call("Runtime.evaluate", { expression, returnByValue: true, awaitPromise: true, }); if (response.error) throw new Error(response.error.message ?? "CDP error"); if (response.result?.exceptionDetails) throw new Error(response.result.exceptionDetails.text ?? "eval failed"); return response.result?.result?.value; }, close() { ws.close(); }, }; } async function findCommand(commands: string[]) { for (const command of commands) { const found = await execFileAsync("sh", ["-c", `command -v ${command}`]) .then((result) => result.stdout.trim()) .catch(() => ""); if (found && existsSync(found)) return found; } return undefined; } function sleep(ms: number) { return new Promise((resolve) => setTimeout(resolve, ms)); } main().catch((err) => { console.error(err instanceof Error ? err.message : String(err)); process.exit(1); });