| 1 | #!/usr/bin/env node |
| 2 | import { readFileSync, writeFileSync } from "node:fs"; |
| 3 | import path from "node:path"; |
| 4 | import { fileURLToPath } from "node:url"; |
| 5 | import { hex, paletteColor } from "./terminal-palette.mjs"; |
| 6 | |
| 7 | const webRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); |
| 8 | const inputDir = path.join(webRoot, "lib", "terminal-captures", "released"); |
| 9 | const outPath = path.join(webRoot, "lib", "released-capture.generated.ts"); |
| 10 | |
| 11 | const DEFAULT_FG = paletteColor(252); |
| 12 | const DEFAULT_BG = paletteColor(234); |
| 13 | |
| 14 | const ESCAPE_OR_CONTROL = /\x1b\[([0-9;]*)m|[\x00-\x1f\x7f]/gu; |
| 15 | |
| 16 | function freshState() { |
| 17 | return { fg: null, bg: null, bold: false, dim: false, italic: false, underline: false, strike: false, reverse: false }; |
| 18 | } |
| 19 | |
| 20 | function applySgr(state, params, where) { |
| 21 | const p = params.length ? params : [0]; |
| 22 | for (let i = 0; i < p.length; i++) { |
| 23 | const c = p[i]; |
| 24 | if (c === 0) Object.assign(state, freshState()); |
| 25 | else if (c === 1) state.bold = true; |
| 26 | else if (c === 2) state.dim = true; |
| 27 | else if (c === 3) state.italic = true; |
| 28 | else if (c === 4) state.underline = true; |
| 29 | else if (c === 7) state.reverse = true; |
| 30 | else if (c === 9) state.strike = true; |
| 31 | else if (c === 22) state.bold = state.dim = false; |
| 32 | else if (c === 23) state.italic = false; |
| 33 | else if (c === 24) state.underline = false; |
| 34 | else if (c === 27) state.reverse = false; |
| 35 | else if (c === 29) state.strike = false; |
| 36 | else if (c >= 30 && c <= 37) state.fg = paletteColor(c - 30); |
| 37 | else if (c >= 90 && c <= 97) state.fg = paletteColor(c - 90 + 8); |
| 38 | else if (c >= 40 && c <= 47) state.bg = paletteColor(c - 40); |
| 39 | else if (c >= 100 && c <= 107) state.bg = paletteColor(c - 100 + 8); |
| 40 | else if (c === 39) state.fg = null; |
| 41 | else if (c === 49) state.bg = null; |
| 42 | else if ((c === 38 || c === 48) && p[i + 1] === 5 && p[i + 2] <= 255) { |
| 43 | state[c === 38 ? "fg" : "bg"] = paletteColor(p[i + 2]); |
| 44 | i += 2; |
| 45 | } else if ((c === 38 || c === 48) && p[i + 1] === 2 && p.slice(i + 2, i + 5).every((v) => v <= 255) && i + 4 < p.length) { |
| 46 | state[c === 38 ? "fg" : "bg"] = hex(p[i + 2], p[i + 3], p[i + 4]); |
| 47 | i += 4; |
| 48 | } else { |
| 49 | throw new Error(`${where}: unhandled SGR ${params.join(";")}`); |
| 50 | } |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | function styleOf(state) { |
| 55 | let fg = state.fg ?? DEFAULT_FG; |
| 56 | let bg = state.bg ?? DEFAULT_BG; |
| 57 | if (state.reverse) [fg, bg] = [bg, fg]; |
| 58 | return { |
| 59 | fg, |
| 60 | bg, |
| 61 | ...(state.bold ? { bold: true } : {}), |
| 62 | ...(state.italic ? { italic: true } : {}), |
| 63 | ...(state.dim ? { dim: true } : {}), |
| 64 | ...(state.underline ? { underline: true } : {}), |
| 65 | ...(state.strike ? { strike: true } : {}), |
| 66 | }; |
| 67 | } |
| 68 | |
| 69 | function parse(ansi, columns, rows, where) { |
| 70 | const state = freshState(); |
| 71 | const input = ansi.endsWith("\n") ? ansi.slice(0, -1) : ansi; |
| 72 | const cellRows = input.split("\n").map((line, row) => { |
| 73 | const cells = []; |
| 74 | let last = 0; |
| 75 | for (const match of line.matchAll(ESCAPE_OR_CONTROL)) { |
| 76 | for (const ch of line.slice(last, match.index)) cells.push([ch, styleOf(state)]); |
| 77 | if (match[1] === undefined) throw new Error(`${where} row ${row + 1}: unhandled control ${JSON.stringify(match[0])}`); |
| 78 | applySgr(state, match[1] === "" ? [] : match[1].split(";").map(Number), `${where} row ${row + 1}`); |
| 79 | last = match.index + match[0].length; |
| 80 | } |
| 81 | for (const ch of line.slice(last)) cells.push([ch, styleOf(state)]); |
| 82 | if (cells.length > columns) throw new Error(`${where} row ${row + 1}: ${cells.length} cells, wider than ${columns}`); |
| 83 | const blank = styleOf(freshState()); |
| 84 | while (cells.length < columns) cells.push([" ", blank]); |
| 85 | return cells; |
| 86 | }); |
| 87 | if (cellRows.length !== rows) throw new Error(`${where}: ${cellRows.length} rows, provenance says ${rows}`); |
| 88 | return cellRows; |
| 89 | } |
| 90 | |
| 91 | function compact(cellRows) { |
| 92 | const styles = []; |
| 93 | const styleIndex = new Map(); |
| 94 | const indexOf = (style) => { |
| 95 | const key = JSON.stringify(style); |
| 96 | if (!styleIndex.has(key)) { |
| 97 | styleIndex.set(key, styles.length); |
| 98 | styles.push(style); |
| 99 | } |
| 100 | return styleIndex.get(key); |
| 101 | }; |
| 102 | const lines = cellRows.map((cells) => { |
| 103 | const runs = []; |
| 104 | for (const [ch, style] of cells) { |
| 105 | const last = runs.at(-1); |
| 106 | if (ch === " ") { |
| 107 | const visible = (s) => `${s.bg}|${s.underline ? 1 : 0}|${s.strike ? 1 : 0}|${s.dim ? 1 : 0}`; |
| 108 | if (last && visible(styles[last[1]]) === visible(style)) { |
| 109 | last[0] += ch; |
| 110 | continue; |
| 111 | } |
| 112 | const plain = { fg: DEFAULT_FG, bg: style.bg, ...(style.dim ? { dim: true } : {}), ...(style.underline ? { underline: true } : {}), ...(style.strike ? { strike: true } : {}) }; |
| 113 | runs.push([ch, indexOf(plain)]); |
| 114 | continue; |
| 115 | } |
| 116 | const index = indexOf(style); |
| 117 | if (last && last[1] === index) last[0] += ch; |
| 118 | else runs.push([ch, index]); |
| 119 | } |
| 120 | return runs; |
| 121 | }); |
| 122 | return { styles, lines }; |
| 123 | } |
| 124 | |
| 125 | function strip(ansi) { |
| 126 | return ansi.replace(ESCAPE_OR_CONTROL, (m, sgr) => { |
| 127 | if (sgr === undefined && m !== "\n") throw new Error(`unhandled control ${JSON.stringify(m)}`); |
| 128 | return sgr === undefined ? m : ""; |
| 129 | }); |
| 130 | } |
| 131 | |
| 132 | function generate() { |
| 133 | const provenance = JSON.parse(readFileSync(path.join(inputDir, "provenance.json"), "utf8")); |
| 134 | const versionLine = provenance.binary.version_line; |
| 135 | const raw = new Map(); |
| 136 | const frames = {}; |
| 137 | for (const entry of provenance.frames) { |
| 138 | const where = entry.file; |
| 139 | const ansi = readFileSync(path.join(inputDir, entry.file), "utf8"); |
| 140 | let cellRows; |
| 141 | if (entry.crop_of) { |
| 142 | const parent = raw.get(entry.crop_of); |
| 143 | if (!parent) throw new Error(`${where}: crop_of ${entry.crop_of} must be listed before its crop`); |
| 144 | const { first, last } = entry.crop_rows; |
| 145 | cellRows = parent.cellRows.slice(first - 1, last); |
| 146 | const own = strip(ansi).replace(/\n$/, "").split("\n"); |
| 147 | const sliced = cellRows.map((cells) => cells.map(([ch]) => ch).join("")); |
| 148 | const trimmed = (rows) => rows.map((row) => row.replace(/ +$/, "")); |
| 149 | if (JSON.stringify(trimmed(own)) !== JSON.stringify(trimmed(sliced))) { |
| 150 | throw new Error(`${where}: is not rows ${first}-${last} of ${entry.crop_of}`); |
| 151 | } |
| 152 | if (cellRows.length !== entry.rows) throw new Error(`${where}: ${cellRows.length} rows, provenance says ${entry.rows}`); |
| 153 | } else { |
| 154 | cellRows = parse(ansi, entry.columns, entry.rows, where); |
| 155 | raw.set(entry.id, { cellRows }); |
| 156 | } |
| 157 | const { styles, lines } = compact(cellRows); |
| 158 | frames[entry.id] = { |
| 159 | id: entry.id, |
| 160 | file: `web/lib/terminal-captures/released/${entry.file}`, |
| 161 | state: entry.shows, |
| 162 | provenance: "released", |
| 163 | versionLine, |
| 164 | cols: entry.columns, |
| 165 | rows: entry.rows, |
| 166 | shows: { |
| 167 | testRun: entry.shows_test_run, |
| 168 | askPosture: entry.shows_ask_posture, |
| 169 | modelName: entry.shows_model_name, |
| 170 | modelConnected: entry.model_connected, |
| 171 | taskSession: entry.in_task_session, |
| 172 | }, |
| 173 | cropOf: entry.crop_of ?? null, |
| 174 | cropRows: entry.crop_rows ? [entry.crop_rows.first, entry.crop_rows.last] : null, |
| 175 | styles, |
| 176 | lines, |
| 177 | }; |
| 178 | } |
| 179 | const meta = { |
| 180 | capture: provenance.capture, |
| 181 | versionLine, |
| 182 | releaseTag: provenance.binary.release_tag, |
| 183 | asset: provenance.binary.asset, |
| 184 | releaseChecksumLine: provenance.binary.release_checksum_line, |
| 185 | defaultFg: DEFAULT_FG, |
| 186 | defaultBg: DEFAULT_BG, |
| 187 | }; |
| 188 | return `// GENERATED by web/scripts/render-released-capture.mjs — do not edit. |
| 189 | // Source: web/lib/terminal-captures/released/ (${versionLine}, tmux capture-pane -p -e). |
| 190 | import type { TerminalCaptureFrame } from "./terminal-capture-types"; |
| 191 | |
| 192 | export type ReleasedCaptureFrame = Omit<TerminalCaptureFrame, "provenance"> & { |
| 193 | id: string; |
| 194 | provenance: "released"; |
| 195 | versionLine: string; |
| 196 | shows: { |
| 197 | testRun: boolean; |
| 198 | askPosture: boolean; |
| 199 | modelName: boolean; |
| 200 | modelConnected: boolean; |
| 201 | taskSession: boolean; |
| 202 | }; |
| 203 | cropOf: string | null; |
| 204 | cropRows: [number, number] | null; |
| 205 | }; |
| 206 | |
| 207 | export const RELEASED_CAPTURE_META = ${JSON.stringify(meta, null, 2)} as const; |
| 208 | |
| 209 | export const RELEASED_CAPTURE_FRAMES = ${JSON.stringify(frames)} as const satisfies Record<string, ReleasedCaptureFrame>; |
| 210 | |
| 211 | export type ReleasedCaptureFrameId = keyof typeof RELEASED_CAPTURE_FRAMES; |
| 212 | `; |
| 213 | } |
| 214 | |
| 215 | if (process.argv.includes("--check")) { |
| 216 | let current = ""; |
| 217 | try { |
| 218 | current = readFileSync(outPath, "utf8"); |
| 219 | } catch { |
| 220 | } |
| 221 | if (current !== generate()) { |
| 222 | console.error("released-capture.generated.ts is stale: run node scripts/render-released-capture.mjs"); |
| 223 | process.exit(1); |
| 224 | } |
| 225 | console.log("released-capture.generated.ts is current"); |
| 226 | } else { |
| 227 | writeFileSync(outPath, generate()); |
| 228 | console.log(`wrote ${path.relative(webRoot, outPath)}`); |
| 229 | } |
| 230 |