decklight 0.10.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 (117) hide show
  1. package/NOTICE +2 -0
  2. package/PLATFORM.md +17 -0
  3. package/README.md +53 -25
  4. package/SPEC.md +1239 -67
  5. package/cli/agents.mjs +139 -15
  6. package/cli/bundle.mjs +68 -2
  7. package/cli/cast.mjs +45 -14
  8. package/cli/check-fixes.mjs +12 -4
  9. package/cli/check-watch.mjs +151 -0
  10. package/cli/check.mjs +460 -71
  11. package/cli/code-editor.mjs +287 -0
  12. package/cli/commands.mjs +13 -2
  13. package/cli/commit-message.mjs +34 -7
  14. package/cli/commit-split.mjs +123 -23
  15. package/cli/decklight.mjs +11 -1
  16. package/cli/design-system-edit.mjs +37 -1
  17. package/cli/edit-address.mjs +184 -0
  18. package/cli/edit-git.mjs +21 -4
  19. package/cli/edit-handover.mjs +136 -25
  20. package/cli/edit-look.mjs +45 -1
  21. package/cli/edit-open.mjs +143 -0
  22. package/cli/edit-slides.mjs +1043 -67
  23. package/cli/edit-translate.mjs +243 -0
  24. package/cli/edit.mjs +3182 -267
  25. package/cli/editor-support.mjs +286 -0
  26. package/cli/enhance.mjs +148 -20
  27. package/cli/find-replace.mjs +142 -0
  28. package/cli/fix-review.mjs +368 -0
  29. package/cli/init.mjs +93 -19
  30. package/cli/keep-awake.mjs +68 -0
  31. package/cli/migrate-writing.mjs +214 -0
  32. package/cli/narrate.mjs +51 -10
  33. package/cli/open.mjs +29 -9
  34. package/cli/outside-edit.mjs +257 -0
  35. package/cli/paste.mjs +92 -0
  36. package/cli/pdf.mjs +61 -2
  37. package/cli/pptx-export.mjs +3 -1
  38. package/cli/publish.mjs +24 -3
  39. package/cli/record.mjs +19 -8
  40. package/cli/rewrite.mjs +265 -0
  41. package/cli/runtime-link.mjs +218 -17
  42. package/cli/serve.mjs +7 -4
  43. package/cli/setup.mjs +2 -2
  44. package/cli/skill-content.mjs +212 -8
  45. package/cli/skills/slide-writing.md +333 -0
  46. package/cli/skills/voiceover.md +423 -0
  47. package/cli/skills.mjs +36 -13
  48. package/cli/starter-full.mjs +353 -0
  49. package/cli/supervise.mjs +14 -0
  50. package/cli/theme.mjs +3 -2
  51. package/cli/translate-core.mjs +466 -0
  52. package/cli/translate-files.mjs +149 -0
  53. package/cli/translate.mjs +458 -0
  54. package/cli/util.mjs +25 -0
  55. package/cli/vocabulary-docs.mjs +138 -0
  56. package/dist/decklight.css +2087 -91
  57. package/dist/decklight.js +367 -203
  58. package/dist/decklight.js.map +4 -4
  59. package/docs/GLOSSARY.md +9 -2
  60. package/docs/WRITING_RESEARCH.md +327 -0
  61. package/package.json +5 -3
  62. package/themes/coastal.css +3 -0
  63. package/themes/metropolis.css +2 -0
  64. package/themes/reveal-blood.css +3 -0
  65. package/themes/reveal-league.css +2 -0
  66. package/themes/reveal-moon.css +2 -0
  67. package/themes/reveal-serif.css +1 -0
  68. package/themes/reveal-sky.css +1 -0
  69. package/themes/reveal-solarized.css +4 -0
  70. package/tools/brand-palette.mjs +6 -1
  71. package/tools/build-groups.mjs +28 -8
  72. package/tools/cdp.mjs +176 -0
  73. package/tools/chart-spec.mjs +242 -0
  74. package/tools/click-match.mjs +70 -0
  75. package/tools/code-options.mjs +174 -0
  76. package/tools/conversation.mjs +49 -0
  77. package/tools/deck-family.mjs +101 -0
  78. package/tools/deck-html.mjs +212 -15
  79. package/tools/design-system-format.mjs +15 -1
  80. package/tools/diagram-shapes.mjs +221 -0
  81. package/tools/elevenlabs-tts.mjs +62 -53
  82. package/tools/face-clip.mjs +96 -0
  83. package/tools/face-layout.mjs +94 -0
  84. package/tools/gemini-tts.mjs +1 -1
  85. package/tools/invisible-in-print.mjs +27 -0
  86. package/tools/lipsync-auto.mjs +197 -0
  87. package/tools/lipsync-config.mjs +16 -0
  88. package/tools/lipsync-engines.mjs +22 -4
  89. package/tools/lipsync-server.mjs +8 -5
  90. package/tools/lipsync.mjs +122 -30
  91. package/tools/local-voice.mjs +1 -1
  92. package/tools/mouth-file.mjs +26 -0
  93. package/tools/mouth.mjs +320 -0
  94. package/tools/narration-manifest.mjs +24 -4
  95. package/tools/narration-synth.mjs +96 -76
  96. package/tools/recording-impact.mjs +16 -1
  97. package/tools/sentences.mjs +7 -1
  98. package/tools/starters.mjs +402 -0
  99. package/tools/steps.mjs +118 -0
  100. package/tools/take-check.mjs +146 -0
  101. package/tools/template-theme.mjs +3 -1
  102. package/tools/test-impact.mjs +36 -12
  103. package/tools/theme-check.mjs +196 -1
  104. package/tools/tone-cue.mjs +108 -0
  105. package/tools/tts-cache.mjs +9 -3
  106. package/tools/tts-engines.mjs +100 -11
  107. package/tools/video-cache.mjs +93 -0
  108. package/tools/video-live.mjs +349 -0
  109. package/tools/video-options.mjs +11 -0
  110. package/tools/video.mjs +772 -127
  111. package/tools/viseme-fit.mjs +27 -0
  112. package/tools/viseme-match.mjs +77 -0
  113. package/tools/vocabulary.mjs +397 -0
  114. package/tools/voice-renumber.mjs +605 -0
  115. package/tools/voiceover-server.mjs +42 -11
  116. package/tools/voiceover.mjs +48 -20
  117. package/dist/build-info.json +0 -1
