decklight 0.3.0 → 0.5.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "decklight",
3
- "version": "0.3.0",
3
+ "version": "0.5.0",
4
4
  "description": "A presentation library designed to be authored by AI agents and humans alike: single-file decks, Keynote-style builds, theme-aware SVG diagrams, and truthful terminal recordings.",
5
5
  "type": "module",
6
6
  "main": "dist/decklight.js",
@@ -36,8 +36,10 @@
36
36
  "scripts": {
37
37
  "build": "node build.mjs",
38
38
  "prepare": "npm run build",
39
- "test": "node --test test/*.test.mjs",
40
- "verify": "npm run build && node test/verify.mjs"
39
+ "test": "node test/run.mjs",
40
+ "verify": "npm run build && node test/verify.mjs",
41
+ "soak": "node test/soak.mjs",
42
+ "cross-engine": "node test/cross-engine.mjs"
41
43
  },
42
44
  "engines": {
43
45
  "node": ">=20"
@@ -50,7 +52,8 @@
50
52
  "optionalDependencies": {
51
53
  "js-yaml": "^4.3.0",
52
54
  "node-pty": "^1.1.0",
53
- "sigstore": "^5.0.0"
55
+ "sigstore": "^5.0.0",
56
+ "playwright": "^1.56.0"
54
57
  },
55
58
  "author": "Gilles Philippart <gilles.philippart@gmail.com>",
56
59
  "license": "Apache-2.0"
package/tools/chrome.mjs CHANGED
@@ -8,27 +8,53 @@
8
8
 
9
9
  import { existsSync } from 'node:fs';
10
10
 
11
- const CANDIDATES = [
12
- '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
13
- '/usr/bin/google-chrome', '/usr/bin/google-chrome-stable',
14
- '/usr/bin/chromium', '/usr/bin/chromium-browser',
15
- '/snap/bin/chromium',
16
- `${process.env.HOME}/.nix-profile/bin/chromium`,
17
- ];
11
+ /**
12
+ * Where a browser installs itself, per platform.
13
+ *
14
+ * Windows was simply missing, which is not a small omission: with nothing here
15
+ * to find, `findChrome` returned null on every Windows machine that had not set
16
+ * $CHROME, so `decklight pdf`, `decklight video` and tools/shot.mjs all refused
17
+ * to run on the platform — on decks they render perfectly everywhere else.
18
+ *
19
+ * `%LOCALAPPDATA%` first among the Windows paths because a per-user install
20
+ * (what Chrome's own installer does without admin rights) is both the common
21
+ * case and the one no fixed path can guess. Edge is deliberately NOT listed
22
+ * even though it is Chromium and would probably work: "probably" is not
23
+ * something to hard-code into every render path, and `$CHROME` already lets
24
+ * anyone point at it deliberately.
25
+ */
26
+ export const candidates = (platform = process.platform, env = process.env) => (platform === 'win32'
27
+ ? [
28
+ `${env.LOCALAPPDATA ?? ''}\\Google\\Chrome\\Application\\chrome.exe`,
29
+ 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe',
30
+ 'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe',
31
+ `${env.LOCALAPPDATA ?? ''}\\Chromium\\Application\\chrome.exe`,
32
+ 'C:\\Program Files\\Chromium\\Application\\chrome.exe',
33
+ ].filter((p) => !p.startsWith('\\'))
34
+ : [
35
+ '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
36
+ '/usr/bin/google-chrome', '/usr/bin/google-chrome-stable',
37
+ '/usr/bin/chromium', '/usr/bin/chromium-browser',
38
+ '/snap/bin/chromium',
39
+ `${env.HOME}/.nix-profile/bin/chromium`,
40
+ ]);
18
41
 
19
- /** The browser to drive: $CHROME wins, else the first one installed. */
20
42
  /**
21
- * Where Chrome is, or null — the non-fatal half. `decklight report-bug` needs
22
- * to REPORT that a machine has no Chrome, which it cannot do if merely asking
23
- * exits the process.
43
+ * Where Chrome is, or null — the non-fatal half. `$CHROME` wins, else the first
44
+ * one installed. `decklight report-bug` needs to REPORT that a machine has no
45
+ * Chrome, which it cannot do if merely asking exits the process.
46
+ *
47
+ * Pure over injected `exists`/`platform`/`env`, the way tools/local-voice.mjs
48
+ * is: the whole point is branching on an operating system the tests are not
49
+ * running on, and a branch nothing can reach is a branch nobody can check.
24
50
  */
25
- export function findChrome() {
26
- return process.env.CHROME || process.env.DECKLIGHT_CHROME
27
- || CANDIDATES.find((p) => existsSync(p)) || null;
51
+ export function findChrome({ exists = existsSync, platform = process.platform, env = process.env } = {}) {
52
+ return env.CHROME || env.DECKLIGHT_CHROME
53
+ || candidates(platform, env).find((p) => exists(p)) || null;
28
54
  }
29
55
 
30
- export function chromeBin(who = 'chrome') {
31
- const bin = findChrome();
56
+ export function chromeBin(who = 'chrome', opts = {}) {
57
+ const bin = findChrome(opts);
32
58
  if (!bin) {
33
59
  console.error(`${who}: no Chrome found — install one, or point $CHROME at it`);
34
60
  process.exit(1);
@@ -1,6 +1,10 @@
1
1
  // Copyright 2026 Gilles Philippart
2
2
  // SPDX-License-Identifier: Apache-2.0
3
3
 
4
+ import { execFileSync } from 'node:child_process';
5
+ import { existsSync } from 'node:fs';
6
+ import { delimiter, join } from 'node:path';
7
+
4
8
  // What can this machine say out loud, without a credential and without a
5
9
  // download?
6
10
  //
@@ -120,10 +124,37 @@ export function sapiArgs(text, voice, file) {
120
124
  * reason THIS machine has none, which differs enough between an Android
121
125
  * device, a bare Linux box and a Mac with a broken `say` to be worth saying.
122
126
  */
127
+ /**
128
+ * Is `bin` runnable? The default for the probe below.
129
+ *
130
+ * This has to be a REAL answer, and that is the whole point of it existing:
131
+ * `hasBin` defaulted to `() => false`, so every caller that did not inject one
132
+ * — `tools/tts-engines.mjs` creating a `say`/`sapi` engine is the only one, and
133
+ * it is the one that matters — was told the machine had no synthesizer, on a
134
+ * Mac where `say -v '?'` lists forty voices. The seams here exist so the tests
135
+ * can drive every OS from one OS; a seam whose DEFAULT is "no" turns the
136
+ * production path into a stub that always refuses, and every test still passes
137
+ * because every test injects.
138
+ */
139
+ export function onPath(bin, env = process.env) {
140
+ const exts = process.platform === 'win32' ? ['.exe', '.cmd', '.bat', ''] : [''];
141
+ for (const dir of String(env.PATH ?? '').split(delimiter)) {
142
+ if (!dir) continue;
143
+ for (const ext of exts) if (existsSync(join(dir, bin + ext))) return true;
144
+ }
145
+ return false;
146
+ }
147
+
148
+ /** Run a probe and return its stdout; anything at all going wrong is ''. */
149
+ export const probe = (bin, args) => {
150
+ try { return execFileSync(bin, args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }); }
151
+ catch { return ''; }
152
+ };
153
+
123
154
  export function detectLocalVoice({
124
155
  platform = process.platform,
125
- hasBin = () => false,
126
- exec = () => '',
156
+ hasBin = onPath,
157
+ exec = probe,
127
158
  lang,
128
159
  } = {}) {
129
160
  if (platform === 'android') {
@@ -125,7 +125,12 @@ export function validateTheme(css) {
125
125
 
126
126
  /** A theme name from a path or URL: the basename, minus .css. */
127
127
  export function themeNameFrom(source) {
128
- const last = String(source ?? '').split(/[?#]/)[0].split('/').filter(Boolean).pop() ?? '';
128
+ // Both separators, because `source` is either a URL (always `/`) or a local
129
+ // path (`\` on Windows). Splitting on `/` alone made the whole path the
130
+ // name there — `decklight theme check C:\themes\aurora.css` reported
131
+ // `✔ C:\themes\aurora`, and `theme add` would then have tried to install
132
+ // under a name validThemeName refuses, from a file that was perfectly fine.
133
+ const last = String(source ?? '').split(/[?#]/)[0].split(/[/\\]/).filter(Boolean).pop() ?? '';
129
134
  return last.replace(/\.css$/i, '');
130
135
  }
131
136
 
@@ -347,7 +347,16 @@ function createNative({ kind, voice, shell = 'powershell.exe' }) {
347
347
  execFileSync(bin, build(line, voice, file), { stdio: ['ignore', 'ignore', 'pipe'] });
348
348
  const wav = readFileSync(file);
349
349
  if (!wav.length) throw new Error(`${kind} produced no audio`);
350
- return wav;
350
+ // `{ wav, usage }`, like every other engine and like this file's own
351
+ // contract at the top. It returned a bare Buffer, so a caller that
352
+ // destructured `{ wav }` — tools/voiceover.mjs does — got undefined and
353
+ // wrote it to disk. Nobody had ever reached this line: detectLocalVoice's
354
+ // default probe answered "no synthesizer" first, so the shape was wrong
355
+ // behind a door that never opened.
356
+ return {
357
+ wav,
358
+ usage: { model: voice ?? kind, chars: line.length, cost: 0, note: `${line.length} chars · local` },
359
+ };
351
360
  } catch (e) {
352
361
  throw new Error(`${kind}: ${String(e.stderr ?? e.message).trim().split('\n')[0] || 'synthesis failed'}`);
353
362
  } finally {
package/tools/video.mjs CHANGED
@@ -6,12 +6,14 @@
6
6
  //
7
7
  // decklight video deck.html -o deck.mp4
8
8
  // [--narration <dir>] [--size 1280x720] [--fps 30] [--hold 5]
9
- // [--theme <name>] [--slides a-b] [--voiceover]
9
+ // [--build-hold <s>] [--theme <name>] [--slides a-b] [--voiceover]
10
10
  //
11
- // One still per slide (final build state), each held for the duration of its
12
- // narration audio plus a short tail, muxed with that audio into one mp4 — a
13
- // deck with generated narration becomes a watchable, shareable video in one
14
- // command. Narration resolves --narration <dir> → <deckdir>/voiceover/
11
+ // A still per FRAME — a narrated slide is one still, fully built, held for its
12
+ // audio; a silent slide builds as it goes, one still per step — muxed with the
13
+ // audio into one mp4, so a deck becomes a watchable, shareable video in one
14
+ // command. Every frame of a silent slide holds --hold, builds included, so a
15
+ // build lands at the pace the deck moves at; --build-hold paces the build-up
16
+ // frames alone. Narration resolves --narration <dir> → <deckdir>/voiceover/
15
17
  // (the manifest tools/voiceover.mjs writes) → a fully silent deck where every
16
18
  // slide holds --hold seconds (per-slide override: data-video-hold="8" on the
17
19
  // section). Silent slides still carry a silent audio segment (anullsrc) so the
@@ -24,9 +26,11 @@
24
26
  // --allow-file-access-from-files (#229): that flag let a deck's own JS read any
25
27
  // local file and exfiltrate it, and video renders decks you may not have
26
28
  // vetted. No puppeteer, no CDP, no new deps — which is also the honest limit:
27
- // frames are stills, so the character overlay appears but frozen, and timing is
28
- // per-slide, not per-build-step (animated lipsync needs a CDP screencast — a
29
- // Node ≥22 follow-up).
29
+ // frames are stills, so the character overlay appears but frozen and a build
30
+ // CUTS rather than animating (animated capture needs a CDP screencast — a
31
+ // Node ≥22 follow-up). How far each slide builds is asked of the deck itself,
32
+ // in one extra load, because the grouping is the runtime's and a second counter
33
+ // written here would be a copy that drifts.
30
34
 
31
35
  import { execFile, execFileSync, spawnSync } from 'node:child_process';
32
36
  import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
@@ -36,7 +40,7 @@ import { promisify } from 'node:util';
36
40
  import { fileURLToPath } from 'node:url';
37
41
  import { chromeBin, chromeArgs } from './chrome.mjs';
38
42
  import { argReader, isMain } from './args.mjs';
39
- import { sectionBodies } from './deck-html.mjs';
43
+ import { injectBeforeBodyEnd, sectionBodies } from './deck-html.mjs';
40
44
  import { serveForRender } from '../cli/present.mjs';
41
45
 
42
46
  const run = promisify(execFile);
@@ -53,12 +57,19 @@ const HELP = `decklight video <deck.html> [options] — render the deck to a nar
53
57
  --fps <n> video frame rate (default 30)
54
58
  --hold <s> seconds a slide without narration holds (default 5;
55
59
  per-slide override: data-video-hold="8" on the section)
60
+ --build-hold <s> seconds each build-up frame holds on a silent slide
61
+ (default: the slide's own hold, so builds move at the
62
+ pace the deck does)
56
63
  --theme <name> render with themes/<name>.css instead of the deck's theme
57
64
  --slides <a-b> only this slide range (1-based, inclusive)
58
65
  --voiceover run the voiceover batch (tools/voiceover.mjs) first
59
66
 
60
- Slides with narration hold for the audio's real duration + ${TAIL_SECONDS}s; slides
61
- without hold --hold seconds over silence, so the audio track stays continuous.
67
+ Every slide BUILDS, one frame per step. A narrated slide takes its timing from
68
+ its own audio: ⟨CLICK⟩ in the speaker notes splits the narration, and segment k
69
+ is spoken over build step k — the same rule the live player follows. Without
70
+ markers it holds fully built for the audio's real duration. A silent slide holds
71
+ --hold seconds, --build-hold per step. Either way the audio track is continuous
72
+ and the finished slide gets a ${TAIL_SECONDS}s breath before the cut.
62
73
  Needs ffmpeg + ffprobe on PATH, and a Chrome ($CHROME or an installed one).
63
74
  `;
64
75
 
@@ -93,7 +104,38 @@ export function extractHolds(html, defaultHold) {
93
104
  }
94
105
 
95
106
  /**
96
- * The per-slide schedule: which audio plays under slide n, and for how long.
107
+ * An oversized step: the engine clamps it to the slide's last build, so this
108
+ * always renders a slide fully built however many steps it turns out to have.
109
+ * Every slide's FINAL frame is captured here rather than at a counted step, so
110
+ * a miscount can shorten the build-up but can never lose the finished slide.
111
+ */
112
+ export const LAST_STEP = 999;
113
+
114
+ const round = (s) => Math.round(s * 1000) / 1000;
115
+
116
+ /**
117
+ * The schedule: which frame of which slide is on screen, under what audio, for
118
+ * how long.
119
+ *
120
+ * ONE ENTRY PER FRAME, not per slide. A silent slide with builds is a sequence
121
+ * — the slide bare, then each build revealed — because a video of a built slide
122
+ * that opens fully built has thrown away the thing the builds were for. A
123
+ * A NARRATED slide follows its own notes: where those notes are segmented by
124
+ * ⟨CLICK⟩ and the segment count matches the build count, segment k narrates
125
+ * build step k and holds for that segment's REAL audio. Nothing is inferred —
126
+ * the markers are the author's, tools/voiceover.mjs synthesises one file per
127
+ * segment, and this reads their ffprobe'd durations. A narrated slide with no
128
+ * markers, or a count that does not line up, is one fully-built still for the
129
+ * length of its audio, as it always was.
130
+ *
131
+ * Timing, for a silent slide with `b` build steps (so `b + 1` frames): EVERY
132
+ * frame holds for the slide's hold, so a build lands at the pace the rest of
133
+ * the deck moves at and the deck gets longer the more it builds. Splitting the
134
+ * hold across the frames instead — keeping the deck's length fixed — was tried
135
+ * first and reads far too fast: the more a slide has to say, the less time each
136
+ * beat of it got, which is exactly backwards. `buildHold` overrides the
137
+ * build-up frames alone, for a deck that wants its builds quicker (or slower)
138
+ * than its slides.
97
139
  *
98
140
  * @param {Array|null} manifest manifest.slides from tools/voiceover.mjs
99
141
  * ({ file } per slide, null for silent slides) —
@@ -101,18 +143,62 @@ export function extractHolds(html, defaultHold) {
101
143
  * @param {object} durations audio file → real (ffprobe) seconds
102
144
  * @param {number[]} holds per-slide hold seconds (one per section)
103
145
  * @param {{from,to}} [range] 1-based inclusive slide range
104
- * @returns {Array<{slide, audio, duration}>} audio null ⇒ silent hold
146
+ * @param {object} [opts] steps: per-slide build-step counts (null ⇒ one
147
+ * frame per slide); buildHold: seconds per
148
+ * build-up frame (null ⇒ the slide's own hold)
149
+ * @returns {Array<{slide, step, audio, duration}>} audio null ⇒ silent hold
105
150
  */
106
- export function planTimeline(manifest, durations, holds, range = null) {
151
+ export function planTimeline(manifest, durations, holds, range = null, { steps = null, buildHold = null, onWarn = null } = {}) {
107
152
  const from = range?.from ?? 1;
108
153
  const to = range?.to ?? holds.length;
109
154
  const plan = [];
110
155
  for (let n = from; n <= to; n++) {
111
- const file = manifest?.[n - 1]?.file ?? null;
156
+ const entry = manifest?.[n - 1] ?? null;
157
+ const file = entry?.file ?? null;
112
158
  const dur = file ? durations?.[file] : null;
113
- plan.push(Number.isFinite(dur)
114
- ? { slide: n, audio: file, duration: Math.round((dur + TAIL_SECONDS) * 1000) / 1000 }
115
- : { slide: n, audio: null, duration: holds[n - 1] });
159
+
160
+ // A narrated slide whose notes are segmented by ⟨CLICK⟩ builds AS IT
161
+ // SPEAKS: segment k narrates build step k. That rule is not invented here —
162
+ // src/core/narration.js already speaks live narration that way ("exactly
163
+ // like a presenter reading the notes and clicking between segments"), and
164
+ // captions, rehearse mode and the notes editor all run on the same
165
+ // segmentation. This makes the recorded render the mirror of it.
166
+ const segs = entry?.segments ?? null;
167
+ const builds = steps?.[n - 1] ?? 0;
168
+ if (Number.isFinite(dur) && segs?.length && builds) {
169
+ const times = segs.map((sg) => durations?.[sg.file]);
170
+ if (segs.length === builds + 1 && times.every((t) => Number.isFinite(t))) {
171
+ segs.forEach((sg, k) => {
172
+ const last = k === segs.length - 1;
173
+ plan.push({
174
+ slide: n,
175
+ step: last ? LAST_STEP : k,
176
+ audio: sg.file,
177
+ // Only the finished slide gets the breath. A build that paused for
178
+ // it would read as hesitation rather than as a beat.
179
+ duration: round(times[k] + (last ? TAIL_SECONDS : 0)),
180
+ });
181
+ });
182
+ continue;
183
+ }
184
+ // A marker count that does not match the build count is the author's to
185
+ // fix, and guessing which build a segment belongs to would bake a wrong
186
+ // sync into an mp4 — worse than no sync. Say which slide, and render it
187
+ // the way an unsegmented one renders.
188
+ onWarn?.(`slide ${n}: ${segs.length} narration segment${segs.length === 1 ? '' : 's'}`
189
+ + ` but ${builds + 1} frames (${builds} build${builds === 1 ? '' : 's'} + the finished slide)`
190
+ + ' — narrating the whole slide over one still instead');
191
+ }
192
+
193
+ if (Number.isFinite(dur)) {
194
+ plan.push({ slide: n, step: LAST_STEP, audio: file, duration: round(dur + TAIL_SECONDS) });
195
+ continue;
196
+ }
197
+ const hold = holds[n - 1];
198
+ if (!builds) { plan.push({ slide: n, step: LAST_STEP, audio: null, duration: hold }); continue; }
199
+ const each = buildHold ?? hold;
200
+ for (let k = 0; k < builds; k++) plan.push({ slide: n, step: k, audio: null, duration: each });
201
+ plan.push({ slide: n, step: LAST_STEP, audio: null, duration: hold });
116
202
  }
117
203
  return plan;
118
204
  }
@@ -184,12 +270,59 @@ const have = (bin) => {
184
270
  catch (e) { return e?.code !== 'ENOENT'; }
185
271
  };
186
272
 
273
+ /**
274
+ * The probe that answers "how many build steps does each slide have?".
275
+ *
276
+ * Asked of the DECK, in a browser, because that is the only place the answer
277
+ * exists: grouping is the runtime's (`src/core/builds.js` — `data-build-stay`,
278
+ * `data-build-self`, nesting, ⟨CLICK⟩ markers), and a second counter written in
279
+ * Node would be a copy that drifts. It reads the count the same way the capture
280
+ * URLs do: `goto(n, LAST_STEP)` clamps, so the resulting `state.step` IS the
281
+ * slide's last step.
282
+ *
283
+ * Injected only for this one load, never for the frame captures — a probe that
284
+ * called `goto` during a screenshot would photograph the wrong slide.
285
+ */
286
+ const STEP_PROBE = `<script>
287
+ (function () {
288
+ function report() {
289
+ var d = window.__decklightProbe, out = [];
290
+ try {
291
+ for (var i = 1; i <= d.state.totalSlides; i++) { d.goto(i, ${LAST_STEP}); out.push(d.state.step); }
292
+ } catch (e) { out = ['err', String(e && e.message)]; }
293
+ var pre = document.createElement('pre');
294
+ pre.textContent = 'DECKLIGHT-BUILD-STEPS ' + JSON.stringify(out);
295
+ document.body.appendChild(pre);
296
+ }
297
+ if (document.readyState === 'complete') setTimeout(report, 30);
298
+ else window.addEventListener('load', function () { setTimeout(report, 30); });
299
+ })();
300
+ </script>`;
301
+
302
+ /** Make the deck's instance reachable, the way test/import-render.mjs does. */
303
+ const exposeInstance = (html) => html.replace(/\bDecklight\s*\.\s*init\s*\(/, 'window.__decklightProbe = Decklight.init(');
304
+
305
+ /** Parse the probe's answer out of a dumped DOM; null when it did not report. */
306
+ export function parseBuildSteps(dom, slides) {
307
+ const m = /DECKLIGHT-BUILD-STEPS (\[[^\]]*\])/.exec(dom);
308
+ if (!m) return null;
309
+ let counts;
310
+ try { counts = JSON.parse(m[1]); } catch { return null; }
311
+ if (!Array.isArray(counts) || counts.some((c) => !Number.isInteger(c) || c < 0)) return null;
312
+ return counts.length === slides ? counts : null;
313
+ }
314
+
187
315
  export async function videoMain(argv, { exec = run, log = console.log } = {}) {
188
316
  const { opt } = argReader(argv);
189
317
  const deckArg = argv.find((a) => !a.startsWith('-') && /\.html?$/i.test(a));
190
- if (argv.includes('--help') || !deckArg) {
191
- (deckArg ? process.stdout : process.stderr).write(HELP);
192
- process.exit(deckArg ? 0 : 1);
318
+ // Two different situations, and the stream and the exit code follow WHICH
319
+ // one happened rather than whether a deck was named. Asking for help is not
320
+ // a failure: it goes to stdout and exits 0, the way every other command
321
+ // answers `--help`. Naming no deck IS a failure: stderr, exit 1.
322
+ const wantsHelp = argv.includes('--help') || argv.includes('-h');
323
+ if (wantsHelp || !deckArg) {
324
+ (wantsHelp ? process.stdout : process.stderr).write(HELP);
325
+ process.exit(wantsHelp ? 0 : 1);
193
326
  }
194
327
  const deck = resolve(deckArg);
195
328
  if (!existsSync(deck)) { console.error(`decklight video: no such deck: ${deck}`); process.exit(1); }
@@ -219,8 +352,13 @@ export async function videoMain(argv, { exec = run, log = console.log } = {}) {
219
352
  const { w, h } = parseSize(opt('--size', '1280x720'));
220
353
  const fps = Number(opt('--fps', '30'));
221
354
  const hold = Number(opt('--hold', '5'));
355
+ const buildHoldArg = opt('--build-hold');
356
+ const buildHold = buildHoldArg === undefined ? null : Number(buildHoldArg);
222
357
  if (!Number.isFinite(fps) || fps <= 0) throw new Error(`--fps must be a positive number`);
223
358
  if (!Number.isFinite(hold) || hold <= 0) throw new Error(`--hold must be positive seconds`);
359
+ if (buildHold !== null && (!Number.isFinite(buildHold) || buildHold <= 0)) {
360
+ throw new Error(`--build-hold must be positive seconds`);
361
+ }
224
362
  const theme = opt('--theme');
225
363
 
226
364
  const html = readFileSync(deck, 'utf8');
@@ -241,57 +379,92 @@ export async function videoMain(argv, { exec = run, log = console.log } = {}) {
241
379
  // real durations, not the manifest's word count: ffprobe each audio file
242
380
  const durations = {};
243
381
  for (let n = range.from; n <= range.to; n++) {
244
- const file = narration?.slides?.[n - 1]?.file;
245
- if (!file || durations[file] != null) continue;
246
- const path = join(narration.dir, file);
247
- if (!existsSync(path)) {
248
- console.warn(` slide ${String(n).padStart(2, '0')}: ${file} is in the manifest but not on disk — holding ${holds[n - 1]}s of silence`);
249
- continue;
382
+ const entry = narration?.slides?.[n - 1];
383
+ // The slide's own audio AND its ⟨CLICK⟩ segments. Measured here rather
384
+ // than trusted from the manifest, for the reason the per-slide durations
385
+ // already are: what a file says it is worth is not what ffprobe says.
386
+ const files = [entry?.file, ...(entry?.segments ?? []).map((sg) => sg.file)].filter(Boolean);
387
+ for (const file of files) {
388
+ if (durations[file] != null) continue;
389
+ const path = join(narration.dir, file);
390
+ if (!existsSync(path)) {
391
+ console.warn(` slide ${String(n).padStart(2, '0')}: ${file} is in the manifest but not on disk`
392
+ + `${file === entry?.file ? ` — holding ${holds[n - 1]}s of silence` : ' — narrating the whole slide instead'}`);
393
+ continue;
394
+ }
395
+ durations[file] = Number((await exec('ffprobe', ffprobeArgs(path))).stdout.trim());
250
396
  }
251
- durations[file] = Number((await exec('ffprobe', ffprobeArgs(path))).stdout.trim());
252
397
  }
253
398
 
254
- plan = planTimeline(narration?.slides ?? null, durations, holds, range);
255
- log(`${basename(deck)}: ${plan.length} slide${plan.length === 1 ? '' : 's'}, `
256
- + `${plan.filter((p) => p.audio).length} narrated`
257
- + (narration ? ` (${narration.dir})` : ' (silent)'));
258
399
 
259
400
  // --theme rides on the deck's response in memory (no temp file): only the
260
401
  // deck itself gets the injected link; every other html asset under the root
261
402
  // is served untouched. Over the loopback origin `themes/…` resolves exactly
262
403
  // as the sibling-copy path used to, so a themed render is unchanged.
263
- const inject = theme
264
- ? (text, file) => (resolve(file) === deck
404
+ let probing = false;
405
+ const inject = (text, file) => {
406
+ if (resolve(file) !== deck) return text;
407
+ let out = theme
265
408
  ? text.replace(/(<\/head>)/i, `<link rel="stylesheet" href="themes/${theme}.css">$1`)
266
- : text)
267
- : null;
409
+ : text;
410
+ if (probing) out = injectBeforeBodyEnd(exposeInstance(out), STEP_PROBE) ?? out;
411
+ return out;
412
+ };
268
413
  const deckPath = '/' + relative(root, deck).split(sep).join('/');
269
414
 
270
415
  const work = mkdtempSync(join(tmpdir(), 'decklight-video-'));
271
416
  const server = await serveForRender(root, { html: inject });
272
417
  try {
273
418
  const chrome = chromeBin('video');
419
+
420
+ // Ask the deck how far each slide builds, in one extra load, before any
421
+ // frame is captured. A deck that will not answer is not an error: the
422
+ // plan falls back to one fully-built still per slide, which is what this
423
+ // command did before builds had frames of their own.
424
+ probing = true;
425
+ let steps = null;
426
+ try {
427
+ const dom = await exec(chrome, chromeArgs(
428
+ '--hide-scrollbars', `--window-size=${w},${h}`,
429
+ '--virtual-time-budget=2500', '--dump-dom', `${server.origin}${deckPath}`,
430
+ ), { maxBuffer: 64 * 1024 * 1024 });
431
+ steps = parseBuildSteps(dom.stdout, holds.length);
432
+ } catch { /* fall through to one frame per slide */ }
433
+ probing = false;
434
+ if (!steps) console.warn(' builds: the deck did not report its build steps — one still per slide');
435
+
436
+ plan = planTimeline(narration?.slides ?? null, durations, holds, range,
437
+ { steps, buildHold, onWarn: (w) => console.warn(` ${w}`) });
438
+ const slideCount = new Set(plan.map((p) => p.slide)).size;
439
+ log(`${basename(deck)}: ${slideCount} slide${slideCount === 1 ? '' : 's'}, `
440
+ + `${plan.filter((p) => p.audio).length} narrated`
441
+ + (plan.length > slideCount ? `, ${plan.length} frames` : '')
442
+ + (narration ? ` (${narration.dir})` : ' (silent)'));
443
+
274
444
  const segments = [];
445
+ let f = 0;
275
446
  for (const p of plan) {
276
447
  const nn = String(p.slide).padStart(2, '0');
277
- const frame = join(work, `frame-${nn}.png`);
278
- // one one-shot Chrome per frame; #/n/999 clamps to the last build step
448
+ const id = `${nn}-${String(f++).padStart(3, '0')}`;
449
+ const frame = join(work, `frame-${id}.png`);
450
+ // one one-shot Chrome per frame; LAST_STEP clamps to the last build
279
451
  await exec(chrome, chromeArgs(
280
452
  '--hide-scrollbars',
281
453
  '--autoplay-policy=no-user-gesture-required',
282
454
  `--window-size=${w},${h}`,
283
455
  '--virtual-time-budget=1500',
284
456
  `--screenshot=${frame}`,
285
- `${server.origin}${deckPath}#/${p.slide}/999`,
457
+ `${server.origin}${deckPath}#/${p.slide}/${p.step}`,
286
458
  ));
287
459
  if (!existsSync(frame)) throw new Error(`chrome produced no frame for slide ${p.slide}`);
288
- const seg = join(work, `seg-${nn}.mp4`);
460
+ const seg = join(work, `seg-${id}.mp4`);
289
461
  await exec('ffmpeg', segmentArgs({
290
462
  frame, duration: p.duration, fps, out: seg,
291
463
  audio: p.audio ? join(narration.dir, p.audio) : null,
292
464
  }));
293
465
  segments.push(seg);
294
- log(` slide ${nn}: ${p.duration.toFixed(1)}s ${p.audio ?? '(silence)'}`);
466
+ const where = p.step === LAST_STEP ? '' : ` · build ${p.step}`;
467
+ log(` slide ${nn}${where}: ${p.duration.toFixed(1)}s ${p.audio ?? '(silence)'}`);
295
468
  }
296
469
 
297
470
  const list = join(work, 'concat.txt');