decklight 0.9.0 → 0.11.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.
Files changed (133) hide show
  1. package/NOTICE +2 -0
  2. package/PLATFORM.md +61 -3
  3. package/README.md +58 -28
  4. package/SPEC.md +1326 -85
  5. package/cli/agent-review.mjs +5 -4
  6. package/cli/agents.mjs +148 -18
  7. package/cli/bundle-audio.mjs +10 -3
  8. package/cli/bundle-module.mjs +95 -0
  9. package/cli/bundle.mjs +125 -7
  10. package/cli/cast.mjs +86 -19
  11. package/cli/check-fixes.mjs +194 -0
  12. package/cli/check-watch.mjs +151 -0
  13. package/cli/check.mjs +491 -75
  14. package/cli/code-editor.mjs +287 -0
  15. package/cli/commands.mjs +13 -2
  16. package/cli/commit-flow.mjs +7 -3
  17. package/cli/commit-message.mjs +35 -8
  18. package/cli/commit-split.mjs +125 -25
  19. package/cli/deck-refs.mjs +8 -3
  20. package/cli/decklight.mjs +11 -1
  21. package/cli/design-system-edit.mjs +37 -1
  22. package/cli/design-system-refs.mjs +263 -6
  23. package/cli/design-system.mjs +82 -14
  24. package/cli/edit-address.mjs +184 -0
  25. package/cli/edit-git.mjs +23 -6
  26. package/cli/edit-handover.mjs +257 -40
  27. package/cli/edit-look.mjs +293 -6
  28. package/cli/edit-open.mjs +143 -0
  29. package/cli/edit-slides.mjs +1043 -67
  30. package/cli/edit-translate.mjs +243 -0
  31. package/cli/edit.mjs +3680 -319
  32. package/cli/editor-support.mjs +286 -0
  33. package/cli/enhance.mjs +157 -27
  34. package/cli/find-replace.mjs +142 -0
  35. package/cli/fix-review.mjs +368 -0
  36. package/cli/git.mjs +13 -0
  37. package/cli/init.mjs +101 -22
  38. package/cli/keep-awake.mjs +68 -0
  39. package/cli/marketplace-autocheck.mjs +200 -0
  40. package/cli/marketplace.mjs +250 -13
  41. package/cli/migrate-writing.mjs +214 -0
  42. package/cli/narrate.mjs +121 -5
  43. package/cli/open.mjs +53 -15
  44. package/cli/outside-edit.mjs +257 -0
  45. package/cli/paste.mjs +92 -0
  46. package/cli/pdf.mjs +88 -10
  47. package/cli/pptx-export.mjs +10 -5
  48. package/cli/publish.mjs +24 -3
  49. package/cli/record.mjs +86 -15
  50. package/cli/remote.mjs +32 -6
  51. package/cli/rewrite.mjs +265 -0
  52. package/cli/runtime-link.mjs +218 -17
  53. package/cli/serve.mjs +9 -6
  54. package/cli/setup.mjs +2 -2
  55. package/cli/skill-content.mjs +251 -10
  56. package/cli/skills/slide-writing.md +333 -0
  57. package/cli/skills/voiceover.md +423 -0
  58. package/cli/skills.mjs +282 -15
  59. package/cli/starter-full.mjs +353 -0
  60. package/cli/supervise.mjs +14 -0
  61. package/cli/theme-refs.mjs +14 -2
  62. package/cli/theme.mjs +3 -2
  63. package/cli/translate-core.mjs +466 -0
  64. package/cli/translate-files.mjs +149 -0
  65. package/cli/translate.mjs +458 -0
  66. package/cli/units.mjs +75 -7
  67. package/cli/util.mjs +25 -0
  68. package/cli/vocabulary-docs.mjs +138 -0
  69. package/dist/decklight.css +2506 -113
  70. package/dist/decklight.js +385 -175
  71. package/dist/decklight.js.map +4 -4
  72. package/docs/GLOSSARY.md +9 -2
  73. package/docs/WRITING_RESEARCH.md +327 -0
  74. package/package.json +5 -3
  75. package/themes/coastal.css +3 -0
  76. package/themes/metropolis.css +2 -0
  77. package/themes/reveal-blood.css +3 -0
  78. package/themes/reveal-league.css +2 -0
  79. package/themes/reveal-moon.css +2 -0
  80. package/themes/reveal-serif.css +1 -0
  81. package/themes/reveal-sky.css +1 -0
  82. package/themes/reveal-solarized.css +4 -0
  83. package/tools/brand-palette.mjs +6 -1
  84. package/tools/build-groups.mjs +28 -8
  85. package/tools/cdp.mjs +176 -0
  86. package/tools/chart-spec.mjs +242 -0
  87. package/tools/click-match.mjs +70 -0
  88. package/tools/code-options.mjs +174 -0
  89. package/tools/conversation.mjs +49 -0
  90. package/tools/deck-family.mjs +101 -0
  91. package/tools/deck-html.mjs +212 -15
  92. package/tools/design-system-format.mjs +40 -1
  93. package/tools/design-system-migrations.mjs +207 -0
  94. package/tools/diagram-shapes.mjs +221 -0
  95. package/tools/elevenlabs-tts.mjs +62 -53
  96. package/tools/exec.mjs +10 -2
  97. package/tools/face-clip.mjs +96 -0
  98. package/tools/face-layout.mjs +94 -0
  99. package/tools/gemini-tts.mjs +1 -1
  100. package/tools/invisible-in-print.mjs +27 -0
  101. package/tools/lipsync-auto.mjs +197 -0
  102. package/tools/lipsync-config.mjs +16 -0
  103. package/tools/lipsync-engines.mjs +22 -4
  104. package/tools/lipsync-server.mjs +8 -5
  105. package/tools/lipsync.mjs +122 -30
  106. package/tools/local-voice.mjs +1 -1
  107. package/tools/mouth-file.mjs +26 -0
  108. package/tools/mouth.mjs +320 -0
  109. package/tools/narration-manifest.mjs +100 -6
  110. package/tools/narration-synth.mjs +96 -76
  111. package/tools/recording-impact.mjs +16 -1
  112. package/tools/sentences.mjs +7 -1
  113. package/tools/site-clip.mjs +114 -0
  114. package/tools/starters.mjs +402 -0
  115. package/tools/steps.mjs +118 -0
  116. package/tools/take-check.mjs +146 -0
  117. package/tools/template-theme.mjs +3 -1
  118. package/tools/test-impact.mjs +36 -12
  119. package/tools/theme-check.mjs +196 -1
  120. package/tools/tone-cue.mjs +108 -0
  121. package/tools/tts-cache.mjs +9 -3
  122. package/tools/tts-engines.mjs +100 -11
  123. package/tools/video-cache.mjs +93 -0
  124. package/tools/video-live.mjs +349 -0
  125. package/tools/video-options.mjs +11 -0
  126. package/tools/video.mjs +825 -117
  127. package/tools/viseme-fit.mjs +27 -0
  128. package/tools/viseme-match.mjs +77 -0
  129. package/tools/vocabulary.mjs +397 -0
  130. package/tools/voice-renumber.mjs +605 -0
  131. package/tools/voiceover-server.mjs +42 -11
  132. package/tools/voiceover.mjs +48 -20
  133. package/dist/build-info.json +0 -1
