decklight 0.8.1 → 0.9.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/PLATFORM.md +666 -0
  2. package/README.md +224 -150
  3. package/SPEC.md +732 -886
  4. package/cli/agent-review.mjs +245 -0
  5. package/cli/agents.mjs +25 -5
  6. package/cli/associate.mjs +12 -12
  7. package/cli/audit.mjs +42 -10
  8. package/cli/banner.mjs +41 -17
  9. package/cli/bundle-audio.mjs +183 -0
  10. package/cli/bundle.mjs +383 -31
  11. package/cli/cast.mjs +7 -7
  12. package/cli/check.mjs +961 -0
  13. package/cli/clone-deck.mjs +179 -0
  14. package/cli/commands.mjs +345 -0
  15. package/cli/comments.mjs +64 -18
  16. package/cli/commit-flow.mjs +44 -19
  17. package/cli/commit-message.mjs +51 -74
  18. package/cli/commit-split.mjs +601 -0
  19. package/cli/deck-refs.mjs +59 -0
  20. package/cli/deck-routes.mjs +67 -0
  21. package/cli/deckfile.mjs +3 -5
  22. package/cli/decklight.mjs +68 -289
  23. package/cli/design-system-deps.mjs +209 -0
  24. package/cli/design-system-edit.mjs +194 -0
  25. package/cli/design-system-refs.mjs +409 -0
  26. package/cli/design-system.mjs +429 -0
  27. package/cli/doctor.mjs +115 -0
  28. package/cli/edit-git.mjs +353 -0
  29. package/cli/edit-handover.mjs +445 -0
  30. package/cli/edit-look.mjs +388 -0
  31. package/cli/edit-slides.mjs +683 -0
  32. package/cli/edit.mjs +2126 -842
  33. package/cli/enhance.mjs +483 -0
  34. package/cli/extension.mjs +10 -10
  35. package/cli/font-refs.mjs +273 -0
  36. package/cli/font.mjs +246 -0
  37. package/cli/git-tree.mjs +1 -1
  38. package/cli/git.mjs +65 -11
  39. package/cli/import.mjs +56 -10
  40. package/cli/init.mjs +400 -234
  41. package/cli/library.mjs +127 -0
  42. package/cli/loader.mjs +3 -1
  43. package/cli/marketplace.mjs +215 -21
  44. package/cli/narrate.mjs +176 -0
  45. package/cli/open-browser.mjs +63 -0
  46. package/cli/open.mjs +943 -0
  47. package/cli/pdf.mjs +41 -13
  48. package/cli/pkg.mjs +44 -2
  49. package/cli/plugin.mjs +43 -41
  50. package/cli/port-conflict.mjs +53 -23
  51. package/cli/pptx-export.mjs +57 -24
  52. package/cli/publish.mjs +8 -4
  53. package/cli/qr.mjs +1 -1
  54. package/cli/record.mjs +14 -12
  55. package/cli/remote.mjs +11 -11
  56. package/cli/restore.mjs +11 -4
  57. package/cli/review-ref.mjs +125 -0
  58. package/cli/review-remote.mjs +92 -48
  59. package/cli/review-routes.mjs +254 -0
  60. package/cli/review-store.mjs +47 -7
  61. package/cli/review-submit.mjs +47 -57
  62. package/cli/runtime-link.mjs +560 -0
  63. package/cli/serve.mjs +235 -44
  64. package/cli/setup.mjs +112 -0
  65. package/cli/sign.mjs +1 -1
  66. package/cli/skill-content.mjs +190 -33
  67. package/cli/skills.mjs +107 -24
  68. package/cli/start.mjs +110 -0
  69. package/cli/supervise.mjs +6 -6
  70. package/cli/theme-refs.mjs +515 -0
  71. package/cli/theme.mjs +181 -137
  72. package/cli/trust.mjs +83 -0
  73. package/cli/units.mjs +39 -42
  74. package/cli/update-check.mjs +1 -5
  75. package/cli/upgrade.mjs +194 -28
  76. package/cli/upstream.mjs +4 -3
  77. package/cli/util.mjs +4 -4
  78. package/cli/wizard.mjs +6 -6
  79. package/dist/build-info.json +1 -1
  80. package/dist/decklight.css +1126 -49
  81. package/dist/decklight.js +212 -115
  82. package/dist/decklight.js.map +4 -4
  83. package/docs/GLOSSARY.md +141 -0
  84. package/docs/architecture.svg +17 -17
  85. package/package.json +4 -2
  86. package/themes/README.md +9 -8
  87. package/themes/reveal-solarized.css +10 -0
  88. package/tools/args.mjs +20 -0
  89. package/tools/atomic-write.mjs +48 -0
  90. package/tools/brand-palette.mjs +717 -0
  91. package/tools/bridge.mjs +1 -1
  92. package/tools/build-groups.mjs +42 -0
  93. package/tools/color.mjs +48 -0
  94. package/tools/deck-html.mjs +396 -11
  95. package/tools/design-system-format.mjs +753 -0
  96. package/tools/elevenlabs-tts.mjs +110 -17
  97. package/tools/exec.mjs +1 -1
  98. package/tools/extension-check.mjs +31 -7
  99. package/tools/font-format.mjs +190 -0
  100. package/tools/font-stacks.mjs +24 -0
  101. package/tools/gemini-tts.mjs +3 -0
  102. package/tools/lipsync-config.mjs +103 -0
  103. package/tools/lipsync-engines.mjs +205 -2
  104. package/tools/lipsync-server.mjs +264 -41
  105. package/tools/lipsync.mjs +37 -18
  106. package/tools/local-voice.mjs +32 -42
  107. package/tools/narration-manifest.mjs +196 -0
  108. package/tools/narration-synth.mjs +416 -0
  109. package/tools/pptx.mjs +776 -19
  110. package/tools/publish-targets.mjs +1 -1
  111. package/tools/publish-voices.mjs +3 -3
  112. package/tools/recording-impact.mjs +7 -3
  113. package/tools/render-theme.mjs +33 -0
  114. package/tools/review-anchor.mjs +28 -12
  115. package/tools/semver.mjs +40 -0
  116. package/tools/sentences.mjs +180 -0
  117. package/tools/shot.mjs +14 -7
  118. package/tools/site-voices.mjs +232 -0
  119. package/tools/template-theme.mjs +1 -1
  120. package/tools/test-impact.mjs +17 -10
  121. package/tools/theme-check.mjs +30 -3
  122. package/tools/tts-cache.mjs +4 -3
  123. package/tools/tts-engines.mjs +38 -20
  124. package/tools/tts-setup.mjs +7 -7
  125. package/tools/video-options.mjs +34 -0
  126. package/tools/video.mjs +461 -48
  127. package/tools/voiceover-server.mjs +185 -104
  128. package/tools/voiceover.mjs +119 -261
  129. package/tools/zip.mjs +1 -1
  130. package/cli/dev.mjs +0 -623
  131. package/cli/present.mjs +0 -853
  132. package/cli/review.mjs +0 -361
  133. package/tools/publish-site-voices.mjs +0 -75