package/cli/agents.mjs CHANGED
@@ -25,6 +25,7 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
25
25
  import path, { dirname, join } from 'node:path';
26
26
  import { configHome } from './marketplace.mjs';
27
27
  import { listUnits } from './units.mjs';
28
+ import { unleashedEnv } from './supervise.mjs';
28
29
 
29
30
  export const AGENTS = [
30
31
  {
@@ -35,21 +36,29 @@ export const AGENTS = [
35
36
  // call is a line — so the deck's chip can say WHAT the agent is doing
36
37
  // instead of only how long it has been doing it.
37
38
  // --allowedTools: acceptEdits covers the file, not the shell, and the
38
- // skill asks the agent to render the deck (`npx decklight pdf …`) to
39
+ // skill asks the agent to render the deck (`npx decklight@latest pdf …`) to
39
40
  // check nothing overflows before it is done. Only decklight's own CLI
40
- // is allowed; everything else still needs a permission it has no TTY
41
- // to ask for, which is the point.
41
+ // is allowed, in each form the skill and AGENTS.md name (a rule is a
42
+ // prefix, so `npx decklight` does not cover `npx decklight@latest`,
43
+ // #901); everything else still needs a permission it has no TTY to ask
44
+ // for, which is the point.
42
45
  // --add-dir: claude reads only inside the project unless told, and a
43
46
  // migration's skill lives in a marketplace checkout under ~/.decklight
44
47
  // (#893): each folder a job must read is named, and nothing more.
45
48
  args: (prompt, deck, { dirs = [] } = {}) => ['-p', prompt, '--permission-mode', 'acceptEdits',
46
- '--allowedTools', 'Bash(npx decklight:*)', 'Bash(decklight:*)',
49
+ '--allowedTools', 'Bash(npx decklight:*)', 'Bash(npx decklight@latest:*)', 'Bash(decklight:*)',
47
50
  ...dirs.flatMap((d) => ['--add-dir', d]),
48
51
  '--output-format', 'stream-json', '--verbose'],
49
52
  stream: 'claude-json',
50
53
  // no --permission-mode: an ASK is read-only by construction, and a
51
54
  // commit-message call has no business being able to edit the deck.
52
55
  ask: (prompt) => ['-p', prompt],
56
+ // How each CLI takes a model (#918): appended after the rest, which every
57
+ // parser here accepts. `model: null` is a CLI with no flag for it, said
58
+ // as such rather than a setting quietly dropped.
59
+ model: (id) => ['--model', id],
60
+ // what the card's model field offers; any other id can still be typed
61
+ models: ['opus', 'sonnet', 'haiku'],
53
62
  },
54
63
  {
55
64
  name: 'codex', label: 'Codex CLI', bin: 'codex',
@@ -57,6 +66,7 @@ export const AGENTS = [
57
66
  // the workspace sandbox while allowing file writes.
58
67
  args: (prompt) => ['exec', '--full-auto', prompt],
59
68
  ask: (prompt) => ['exec', '--sandbox', 'read-only', prompt],
69
+ model: (id) => ['-m', id],
60
70
  },
61
71
  {
62
72
  name: 'bob', label: 'IBM Bob', bin: 'bob',
@@ -64,26 +74,33 @@ export const AGENTS = [
64
74
  // it from hanging on the license prompt when there is no TTY.
65
75
  args: (prompt) => ['-p', prompt, '--accept-license'],
66
76
  ask: (prompt) => ['-p', prompt, '--accept-license'],
77
+ model: null,
67
78
  },
68
79
  {
69
80
  name: 'gemini', label: 'Gemini CLI', bin: 'gemini',
70
81
  args: (prompt) => ['--yolo', '-p', prompt],
71
82
  ask: (prompt) => ['-p', prompt],
83
+ model: (id) => ['-m', id],
72
84
  },
73
85
  {
74
86
  name: 'copilot', label: 'GitHub Copilot CLI', bin: 'copilot',
75
87
  args: (prompt) => ['-p', prompt, '--allow-all-tools'],
76
88
  ask: (prompt) => ['-p', prompt],
89
+ model: (id) => ['--model', id],
77
90
  },
78
91
  {
79
92
  name: 'opencode', label: 'OpenCode', bin: 'opencode',
80
93
  args: (prompt) => ['run', prompt],
81
94
  ask: (prompt) => ['run', prompt],
95
+ // provider/model, e.g. anthropic/claude-sonnet-4
96
+ model: (id) => ['-m', id],
82
97
  },
83
98
  {
84
99
  name: 'goose', label: 'Goose', bin: 'goose',
85
100
  args: (prompt) => ['run', '-t', prompt],
86
101
  ask: (prompt) => ['run', '-t', prompt],
102
+ // goose reads its model from its own config (GOOSE_MODEL), not argv
103
+ model: null,
87
104
  },
88
105
  {
89
106
  name: 'aider', label: 'Aider', bin: 'aider',
@@ -92,16 +109,19 @@ export const AGENTS = [
92
109
  args: (prompt, deck) => ['--yes-always', '--no-auto-commits', '--message', prompt, deck],
93
110
  // no deck on the command line either: aider edits what it is given
94
111
  ask: (prompt) => ['--yes-always', '--no-auto-commits', '--message', prompt],
112
+ model: (id) => ['--model', id],
95
113
  },
96
114
  {
97
115
  name: 'cursor', label: 'Cursor CLI', bin: 'cursor-agent',
98
116
  args: (prompt) => ['-p', prompt, '--force'],
99
117
  ask: (prompt) => ['-p', prompt],
118
+ model: (id) => ['--model', id],
100
119
  },
101
120
  {
102
121
  name: 'qwen', label: 'Qwen Code', bin: 'qwen',
103
122
  args: (prompt) => ['--yolo', '-p', prompt],
104
123
  ask: (prompt) => ['-p', prompt],
124
+ model: (id) => ['-m', id],
105
125
  },
106
126
  ];
107
127
 
@@ -139,6 +159,9 @@ export function installedAgents(home = configHome()) {
139
159
  bin: d.bin,
140
160
  installed: true,
141
161
  args: (prompt, deck) => expandArgs(d.args, prompt, deck),
162
+ // optional: `"model": ["--model", "{model}"]`, a template like `args`
163
+ model: Array.isArray(d.model) && d.model.every((a) => typeof a === 'string')
164
+ ? (id) => d.model.map((a) => a.replaceAll('{model}', id)) : null,
142
165
  });
143
166
  } catch { /* a descriptor we cannot read is one agent, not the roster */ }
144
167
  }
@@ -267,22 +290,106 @@ export function detectAgents({ env = process.env, hasBin = canRun, home } = {})
267
290
  /** Where the preferred agent is remembered — beside the unit library. */
268
291
  export const agentConfigPath = (home = configHome()) => join(home, 'agent.json');
269
292
 
270
- /** The remembered agent's name, or null. A missing file is first-run. */
271
- export function preferredAgent(home = configHome()) {
293
+ /** What agent.json holds, `{}` when there is none (first run) or it is unreadable. */
294
+ function readAgentConfig(home) {
272
295
  try {
273
296
  const saved = JSON.parse(readFileSync(agentConfigPath(home), 'utf8'));
274
- return typeof saved?.preferred === 'string' ? saved.preferred : null;
275
- } catch { return null; }
297
+ return saved && typeof saved === 'object' && !Array.isArray(saved) ? saved : {};
298
+ } catch { return {}; }
276
299
  }
277
300
 
278
- /** Remember `name` as the agent `A` reaches for; `null` forgets it. */
279
- export function setPreferredAgent(name, home = configHome()) {
301
+ /** Write agent.json; each setter changes its own key and keeps the others. */
302
+ function writeAgentConfig(change, home) {
280
303
  const file = agentConfigPath(home);
281
304
  mkdirSync(dirname(file), { recursive: true });
282
- writeFileSync(file, `${JSON.stringify({ preferred: name ?? null }, null, 2)}\n`);
305
+ writeFileSync(file, `${JSON.stringify({ ...readAgentConfig(home), ...change }, null, 2)}\n`);
283
306
  return file;
284
307
  }
285
308
 
309
+ /** The remembered agent's name, or null. A missing file is first-run. */
310
+ export function preferredAgent(home = configHome()) {
311
+ const saved = readAgentConfig(home);
312
+ return typeof saved.preferred === 'string' ? saved.preferred : null;
313
+ }
314
+
315
+ /** Remember `name` as the agent `A` reaches for; `null` forgets it. */
316
+ export function setPreferredAgent(name, home = configHome()) {
317
+ return writeAgentConfig({ preferred: name ?? null }, home);
318
+ }
319
+
320
+ // ── the model it runs on (#918) ─────────────────────────────────────────────
321
+ // Decklight's own choice, for decklight's runs only: passed as the agent's
322
+ // model flag, so the user's own default (`"model"` in ~/.claude/settings.json)
323
+ // stays what a plain `claude` opens on. Nothing set means no flag at all, and
324
+ // the agent's own default applies exactly as it always did.
325
+
326
+ /** The two kinds of run: an edit (`args`) and a question (`ask`). */
327
+ const MODEL_KEYS = { edit: 'models', ask: 'askModels' };
328
+ /** The per-run override for each kind; `--agent-model` and `--agent-ask-model` set them. */
329
+ export const MODEL_ENV = { edit: 'DECKLIGHT_AGENT_MODEL', ask: 'DECKLIGHT_AGENT_ASK_MODEL' };
330
+
331
+ const modelId = (v) => (typeof v === 'string' && v.trim() ? v.trim() : null);
332
+
333
+ /** The models remembered for `name`: `{ edit, ask }`, each an id or null. */
334
+ export function rememberedModels(name, home = configHome()) {
335
+ const saved = readAgentConfig(home);
336
+ const pick = (key) => modelId(saved[key]?.[name]);
337
+ return { edit: pick(MODEL_KEYS.edit), ask: pick(MODEL_KEYS.ask) };
338
+ }
339
+
340
+ /** Remember `model` for `name`'s `task` (edit | ask); `null` forgets it. */
341
+ export function setAgentModel(name, model, { task = 'edit', home = configHome() } = {}) {
342
+ const key = MODEL_KEYS[task];
343
+ if (!key) throw new Error(`no such task: ${task}`);
344
+ const all = { ...(readAgentConfig(home)[key] ?? {}) };
345
+ const id = modelId(model);
346
+ if (id) all[name] = id; else delete all[name];
347
+ return writeAgentConfig({ [key]: all }, home);
348
+ }
349
+
350
+ /**
351
+ * Which model `name` runs `task` on, and where that came from: `{ model,
352
+ * source }`, `source` one of 'run' (the flag or env var), 'saved' or null.
353
+ *
354
+ * The same precedence as the agent itself — this run's choice, then the
355
+ * remembered one, then the agent's own default — with one step more for a
356
+ * question: its own setting first, then the edit's, so `--agent-model haiku`
357
+ * alone moves a run's commit subjects too. A run's choice of either kind beats
358
+ * a remembered one of either kind: it was made later, for this run.
359
+ */
360
+ export function agentModel(name, { task = 'edit', env = process.env, home = configHome() } = {}) {
361
+ const saved = rememberedModels(name, home);
362
+ const order = task === 'ask'
363
+ ? [[env[MODEL_ENV.ask], 'run'], [env[MODEL_ENV.edit], 'run'], [saved.ask, 'saved'], [saved.edit, 'saved']]
364
+ : [[env[MODEL_ENV.edit], 'run'], [saved.edit, 'saved']];
365
+ for (const [v, source] of order) if (modelId(v)) return { model: modelId(v), source };
366
+ return { model: null, source: null };
367
+ }
368
+
369
+ /**
370
+ * The argv tail that puts `agent` on its model, and what the run reports:
371
+ * `{ flag, model, unsupported }`. An agent whose CLI takes no model flag gets
372
+ * no flag and says which model it could not take, so the caller can show the
373
+ * setting as unavailable instead of pretending it applied.
374
+ */
375
+ function modelFlag(agent, task, { env, home, model }) {
376
+ const id = model !== undefined ? modelId(model) : agentModel(agent.name, { task, env, home }).model;
377
+ if (!id) return { flag: [], model: null, unsupported: null };
378
+ if (typeof agent.model !== 'function') return { flag: [], model: null, unsupported: id };
379
+ return { flag: agent.model(id), model: id, unsupported: null };
380
+ }
381
+
382
+ /** Put `--agent-model` / `--agent-ask-model` into `env` for every agent this process starts. */
383
+ export function applyModelFlags(opt, env = process.env) {
384
+ for (const [task, flag] of [['edit', '--agent-model'], ['ask', '--agent-ask-model']]) {
385
+ const v = opt(flag);
386
+ if (typeof v === 'string' && v.trim()) env[MODEL_ENV[task]] = v.trim();
387
+ }
388
+ }
389
+
390
+ /** Can `agent` be told a model at all? */
391
+ export const takesModel = (agent) => typeof agent?.model === 'function';
392
+
286
393
  /**
287
394
  * Why `name` cannot be run, as a line naming the way out (#125).
288
395
  *
@@ -335,26 +442,30 @@ export function agentUnavailable(name, roster, home = configHome(),
335
442
  * whose unit declares one template and cannot be asked for a second — noted
336
443
  * rather than hidden, since it is the one path here that stays writable.
337
444
  */
338
- export function agentAsk(name, prompt, { env = process.env, hasBin = canRun, home, spec = spawnSpec } = {}) {
445
+ export function agentAsk(name, prompt, { env = process.env, hasBin = canRun, home, spec = spawnSpec, model } = {}) {
339
446
  const roster = detectAgents({ env, hasBin, home });
340
447
  const wanted = name ?? preferredAgent(home);
341
448
  const agent = wanted ? roster.find((a) => a.name === wanted) : roster[0];
342
449
  if (!agent) return null;
343
450
  const how = spec(agent.bin, { env }) ?? { bin: agent.bin, prefix: [] };
344
451
  const build = agent.ask ?? agent.args;
452
+ const m = modelFlag(agent, 'ask', { env, home, model });
345
453
  return {
346
454
  bin: how.bin,
347
- args: [...how.prefix, ...build(prompt)],
455
+ args: [...how.prefix, ...build(prompt), ...m.flag],
348
456
  label: agent.label,
349
457
  name: agent.name,
458
+ model: m.model,
459
+ modelUnsupported: m.unsupported,
350
460
  readOnly: !!agent.ask,
461
+ env: unleashedEnv(env),
351
462
  };
352
463
  }
353
464
 
354
465
  /** 1 → first, 2 → second … for a sentence an agent reads. */
355
466
  const ordinal = (n) => (n === 1 ? 'first' : n === 2 ? 'second' : n === 3 ? 'third' : `${n}th`);
356
467
 
357
- export function agentCommand(name, instruction, deck, { env = process.env, hasBin = canRun, home, spec = spawnSpec, slide = null, dirs = [] } = {}) {
468
+ export function agentCommand(name, instruction, deck, { env = process.env, hasBin = canRun, home, spec = spawnSpec, slide = null, dirs = [], model } = {}) {
358
469
  const roster = detectAgents({ env, hasBin, home });
359
470
  // Precedence, matching how every other saved choice resolves (PRESENTING):
360
471
  // an explicit name > the remembered preference > the first detected agent.
@@ -383,21 +494,34 @@ export function agentCommand(name, instruction, deck, { env = process.env, hasBi
383
494
  // mode). The skill tells an agent that opened the deck on its own to call
384
495
  // the commit route; one started by A must not, or the edit lands twice.
385
496
  'decklight started you and will commit your edit itself when you finish, under your summary: do not call the commit route. ' +
497
+ // The summary is the commit subject, and the slide number above is the
498
+ // likeliest word in it. A number stops being true when a slide is
499
+ // inserted above it, and `git log` then points at the wrong slide.
500
+ 'In that summary, name a slide by its title, or by a few words describing it when it has none, never by its number. ' +
386
501
  `Apply this change, editing the file in place: ${instruction}`;
387
502
  // The spawn spec, not the bare name: on Windows an npm-installed agent is a
388
503
  // batch shim, and `prefix` is the script node has to be handed for the
389
504
  // arguments below to stay arguments (#307). On POSIX it is empty and this is
390
505
  // the same command it always was.
391
506
  const how = spec(agent.bin, { env }) ?? { bin: agent.bin, prefix: [] };
507
+ // the model (#918): `model` given wins, else this run's, else the remembered one
508
+ const m = modelFlag(agent, 'edit', { env, home, model });
392
509
  return {
393
510
  bin: how.bin,
394
- args: [...how.prefix, ...agent.args(prompt, deck, { dirs })],
511
+ args: [...how.prefix, ...agent.args(prompt, deck, { dirs }), ...m.flag],
395
512
  label: agent.label,
396
513
  name: agent.name,
514
+ // the model it was told to run on, or null for its own default; and one
515
+ // it was set to but cannot take (no model flag), for the caller to say so
516
+ model: m.model,
517
+ modelUnsupported: m.unsupported,
397
518
  // which stream dialect stdout speaks, if any — the server's activity
398
519
  // parser keys off it, and agents without one still get the generic
399
520
  // last-line clue
400
521
  stream: agent.stream ?? null,
522
+ // what to spawn it with: the server's environment minus `open`'s leash,
523
+ // or every decklight command the agent runs exits at once (#901)
524
+ env: unleashedEnv(env),
401
525
  };
402
526
  }
403
527
 
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';
@@ -211,7 +211,62 @@ function mergeDecks(jobs, baseDir, notices) {
211
211
  * written: where it went and the notes printed after it, for a caller (the edit
212
212
  * server's bundle card) that says them somewhere other than this terminal.
213
213
  */
214
- export async function bundleMain(argv = process.argv.slice(2), { client, estimate = false, report = null } = {}) {
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
+ }
215
270
 
216
271
  if (!argv.length || argv.includes('--help') || argv.includes('-h')) {
217
272
  process.stdout.write(`decklight bundle — flatten deck(s) into one self-contained HTML file
@@ -223,6 +278,11 @@ Usage:
223
278
  decklight bundle <a.html> <b.html> … [-o out.html] [--title "…"] [--themes …]
224
279
 
225
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
226
286
  -o <file> output path (default: <deck>-standalone.html, or
227
287
  <deck>-course.html when merging)
228
288
  --all follow the deck's playlist and merge EVERY module into
@@ -428,6 +488,10 @@ if (linked) {
428
488
  html = linkRuntime(html);
429
489
  // said in the summary: the source deck carries no runtime of its own
430
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);
431
495
 
432
496
  const themeLinkRe = /<link\b[^>]*rel=["']stylesheet["'][^>]*href=["']([^"']*themes\/([\w-]+)\.css)["'][^>]*>/i;
433
497
  const themeLinkM = html.match(themeLinkRe);
@@ -869,6 +933,8 @@ if (!jobs) {
869
933
  // though it were finished. Bytes, not a path, for exactly this reason.
870
934
  // An estimate (the edit server's bundle card) stops here: the file as it
871
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);
872
938
  if (estimate) return { base: Buffer.byteLength(html, 'utf8'), audio: audioEstimate };
873
939
 
874
940
  let bundleSig = null;
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
@@ -148,15 +174,16 @@ function setupLine(shellBase) {
148
174
  * (without allowFail) non-zero exits.
149
175
  */
150
176
  export async function recordScript(script, { scriptDir, allowFail = false, log = () => {} }) {
177
+ checkSteps(script.steps);
151
178
  const { pty } = loadDeps();
152
179
  const shellName = script.shell || path.basename(process.env.SHELL || 'zsh');
153
180
  const shellPath = shellName.includes('/') ? shellName : `/bin/${shellName}`;
154
- if (!fs.existsSync(shellPath)) throw new Error(`shell not found: ${shellPath}`);
181
+ if (!fs.existsSync(shellPath)) fail(`shell not found: ${shellPath}`);
155
182
  const cols = script.cols ?? 100;
156
183
  const rows = script.rows ?? 28;
157
184
  const base = scriptDir || process.cwd();
158
185
  const cwd = script.cwd ? path.resolve(base, expandHome(script.cwd)) : base;
159
- if (!fs.existsSync(cwd)) throw new Error(`cwd not found: ${cwd}`);
186
+ if (!fs.existsSync(cwd)) fail(`cwd not found: ${cwd}`);
160
187
 
161
188
  const redactions = (script.redact || []).map(r => new RegExp(r, 'g'));
162
189
  const redact = s => redactions.reduce((acc, re) => acc.replace(re, '▓▓▓'), s);
@@ -186,14 +213,20 @@ export async function recordScript(script, { scriptDir, allowFail = false, log =
186
213
  term.onData(d => { buffer += d; if (onChunk) onChunk(d); });
187
214
  term.onExit(() => { shellDead = true; if (onExitCb) onExitCb(); });
188
215
 
189
- 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) => {
190
220
  const started = Date.now();
191
221
  const tick = () => {
192
222
  const m = test();
193
223
  if (m) return resolve(m);
194
224
  if (isCancelled?.()) return reject(new Error('cancelled'));
195
225
  if (shellDead) return reject(new Error(`shell died while waiting for ${what}`));
196
- 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
+ }
197
230
  setTimeout(tick, 15);
198
231
  };
199
232
  tick();
@@ -202,7 +235,7 @@ export async function recordScript(script, { scriptDir, allowFail = false, log =
202
235
  try {
203
236
  // --- setup phase: silence echo & prompts, then discard everything so far
204
237
  term.write(setupLine(path.basename(shellPath)));
205
- await waitFor(() => buffer.includes(READY_MARK), 10_000, 'shell setup');
238
+ await waitFor(() => buffer.includes(READY_MARK), 10_000, 'shell setup', { setup: true });
206
239
  buffer = '';
207
240
 
208
241
  const sessionEnv = { ...process.env, ...scriptEnv };
@@ -211,15 +244,12 @@ export async function recordScript(script, { scriptDir, allowFail = false, log =
211
244
  for (const [idx, step] of (script.steps || []).entries()) {
212
245
  // Pure pause step: sleeps for real (session truthfulness — background
213
246
  // state may be advancing) and records a timing marker.
214
- if (step && typeof step.sleep === 'number' && step.cmd === undefined) {
247
+ if (step.cmd === undefined) {
215
248
  await new Promise(r => setTimeout(r, step.sleep * 1000));
216
249
  steps.push({ sleep: round3(step.sleep) });
217
250
  log(` ✓ (sleep ${step.sleep}s)`);
218
251
  continue;
219
252
  }
220
- // YAML gotcha: `cmd: false` / `cmd: 42` parse as scalars — coerce.
221
- if (step && (typeof step.cmd === 'boolean' || typeof step.cmd === 'number')) step.cmd = String(step.cmd);
222
- if (!step || typeof step.cmd !== 'string') throw new Error(`step ${idx + 1}: missing "cmd"`);
223
253
  const timeoutMs = (step.timeout ?? 60) * 1000;
224
254
  const chunks = [];
225
255
  const t0 = process.hrtime.bigint();
@@ -254,7 +284,7 @@ export async function recordScript(script, { scriptDir, allowFail = false, log =
254
284
  const found = await waitFor(() => {
255
285
  const mm = collected.slice(searchFrom).match(re);
256
286
  return mm ? { end: searchFrom + mm.index + mm[0].length } : null;
257
- }, 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 });
258
288
  searchFrom = found.end;
259
289
  let text, display;
260
290
  if (it.send && typeof it.send === 'object' && 'secret' in it.send) {
@@ -291,7 +321,7 @@ export async function recordScript(script, { scriptDir, allowFail = false, log =
291
321
  if (interactState.error) throw interactState.error;
292
322
  if (!interactState.done && interactState.pending) {
293
323
  const err = `step ${idx + 1} exited before expect /${interactState.pending}/ matched: ${step.cmd}`;
294
- if (!allowFail) throw new Error(err);
324
+ if (!allowFail) fail(err);
295
325
  log(` ⚠ ${err}`);
296
326
  }
297
327
  const exit = parseInt(m[1], 10);
@@ -332,7 +362,7 @@ export async function recordScript(script, { scriptDir, allowFail = false, log =
332
362
  // 130 is how a command ends when the script itself pressed Ctrl-C:
333
363
  // that is the step working (a server stopped), not failing
334
364
  if (exit !== 0 && !(exit === 130 && interactState.interrupted) && !allowFail) {
335
- throw new Error(`step ${idx + 1} exited ${exit}: ${step.cmd} (use --allow-fail to record failures as content)`);
365
+ fail(`step ${idx + 1} exited ${exit}: ${step.cmd} (use --allow-fail to record failures as content)`);
336
366
  }
337
367
  }
338
368
  finished = true;
@@ -578,6 +608,7 @@ export async function castMain(argv = process.argv.slice(2)) {
578
608
 
579
609
  const script = yaml.load(fs.readFileSync(scriptPath, 'utf8'));
580
610
  if (!script || !Array.isArray(script.steps) || !script.steps.length) fail('script has no steps');
611
+ checkSteps(script.steps);
581
612
 
582
613
  const shellName = script.shell || path.basename(process.env.SHELL || 'zsh');
583
614
  if (!quiet) console.log(`recording ${script.steps.length} step${script.steps.length === 1 ? '' : 's'} in ${shellName}…`);
@@ -34,7 +34,7 @@ import { deckBehind, designSystemRefs, marketplaceDesignSystems, planMigration }
34
34
  import { configHome, loadRegistry } from './marketplace.mjs';
35
35
  import { applyRenames, composeRenames, findRenamed, migrationsOf } from '../tools/design-system-migrations.mjs';
36
36
  import { tokenPrefixOf } from '../tools/design-system-format.mjs';
37
- import { locateSlide, sectionBodies } from '../tools/deck-html.mjs';
37
+ import { locateSlide, sectionBodies, slideName } from '../tools/deck-html.mjs';
38
38
 
39
39
  /** The rules whose fix is deterministic and safe to apply to every slide at once. */
40
40
  export const BATCH_RULES = ['off-role'];
@@ -157,7 +157,7 @@ export function quickFixes(findings, html, dir, { home = configHome(), deck = 'd
157
157
  if (!found.length) return null;
158
158
  return {
159
159
  kind: 'rename', slide: f.slide, batch: true,
160
- label: `Rename ${found.length === 1 ? `${found[0].from} → ${found[0].to}` : `${found.length} roles to their successors`} on slide ${f.slide}`,
160
+ label: `Rename ${found.length === 1 ? `${found[0].from} → ${found[0].to}` : `${found.length} roles to their successors`} on ${slideName(sectionBodies(html)[f.slide - 1])}`,
161
161
  };
162
162
  }
163
163
  case 'ds-unresolved': {
@@ -182,5 +182,13 @@ export function quickFixes(findings, html, dir, { home = configHome(), deck = 'd
182
182
  });
183
183
  }
184
184
 
185
- /** `fix: <rule> on slide N`, or `fix: <rule>` for the deck — the commit a quick fix makes. */
186
- export const fixSubject = (rule, slide = null) => `fix: ${rule}${slide ? ` on slide ${slide}` : ''}`;
185
+ /**
186
+ * `fix: <rule> on "Slide Title"`, or `fix: <rule>` for the deck — the commit a
187
+ * quick fix makes. `slide` is the slide's number, named from `html` the way
188
+ * every subject decklight writes names one (`slideName`), never by the number.
189
+ */
190
+ export const fixSubject = (rule, slide = null, html = '') => {
191
+ const body = slide ? sectionBodies(String(html ?? ''))[slide - 1] : undefined;
192
+ const name = body === undefined ? null : slideName(body);
193
+ return `fix: ${rule}${name ? ` on ${name}` : ''}`;
194
+ };