package/cli/bundle.mjs CHANGED
@@ -46,7 +46,7 @@ import fs from 'node:fs';
46
46
  import path from 'node:path';
47
47
  import { makeFail, scriptSafe, runMain } from './util.mjs';
48
48
  import { inlineRuntime, packageAsset, PKG, THEMES_DIR } from './pkg.mjs';
49
- import { configBlock, configTheme, firstExecutableScript, hasEmbeddedRuntime, hasRuntime, linkRuntime } from './runtime-link.mjs';
49
+ import { configBlock, configTheme, firstExecutableScript, hasEmbeddedRuntime, hasRuntime, linkRuntime, withDoctype } from './runtime-link.mjs';
50
50
  import { addedThemeStyle, markedRefs, markedShipped, markedSources, resolveThemeRef, stillValid } from './theme-refs.mjs';
51
51
  import { bundleDesignSystem, designSystemRefs, packageVerdict, resolveDesignSystemRef } from './design-system-refs.mjs';
52
52
  import { bundleFont, fontRefs, fontVerdict, resolveFontRef } from './font-refs.mjs';
@@ -55,6 +55,7 @@ import { escapeHtml } from '../tools/escape.mjs';
55
55
  import { isMain } from '../tools/args.mjs';
56
56
  import { AUDIO_CHOICES, CODECS, estimateAudio, inlineAudio, narrationAudio, sizeLabel } from './bundle-audio.mjs';
57
57
  import { injectBeforeBodyEnd } from '../tools/deck-html.mjs';
58
+ import { deckModules, pickModule, renumber, sliceManifest, sliceModule, slug } from './bundle-module.mjs';
58
59
 
59
60
  const fail = makeFail('bundle');
60
61
 
