@skilldeck/studio 0.0.0-stage → 1.0.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,379 @@
1
+ #!/usr/bin/env node
2
+ // studio / render.mjs
3
+ //
4
+ // Render an HTML composition deterministically. Headless Chrome is driven over raw
5
+ // CDP; for every frame the page's clock is seeked with window.__studio.seek(t) and
6
+ // the viewport is captured as PNG. `render` then encodes the frames with ffmpeg if
7
+ // it is on PATH, or prints the exact ffmpeg command to run.
8
+ //
9
+ // node render.mjs snapshot <comp.html> [--at 0,1.5,3] [--out dir] [--json]
10
+ // node render.mjs render <comp.html> [--out clip.mp4] [--from s] [--to s] [--fps n]
11
+ // [--scale n] [--audio file] [--crf n]
12
+ // [--frames dir] [--keep-frames] [--no-encode] [--json]
13
+ //
14
+ // Exit 0 on success, 1 when rendering or encoding fails, 2 on bad usage or a
15
+ // missing environment piece (Chrome, Node 22). Zero dependencies. Node 22+.
16
+
17
+ import { realpathSync } from 'node:fs'
18
+ import { fileURLToPath } from 'node:url'
19
+ import { spawnSync } from 'node:child_process'
20
+ import fs from 'node:fs'
21
+ import path from 'node:path'
22
+ import { parseArgs } from 'node:util'
23
+ import { pathToFileURL } from 'node:url'
24
+ import { CDP, findChrome, launchChrome, openPage } from './lib/cdp.mjs'
25
+ import { lintFile } from './lint-comp.mjs'
26
+
27
+ const HELP = `render: snapshot or render an HTML composition with headless Chrome
28
+
29
+ node render.mjs snapshot <comp.html> [--at 0,1.5,3] [--out dir] [--scale n] [--json]
30
+ PNG stills at the given times (default: the middle of every scene)
31
+
32
+ node render.mjs render <comp.html> [options]
33
+ --out <file> output video (default <name>.mp4; .mp4, .webm, .mov or .gif)
34
+ --from <s> start time in seconds (default 0)
35
+ --to <s> end time in seconds (default the composition duration)
36
+ --fps <n> override data-fps
37
+ --scale <n> device scale factor, e.g. 2 for a 2x render (default 1)
38
+ --audio <file> mux an audio track
39
+ --crf <n> quality for H.264/VP9 (default 18 / 32)
40
+ --frames <dir> where PNG frames go (default <out>_frames)
41
+ --keep-frames keep the PNGs after encoding
42
+ --no-encode write frames only and print the ffmpeg command
43
+ --json machine-readable result
44
+
45
+ Chrome: found automatically, or set CHROME_PATH. ffmpeg: used from PATH when present.
46
+ Exit codes: 0 ok, 1 render/encode failure, 2 usage or environment error.
47
+ `
48
+
49
+ const EPS = 1e-9
50
+
51
+ export class UsageError extends Error {
52
+ constructor(msg) {
53
+ super(msg)
54
+ this.exitCode = 2
55
+ }
56
+ }
57
+
58
+ /** Parse CLI arguments into a normalized options object. Throws UsageError. */
59
+ export function parseRenderArgs(argv) {
60
+ let parsed
61
+ try {
62
+ parsed = parseArgs({
63
+ args: argv,
64
+ allowPositionals: true,
65
+ strict: true,
66
+ options: {
67
+ at: { type: 'string' },
68
+ out: { type: 'string', short: 'o' },
69
+ from: { type: 'string' },
70
+ to: { type: 'string' },
71
+ fps: { type: 'string' },
72
+ scale: { type: 'string' },
73
+ audio: { type: 'string' },
74
+ crf: { type: 'string' },
75
+ frames: { type: 'string' },
76
+ 'keep-frames': { type: 'boolean', default: false },
77
+ 'no-encode': { type: 'boolean', default: false },
78
+ timeout: { type: 'string' },
79
+ json: { type: 'boolean', default: false },
80
+ help: { type: 'boolean', short: 'h', default: false },
81
+ },
82
+ })
83
+ } catch (e) {
84
+ throw new UsageError(e.message)
85
+ }
86
+ const { values: v, positionals } = parsed
87
+ const [cmd, file, ...extra] = positionals
88
+ if (v.help) return { help: true }
89
+ if (!['snapshot', 'render'].includes(cmd)) throw new UsageError(`expected "snapshot" or "render", got ${cmd ? `"${cmd}"` : 'nothing'}`)
90
+ if (!file) throw new UsageError(`${cmd}: name a composition .html file`)
91
+ if (extra.length) throw new UsageError(`unexpected argument "${extra[0]}"`)
92
+ const number = (name, { min = -Infinity, int = false } = {}) => {
93
+ if (v[name] === undefined) return undefined
94
+ const n = Number(v[name])
95
+ if (!Number.isFinite(n) || n < min || (int && !Number.isInteger(n))) throw new UsageError(`--${name} must be a number${min > -Infinity ? ` >= ${min}` : ''}`)
96
+ return n
97
+ }
98
+ const at =
99
+ v.at === undefined
100
+ ? undefined
101
+ : v.at.split(',').map((s) => {
102
+ const n = Number(s.trim())
103
+ if (!s.trim() || !Number.isFinite(n) || n < 0) throw new UsageError(`--at takes comma-separated seconds, got "${s}"`)
104
+ return n
105
+ })
106
+ const opts = {
107
+ cmd,
108
+ file,
109
+ at,
110
+ out: v.out,
111
+ from: number('from', { min: 0 }),
112
+ to: number('to', { min: 0 }),
113
+ fps: number('fps', { min: 1 }),
114
+ scale: number('scale', { min: 0.1 }) ?? 1,
115
+ audio: v.audio,
116
+ crf: number('crf', { min: 0, int: true }),
117
+ frames: v.frames,
118
+ keepFrames: v['keep-frames'],
119
+ encode: !v['no-encode'],
120
+ timeoutMs: (number('timeout', { min: 1 }) ?? 60) * 1000,
121
+ json: v.json,
122
+ }
123
+ if (opts.from !== undefined && opts.to !== undefined && opts.to <= opts.from) throw new UsageError('--to must be after --from')
124
+ return opts
125
+ }
126
+
127
+ /** Frame indices and times for [from, to) at fps. Frame i is at t = i / fps. */
128
+ export function frameTimes({ fps, duration, from = 0, to = duration }) {
129
+ const first = Math.max(0, Math.ceil(from * fps - 1e-6))
130
+ const last = Math.ceil(Math.min(to, duration) * fps - 1e-6) // exclusive
131
+ const out = []
132
+ for (let i = first; i < last; i++) out.push({ index: i, t: i / fps })
133
+ return out
134
+ }
135
+
136
+ /** Default snapshot times: the middle of every scene, plus 0, de-duplicated and sorted. */
137
+ export function defaultSnapshotTimes(scenes, duration) {
138
+ const ts = [0, ...scenes.map((s) => s.start + s.duration / 2)].filter((t) => t >= 0 && t < duration + EPS)
139
+ return [...new Set(ts.map((t) => Number(t.toFixed(3))))].sort((a, b) => a - b)
140
+ }
141
+
142
+ /** ffmpeg arguments to encode frame_%05d.png in framesDir into `out`. */
143
+ export function ffmpegArgs({ fps, framesDir, out, audio, crf, pattern = 'frame_%05d.png' }) {
144
+ const ext = path.extname(out).toLowerCase()
145
+ const input = ['-y', '-hide_banner', '-loglevel', 'error', '-framerate', String(fps), '-start_number', '0', '-i', path.join(framesDir, pattern)]
146
+ const even = ['-vf', 'pad=ceil(iw/2)*2:ceil(ih/2)*2']
147
+ if (ext === '.gif') {
148
+ return [...input, '-vf', 'split[a][b];[a]palettegen=stats_mode=diff[p];[b][p]paletteuse=dither=bayer', '-loop', '0', out]
149
+ }
150
+ const withAudio = audio ? ['-i', audio] : []
151
+ if (ext === '.webm') {
152
+ return [...input, ...withAudio, ...even, '-c:v', 'libvpx-vp9', '-b:v', '0', '-crf', String(crf ?? 32), '-pix_fmt', 'yuv420p', ...(audio ? ['-c:a', 'libopus', '-shortest'] : []), out]
153
+ }
154
+ if (ext === '.mov') {
155
+ return [...input, ...withAudio, '-c:v', 'prores_ks', '-profile:v', '3', '-pix_fmt', 'yuv422p10le', ...(audio ? ['-c:a', 'pcm_s16le', '-shortest'] : []), out]
156
+ }
157
+ return [...input, ...withAudio, ...even, '-c:v', 'libx264', '-preset', 'medium', '-crf', String(crf ?? 18), '-pix_fmt', 'yuv420p', '-movflags', '+faststart', ...(audio ? ['-c:a', 'aac', '-b:a', '192k', '-shortest'] : []), out]
158
+ }
159
+
160
+ /** Quote an argv for a POSIX shell, so the printed command can be pasted. */
161
+ export function shellQuote(args) {
162
+ return args.map((a) => (/^[\w@%+=:,./-]+$/.test(a) ? a : `'${String(a).replace(/'/g, `'\\''`)}'`)).join(' ')
163
+ }
164
+
165
+ /** Absolute path of an executable on PATH, or null. */
166
+ export function which(cmd, env = process.env) {
167
+ const exts = process.platform === 'win32' ? (env.PATHEXT ?? '.EXE;.CMD;.BAT').split(';') : ['']
168
+ for (const dir of (env.PATH ?? '').split(path.delimiter).filter(Boolean)) {
169
+ for (const ext of exts) {
170
+ const p = path.join(dir, cmd + ext)
171
+ try {
172
+ if (fs.statSync(p).isFile()) return p
173
+ } catch {}
174
+ }
175
+ }
176
+ return null
177
+ }
178
+
179
+ // ---------------------------------------------------------------------------
180
+ // Driving the page
181
+ // ---------------------------------------------------------------------------
182
+
183
+ /**
184
+ * Open a composition in headless Chrome at its native size and wait for the
185
+ * runtime to be ready. Returns { page, config, scenes, issues, close }.
186
+ */
187
+ export async function openComposition(file, { scale = 1, timeoutMs = 60000 } = {}) {
188
+ const abs = path.resolve(file)
189
+ const lint = lintFile(abs)
190
+ if (!lint.config || !Number.isInteger(lint.config.width) || !Number.isInteger(lint.config.height)) {
191
+ throw new Error('composition root is missing or has no valid data-width / data-height (run lint)')
192
+ }
193
+ const chrome = findChrome()
194
+ if (!chrome.path) throw Object.assign(new Error(chrome.error), { exitCode: 2 })
195
+ const browser = await launchChrome({ chromePath: chrome.path })
196
+ let cdp
197
+ const close = async () => {
198
+ if (cdp) {
199
+ let t
200
+ await Promise.race([cdp.send('Browser.close').catch(() => {}), new Promise((r) => (t = setTimeout(r, 2000)))])
201
+ clearTimeout(t)
202
+ cdp.close()
203
+ }
204
+ await browser.close()
205
+ }
206
+ try {
207
+ cdp = await CDP.connect(browser.wsUrl)
208
+ const page = await openPage(cdp)
209
+ const issues = []
210
+ const urls = new Map()
211
+ page.on('Runtime.exceptionThrown', (p) => issues.push({ kind: 'exception', message: p.exceptionDetails?.exception?.description ?? p.exceptionDetails?.text }))
212
+ page.on('Runtime.consoleAPICalled', (p) => {
213
+ if (p.type === 'error') issues.push({ kind: 'console', message: p.args.map((a) => a.value ?? a.description ?? '').join(' ') })
214
+ })
215
+ page.on('Network.requestWillBeSent', (p) => urls.set(p.requestId, p.request.url))
216
+ page.on('Network.loadingFailed', (p) => issues.push({ kind: 'network', message: `${p.errorText}: ${urls.get(p.requestId) ?? p.requestId}` }))
217
+ await Promise.all([page.send('Page.enable'), page.send('Runtime.enable'), page.send('Network.enable')])
218
+ await page.send('Page.addScriptToEvaluateOnNewDocument', { source: 'window.__STUDIO_RENDER__ = true' })
219
+ const { width, height } = lint.config
220
+ await page.send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: scale, mobile: false })
221
+ const loaded = page.once('Page.loadEventFired', { timeoutMs })
222
+ await page.send('Page.navigate', { url: pathToFileURL(abs).href })
223
+ await loaded
224
+ const info = await page.evaluate(
225
+ `(async () => {
226
+ if (!window.__studio || typeof window.__studio.seek !== 'function') return null
227
+ const config = await window.__studio.ready
228
+ return { config: window.__studio.config || config, scenes: (window.__studio.scenes || []).map(s => ({ id: s.id, start: s.start, duration: s.duration, track: s.track })) }
229
+ })()`,
230
+ { timeoutMs },
231
+ )
232
+ if (!info) throw new Error('the page has no window.__studio.seek(t): include the studio runtime (see video-compose)')
233
+ return { page, config: info.config, scenes: info.scenes, issues, close }
234
+ } catch (e) {
235
+ await close()
236
+ throw e
237
+ }
238
+ }
239
+
240
+ /** Seek the clock to t and capture the viewport as a PNG buffer. */
241
+ export async function captureAt(page, t, { timeoutMs = 60000 } = {}) {
242
+ await page.evaluate(`window.__studio.seek(${Number(t)}).then(() => true)`, { timeoutMs })
243
+ const { data } = await page.send('Page.captureScreenshot', { format: 'png', fromSurface: true, captureBeyondViewport: false })
244
+ return Buffer.from(data, 'base64')
245
+ }
246
+
247
+ const log = (opts, msg) => {
248
+ if (!opts.json) process.stderr.write(msg)
249
+ }
250
+
251
+ export async function snapshot(opts) {
252
+ const comp = await openComposition(opts.file, opts)
253
+ try {
254
+ const times = (opts.at ?? defaultSnapshotTimes(comp.scenes, comp.config.duration)).map((t) => Math.min(t, comp.config.duration))
255
+ const outDir = path.resolve(opts.out ?? `${path.basename(opts.file, path.extname(opts.file))}_snapshots`)
256
+ fs.mkdirSync(outDir, { recursive: true })
257
+ const files = []
258
+ for (const t of times) {
259
+ const png = await captureAt(comp.page, t, opts)
260
+ const f = path.join(outDir, `t${t.toFixed(3).padStart(8, '0')}s.png`)
261
+ fs.writeFileSync(f, png)
262
+ files.push({ t, file: f })
263
+ log(opts, `snapshot ${t.toFixed(3)}s -> ${f}\n`)
264
+ }
265
+ return { ok: comp.issues.length === 0, config: comp.config, snapshots: files, issues: comp.issues }
266
+ } finally {
267
+ await comp.close()
268
+ }
269
+ }
270
+
271
+ export async function render(opts) {
272
+ const base = path.basename(opts.file, path.extname(opts.file))
273
+ const out = path.resolve(opts.out ?? `${base}.mp4`)
274
+ const framesDir = path.resolve(opts.frames ?? `${out.slice(0, -path.extname(out).length || undefined)}_frames`)
275
+ if (opts.audio && !fs.existsSync(opts.audio)) throw new UsageError(`--audio file not found: ${opts.audio}`)
276
+ const comp = await openComposition(opts.file, opts)
277
+ const fps = opts.fps ?? comp.config.fps
278
+ const frames = frameTimes({ fps, duration: comp.config.duration, from: opts.from ?? 0, to: opts.to ?? comp.config.duration })
279
+ if (!frames.length) {
280
+ await comp.close()
281
+ throw new UsageError('no frames in the requested range')
282
+ }
283
+ fs.mkdirSync(framesDir, { recursive: true })
284
+ for (const f of fs.readdirSync(framesDir)) if (/^frame_\d+\.png$/.test(f)) fs.rmSync(path.join(framesDir, f))
285
+ const started = Date.now()
286
+ try {
287
+ for (let n = 0; n < frames.length; n++) {
288
+ const png = await captureAt(comp.page, frames[n].t, opts)
289
+ fs.writeFileSync(path.join(framesDir, `frame_${String(n).padStart(5, '0')}.png`), png)
290
+ if (process.stderr.isTTY && (n % Math.max(1, Math.round(frames.length / 20)) === 0 || n === frames.length - 1)) log(opts, `\rframe ${n + 1}/${frames.length}`)
291
+ }
292
+ if (process.stderr.isTTY) log(opts, '\n')
293
+ } finally {
294
+ await comp.close()
295
+ }
296
+ const args = ffmpegArgs({ fps, framesDir, out, audio: opts.audio, crf: opts.crf })
297
+ const ffmpeg = which('ffmpeg')
298
+ const result = {
299
+ ok: true,
300
+ config: { ...comp.config, fps },
301
+ frames: frames.length,
302
+ from: frames[0].t,
303
+ to: frames[frames.length - 1].t + 1 / fps,
304
+ framesDir,
305
+ renderSeconds: Number(((Date.now() - started) / 1000).toFixed(2)),
306
+ ffmpegCommand: shellQuote(['ffmpeg', ...args]),
307
+ encoded: false,
308
+ out: null,
309
+ issues: comp.issues,
310
+ }
311
+ if (!opts.encode || !ffmpeg) {
312
+ result.note = ffmpeg ? 'encoding skipped (--no-encode)' : 'ffmpeg is not on PATH: install it, then run this command'
313
+ return result
314
+ }
315
+ fs.mkdirSync(path.dirname(out), { recursive: true })
316
+ const r = spawnSync(ffmpeg, args, { encoding: 'utf8' })
317
+ if (r.status !== 0) {
318
+ result.ok = false
319
+ result.error = `ffmpeg failed (exit ${r.status}): ${(r.stderr || '').trim().slice(-1500)}`
320
+ return result
321
+ }
322
+ result.encoded = true
323
+ result.out = out
324
+ if (!opts.keepFrames) {
325
+ fs.rmSync(framesDir, { recursive: true, force: true })
326
+ result.framesDir = null
327
+ }
328
+ return result
329
+ }
330
+
331
+ function printResult(r, cmd) {
332
+ if (cmd === 'snapshot') {
333
+ console.log(`${r.snapshots.length} snapshot(s) of ${r.config.width}x${r.config.height}`)
334
+ } else {
335
+ console.log(`${r.frames} frames at ${r.config.fps} fps (${r.from}s-${Number(r.to.toFixed(3))}s) in ${r.renderSeconds}s`)
336
+ if (r.encoded) console.log(`wrote ${r.out}`)
337
+ else if (r.error) console.log(r.error)
338
+ else console.log(`frames in ${r.framesDir}\n${r.note}\n\n ${r.ffmpegCommand}\n`)
339
+ }
340
+ for (const i of r.issues) console.log(`page ${i.kind}: ${i.message}`)
341
+ }
342
+
343
+ async function main(argv) {
344
+ let opts
345
+ try {
346
+ opts = parseRenderArgs(argv)
347
+ } catch (e) {
348
+ process.stderr.write(`render: ${e.message}\n\n${HELP}`)
349
+ return 2
350
+ }
351
+ if (opts.help) {
352
+ process.stdout.write(HELP)
353
+ return 0
354
+ }
355
+ if (!fs.existsSync(opts.file)) {
356
+ process.stderr.write(`render: ${opts.file} not found\n`)
357
+ return 2
358
+ }
359
+ try {
360
+ const r = opts.cmd === 'snapshot' ? await snapshot(opts) : await render(opts)
361
+ if (opts.json) console.log(JSON.stringify(r, null, 2))
362
+ else printResult(r, opts.cmd)
363
+ return r.error ? 1 : 0
364
+ } catch (e) {
365
+ const code = e.exitCode ?? (e.code === 'ENOCHROME' || e.code === 'ENODE' ? 2 : 1)
366
+ if (opts.json) console.log(JSON.stringify({ ok: false, error: e.message }, null, 2))
367
+ else process.stderr.write(`render: ${e.message}\n`)
368
+ return code
369
+ }
370
+ }
371
+
372
+ // Run only when this file is the entry point. Real paths are compared because
373
+ // the path Node was given can be a symlink (macOS /tmp and /var, a linked
374
+ // skills folder), and then it never equals the module's own URL.
375
+ function isEntryPoint(url) {
376
+ try { return Boolean(process.argv[1]) && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(url)) } catch { return false }
377
+ }
378
+
379
+ if (isEntryPoint(import.meta.url)) process.exitCode = await main(process.argv.slice(2))