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
@@ -22,6 +22,8 @@
22
22
  // waiting on it. Nothing here reads those bindings until a request arrives.
23
23
 
24
24
  import { existsSync } from 'node:fs';
25
+ import { randomUUID } from 'node:crypto';
26
+ import { keepAwake } from './keep-awake.mjs';
25
27
  import { basename, dirname, relative, resolve, sep } from 'node:path';
26
28
  import { fileURLToPath } from 'node:url';
27
29
  import { spawn } from 'node:child_process';
@@ -30,6 +32,7 @@ import { EXPORT_KINDS, alreadyOneFile, videoExportProblem } from './edit.mjs';
30
32
  import { oneline, remoteLine, remoteState } from './git.mjs';
31
33
  import { configTheme } from './runtime-link.mjs';
32
34
  import { CommandError } from './util.mjs';
35
+ import { unleashedEnv } from './supervise.mjs';
33
36
  import { THEME_NAME, GEN_THEME } from '../tools/render-theme.mjs';
34
37
  import { locateSlide, sectionChildRanges } from '../tools/deck-html.mjs';
35
38
 
@@ -62,8 +65,10 @@ export function moduleProblem(module) {
62
65
  * it ends, so `/deck/ping` can tell a page that loads mid-render there is one
63
66
  * to stop.
64
67
  */
65
- export function registerHandoverRoutes(routes, { readDeck, deckPath, root, gitOn, broadcast = () => {}, onExport = () => {} }) {
68
+ export function registerHandoverRoutes(routes, { readDeck, deckPath, root, gitOn, broadcast = () => {}, onExport = () => {}, inhibit = keepAwake }) {
66
69
  let exporting = false; // an export in flight — one browser, one output path, any kind
70
+ let latest = null;
71
+ const results = new Map();
67
72
  let stopExport = null; // stops it, while it is one that can be stopped
68
73
  let publishing = false; // a publish in flight — one push at a time
69
74
 
@@ -101,7 +106,31 @@ export function registerHandoverRoutes(routes, { readDeck, deckPath, root, gitOn
101
106
  * And it can be STOPPED (`exportStopRoute`), so a ten-minute video started
102
107
  * on the wrong slides is not a reason to kill the session it runs in.
103
108
  */
104
- async function exportRoute({ url, body, json }) {
109
+ async function exportRoute(request) {
110
+ const id = request.url.searchParams.get('id') ?? randomUUID();
111
+ if (!/^[a-z0-9-]{1,80}$/i.test(id)) return request.json(400, { ok: false, error: 'invalid export ID' });
112
+ if (results.has(id)) return request.json(409, { ok: false, error: 'export ID already used' });
113
+ let snapshot = { id, state: 'pending' };
114
+ results.set(id, snapshot);
115
+ const update = (data) => {
116
+ snapshot = { ...snapshot, ...data };
117
+ results.set(id, snapshot);
118
+ latest = snapshot;
119
+ broadcast('export', snapshot);
120
+ };
121
+ try {
122
+ const { code, result } = await runExport(request, { update, json: (code, result) => ({ code, result }) });
123
+ if (snapshot.state === 'pending') results.set(id, { id, state: 'done', kind: result.kind, result });
124
+ else update({ state: 'done', result, ...result });
125
+ return request.json(code, result);
126
+ } finally {
127
+ if (results.get(id)?.state === 'pending') results.delete(id);
128
+ const finished = [...results].filter(([, job]) => job.state === 'done');
129
+ for (const [key] of finished.slice(0, -32)) results.delete(key);
130
+ }
131
+ }
132
+
133
+ async function runExport({ body }, { update, json }) {
105
134
  const req = JSON.parse(body || '{}');
106
135
  const kind = req.kind ?? 'pptx';
107
136
  const job = EXPORT_KINDS[kind];
@@ -140,11 +169,46 @@ export function registerHandoverRoutes(routes, { readDeck, deckPath, root, gitOn
140
169
  if (bad) return json(400, { ok: false, error: bad });
141
170
  }
142
171
  if (exporting) return json(409, { ok: false, error: 'an export is already running' });
172
+ const video = kind === 'video' ? await import('../tools/video.mjs') : null;
173
+ const narration = req.synthesize?.dir ?? req.narration ?? null;
174
+ let track, report, html, range;
175
+ const anyway = req.allowStale === true;
176
+ const readTrack = () => {
177
+ if (req.silent) return null;
178
+ const dir = narration ? resolve(dirname(deckPath), narration) : null;
179
+ if (req.synthesize && !existsSync(resolve(dir, 'manifest.json'))) return { dir, slides: [], fresh: true };
180
+ return video.resolveNarration(deckPath, dir, { allowEmpty: true });
181
+ };
182
+ const checkTrack = () => video.checkVideoTrack(html, track, range, { face: req.face !== 'off', character: req.character });
183
+ const needsFix = () => report.missing.length || report.stale.length || report.lipsync.length;
184
+ const hasTrackVoice = () => track?.fresh || !!(track?.engine && (track.voice || track.voiceId));
185
+ const preflight = () => {
186
+ const engine = track?.engine ?? (track?.fresh ? req.synthesize.engine : null);
187
+ const audioSlides = new Set([...report.missing, ...report.stale]).size;
188
+ return json(409, { ok: false, error: 'the selected voice needs attention before recording', preflight: {
189
+ ...report, engine, audioSlides, canFix: !audioSlides || hasTrackVoice(),
190
+ ...(audioSlides && engine && !hasTrackVoice() ? { voiceUnknown: true } : {}),
191
+ metered: ['elevenlabs', 'gemini', 'chirp'].includes(engine),
192
+ } });
193
+ };
194
+ if (video) {
195
+ try {
196
+ html = readDeck();
197
+ range = video.parseSlideRange(req.slides, video.extractHolds(html).length);
198
+ track = readTrack();
199
+ if (!anyway) report = await checkTrack();
200
+ } catch (e) {
201
+ return json(400, { ok: false, error: oneline(e) });
202
+ }
203
+ if (!anyway && needsFix() && (req.fix !== true || ((report.missing.length || report.stale.length)
204
+ && !hasTrackVoice()))) return preflight();
205
+ }
143
206
  const { findChrome } = await import('../tools/chrome.mjs');
144
207
  // every file but the bundle is a render; the bundle launches no browser
145
208
  if (kind !== 'bundle' && !findChrome()) {
146
209
  return json(503, { ok: false, error: 'no Chrome found — install one, or point $CHROME at it' });
147
210
  }
211
+ if (exporting) return json(409, { ok: false, error: 'an export is already running' });
148
212
  exporting = true;
149
213
  // Every kind but the bundle: the bundle launches nothing and is seconds
150
214
  // from done, so there is nothing to stop part-way.
@@ -154,31 +218,73 @@ export function registerHandoverRoutes(routes, { readDeck, deckPath, root, gitOn
154
218
  const started = Date.now();
155
219
  console.log(` export: ${basename(deckPath)} → ${job.what}${req.slides ? ` of slides ${req.slides}` : ''}`
156
220
  + `${req.synthesize ? `, voiced by ${req.synthesize.engine} into ${req.synthesize.dir}/` : ''} …`);
157
- broadcast('export', { state: 'start', kind, what: job.what });
221
+ let awake;
158
222
  try {
159
- let out, code, reason = null, subs = null, notes = null;
223
+ awake = await inhibit({ display: kind === 'video' && req.render === 'live' });
224
+ update({ state: 'start', kind, what: job.what, awake: awake.active, displayAwake: awake.displayActive });
225
+ if (stop.signal.aborted) return stopped();
226
+ let out, code, reason = null, subs = null, notes = null, droppedFrames = 0;
160
227
  if (kind === 'video') {
161
- const { videoOut, videoProgress, voiceoverProgress, subtitlesOut } = await import('../tools/video.mjs');
228
+ const { videoOut, videoProgress, voiceoverProgress, subtitlesOut, revoiceStale } = video;
162
229
  out = videoOut(deckPath, req.slides || null, req.format || 'mp4');
163
230
  subs = req.subtitles === 'file' ? subtitlesOut(out, req.format || 'mp4') : null;
164
- // Two phases, each told apart on the channel: voicing is minutes on a
165
- // cloud engine, and a row that said "rendering" through all of it would
166
- // read as stuck on slide one.
167
- if (req.synthesize) {
168
- ({ code, reason } = await runTool('voiceover', await voiceoverArgv(req),
169
- voiceoverProgress((n, of) => broadcast('export', { state: 'slide', kind, phase: 'voice', n, of })), stop.signal));
231
+ const tick = (phase) => (n, of) => update({ state: 'slide', phase, n, of });
232
+ if (!anyway && needsFix()) {
233
+ const slides = [...new Set([...report.missing, ...report.stale])].sort((a, b) => a - b);
234
+ if (slides.length && track.engine) {
235
+ const result = await revoiceStale({
236
+ html, narration: track, stale: slides, missing: report.missing, lipsync: null,
237
+ onSlide: tick('voice'), signal: stop.signal,
238
+ });
239
+ if (!result.ok) ({ code, reason } = { code: 1, reason: result.why });
240
+ } else if (slides.length) {
241
+ ({ code, reason } = await runTool('voiceover', [...await voiceoverArgv(req), '--no-face'],
242
+ voiceoverProgress(tick('voice')), stop.signal));
243
+ }
244
+ if (!code && !stop.signal.aborted) {
245
+ track = readTrack();
246
+ report = await checkTrack();
247
+ if (report.lipsync.length) {
248
+ let done = 0;
249
+ const files = [...new Set(report.lipsync.map((item) => item.audio))];
250
+ const lipTick = tick('lipsync');
251
+ lipTick(0, files.length);
252
+ ({ code, reason } = await runTool('lipsync',
253
+ [track.dir, '--visemes', '--no-veo', '--audio-files', JSON.stringify(files)],
254
+ (line) => { if (/cues →/.test(line)) lipTick(++done, files.length); }, stop.signal));
255
+ }
256
+ }
257
+ if (!stop.signal.aborted) {
258
+ html = readDeck();
259
+ range = video.parseSlideRange(req.slides, video.extractHolds(html).length);
260
+ track = readTrack();
261
+ report = await checkTrack();
262
+ if (needsFix()) {
263
+ if (reason) report.repairError = reason;
264
+ return preflight();
265
+ }
266
+ code = 0;
267
+ }
170
268
  }
171
269
  if (!code && !stop.signal.aborted) {
172
- const narration = req.synthesize?.dir ?? req.narration ?? null;
270
+ const progress = videoProgress(tick('render'));
173
271
  ({ code, reason } = await runTool('video', [deckPath, '-o', out, ...themed,
174
272
  ...(req.slides ? ['--slides', req.slides] : []),
175
273
  ...(req.format ? ['--format', req.format] : []),
176
274
  ...(req.quality ? ['--quality', req.quality] : []),
275
+ ...(req.render ? ['--render', req.render] : []),
177
276
  ...(req.subtitles ? ['--subtitles', req.subtitles] : []),
178
- ...(narration ? ['--narration', resolve(dirname(deckPath), narration)] : req.silent ? ['--no-narration'] : []),
179
- // the card showed the track as recorded from older notes and it was picked anyway (#536)
180
- ...(req.allowStale === true ? ['--allow-stale'] : [])],
181
- videoProgress((n, of) => broadcast('export', { state: 'slide', kind, phase: 'render', n, of })), stop.signal));
277
+ ...(req.face === 'off' ? ['--no-face'] : []),
278
+ ...(req.character ? ['--character', req.character] : []),
279
+ ...(narration && track?.slides.length ? ['--narration', track.dir] : narration || req.silent ? ['--no-narration'] : []),
280
+ // Preflight owns repairs for the card, including the as-is path.
281
+ '--no-revoice', '--no-remake-visemes',
282
+ ...(anyway ? ['--allow-stale'] : [])],
283
+ (line) => {
284
+ const dropped = /^\s+live capture: warning — (\d+) dropped/.exec(line);
285
+ if (dropped) droppedFrames = Number(dropped[1]);
286
+ progress(line);
287
+ }, stop.signal));
182
288
  }
183
289
  } else if (kind === 'bundle') {
184
290
  // No -o: the CLI names the file, beside the deck, so the row and
@@ -203,7 +309,7 @@ export function registerHandoverRoutes(routes, { readDeck, deckPath, root, gitOn
203
309
  out = pptxOut(deckPath);
204
310
  code = await pptxMain([deckPath, ...themed], {
205
311
  log: (line) => console.log(` ${line}`),
206
- onSlide: (n, of) => broadcast('export', { state: 'slide', kind, n, of }),
312
+ onSlide: (n, of) => update({ state: 'slide', n, of }),
207
313
  signal: stop.signal,
208
314
  });
209
315
  } else {
@@ -215,17 +321,16 @@ export function registerHandoverRoutes(routes, { readDeck, deckPath, root, gitOn
215
321
  const file = relative(process.cwd(), out) || basename(out);
216
322
  const seconds = Math.round((Date.now() - started) / 100) / 10;
217
323
  if (code !== 0) {
218
- broadcast('export', { state: 'done', kind, ok: false });
219
324
  return json(500, { ok: false, error: reason ?? 'the export refused — see the edit server\'s output' });
220
325
  }
221
326
  // A render with nothing spoken writes no subtitles and says so; the deck
222
327
  // is told of a file only when there is one to open.
223
328
  const voiced = {
224
- ...(req.synthesize ? { voiced: req.synthesize.dir } : {}),
329
+ ...(req.synthesize && track?.slides.length ? { voiced: req.synthesize.dir } : {}),
225
330
  ...(subs && existsSync(subs) ? { subtitles: relative(process.cwd(), subs) || basename(subs) } : {}),
226
331
  };
227
- broadcast('export', { state: 'done', kind, ok: true, file, seconds, ...voiced });
228
- return json(200, { ok: true, kind, what: job.what, file, seconds, ...voiced, ...(notes ? { notes } : {}) });
332
+ return json(200, { ok: true, kind, what: job.what, file, seconds, ...voiced,
333
+ ...(notes ? { notes } : {}), ...(droppedFrames ? { droppedFrames } : {}) });
229
334
  } catch (e) {
230
335
  if (stop.signal.aborted) return stopped();
231
336
  // A render that hangs or a Chrome that dies is the export's problem,
@@ -235,9 +340,9 @@ export function registerHandoverRoutes(routes, { readDeck, deckPath, root, gitOn
235
340
  // sentence is what fits on a card, and the card has the list already.
236
341
  const said = e instanceof CommandError ? e.message.split('\n')[0].replace(/\s+—[^—]*:$/, '') : oneline(e);
237
342
  console.log(` export: ${job.what} failed — ${said}`);
238
- broadcast('export', { state: 'done', kind, ok: false, error: said });
239
343
  return json(500, { ok: false, error: said });
240
344
  } finally {
345
+ await awake?.release();
241
346
  exporting = false;
242
347
  stopExport = null;
243
348
  onExport(null);
@@ -249,7 +354,6 @@ export function registerHandoverRoutes(routes, { readDeck, deckPath, root, gitOn
249
354
  function stopped() {
250
355
  const kept = req.synthesize && existsSync(resolve(dirname(deckPath), req.synthesize.dir)) ? { voiced: req.synthesize.dir } : {};
251
356
  console.log(` export: ${job.what} stopped — nothing written`);
252
- broadcast('export', { state: 'done', kind, ok: false, stopped: true, ...kept });
253
357
  return json(200, { ok: false, stopped: true, kind, what: job.what, ...kept });
254
358
  }
255
359
  }
@@ -286,10 +390,13 @@ export function registerHandoverRoutes(routes, { readDeck, deckPath, root, gitOn
286
390
  const script = fileURLToPath(new URL(`../tools/${name}.mjs`, import.meta.url));
287
391
  const cwd = deckPath.startsWith(process.cwd() + sep) ? process.cwd() : dirname(deckPath);
288
392
  return new Promise((done) => {
289
- const child = spawn(process.execPath, [script, ...argv], { cwd, stdio: ['ignore', 'pipe', 'pipe'] });
393
+ const stopOverIPC = process.platform === 'win32' && name === 'video';
394
+ const stdio = ['ignore', 'pipe', 'pipe', ...(stopOverIPC ? ['ipc'] : [])];
395
+ const child = spawn(process.execPath, [script, ...argv], { cwd, env: unleashedEnv(), stdio });
290
396
  let hard = null;
291
397
  const stop = () => {
292
- child.kill('SIGTERM');
398
+ if (stopOverIPC && child.connected) child.send('stop-video', () => {});
399
+ else child.kill('SIGTERM');
293
400
  hard = setTimeout(() => child.kill('SIGKILL'), STOP_GRACE_MS);
294
401
  };
295
402
  if (signal?.aborted) stop(); else signal?.addEventListener('abort', stop, { once: true });
@@ -541,6 +648,10 @@ export function registerHandoverRoutes(routes, { readDeck, deckPath, root, gitOn
541
648
  }
542
649
 
543
650
  routes.set('POST /deck/edit/export', exportRoute);
651
+ routes.set('GET /deck/edit/export/status', ({ url, json }) => {
652
+ const id = url.searchParams.get('id');
653
+ return json(200, { ok: true, job: id ? results.get(id) ?? null : latest });
654
+ });
544
655
  routes.set('POST /deck/edit/export/stop', exportStopRoute);
545
656
  routes.set('GET /deck/edit/export/estimate', exportEstimateRoute);
546
657
  routes.set('GET /deck/edit/inspect', inspectRoute);
package/cli/edit-look.mjs CHANGED
@@ -31,7 +31,7 @@ import { basename, dirname } from 'node:path';
31
31
  import { fileURLToPath } from 'node:url';
32
32
 
33
33
  import { oneline } from './git.mjs';
34
- import { setDeckTheme, setDeckBrandThemesOnly } from './runtime-link.mjs';
34
+ import { setDeckTheme, setDeckBrandThemesOnly, setDeckConfig, setDeckTitle, deckSettings } from './runtime-link.mjs';
35
35
 
36
36
  /**
37
37
  * Put the look routes into `routes`, the table cli/edit.mjs dispatches on, and
@@ -97,6 +97,48 @@ export function registerLookRoutes(routes, {
97
97
  return json(200, { ok: true, changed, inPlace: changed && inPlace === true, ...history.counts() });
98
98
  }
99
99
 
100
+ /**
101
+ * `GET /deck/edit/config`: what Deck settings… shows (PRESENTING_EDITING),
102
+ * read from the file: the page's title, each setting (the default where the
103
+ * file says nothing), and whether this deck's configuration can be
104
+ * rewritten, with the one sentence saying why not.
105
+ */
106
+ function configGetRoute({ json }) {
107
+ return json(200, { ok: true, ...deckSettings(readDeck()) });
108
+ }
109
+ /**
110
+ * `POST /deck/edit/config` `{ set?: { key: value | null }, title? }`: the
111
+ * deck's own settings, saved in the file (setDeckConfig, setDeckTitle), in
112
+ * one edit and one undo. A value back at its default takes the key off. Not
113
+ * quiet: the runtime reads these when the deck loads, so every page reloads.
114
+ * A deck whose configuration is code, or elsewhere, is a 409 saying why.
115
+ */
116
+ function configPostRoute({ body, json }) {
117
+ const { set = null, title } = JSON.parse(body || '{}');
118
+ if (set === null && title === undefined) return json(400, { ok: false, error: 'nothing to set' });
119
+ if (title !== undefined && typeof title !== 'string') return json(400, { ok: false, error: 'a title is text' });
120
+ const before = readDeck();
121
+ const why = deckSettings(before).why;
122
+ if (set && why) return json(409, { ok: false, error: `this deck’s settings cannot be saved here: ${why}` });
123
+ let changed;
124
+ try {
125
+ changed = applyEdit((html) => {
126
+ let out = html;
127
+ if (set) {
128
+ const next = setDeckConfig(out, set);
129
+ if (next === null) throw Object.assign(new Error('this deck’s configuration could not be rewritten in place'), { code: 'UNWRITABLE' });
130
+ out = next;
131
+ }
132
+ if (title !== undefined) out = setDeckTitle(out, title);
133
+ return out;
134
+ });
135
+ } catch (e) {
136
+ return json(e.code === 'UNWRITABLE' ? 409 : 400, { ok: false, error: String(e.message).split('\n')[0] });
137
+ }
138
+ if (changed) console.log(` deck settings: ${[...Object.entries(set ?? {}).map(([k, v]) => `${k}=${JSON.stringify(v)}`), ...(title !== undefined ? [`title=${JSON.stringify(title)}`] : [])].join(', ')}`);
139
+ return json(200, { ok: true, changed, ...deckSettings(readDeck()), ...history.counts() });
140
+ }
141
+
100
142
  // ── marketplace themes, and marking (THEME_BROWSE#UI) ─────────────────
101
143
  // What the overlay lists while authoring: every theme of every registered
102
144
  // marketplace, each saying whether this deck marks it. Cache-only by
@@ -569,6 +611,8 @@ export function registerLookRoutes(routes, {
569
611
 
570
612
  routes.set('POST /deck/edit/theme', themeRoute);
571
613
  routes.set('POST /deck/edit/brand-themes', brandThemesRoute);
614
+ routes.set('GET /deck/edit/config', configGetRoute);
615
+ routes.set('POST /deck/edit/config', configPostRoute);
572
616
  routes.set('GET /deck/edit/theme/browse', themeBrowseRoute);
573
617
  routes.set('POST /deck/edit/theme/add', themeAddRoute);
574
618
  routes.set('POST /deck/edit/theme/mark', themeMarkRoute);
@@ -0,0 +1,143 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ // Open in your editor (PRESENTING_EDITING): from a slide or an element on
5
+ // screen to its place in the deck FILE, in the author's code editor.
6
+ //
7
+ // GET /deck/edit/editor the saved choice and what this machine offers
8
+ // POST /deck/edit/editor { editor, template? }: remember the choice
9
+ // POST /deck/edit/open { slide, index?, path?, tag? }: open the deck
10
+ // at that slide's <section>, or at that element
11
+ //
12
+ // The address is the one every element route takes (cli/edit-address.mjs):
13
+ // a slide, an element's raw index among the section's children, and for a
14
+ // node inside it the file's `path` below it and the `tag` the page saw. The
15
+ // line and column come from the file's own offsets, so a path the file does
16
+ // not have is stale (409), never a guess.
17
+ //
18
+ // Nothing of the request reaches the command but the line and the column,
19
+ // numbers the server computed itself. The program is the author's saved
20
+ // choice, the file is always the deck being served, and it is started as an
21
+ // argument array without a shell (cli/code-editor.mjs). The two POSTs answer
22
+ // this server's own page only (isOwnOrigin): a plugin's sandboxed frame or
23
+ // another loopback page cannot set a command, nor start one.
24
+
25
+ import { locateSlide } from '../tools/deck-html.mjs';
26
+ import { locateElement, nodeAt, checkPath } from './edit-address.mjs';
27
+ import { detectEditors, loadEditorChoice, saveEditorChoice, checkChoice, choiceLabel, editorCommand, launchEditor } from './code-editor.mjs';
28
+
29
+ /** Line and column (both from 1) of `offset` in `text`: columns count characters, a tab one. */
30
+ export function lineColumn(text, offset) {
31
+ const before = text.slice(0, offset);
32
+ const lineStart = before.lastIndexOf('\n') + 1;
33
+ return { line: (before.match(/\n/g)?.length ?? 0) + 1, column: [...before.slice(lineStart)].length + 1 };
34
+ }
35
+
36
+ /**
37
+ * Where an address starts in the deck file: `{ offset, line, column }` of
38
+ * slide `slide`'s `<section`, or with `index` of that element's open tag, or
39
+ * with `path` of the node there. A slide or an index the file does not have
40
+ * throws; a path it does not have, or a tag that is not the page's, is STALE.
41
+ */
42
+ export function sourcePosition(html, { slide, index = null, path = null, tag = null }) {
43
+ const { parts, idx } = locateSlide(html, slide);
44
+ // parts: [preamble, '<section', body1, '<section', body2, …]
45
+ const sectionAt = parts.slice(0, idx - 1).join('').length;
46
+ if (index === null) return { offset: sectionAt, ...lineColumn(html, sectionAt) };
47
+ const { seg, r } = locateElement(html, slide, index);
48
+ const bodyAt = sectionAt + parts[idx - 1].length;
49
+ const el = seg.slice(r.start, r.end);
50
+ const at = nodeAt(el, path ? checkPath(path) : [], { slide, index, tag });
51
+ const offset = bodyAt + r.start + at.start;
52
+ return { offset, ...lineColumn(html, offset) };
53
+ }
54
+
55
+ /**
56
+ * The three routes, given what they need of the edit server: the deck's
57
+ * text and path, the gate that says a request is this server's own page,
58
+ * and (for the tests) the environment the editor is looked up in and the
59
+ * spawner that starts it.
60
+ */
61
+ export function registerOpenRoutes(routes, {
62
+ readDeck, deckPath, ownOrigin, env = process.env, spawn, platform = process.platform, exists, log = console.log,
63
+ }) {
64
+ const where = { env, platform, ...(exists ? { exists } : {}) };
65
+ const state = () => {
66
+ const chosen = loadEditorChoice(env);
67
+ return {
68
+ chosen: chosen ? { ...chosen, label: choiceLabel(chosen, { env }) } : null,
69
+ editors: detectEditors(where),
70
+ };
71
+ };
72
+ const refuseForeign = (req, json) => {
73
+ if (ownOrigin(req)) return false;
74
+ json(403, { ok: false, error: 'only this deck\'s own page can open your editor' });
75
+ return true;
76
+ };
77
+
78
+ /** `GET /deck/edit/editor`: what is chosen, and what the chooser lists. */
79
+ function editorStateRoute({ json }) {
80
+ return json(200, { ok: true, ...state() });
81
+ }
82
+
83
+ /** `POST /deck/edit/editor` `{ editor, template? }`: remember it; `{ editor: null }` forgets it. */
84
+ function editorSaveRoute({ req, body, json }) {
85
+ if (refuseForeign(req, json)) return;
86
+ const asked = JSON.parse(body || '{}');
87
+ if (asked?.editor === null) {
88
+ saveEditorChoice(null, env);
89
+ log(' editor: choice forgotten');
90
+ return json(200, { ok: true, ...state() });
91
+ }
92
+ let choice;
93
+ try { choice = checkChoice(asked); } catch (e) { return json(400, { ok: false, error: String(e.message || e) }); }
94
+ // a named editor this machine does not have is not a choice to keep
95
+ const offered = detectEditors(where).find((e) => e.id === choice.editor);
96
+ if (!offered) return json(400, { ok: false, error: `${choiceLabel(choice, { env })} is not on this machine` });
97
+ if (offered.blocked) return json(400, { ok: false, error: offered.blocked });
98
+ saveEditorChoice(choice, env);
99
+ log(` editor: ${choiceLabel(choice, { env })} remembered`);
100
+ return json(200, { ok: true, ...state() });
101
+ }
102
+
103
+ /**
104
+ * `POST /deck/edit/open` `{ slide, index?, path?, tag? }`: the deck opened
105
+ * in the saved editor at that place. 409 for an address the file does not
106
+ * have (stale, like the other element routes); 428 with `choose: true`
107
+ * before an editor is chosen; 422 with `reason` when the chosen one cannot
108
+ * be started from here (not installed, a terminal editor).
109
+ */
110
+ async function openRoute({ req, body, json }) {
111
+ if (refuseForeign(req, json)) return;
112
+ const { slide, index = null, path = null, tag = null } = JSON.parse(body || '{}');
113
+ if (!Number.isInteger(slide) || slide < 1 || (index !== null && (!Number.isInteger(index) || index < 0))
114
+ || (path !== null && !Array.isArray(path)) || (path !== null && index === null) || (tag !== null && typeof tag !== 'string')) {
115
+ return json(400, { ok: false, error: 'bad payload' });
116
+ }
117
+ let pos;
118
+ try {
119
+ pos = sourcePosition(readDeck(), { slide, index, path, tag });
120
+ } catch (e) {
121
+ if (e.code === 'STALE' || /^no slide \d|no element at index/.test(e.message)) {
122
+ return json(409, { ok: false, stale: true, error: String(e.message || e).split('\n')[0] });
123
+ }
124
+ if (e.message === 'bad path') return json(400, { ok: false, error: 'bad payload' });
125
+ throw e;
126
+ }
127
+ const choice = loadEditorChoice(env);
128
+ if (!choice) return json(428, { ok: false, choose: true, error: 'choose your code editor first', ...state() });
129
+ const cmd = editorCommand(choice, { file: deckPath, line: pos.line, column: pos.column }, where);
130
+ if (!cmd.ok) return json(422, { ok: false, reason: cmd.reason, error: cmd.error, ...state() });
131
+ const started = await launchEditor(cmd, { baseEnv: env, ...(spawn ? { spawn } : {}) });
132
+ if (!started.ok) {
133
+ return json(422, { ok: false, reason: 'missing', error: `${cmd.label} did not start: ${started.error}`, ...state() });
134
+ }
135
+ log(` editor: slide ${slide}${index === null ? '' : ` #${index}${path?.length ? ` › ${path.join('.')}` : ''}`} opened in ${cmd.label} at line ${pos.line}`);
136
+ return json(200, { ok: true, line: pos.line, column: pos.column, editor: cmd.label });
137
+ }
138
+
139
+ routes.set('GET /deck/edit/editor', editorStateRoute);
140
+ routes.set('POST /deck/edit/editor', editorSaveRoute);
141
+ routes.set('POST /deck/edit/open', openRoute);
142
+ return routes;
143
+ }