@@ -204,18 +205,84 @@ function mergeDecks(jobs, baseDir, notices) {
204
205
 
205
206
  // ---------------------------------------------------------------- arguments
206
207
 
207
- /** `client` is the sigstore seam — see publishMain; omitted, the real one is used. */
208
- export async function bundleMain(argv = process.argv.slice(2), { client, estimate = false } = {}) {
208
+ /**
209
+ * `client` is the sigstore seam — see publishMain; omitted, the real one is used.
210
+ * `report`, when given, is filled with `{ out, notices }` once the file is
211
+ * written: where it went and the notes printed after it, for a caller (the edit
212
+ * server's bundle card) that says them somewhere other than this terminal.
213
+ */
214
+ /**
215
+ * `--languages all|fr,es` (SPEC TRANSLATION_SWITCH): the deck and each of its
216
+ * languages, every one bundled as a self-contained file of its own beside the
217
+ * output (`out.html`, `out.fr.html`), each switch linking the others by
218
+ * their new names. Every other option applies to each file alike.
219
+ */
220
+ async function bundleLanguages(argv, at, opts) {
221
+ const { knownLanguages, languageFiles } = await import('./translate-files.mjs');
222
+ const { withAlternates } = await import('./translate-core.mjs');
223
+ const { withConfigKeys } = await import('./runtime-link.mjs');
224
+ const { deckLang } = await import('../tools/deck-html.mjs');
225
+ const spec = argv[at + 1];
226
+ if (!spec || spec.startsWith('-')) fail('--languages takes all, or the languages to carry: --languages fr,es');
227
+ const rest = [...argv.slice(0, at), ...argv.slice(at + 2)];
228
+ const valueFlags = new Set(['-o', '--themes', '--theme', '--transform', '--title', '--module']);
229
+ const inputs = rest.filter((a, i) => !a.startsWith('-') && !valueFlags.has(rest[i - 1]) && !(rest[i - 1] === '--audio' && AUDIO_CHOICES.includes(a)));
230
+ if (inputs.length !== 1 || rest.includes('--all')) fail('--languages bundles one deck and its languages: give the source deck alone');
231
+ const source = path.resolve(inputs[0]);
232
+ if (!fs.existsSync(source)) fail(`deck not found: ${source}`);
233
+ const sourceHtml = fs.readFileSync(source, 'utf8');
234
+ const known = knownLanguages(source, sourceHtml).filter((l) => fs.existsSync(languageFiles(source, l).deck));
235
+ const langs = spec === 'all' ? known : spec.split(',').map((s) => s.trim()).filter(Boolean);
236
+ for (const l of langs) if (!fs.existsSync(languageFiles(source, l).deck)) fail(`no ${path.basename(languageFiles(source, l).deck)} beside ${path.basename(source)} — decklight translate ${path.basename(source)} --to ${l}`);
237
+ if (!langs.length) fail(`${path.basename(source)} has no translations to carry — decklight translate ${path.basename(source)} --to fr`);
238
+ const oi = rest.indexOf('-o');
239
+ const out = path.resolve(oi >= 0 ? rest[oi + 1] : path.join(path.dirname(source), `${path.basename(source, '.html')}-standalone.html`));
240
+ const outFor = (l) => out.replace(/(\.html?)?$/i, (ext) => `.${l}${ext || '.html'}`);
241
+ const withOut = (file, o) => { const r = rest.map((a) => (path.resolve(a) === source ? file : a)); const j = r.indexOf('-o'); if (j >= 0) r.splice(j, 2); return [...r, '-o', o]; };
242
+ const from = deckLang(sourceHtml);
243
+ const alternates = [...(from ? [{ lang: from, href: path.basename(out) }] : []), ...langs.map((l) => ({ lang: l, href: path.basename(outFor(l)) }))];
244
+ const written = [out];
245
+ await bundleMain(withOut(source, out), { ...opts, finalize: (html) => withAlternates(withConfigKeys(html, { languages: langs, translationOf: null }) ?? html, []) });
246
+ for (const l of langs) {
247
+ await bundleMain(withOut(languageFiles(source, l).deck, outFor(l)), {
248
+ ...opts, finalize: (html) => withAlternates(withConfigKeys(html, { languages: null, translationOf: path.basename(out) }) ?? html, alternates),
249
+ });
250
+ written.push(outFor(l));
251
+ }
252
+ process.stdout.write(`languages: ${[from, ...langs].filter(Boolean).join(', ')} — ${written.map((w) => path.basename(w)).join(', ')}, each self-contained, each switching to the others\n`);
253
+ if (opts.report) Object.assign(opts.report, { languages: written });
254
+ return 0;
255
+ }
256
+
257
+ /** A file that travels alone shows no language switch: a link to a file that did not travel is a dead row. */
258
+ async function oneLanguage(html) {
259
+ if (!/"languages"\s*:|"translationOf"\s*:|data-decklight-lang/.test(html)) return html;
260
+ const { withAlternates } = await import('./translate-core.mjs');
261
+ const { withConfigKeys } = await import('./runtime-link.mjs');
262
+ return withAlternates(withConfigKeys(html, { languages: null, translationOf: null }) ?? html, []);
263
+ }
264
+
265
+ export async function bundleMain(argv = process.argv.slice(2), { client, estimate = false, report = null, finalize = null } = {}) {
266
+ {
267
+ const at = argv.indexOf('--languages');
268
+ if (at >= 0) return bundleLanguages(argv, at, { client, estimate, report });
269
+ }
209
270
 
210
271
  if (!argv.length || argv.includes('--help') || argv.includes('-h')) {
211
272
  process.stdout.write(`decklight bundle — flatten deck(s) into one self-contained HTML file
212
273
 
213
274
  Usage:
214
275
  decklight bundle <deck.html> [-o out.html] [--audio [original|aac|opus]] [--sign] [--deck] [--themes current|all|…]
276
+ decklight bundle <deck.html> --module <title | n> [-o out.html] [--audio …] [--themes …]
215
277
  decklight bundle <deck.html> --all [-o out.html] [--title "…"] [--themes …]
216
278
  decklight bundle <a.html> <b.html> … [-o out.html] [--title "…"] [--themes …]
217
279
 
218
280
  Options:
281
+ --languages <all|fr,es>
282
+ carry the deck's translations too (decklight translate):
283
+ each as a self-contained file of its own beside the output
284
+ (out.html, out.fr.html), its language switch linking the
285
+ others. Without it the file is one language and shows no switch
219
286
  -o <file> output path (default: <deck>-standalone.html, or
220
287
  <deck>-course.html when merging)
221
288
  --all follow the deck's playlist and merge EVERY module into
@@ -232,6 +299,10 @@ Options:
232
299
  --sign, because the container is the signed artifact. A
233
300
  .decklight renamed to .html still plays in a browser: the
234
301
  deck comes first in the file and the metadata is appended.
302
+ --module <t|n> bundle one chapter of the deck: the slides from its
303
+ <section data-module="…"> up to the next one, named by
304
+ title or by number. The chapter's narration comes with it,
305
+ renumbered to its slides (--audio carries it inside)
235
306
  --title <t> <title> for the multi-module deck
236
307
  --transform <name> run an installed build-time transform (decklight library
237
308
  add transform <name>) on the deck's own source before anything else
@@ -273,6 +344,7 @@ let outPath = null, themesSel = 'current', all = false, mergedTitle = null, sign
273
344
  let allowMissingSystems = false;
274
345
  let allowMissingFonts = false;
275
346
  let audioChoice = null;
347
+ let moduleWant = null;
276
348
  const transformNames = [];
277
349
  for (let i = 0; i < argv.length; i++) {
278
350
  const a = argv[i];
@@ -287,6 +359,10 @@ for (let i = 0; i < argv.length; i++) {
287
359
  // an attestation. Naming the implication beats refusing the obvious command.
288
360
  else if (a === '--deck') { deckFile = true; sign = true; }
289
361
  else if (a === '--title') mergedTitle = argv[++i];
362
+ else if (a === '--module') {
363
+ moduleWant = argv[++i];
364
+ if (moduleWant == null || moduleWant.startsWith('-')) fail('--module takes a chapter: its title, or its number');
365
+ }
290
366
  else if (a === '--allow-missing-design-systems') allowMissingSystems = true;
291
367
  else if (a === '--allow-missing-fonts') allowMissingFonts = true;
292
368
  // `--audio` alone is the files as recorded; a codec after it re-encodes them
@@ -297,6 +373,7 @@ for (let i = 0; i < argv.length; i++) {
297
373
  }
298
374
  if (!inputs.length) fail('no deck given');
299
375
  if (all && inputs.length > 1) fail('--all takes a single deck (it follows that deck’s playlist)');
376
+ if (moduleWant != null && inputs.length > 1) fail('--module takes a single deck (it bundles one chapter of it)');
300
377
 
301
378
  const firstPath = path.resolve(inputs[0]);
302
379
  if (!fs.existsSync(firstPath)) fail(`deck not found: ${firstPath}`);
@@ -309,6 +386,14 @@ if (all) {
309
386
  const src = fs.readFileSync(firstPath, 'utf8');
310
387
  const modules = parsePlaylist(src);
311
388
  if (!modules.length) fail('--all: the deck has no parseable playlist ({ title, href } modules)');
389
+ if (moduleWant != null) {
390
+ // A playlist's module is a file of its own: bundling it is bundling that file.
391
+ const k = /^\d+$/.test(moduleWant.trim()) ? Number(moduleWant) - 1
392
+ : modules.findIndex((m) => m.title.toLowerCase() === moduleWant.trim().toLowerCase());
393
+ fail(modules[k]
394
+ ? `--module with --all: a playlist module is a file of its own — bundle it as one:\n decklight bundle ${path.join(path.relative(process.cwd(), deckDir) || '.', modules[k].href)}`
395
+ : '--module bundles one chapter of a single deck; --all merges a playlist — use one or the other');
396
+ }
312
397
  jobs = modules.map((m) => {
313
398
  const p = path.resolve(deckDir, m.href);
314
399
  if (!fs.existsSync(p)) fail(`playlist module not found: ${m.href} (${p})`);
@@ -323,6 +408,8 @@ if (all) {
323
408
  }
324
409
 
325
410
  let html;
411
+ // `--module`: the chapter being bundled; its narration is renumbered to it
412
+ let chapter = null;
326
413
  if (jobs) {
327
414
  html = mergeDecks(jobs, deckDir, notices);
328
415
  const t = mergedTitle ||
@@ -332,8 +419,20 @@ if (jobs) {
332
419
  path.join(deckDir, path.basename(firstPath, '.html') + '-course.html'));
333
420
  } else {
334
421
  html = fs.readFileSync(firstPath, 'utf8');
422
+ let suffix = '-standalone';
423
+ if (moduleWant != null) {
424
+ const bounds = containerBounds(html);
425
+ if (!bounds) fail(`no .decklight container in ${firstPath}`);
426
+ const { modules, spans } = deckModules(html, bounds);
427
+ try { chapter = pickModule(modules, moduleWant); } catch (e) { fail(e.message); }
428
+ html = sliceModule(html, bounds, spans, chapter);
429
+ html = html.replace(/<title>([^<]*)<\/title>/i, (t, was) =>
430
+ `<title>${was.trim() ? `${was.trim()} · ` : ''}${escapeHtml(chapter.title)}</title>`);
431
+ suffix = `-${slug(chapter.title)}`;
432
+ notices.push(`module ${chapter.n} of ${modules.length}: ${chapter.title} — slides ${chapter.offset + 1}–${chapter.offset + chapter.count} of the deck, 1–${chapter.count} in the bundle`);
433
+ }
335
434
  outPath = path.resolve(outPath ||
336
- path.join(deckDir, path.basename(firstPath, '.html') + '-standalone.html'));
435
+ path.join(deckDir, path.basename(firstPath, '.html') + suffix + '.html'));
337
436
  }
338
437
 
339
438
  // What went into the file and where each piece came from, said once at the end
@@ -389,6 +488,10 @@ if (linked) {
389
488
  html = linkRuntime(html);
390
489
  // said in the summary: the source deck carries no runtime of its own
391
490
  }
491
+ // A bundle is served from wherever it lands, by a server that adds nothing:
492
+ // a deck written without a doctype gets one here, or it would lay out in
493
+ // quirks mode there (#1190). linkRuntime already did it for a linked deck.
494
+ html = withDoctype(html);
392
495
 
393
496
  const themeLinkRe = /<link\b[^>]*rel=["']stylesheet["'][^>]*href=["']([^"']*themes\/([\w-]+)\.css)["'][^>]*>/i;
394
497
  const themeLinkM = html.match(themeLinkRe);
@@ -695,6 +798,11 @@ html = html.replace(
695
798
  if (vm) {
696
799
  // vm[1] is the whole STEM (`slide-07`, `slide-07-02`) — the same name
697
800
  // the runtime looks the block up by, so the two cannot drift apart.
801
+ if (chapter) {
802
+ // the chapter's own timelines, under the slide number the bundle asks for
803
+ vm[1] = renumber(vm[1], chapter);
804
+ if (!vm[1]) continue;
805
+ }
698
806
  if (seen.has(vm[1])) {
699
807
  notices.push(`character visemes: ${d}/${f} skipped — ${vm[1]} already inlined from another track`);
700
808
  continue;
@@ -704,7 +812,9 @@ html = html.replace(
704
812
  + `${scriptSafe(fs.readFileSync(path.join(abs, f), 'utf8'))}\n</script>`);
705
813
  } else if (/^slide-\d+\.mp4$/.test(f)) mp4s++;
706
814
  }
707
- if (mp4s) {
815
+ if (mp4s && chapter) {
816
+ notices.push(`character video: ${mp4s} slide-NN.mp4 in ${d}/ are numbered for the whole deck and stay external — the chapter's character plays from its visemes`);
817
+ } else if (mp4s) {
708
818
  notices.push(`character video: ${mp4s} slide-NN.mp4 in ${d}/ stay external — ship the folder next to the bundle`);
709
819
  }
710
820
  }
@@ -734,8 +844,13 @@ html = html.replace(
734
844
  notices.push(`narration manifest: ${rel} not found — the bundle will fetch it at runtime`);
735
845
  continue;
736
846
  }
847
+ let text = fs.readFileSync(abs, 'utf8');
848
+ if (chapter) {
849
+ // the manifest is indexed by slide: cut it to the chapter's
850
+ try { text = JSON.stringify(sliceManifest(JSON.parse(text), chapter), null, 1); } catch { /* not JSON: inlined as it is */ }
851
+ }
737
852
  embeds.push(`<script type="application/json" data-decklight-voices="${rel.replace(/"/g, '&quot;')}">\n`
738
- + `${scriptSafe(fs.readFileSync(abs, 'utf8'))}\n</script>`);
853
+ + `${scriptSafe(text)}\n</script>`);
739
854
  n++;
740
855
  }
741
856
  if (n) notices.push(`narration: inlined ${n} voice manifest(s) — the audio stays in its bucket`);
@@ -751,7 +866,7 @@ html = html.replace(
751
866
  // files it left out or took in.
752
867
  let audioEstimate = null;
753
868
  {
754
- const { found, remote, folders } = narrationAudio(html, deckDir);
869
+ const { found, remote, folders } = narrationAudio(html, deckDir, chapter);
755
870
  if (estimate) {
756
871
  if (found.size) audioEstimate = { ...(await estimateAudio(found)), folders };
757
872
  } else if (found.size && audioChoice) {
@@ -818,6 +933,8 @@ if (!jobs) {
818
933
  // though it were finished. Bytes, not a path, for exactly this reason.
819
934
  // An estimate (the edit server's bundle card) stops here: the file as it
820
935
  // would be without its audio, and what each way of carrying the audio adds.
936
+ // its languages: the ones that travel with it, or none (TRANSLATION_SWITCH)
937
+ html = finalize ? finalize(html) : await oneLanguage(html);
821
938
  if (estimate) return { base: Buffer.byteLength(html, 'utf8'), audio: audioEstimate };
822
939
 
823
940
  let bundleSig = null;
@@ -910,6 +1027,7 @@ if (bundleSig) {
910
1027
  }
911
1028
  }
912
1029
  for (const n of notices) process.stdout.write(`note: ${n}\n`);
1030
+ if (report) Object.assign(report, { out: outPath, notices });
913
1031
  }
914
1032
 
915
1033
  if (isMain(import.meta.url)) process.exitCode = await runMain('bundle', bundleMain);
package/cli/cast.mjs CHANGED
@@ -36,7 +36,7 @@ import fs from 'node:fs';
36
36
  import path from 'node:path';
37
37
  import os from 'node:os';
38
38
  import { createRequire } from 'node:module';
39
- import { makeFail, runMain, wrongRecorder } from './util.mjs';
39
+ import { CommandError, makeFail, runMain, wrongRecorder } from './util.mjs';
40
40
  import { isMain } from '../tools/args.mjs';
41
41
 
42
42
  const require = createRequire(import.meta.url);
@@ -84,7 +84,7 @@ function resolveSecret(v, env) {
84
84
  const m = v.match(/^\$([A-Za-z_][A-Za-z0-9_]*)/);
85
85
  if (!m) return v;
86
86
  const val = env[m[1]];
87
- if (val === undefined) throw new Error(`secret env var ${m[1]} is not set`);
87
+ if (val === undefined) fail(`secret env var ${m[1]} is not set`);
88
88
  return val + v.slice(m[0].length);
89
89
  }
90
90
 
@@ -106,6 +106,32 @@ function clampIdle(events, maxIdle) {
106
106
  return events;
107
107
  }
108
108
 
109
+ /**
110
+ * Refuse a malformed step before anything runs. Checked inside the step loop,
111
+ * a bad step 5 was only noticed after steps 1–4 had already run, and maybe
112
+ * changed things. A step is a `cmd:` (a YAML scalar is coerced: `cmd: false`
113
+ * parses as a boolean), or a `sleep:` in seconds on its own.
114
+ */
115
+ export function checkSteps(steps) {
116
+ const shape = 'each step is a cmd: to run, or a sleep: in seconds';
117
+ for (const [idx, step] of (steps || []).entries()) {
118
+ const n = idx + 1;
119
+ if (!step || typeof step !== 'object' || Array.isArray(step)) {
120
+ fail(`step ${n} is ${JSON.stringify(step)}, not a mapping: ${shape}`);
121
+ }
122
+ if (typeof step.cmd === 'boolean' || typeof step.cmd === 'number') step.cmd = String(step.cmd);
123
+ if (typeof step.cmd === 'string') continue;
124
+ if (step.cmd !== undefined && step.cmd !== null) fail(`step ${n} has a "cmd" that is not a command line: ${shape}`);
125
+ if ('sleep' in step && step.cmd === undefined) {
126
+ if (typeof step.sleep === 'number') continue;
127
+ fail(`step ${n} has a "sleep" that is not a number of seconds: ${shape}`);
128
+ }
129
+ const keys = Object.keys(step).filter(k => k !== 'cmd');
130
+ const has = keys.length ? ` (it has ${keys.map(k => `"${k}"`).join(', ')})` : '';
131
+ fail(`step ${n} has no "cmd"${has}: ${shape}`);
132
+ }
133
+ }
134
+
109
135
  function shellArgs(shellPath) {
110
136
  const base = path.basename(shellPath);
111
137
  if (base === 'zsh') return ['-f']; // no rc files
@@ -113,6 +139,23 @@ function shellArgs(shellPath) {
113
139
  return [];
114
140
  }
115
141
 
142
+ /**
143
+ * The two lines a step is written as: the command in a brace group, and the
144
+ * sentinel that marks its end. A command stopped with Ctrl-C (an `interact`
145
+ * send of \u0003, the way a server is ended) used to take the sentinel with
146
+ * it: an interactive shell abandons the rest of the line on an interrupt, so
147
+ * the marker never printed and the step timed out. zsh's `always` block runs
148
+ * after an interrupt and bash's INT trap fires on one, both printing the
149
+ * marker with the interrupt's status (130); any other shell keeps the plain
150
+ * form.
151
+ */
152
+ export function stepLine(shellBase, cmd) {
153
+ const mark = (status) => `printf '${GS_OCTAL}DECKLIGHT:%d:${GS_OCTAL}\\n' ${status}`;
154
+ if (shellBase === 'zsh') return `{\n${cmd}\n} always { ${mark('$?')} }\n`;
155
+ if (shellBase === 'bash') return `trap "${mark(130).replace(/"/g, '\\"')}" INT; {\n${cmd}\n}; ${mark('$?')}; trap - INT\n`;
156
+ return `{\n${cmd}\n}; ${mark('$?')}\n`;
157
+ }
158
+
116
159
  function setupLine(shellBase) {
117
160
  const common = `stty -echo; printf '${GS_OCTAL}DECKLIGHT-READY${GS_OCTAL}\\n'`;
118
161
  if (shellBase === 'zsh') return `unsetopt zle prompt_cr prompt_sp banghist 2>/dev/null; PS1=''; PROMPT=''; PS2=''; PROMPT2=''; ${common}\n`;
@@ -131,15 +174,16 @@ function setupLine(shellBase) {
131
174
  * (without allowFail) non-zero exits.
132
175
  */
133
176
  export async function recordScript(script, { scriptDir, allowFail = false, log = () => {} }) {
177
+ checkSteps(script.steps);
134
178
  const { pty } = loadDeps();
135
179
  const shellName = script.shell || path.basename(process.env.SHELL || 'zsh');
136
180
  const shellPath = shellName.includes('/') ? shellName : `/bin/${shellName}`;
137
- if (!fs.existsSync(shellPath)) throw new Error(`shell not found: ${shellPath}`);
181
+ if (!fs.existsSync(shellPath)) fail(`shell not found: ${shellPath}`);
138
182
  const cols = script.cols ?? 100;
139
183
  const rows = script.rows ?? 28;
140
184
  const base = scriptDir || process.cwd();
141
185
  const cwd = script.cwd ? path.resolve(base, expandHome(script.cwd)) : base;
142
- if (!fs.existsSync(cwd)) throw new Error(`cwd not found: ${cwd}`);
186
+ if (!fs.existsSync(cwd)) fail(`cwd not found: ${cwd}`);
143
187
 
144
188
  const redactions = (script.redact || []).map(r => new RegExp(r, 'g'));
145
189
  const redact = s => redactions.reduce((acc, re) => acc.replace(re, '▓▓▓'), s);
@@ -165,17 +209,24 @@ export async function recordScript(script, { scriptDir, allowFail = false, log =
165
209
  let onChunk = null; // (data) => void — active step's collector
166
210
  let shellDead = false;
167
211
  let onExitCb = null;
212
+ let finished = false; // every step recorded — the shell is idle at its prompt
168
213
  term.onData(d => { buffer += d; if (onChunk) onChunk(d); });
169
214
  term.onExit(() => { shellDead = true; if (onExitCb) onExitCb(); });
170
215
 
171
- const waitFor = (test, timeoutMs, what, isCancelled) => new Promise((resolve, reject) => {
216
+ // A timeout is the script's fault when it is waiting on the script (a step,
217
+ // an expect, a wait_for: its own `timeout:` ran out), and decklight's when
218
+ // it is waiting on the shell setup. The shell dying is always decklight's.
219
+ const waitFor = (test, timeoutMs, what, { isCancelled, setup = false } = {}) => new Promise((resolve, reject) => {
172
220
  const started = Date.now();
173
221
  const tick = () => {
174
222
  const m = test();
175
223
  if (m) return resolve(m);
176
224
  if (isCancelled?.()) return reject(new Error('cancelled'));
177
225
  if (shellDead) return reject(new Error(`shell died while waiting for ${what}`));
178
- if (Date.now() - started > timeoutMs) return reject(new Error(`timeout waiting for ${what}`));
226
+ if (Date.now() - started > timeoutMs) {
227
+ const msg = `timeout waiting for ${what}`;
228
+ return reject(setup ? new Error(msg) : new CommandError(msg, 'cast'));
229
+ }
179
230
  setTimeout(tick, 15);
180
231
  };
181
232
  tick();
@@ -184,7 +235,7 @@ export async function recordScript(script, { scriptDir, allowFail = false, log =
184
235
  try {
185
236
  // --- setup phase: silence echo & prompts, then discard everything so far
186
237
  term.write(setupLine(path.basename(shellPath)));
187
- await waitFor(() => buffer.includes(READY_MARK), 10_000, 'shell setup');
238
+ await waitFor(() => buffer.includes(READY_MARK), 10_000, 'shell setup', { setup: true });
188
239
  buffer = '';
189
240
 
190
241
  const sessionEnv = { ...process.env, ...scriptEnv };
@@ -193,15 +244,12 @@ export async function recordScript(script, { scriptDir, allowFail = false, log =
193
244
  for (const [idx, step] of (script.steps || []).entries()) {
194
245
  // Pure pause step: sleeps for real (session truthfulness — background
195
246
  // state may be advancing) and records a timing marker.
196
- if (step && typeof step.sleep === 'number' && step.cmd === undefined) {
247
+ if (step.cmd === undefined) {
197
248
  await new Promise(r => setTimeout(r, step.sleep * 1000));
198
249
  steps.push({ sleep: round3(step.sleep) });
199
250
  log(` ✓ (sleep ${step.sleep}s)`);
200
251
  continue;
201
252
  }
202
- // YAML gotcha: `cmd: false` / `cmd: 42` parse as scalars — coerce.
203
- if (step && (typeof step.cmd === 'boolean' || typeof step.cmd === 'number')) step.cmd = String(step.cmd);
204
- if (!step || typeof step.cmd !== 'string') throw new Error(`step ${idx + 1}: missing "cmd"`);
205
253
  const timeoutMs = (step.timeout ?? 60) * 1000;
206
254
  const chunks = [];
207
255
  const t0 = process.hrtime.bigint();
@@ -217,7 +265,7 @@ export async function recordScript(script, { scriptDir, allowFail = false, log =
217
265
  // lines while parsing, so nothing is buffered for the command's stdin —
218
266
  // interact sends are the only input it can see. The lone `}` line also
219
267
  // makes trailing `#` comments in cmd harmless.
220
- term.write(`{\n${step.cmd}\n}; printf '${GS_OCTAL}DECKLIGHT:%d:${GS_OCTAL}\\n' $?\n`);
268
+ term.write(stepLine(path.basename(shellPath), step.cmd));
221
269
 
222
270
  // interact: watch output, answer prompts (expect/send) — runs alongside
223
271
  // the sentinel wait; secrets are sent for real but recorded as ▓▓▓ and
@@ -225,7 +273,7 @@ export async function recordScript(script, { scriptDir, allowFail = false, log =
225
273
  const interacts = Array.isArray(step.interact) ? step.interact : [];
226
274
  const inputs = [];
227
275
  const stepRedactions = [];
228
- let interactState = { done: interacts.length === 0, error: null, pending: null, cancelled: false };
276
+ let interactState = { done: interacts.length === 0, error: null, pending: null, cancelled: false, interrupted: false };
229
277
  if (interacts.length) {
230
278
  (async () => {
231
279
  let searchFrom = 0;
@@ -236,7 +284,7 @@ export async function recordScript(script, { scriptDir, allowFail = false, log =
236
284
  const found = await waitFor(() => {
237
285
  const mm = collected.slice(searchFrom).match(re);
238
286
  return mm ? { end: searchFrom + mm.index + mm[0].length } : null;
239
- }, timeoutMs, `expect /${it.expect}/ in step ${idx + 1} (${step.cmd})`, () => interactState.cancelled);
287
+ }, timeoutMs, `expect /${it.expect}/ in step ${idx + 1} (${step.cmd})`, { isCancelled: () => interactState.cancelled });
240
288
  searchFrom = found.end;
241
289
  let text, display;
242
290
  if (it.send && typeof it.send === 'object' && 'secret' in it.send) {
@@ -249,6 +297,7 @@ export async function recordScript(script, { scriptDir, allowFail = false, log =
249
297
  display = text;
250
298
  }
251
299
  inputs.push([round3(Number(process.hrtime.bigint() - t0) / 1e9), display]);
300
+ if (text.includes('\x03')) interactState.interrupted = true;
252
301
  term.write(text);
253
302
  interactState.pending = null;
254
303
  }
@@ -272,7 +321,7 @@ export async function recordScript(script, { scriptDir, allowFail = false, log =
272
321
  if (interactState.error) throw interactState.error;
273
322
  if (!interactState.done && interactState.pending) {
274
323
  const err = `step ${idx + 1} exited before expect /${interactState.pending}/ matched: ${step.cmd}`;
275
- if (!allowFail) throw new Error(err);
324
+ if (!allowFail) fail(err);
276
325
  log(` ⚠ ${err}`);
277
326
  }
278
327
  const exit = parseInt(m[1], 10);
@@ -310,14 +359,31 @@ export async function recordScript(script, { scriptDir, allowFail = false, log =
310
359
  ...(inClamped.length ? { input: inClamped } : {}),
311
360
  });
312
361
  log(` ✓ ${step.cmd} (exit ${exit}, ${duration.toFixed(2)}s)`);
313
- if (exit !== 0 && !allowFail) {
314
- throw new Error(`step ${idx + 1} exited ${exit}: ${step.cmd} (use --allow-fail to record failures as content)`);
362
+ // 130 is how a command ends when the script itself pressed Ctrl-C:
363
+ // that is the step working (a server stopped), not failing
364
+ if (exit !== 0 && !(exit === 130 && interactState.interrupted) && !allowFail) {
365
+ fail(`step ${idx + 1} exited ${exit}: ${step.cmd} (use --allow-fail to record failures as content)`);
315
366
  }
316
367
  }
368
+ finished = true;
317
369
  return steps;
318
370
  } finally {
319
- try { term.write('exit\n'); } catch { /* already dead */ }
320
- await new Promise(res => { if (shellDead) return res(); onExitCb = res; setTimeout(res, 1500); });
371
+ // A run that completed leaves the shell at its prompt, where `exit` ends
372
+ // it in a few milliseconds. A run that bailed mid-step (a timeout, an
373
+ // abort) leaves that command in the foreground, where `exit` would only
374
+ // queue behind it until the cap below gave up — so that shell is hung up
375
+ // on directly, which takes its foreground job with it.
376
+ if (finished) { try { term.write('exit\n'); } catch { /* already dead */ } }
377
+ else { try { term.kill(); } catch { /* already dead */ } }
378
+ // The cap is a fallback, so it must not outlive the exit it guards: a
379
+ // pending timer keeps the event loop alive, and this one held every
380
+ // recording open for its full 1.5s after the shell had already gone —
381
+ // ~1.5s per `rec` on a 100ms recording, and the bulk of test/cast.test.mjs.
382
+ await new Promise(res => {
383
+ if (shellDead) return res();
384
+ const cap = setTimeout(res, 1500);
385
+ onExitCb = () => { clearTimeout(cap); res(); };
386
+ });
321
387
  try { term.kill(); } catch { /* already dead */ }
322
388
  }
323
389
  }
@@ -542,6 +608,7 @@ export async function castMain(argv = process.argv.slice(2)) {
542
608
 
543
609
  const script = yaml.load(fs.readFileSync(scriptPath, 'utf8'));
544
610
  if (!script || !Array.isArray(script.steps) || !script.steps.length) fail('script has no steps');
611
+ checkSteps(script.steps);
545
612
 
546
613
  const shellName = script.shell || path.basename(process.env.SHELL || 'zsh');
547
614
  if (!quiet) console.log(`recording ${script.steps.length} step${script.steps.length === 1 ? '' : 's'} in ${shellName}…`);