@@ -0,0 +1,445 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ // The routes that HAND THE DECK OVER: writing it out as another file (pptx,
5
+ // pdf, a one-file bundle, a video), saying how big a bundle would be before
6
+ // it is written, and publishing it to a page the world can read (SPEC
7
+ // PRESENTING). The inspector's read of where a slide lives in the file sits
8
+ // here too: like the rest, it reads the deck and never writes it.
9
+ //
10
+ // They came out of cli/edit.mjs because none of them edits the deck. What they
11
+ // share is the machinery of a long job run beside a live session: a headless
12
+ // Chrome or a child process, a progress feed on the event channel, a flag
13
+ // that keeps two of them from running at once, and the question every one of
14
+ // them asks first, whether the theme on screen is one the deck marks
15
+ // (`unmarkedOnScreen`). Between them they want five of editMain's bindings,
16
+ // and the two in-flight flags they own outright, so those live here with them.
17
+ //
18
+ // The import back to edit.mjs, for the export table and the two checks it
19
+ // shares with the command line, is a deliberate STATIC cycle, for the reason
20
+ // cli/edit-slides.mjs gives: edit.mjs ends in a top-level `await`, so a
21
+ // dynamic import from inside editMain would wait on an evaluation that is
22
+ // waiting on it. Nothing here reads those bindings until a request arrives.
23
+
24
+ import { existsSync } from 'node:fs';
25
+ import { basename, dirname, join, relative, resolve, sep } from 'node:path';
26
+ import { fileURLToPath } from 'node:url';
27
+ import { spawn } from 'node:child_process';
28
+
29
+ import { EXPORT_KINDS, alreadyOneFile, videoExportProblem } from './edit.mjs';
30
+ import { oneline, remoteLine, remoteState } from './git.mjs';
31
+ import { configTheme } from './runtime-link.mjs';
32
+ import { CommandError } from './util.mjs';
33
+ import { THEME_NAME, GEN_THEME } from '../tools/render-theme.mjs';
34
+ import { locateSlide, sectionChildRanges } from '../tools/deck-html.mjs';
35
+
36
+ /**
37
+ * Put the hand-over routes into `routes`, the table cli/edit.mjs dispatches
38
+ * on, and hand it back.
39
+ *
40
+ * `ctx` is the whole of what these handlers may touch: `readDeck()` for the
41
+ * current file, `deckPath` because every export is written beside the deck
42
+ * and named after it, `root` for the repository a publish pushes from,
43
+ * `broadcast` for the export's progress, and `gitOn()` for whether this
44
+ * session has a repository to publish from: a getter, not a copy, because it
45
+ * is a `let` of editMain's and the answer is whatever it holds when a publish
46
+ * asks.
47
+ */
48
+ export function registerHandoverRoutes(routes, { readDeck, deckPath, root, gitOn, broadcast = () => {} }) {
49
+ let exporting = false; // an export in flight — one browser, one output path, any kind
50
+ let publishing = false; // a publish in flight — one push at a time
51
+
52
+ // ── hand-over: the files this deck can be written out as, and publishing ───
53
+
54
+ /**
55
+ * Write the deck out as a file, for the palette's hand-over rows
56
+ * (PRESENTING) — `{ kind }`, one of EXPORT_KINDS.
57
+ *
58
+ * `decklight pptx` and `decklight pdf` need Node and a headless Chrome,
59
+ * so the deck cannot do this itself — the same reason `A` asks the
60
+ * server to run an agent. The work is the commands' own `main`s,
61
+ * unchanged, so what a row writes is exactly what the command line
62
+ * writes.
63
+ *
64
+ * Four things this route owes the session it is running inside:
65
+ *
66
+ * - it must not TAKE THE SERVER DOWN. `chromeBin` exits the process when
67
+ * there is no browser — correct for a one-shot command, fatal here, so
68
+ * Chrome is resolved with the non-fatal `findChrome` first and a machine
69
+ * without one gets a sentence instead of a dead edit server.
70
+ * - it must not run twice at once. Two exports write the same path
71
+ * through two browsers; the second caller is told to wait. ONE flag for
72
+ * every kind, deliberately: two different exports at once is still two
73
+ * browsers on one machine, and the second would only be slower.
74
+ * - it must not block. Both `main`s are async all the way down (pptx
75
+ * serves the deck from THIS process while Chrome fetches it; pdf is
76
+ * async so the session stays answerable while Chrome prints), so live
77
+ * reload, the SSE stream and every other route keep answering while a
78
+ * slide renders. That is also why a row can say "rendering…" and mean it.
79
+ * - it must SAY WHERE IT IS. An export is tens of seconds, so each slide
80
+ * is announced on the `export` channel of the same SSE stream the agent
81
+ * chip rides, and the deck rewrites its one progress row from it.
82
+ */
83
+ async function exportRoute({ url, body, json }) {
84
+ const req = JSON.parse(body || '{}');
85
+ const kind = req.kind ?? 'pptx';
86
+ const job = EXPORT_KINDS[kind];
87
+ if (!job) {
88
+ return json(400, { ok: false, error: `not a file this server writes: ${kind} — try ${Object.keys(EXPORT_KINDS).join(', ')}` });
89
+ }
90
+ // The theme on screen, which the render is told because it cannot see the
91
+ // browser's pick (#547): a name — what `--theme` takes — or, for a theme
92
+ // that lives only in that browser, its tokens as `--gen` takes them
93
+ // (base64url JSON, the form `?gen=` loads; the runtime vets every token).
94
+ if (req.theme != null && !(typeof req.theme === 'string' && THEME_NAME.test(req.theme))) {
95
+ return json(400, { ok: false, error: 'the theme is a theme name' });
96
+ }
97
+ if (req.gen != null && !(typeof req.gen === 'string' && GEN_THEME.test(req.gen))) {
98
+ return json(400, { ok: false, error: 'the generated theme is base64url, at most 16 KB' });
99
+ }
100
+ if (req.theme != null && req.gen != null) return json(400, { ok: false, error: 'one theme — a name or a generated one' });
101
+ if (kind === 'bundle') {
102
+ // A bundle EMBEDS its themes, and a generated one is tokens in this
103
+ // browser with no file to embed. Bundling in the configured theme
104
+ // instead would hand over a file that does not look like the screen.
105
+ if (req.gen != null) {
106
+ return json(400, { ok: false, error: 'a generated theme lives only in this browser — save it (⌃⇧T) and add it with decklight theme add to bundle it' });
107
+ }
108
+ if (alreadyOneFile(readDeck())) {
109
+ return json(409, { ok: false, error: 'this deck is already one file — send it as it is' });
110
+ }
111
+ }
112
+ const unmarked = await unmarkedOnScreen(req.theme, { carried: kind === 'bundle' });
113
+ if (unmarked) return json(409, { ok: false, unmarked, error: `${unmarked} is not marked for this deck` });
114
+ const themed = req.theme ? ['--theme', req.theme] : req.gen ? ['--gen', req.gen] : [];
115
+ if (kind === 'video') {
116
+ const bad = videoExportProblem(req, dirname(deckPath));
117
+ if (bad) return json(400, { ok: false, error: bad });
118
+ }
119
+ if (exporting) return json(409, { ok: false, error: 'an export is already running' });
120
+ const { findChrome } = await import('../tools/chrome.mjs');
121
+ // every file but the bundle is a render; the bundle launches no browser
122
+ if (kind !== 'bundle' && !findChrome()) {
123
+ return json(503, { ok: false, error: 'no Chrome found — install one, or point $CHROME at it' });
124
+ }
125
+ exporting = true;
126
+ const started = Date.now();
127
+ console.log(` export: ${basename(deckPath)} → ${job.what}${req.slides ? ` of slides ${req.slides}` : ''}`
128
+ + `${req.synthesize ? `, voiced by ${req.synthesize.engine} into ${req.synthesize.dir}/` : ''} …`);
129
+ broadcast('export', { state: 'start', kind, what: job.what });
130
+ try {
131
+ let out, code, reason = null, subs = null;
132
+ if (kind === 'video') {
133
+ const { videoOut, videoProgress, voiceoverProgress, subtitlesOut } = await import('../tools/video.mjs');
134
+ out = videoOut(deckPath, req.slides || null, req.format || 'mp4');
135
+ subs = req.subtitles === 'file' ? subtitlesOut(out, req.format || 'mp4') : null;
136
+ // Two phases, each told apart on the channel: voicing is minutes on a
137
+ // cloud engine, and a row that said "rendering" through all of it would
138
+ // read as stuck on slide one.
139
+ if (req.synthesize) {
140
+ ({ code, reason } = await runTool('voiceover', await voiceoverArgv(req),
141
+ voiceoverProgress((n, of) => broadcast('export', { state: 'slide', kind, phase: 'voice', n, of }))));
142
+ }
143
+ if (!code) {
144
+ const narration = req.synthesize?.dir ?? req.narration ?? null;
145
+ ({ code, reason } = await runTool('video', [deckPath, '-o', out, ...themed,
146
+ ...(req.slides ? ['--slides', req.slides] : []),
147
+ ...(req.format ? ['--format', req.format] : []),
148
+ ...(req.quality ? ['--quality', req.quality] : []),
149
+ ...(req.subtitles ? ['--subtitles', req.subtitles] : []),
150
+ ...(narration ? ['--narration', resolve(dirname(deckPath), narration)] : req.silent ? ['--no-narration'] : []),
151
+ // the card showed the track as recorded from older notes and it was picked anyway (#536)
152
+ ...(req.allowStale === true ? ['--allow-stale'] : [])],
153
+ videoProgress((n, of) => broadcast('export', { state: 'slide', kind, phase: 'render', n, of }))));
154
+ }
155
+ } else if (kind === 'bundle') {
156
+ // The CLI's own name for the file, beside the deck, so the row and
157
+ // `decklight bundle` write the same one; `audio` is its --audio
158
+ // ('original', 'aac' or 'opus'), the recorded voice carried inside.
159
+ // bundleMain returns nothing on success and throws a sentence on a
160
+ // refusal — the catch below says it.
161
+ const { bundleMain } = await import('./bundle.mjs');
162
+ const { AUDIO_CHOICES } = await import('./bundle-audio.mjs');
163
+ out = join(dirname(deckPath), `${basename(deckPath).replace(/\.html?$/i, '')}-standalone.html`);
164
+ code = (await bundleMain([deckPath, '-o', out, ...(req.theme ? ['--theme', req.theme] : []),
165
+ ...(AUDIO_CHOICES.includes(req.audio) ? ['--audio', req.audio] : [])])) ?? 0;
166
+ } else if (kind === 'pptx') {
167
+ const { pptxMain, pptxOut } = await import('./pptx-export.mjs');
168
+ out = pptxOut(deckPath);
169
+ code = await pptxMain([deckPath, ...themed], {
170
+ log: (line) => console.log(` ${line}`),
171
+ onSlide: (n, of) => broadcast('export', { state: 'slide', kind, n, of }),
172
+ });
173
+ } else {
174
+ const { pdfMain, pdfOut } = await import('./pdf.mjs');
175
+ out = pdfOut(deckPath, null, job.variant);
176
+ code = await pdfMain([deckPath, ...themed, ...(job.variant ? [`--${job.variant}`] : [])]);
177
+ }
178
+ const file = relative(process.cwd(), out) || basename(out);
179
+ const seconds = Math.round((Date.now() - started) / 100) / 10;
180
+ if (code !== 0) {
181
+ broadcast('export', { state: 'done', kind, ok: false });
182
+ return json(500, { ok: false, error: reason ?? 'the export refused — see the edit server\'s output' });
183
+ }
184
+ // A render with nothing spoken writes no subtitles and says so; the deck
185
+ // is told of a file only when there is one to open.
186
+ const voiced = {
187
+ ...(req.synthesize ? { voiced: req.synthesize.dir } : {}),
188
+ ...(subs && existsSync(subs) ? { subtitles: relative(process.cwd(), subs) || basename(subs) } : {}),
189
+ };
190
+ broadcast('export', { state: 'done', kind, ok: true, file, seconds, ...voiced });
191
+ return json(200, { ok: true, kind, what: job.what, file, seconds, ...voiced });
192
+ } catch (e) {
193
+ // A render that hangs or a Chrome that dies is the export's problem,
194
+ // never the session's: the message goes back to the palette and the
195
+ // server carries on serving the deck.
196
+ console.log(` export: ${job.what} failed — ${oneline(e)}`);
197
+ broadcast('export', { state: 'done', kind, ok: false, error: oneline(e) });
198
+ return json(500, { ok: false, error: oneline(e) });
199
+ } finally {
200
+ exporting = false;
201
+ }
202
+ }
203
+
204
+ /**
205
+ * `decklight video` (and `decklight narrate` before it, when the export
206
+ * voices its slides), run as CHILDREN rather than through their `main`s like
207
+ * the other exports: both end in `process.exit` on every refusal, and each
208
+ * would take this session down or freeze it. A child keeps that where it
209
+ * belongs, and its output is read line by line for the progress it already
210
+ * prints.
211
+ *
212
+ * Served from the same root `pptx` picks: the current directory when the deck
213
+ * is under it, its own directory otherwise.
214
+ */
215
+ function runTool(name, argv, onLine) {
216
+ const script = fileURLToPath(new URL(`../tools/${name}.mjs`, import.meta.url));
217
+ const cwd = deckPath.startsWith(process.cwd() + sep) ? process.cwd() : dirname(deckPath);
218
+ return new Promise((done) => {
219
+ const child = spawn(process.execPath, [script, ...argv], { cwd, stdio: ['ignore', 'pipe', 'pipe'] });
220
+ let pending = '', err = '';
221
+ child.stdout.on('data', (chunk) => {
222
+ pending += chunk;
223
+ for (let i; (i = pending.indexOf('\n')) >= 0;) {
224
+ const line = pending.slice(0, i);
225
+ pending = pending.slice(i + 1);
226
+ console.log(` ${line}`);
227
+ onLine(line);
228
+ }
229
+ });
230
+ child.stderr.on('data', (chunk) => { err += chunk; process.stdout.write(String(chunk).replace(/^/gm, ' ')); });
231
+ child.on('error', (e) => done({ code: 1, reason: oneline(e) }));
232
+ child.on('close', (code) => {
233
+ // the command's own refusal is the sentence the deck shows
234
+ const said = err.split('\n').map((l) => l.trim()).filter(Boolean);
235
+ const prefix = `decklight ${name}:`;
236
+ const refusal = said.findLast((l) => l.startsWith(prefix)) ?? said.at(-1);
237
+ done({ code, reason: code === 0 ? null : (refusal?.replace(prefix, '').trim() ?? null) });
238
+ });
239
+ });
240
+ }
241
+
242
+ /**
243
+ * argv for voicing an export: the live voice the deck is speaking with, as
244
+ * `decklight narrate` spells it. The deck sends what only it knows — the
245
+ * engine and model the bridge answered with, the voice and tone picked in V —
246
+ * and the rest comes from where the bridge itself reads it (the environment,
247
+ * then ~/.config/decklight/tts.json for the same engine), so a sentence
248
+ * already heard live is a cache hit here and not a second bill.
249
+ */
250
+ async function voiceoverArgv({ slides, synthesize: s }) {
251
+ const { loadTtsConfig } = await import('../tools/tts-setup.mjs');
252
+ const { piperModelDir } = await import('../tools/tts-engines.mjs');
253
+ const saved = loadTtsConfig();
254
+ const savedFor = saved?.engine === s.engine ? saved : null;
255
+ const project = process.env.GOOGLE_CLOUD_PROJECT ?? saved?.project;
256
+ const dataDir = savedFor?.dataDir ?? (s.engine === 'piper' ? piperModelDir() : null);
257
+ return [deckPath, '-o', resolve(dirname(deckPath), s.dir), '--engine', s.engine,
258
+ ...(s.voice ? ['--voice', s.voice] : []),
259
+ ...(s.style ? ['--style', s.style] : []),
260
+ ...(s.model ? ['--tts-model', s.model] : []),
261
+ ...(savedFor?.format ? ['--tts-format', savedFor.format] : []),
262
+ ...(dataDir ? ['--data-dir', dataDir] : []),
263
+ ...(project && (s.engine === 'gemini' || s.engine === 'chirp') ? ['--project', project] : []),
264
+ ...(slides ? ['--slides', slides] : [])];
265
+ }
266
+
267
+ /**
268
+ * Publish the deck — and, before that, say where to (PRESENTING).
269
+ *
270
+ * The one row in the palette that reaches OFF this machine. Everything
271
+ * else the deck can ask this server for writes a file beside it; this
272
+ * pushes a page the world can read, and `Z` does not take that back. So
273
+ * it is two routes, not one: the deck asks for the PLAN, shows a person
274
+ * the remote and the URL, and only posts after a second, deliberate
275
+ * press. The arming lives in the deck, not here — an unarmed POST
276
+ * publishes, exactly as the command line does, because a confirmation
277
+ * belongs to the surface that can show somebody what they are agreeing
278
+ * to.
279
+ *
280
+ * `GIT_TERMINAL_PROMPT=0` matters more here than anywhere else: publish
281
+ * pushes with a synchronous git, so a credential prompt would not be
282
+ * asking anybody anything — it would hang the write-mode session on a
283
+ * terminal nobody is looking at.
284
+ */
285
+ async function publishPlanRoute({ json }) {
286
+ if (!gitOn()) return json(409, { ok: false, error: 'git is off for this session — there is nothing to publish from' });
287
+ const remote = remoteState(root);
288
+ if (!remote.url) {
289
+ return json(409, { ok: false, error: `nowhere to publish to — ${remoteLine(remote) || remote.state}` });
290
+ }
291
+ const { pagesUrl } = await import('./publish.mjs');
292
+ // Whether it COULD sign is part of the plan, not a failure after the
293
+ // fact: publish signs by default and refuses rather than publishing
294
+ // unsigned (INTEGRITY), and the deck would otherwise show somebody a
295
+ // URL, take their confirmation, and only then say it cannot.
296
+ //
297
+ // The SENTENCE is built here, not in the deck. The runtime must never
298
+ // so much as name the signing client (test/sign.test.mjs greps src/
299
+ // and dist/ for it — the invariant is that the browser never reaches
300
+ // for it), so the server hands over words the deck only has to show.
301
+ const { loadClient, INSTALL_HINT } = await import('./sign.mjs');
302
+ const canSign = Boolean(await loadClient());
303
+ return json(200, {
304
+ ok: true, remote: remote.remote, branch: 'gh-pages',
305
+ url: pagesUrl(remote.url), bundled: !alreadyOneFile(readDeck()),
306
+ signing: canSign,
307
+ why: canSign ? null : `publish signs the deck first, and that client is not installed — ${INSTALL_HINT}`,
308
+ });
309
+ }
310
+
311
+ async function publishRoute({ body, json }) {
312
+ if (!gitOn()) return json(409, { ok: false, error: 'git is off for this session — there is nothing to publish from' });
313
+ if (publishing) return json(409, { ok: false, error: 'a publish is already running' });
314
+ // The theme on screen is the one the page opens on (SPEC THEME_DISTRIBUTION)
315
+ // — the same question the export card answers, asked the same way.
316
+ const { theme = null } = JSON.parse(body || '{}');
317
+ if (theme != null && !(typeof theme === 'string' && THEME_NAME.test(theme))) {
318
+ return json(400, { ok: false, error: 'the theme is a theme name' });
319
+ }
320
+ const unmarked = await unmarkedOnScreen(theme);
321
+ if (unmarked) return json(409, { ok: false, unmarked, error: `${unmarked} is not marked for this deck` });
322
+ publishing = true;
323
+ const before = process.env.GIT_TERMINAL_PROMPT;
324
+ process.env.GIT_TERMINAL_PROMPT = '0';
325
+ console.log(` publish: ${basename(deckPath)} → gh-pages …`);
326
+ try {
327
+ const { publishMain } = await import('./publish.mjs');
328
+ // A deck that is already one file has nothing to flatten, and the
329
+ // bundler rightly refuses it — the same two cases `decklight
330
+ // publish` has, decided here rather than made the presenter's
331
+ // problem. Everything else is the command's own default, signature
332
+ // included.
333
+ const oneFile = alreadyOneFile(readDeck());
334
+ const args = [deckPath, ...(oneFile ? ['--no-bundle'] : theme ? ['--theme', theme] : [])];
335
+ const r = await publishMain(args);
336
+ console.log(` publish: ${r.url ?? `${r.remote} ${r.branch}`}`);
337
+ return json(200, { ok: true, url: r.url ?? null, branch: r.branch, remote: r.remote, commit: r.commit });
338
+ } catch (e) {
339
+ console.log(` publish: refused — ${oneline(e)}`);
340
+ return json(500, { ok: false, error: oneline(e) });
341
+ } finally {
342
+ process.env.GIT_TERMINAL_PROMPT = before ?? '';
343
+ if (before === undefined) delete process.env.GIT_TERMINAL_PROMPT;
344
+ publishing = false;
345
+ }
346
+ }
347
+
348
+ /**
349
+ * GET /deck/edit/export/estimate?kind=bundle — how big an export would be, before
350
+ * it is written. Only the bundle has one today: the file without its audio
351
+ * (`base`), and what each way of carrying the narration's recorded audio
352
+ * would add (cli/bundle-audio.mjs), so the bundle card can say "Opus — ≈ 2.1
353
+ * MB" before anybody chooses. `audio` is null for a deck with no recorded
354
+ * audio on this disk.
355
+ */
356
+ async function exportEstimateRoute({ url, json }) {
357
+ const kind = url.searchParams.get('kind');
358
+ if (kind !== 'bundle') return json(400, { ok: false, error: `no estimate for ${kind ?? 'that'} — only a bundle has one` });
359
+ const theme = url.searchParams.get('theme');
360
+ if (theme != null && !THEME_NAME.test(theme)) return json(400, { ok: false, error: 'the theme is a theme name' });
361
+ const { bundleMain } = await import('./bundle.mjs');
362
+ const estimate = (argv) => bundleMain([deckPath, ...argv], { estimate: true });
363
+ try {
364
+ // in the theme on screen, as the export will be — or, when that one
365
+ // cannot be bundled yet (the export asks to mark it first), in the
366
+ // deck's own: an estimate a theme's stylesheet away is still one
367
+ let r;
368
+ try { r = await estimate(theme ? ['--theme', theme] : []); } catch (e) {
369
+ if (!theme || !(e instanceof CommandError)) throw e;
370
+ r = await estimate([]);
371
+ }
372
+ return json(200, { ok: true, base: r.base, audio: r.audio });
373
+ } catch (e) {
374
+ if (!(e instanceof CommandError)) throw e;
375
+ return json(409, { ok: false, error: e.message.split('\n')[0] });
376
+ }
377
+ }
378
+
379
+ /**
380
+ * Where slide N lives in the file, for the inspector (`I`, PRESENTING): the
381
+ * slide's lines, each authored top-level child's lines by the same raw index
382
+ * the element routes use, and what `decklight check` would say about it.
383
+ * Read-only, and only the static half of the check: the render half needs a
384
+ * browser and takes seconds, and the panel asks on every slide change.
385
+ */
386
+ async function inspectRoute({ url, json }) {
387
+ const { sectionRanges, staticFindings } = await import('./check.mjs');
388
+ const html = readDeck();
389
+ const ranges = sectionRanges(html);
390
+ const slide = Number(url.searchParams.get('slide'));
391
+ if (!Number.isInteger(slide) || slide < 1 || slide > ranges.length) {
392
+ return json(400, { ok: false, error: `no slide ${url.searchParams.get('slide') ?? ''} — the deck has ${ranges.length}`.trim() });
393
+ }
394
+ // 1-based line of an offset: the newlines before it, plus one
395
+ const breaks = [];
396
+ for (let i = html.indexOf('\n'); i !== -1; i = html.indexOf('\n', i + 1)) breaks.push(i);
397
+ const lineAt = (at) => {
398
+ let lo = 0, hi = breaks.length;
399
+ while (lo < hi) { const mid = (lo + hi) >> 1; if (breaks[mid] < at) lo = mid + 1; else hi = mid; }
400
+ return lo + 1;
401
+ };
402
+ const span = (start, end) => [lineAt(start), lineAt(Math.max(start, end - 1))];
403
+ const range = ranges[slide - 1];
404
+ const { parts, idx } = locateSlide(html, slide);
405
+ const segAt = parts.slice(0, idx).join('').length;
406
+ let blocks = [];
407
+ try {
408
+ blocks = sectionChildRanges(parts[idx]).map((r) => ({ tag: r.tag, lines: span(segAt + r.start, segAt + r.end) }));
409
+ } catch { /* a malformed section still has its own lines */ }
410
+ const findings = staticFindings(html, { dir: dirname(deckPath) })
411
+ .filter((f) => f.slide === slide)
412
+ .map(({ level, rule, message }) => ({ level, rule, message }));
413
+ return json(200, { ok: true, file: basename(deckPath), lines: span(range.start, range.end), blocks, findings });
414
+ }
415
+
416
+ /**
417
+ * The marketplace theme on screen that this deck does not mark, as a
418
+ * reference — or null. An export or a publish of an unmarked theme would
419
+ * come out in a theme the deck does not carry; the card asks first
420
+ * (`409 { unmarked }`), and marking is one more press.
421
+ */
422
+ async function unmarkedOnScreen(theme, { carried = false } = {}) {
423
+ if (!theme) return null;
424
+ const html = readDeck();
425
+ const { markedRefs, markedShipped, marketplaceThemes, shippedThemes } = await import('./theme-refs.mjs');
426
+ if (shippedThemes().includes(theme)) {
427
+ // A render shows a shipped theme without carrying it — every install has
428
+ // it. A BUNDLE carries only what the deck marks, plus the theme it opens
429
+ // on: one it opens on in some other theme is a question first (Gilles'
430
+ // rule), so the file never leaves carrying a theme nobody chose to send.
431
+ if (!carried) return null;
432
+ return markedShipped(html).includes(theme) || theme === configTheme(html) ? null : theme;
433
+ }
434
+ if (markedRefs(html).some((r) => r.name === theme)) return null;
435
+ if (new RegExp(`<style\\b[^>]*\\bdata-theme\\s*=\\s*["']${theme}["']`, 'i').test(html)) return null;
436
+ return marketplaceThemes().themes.find((t) => t.name === theme)?.qualified ?? null;
437
+ }
438
+
439
+ routes.set('POST /deck/edit/export', exportRoute);
440
+ routes.set('GET /deck/edit/export/estimate', exportEstimateRoute);
441
+ routes.set('GET /deck/edit/inspect', inspectRoute);
442
+ routes.set('GET /deck/edit/publish/plan', publishPlanRoute);
443
+ routes.set('POST /deck/edit/publish', publishRoute);
444
+ return routes;
445
+ }