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
@@ -0,0 +1,466 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ /**
5
+ * A deck in several languages, the part that needs no model (SPEC
6
+ * TRANSLATIONS): what is translated in a slide (TRANSLATION_UNITS), the record
7
+ * of what each piece was translated from (TRANSLATION_RECORD), matching the
8
+ * source against that record to say what is behind, and writing the
9
+ * translation, which is the source with its words replaced.
10
+ *
11
+ * Everything here is pure: strings in, strings and plain objects out. The
12
+ * command (cli/translate.mjs) reads and writes the files and asks the agent.
13
+ *
14
+ * WHY THE SOURCE'S STRUCTURE IS RE-READ EVERY TIME. A translation is never
15
+ * edited into shape: `talk.fr.html` is `talk.html` with each unit's text
16
+ * replaced, so a slide moved, restyled or rebuilt in the source is moved,
17
+ * restyled or rebuilt in French by the next run, at no model cost when its
18
+ * words did not change. The record is what makes "did its words change"
19
+ * a string comparison rather than a question for a model.
20
+ */
21
+
22
+ import { createHash } from 'node:crypto';
23
+ import { NOTES_ASIDE, decodeNoteEntities, readNotes, sectionCloseIndex, deckLang } from '../tools/deck-html.mjs';
24
+ import { CLICK_MARK, hasWords } from '../tools/sentences.mjs';
25
+ import { textRuns } from './rewrite.mjs';
26
+ import { deckTitle, setDeckTitle, withConfigKeys } from './runtime-link.mjs';
27
+
28
+ export const RECORD_VERSION = 1;
29
+
30
+ /** The attributes whose words are a slide's (TRANSLATION_UNITS `attr`). */
31
+ export const UNIT_ATTRS = ['alt', 'aria-label', 'title', 'data-title', 'data-module', 'data-steps', 'data-step'];
32
+
33
+ const LETTER = /\p{L}/u;
34
+ const blank = (s, re) => String(s).replace(re, (m) => ' '.repeat(m.length));
35
+ const encText = (s) => String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
36
+ const encAttr = (s) => encText(s).replace(/"/g, '&quot;');
37
+
38
+ /**
39
+ * One beat of notes as text: tags gone (a `<br>` a line break, a closing `<p>`
40
+ * a paragraph), entities read, markers in the square brackets decklight
41
+ * writes, paragraphs a blank line apart, every other run of space one space.
42
+ */
43
+ export function beatText(part) {
44
+ const s = decodeNoteEntities(String(part ?? '')
45
+ .replace(/<br\s*\/?>/gi, '\n')
46
+ .replace(/<\/p\s*>/gi, '\n\n')
47
+ .replace(/<\/?(?:p|div|li|ul|ol|h\d|tr|td|th|table|blockquote)\b[^>]*>/gi, ' ')
48
+ .replace(/<[^>]+>/g, ''))
49
+ .replace(/⟨(\/?)([A-Z][A-Z ]*)⟩/g, (m, close, word) => `[${close}${word.toLowerCase()}]`);
50
+ return s.split(/\n[ \t]*\n/).map((p) => p.replace(/\s+/g, ' ').trim()).filter(Boolean).join('\n\n');
51
+ }
52
+
53
+ /** A chart's strings a reader sees, by path: labels, series names, axis titles, marker, threshold and now labels. */
54
+ function chartStrings(obj) {
55
+ const out = [];
56
+ const take = (holder, key) => {
57
+ if (typeof holder?.[key] === 'string' && LETTER.test(holder[key])) out.push({ holder, key });
58
+ };
59
+ if (Array.isArray(obj.labels)) obj.labels.forEach((_, i) => take(obj.labels, i));
60
+ take(obj, 'x'); take(obj, 'y'); take(obj, 'title');
61
+ if (obj.threshold && typeof obj.threshold === 'object') take(obj.threshold, 'label');
62
+ if (obj.now && typeof obj.now === 'object') take(obj.now, 'label');
63
+ for (const s of Array.isArray(obj.series) ? obj.series : []) {
64
+ if (!s || typeof s !== 'object') continue;
65
+ take(s, 'name');
66
+ for (const m of Array.isArray(s.markers) ? s.markers : []) if (m && typeof m === 'object') take(m, 'label');
67
+ }
68
+ return out;
69
+ }
70
+
71
+ /** A chart's references to a label by its text (`at`, `dashFrom`, `now`), so they follow a translated label. */
72
+ function chartRefs(obj) {
73
+ const out = [];
74
+ const ref = (holder, key) => { if (typeof holder?.[key] === 'string') out.push({ holder, key }); };
75
+ ref(obj, 'now');
76
+ if (obj.now && typeof obj.now === 'object') ref(obj.now, 'at');
77
+ for (const s of Array.isArray(obj.series) ? obj.series : []) {
78
+ if (!s || typeof s !== 'object') continue;
79
+ ref(s, 'dashFrom');
80
+ for (const m of Array.isArray(s.markers) ? s.markers : []) if (m && typeof m === 'object') ref(m, 'at');
81
+ }
82
+ return out;
83
+ }
84
+
85
+ /**
86
+ * A section body (`sectionBodies`: the rest of the open tag, the inside, the
87
+ * close and whatever follows) as units and the edits that write them back:
88
+ * `{ units: [{ kind, text }], edits: [{ start, end, make(texts) }] }`. The
89
+ * units are in the order TRANSLATION_UNITS gives: runs, beats, attributes,
90
+ * labels. The edits never overlap. Pure.
91
+ */
92
+ export function slideParts(body) {
93
+ const src = String(body ?? '');
94
+ const open = src.indexOf('>');
95
+ const closeAt = sectionCloseIndex(src);
96
+ const to = closeAt < 0 ? src.length : closeAt;
97
+ const from = open + 1;
98
+ const inner = src.slice(from, to);
99
+ const units = [];
100
+ const edits = [];
101
+ const add = (kind, text) => { units.push({ kind, text }); return units.length - 1; };
102
+
103
+ // runs: the text the audience reads, cut exactly as the writing tools cut it
104
+ for (const r of textRuns(inner)) {
105
+ const i = add('run', r.text);
106
+ edits.push({ start: from + r.start, end: from + r.end, units: [i], make: (T) => encText(T[i]) });
107
+ }
108
+
109
+ // beats: the notes cut at [click]; the markers are not units, so a
110
+ // translated slide has the source's beats by construction
111
+ const aside = NOTES_ASIDE.exec(inner);
112
+ if (aside) {
113
+ const aStart = from + aside.index + aside[0].indexOf('>') + 1;
114
+ const aEnd = aStart + aside[1].length;
115
+ const parts = readNotes(aside[1]).split(CLICK_MARK).map(beatText);
116
+ const ids = parts.map((p) => (hasWords(p) ? add('beat', p) : -1));
117
+ edits.push({
118
+ start: aStart, end: aEnd,
119
+ // indented under the aside, the way a person writes notes
120
+ make: (T) => {
121
+ const ind = /(?:^|\n)([ \t]*)[^\n]*$/.exec(src.slice(0, aStart))?.[1] ?? '';
122
+ const at = `\n${ind} `;
123
+ const beat = (k) => encText(ids[k] >= 0 ? T[ids[k]] : parts[k]).split('\n').join(at).replace(new RegExp(`${at}(?=${at})`, 'g'), '\n');
124
+ return `${at}${parts.map((_, k) => beat(k)).join(`${at}[click]${at}`)}\n${ind}`;
125
+ },
126
+ });
127
+ }
128
+
129
+ // attributes, the section's own open tag first
130
+ const scan = blank(src.slice(0, to),
131
+ /<(script|style|textarea)\b[^>]*>[\s\S]*?<\/\1\s*>|<!--[\s\S]*?-->|<aside class="notes">[\s\S]*?<\/aside>/gi);
132
+ const tags = [{ index: 0, text: scan.slice(0, from) }];
133
+ for (const m of scan.slice(from).matchAll(/<[a-zA-Z][^>]*>/g)) tags.push({ index: from + m.index, text: m[0] });
134
+ const attrRe = new RegExp(`\\s(${UNIT_ATTRS.join('|')})\\s*=\\s*(?:"([^"]*)"|'([^']*)')`, 'gi');
135
+ for (const tag of tags) {
136
+ for (const m of tag.text.matchAll(attrRe)) {
137
+ const name = m[1].toLowerCase();
138
+ const raw = m[2] ?? m[3] ?? '';
139
+ const vStart = tag.index + m.index + m[0].length - 1 - raw.length;
140
+ const vEnd = vStart + raw.length;
141
+ const value = decodeNoteEntities(raw);
142
+ if (name === 'data-steps') {
143
+ const items = value.split(',').map((x) => x.trim());
144
+ const ids = items.map((x) => (LETTER.test(x) ? add('attr', x) : -1));
145
+ if (ids.some((i) => i >= 0)) edits.push({ start: vStart, end: vEnd, units: ids.filter((i) => i >= 0), make: (T) => encAttr(items.map((x, k) => (ids[k] >= 0 ? T[ids[k]] : x)).join(', ')) });
146
+ } else if (LETTER.test(value)) {
147
+ const i = add('attr', value.trim());
148
+ edits.push({ start: vStart, end: vEnd, units: [i], make: (T) => encAttr(T[i]) });
149
+ }
150
+ }
151
+ }
152
+
153
+ // labels: the words drawn in an SVG diagram …
154
+ const plain = blank(inner, /<(script|style)\b[^>]*>[\s\S]*?<\/\1\s*>|<!--[\s\S]*?-->/gi);
155
+ for (const svg of plain.matchAll(/<svg\b[\s\S]*?<\/svg\s*>/gi)) {
156
+ const base = from + svg.index;
157
+ let at = 0;
158
+ const text = svg[0];
159
+ for (const t of [...text.matchAll(/<[^>]+>/g), { index: text.length, 0: '' }]) {
160
+ const piece = text.slice(at, t.index);
161
+ if (LETTER.test(piece)) {
162
+ const lead = piece.match(/^\s*/)[0].length;
163
+ const trail = piece.match(/\s*$/)[0].length;
164
+ const i = add('label', decodeNoteEntities(piece.slice(lead, piece.length - trail)));
165
+ const s = base + at + lead;
166
+ edits.push({ start: s, end: base + at + piece.length - trail, make: (T) => encText(T[i]) });
167
+ }
168
+ at = t.index + t[0].length;
169
+ }
170
+ }
171
+ // … and in a chart's JSON
172
+ for (const sc of inner.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script\s*>/gi)) {
173
+ if (!/application\/json/i.test(sc[1]) || /data-decklight-config/i.test(sc[1])) continue;
174
+ let obj;
175
+ try { obj = JSON.parse(sc[2]); } catch { continue; }
176
+ if (!obj || typeof obj !== 'object' || Array.isArray(obj) || !(obj.labels || obj.series)) continue;
177
+ const strings = chartStrings(obj);
178
+ if (!strings.length) continue;
179
+ const ids = strings.map(({ holder, key }) => add('label', holder[key].trim()));
180
+ const sStart = from + sc.index + sc[0].indexOf('>') + 1;
181
+ edits.push({
182
+ start: sStart, end: sStart + sc[2].length,
183
+ make: (T) => {
184
+ const copy = JSON.parse(sc[2]);
185
+ const was = new Map();
186
+ chartStrings(copy).forEach(({ holder, key }, k) => { was.set(holder[key], T[ids[k]]); holder[key] = T[ids[k]]; });
187
+ for (const { holder, key } of chartRefs(copy)) if (was.has(holder[key])) holder[key] = was.get(holder[key]);
188
+ return `\n${JSON.stringify(copy)}\n`;
189
+ },
190
+ });
191
+ }
192
+ return { units, edits };
193
+ }
194
+
195
+ /** A section body's units. Pure. */
196
+ export const slideUnits = (body) => slideParts(body).units;
197
+
198
+ /** A section body with `texts[i]` written into unit i. Pure. */
199
+ export function writeSlide(body, texts) {
200
+ const { edits } = slideParts(body);
201
+ let out = String(body ?? '');
202
+ for (const e of [...edits].sort((a, b) => b.start - a.start)) out = out.slice(0, e.start) + e.make(texts) + out.slice(e.end);
203
+ return out;
204
+ }
205
+
206
+ /**
207
+ * A slide's shape, hashed: the section with every unit's text taken out. Two
208
+ * slides with the same shape differ only in words, so a translation whose
209
+ * slide no longer has the shape it was written with was changed in more than
210
+ * its words, and `decklight translate` will not overwrite that silently.
211
+ */
212
+ export function slideShape(body) {
213
+ const n = slideUnits(body).length;
214
+ const written = writeSlide(body, Array.from({ length: n }, () => '•'));
215
+ return createHash('sha1').update(written.replace(/\s+/g, ' ').trim()).digest('hex').slice(0, 12);
216
+ }
217
+
218
+ /** The bodies of a deck's sections, cut so they can be written back: `[preamble, '<section', body, …]`. */
219
+ export const deckParts = (html) => String(html ?? '').split(/(<section\b)/);
220
+ const bodiesOf = (parts) => parts.filter((_, i) => i >= 2 && i % 2 === 0);
221
+
222
+ /** Every slide's units, and the deck's own (its title). Pure. */
223
+ export function deckUnits(html) {
224
+ const title = deckTitle(html);
225
+ return {
226
+ deck: LETTER.test(title) ? [{ kind: 'title', text: title }] : [],
227
+ slides: bodiesOf(deckParts(html)).map(slideUnits),
228
+ };
229
+ }
230
+
231
+ /** A new, empty record for `lang`, translated from `source`. */
232
+ export const emptyRecord = (source, from, lang) => ({ version: RECORD_VERSION, source, from: from ?? null, lang, glossary: {}, deck: [], slides: [], structure: [] });
233
+
234
+ /** Read a record's text; a broken one is an error the caller reports, never an empty record. */
235
+ export function parseRecord(text) {
236
+ const r = JSON.parse(text);
237
+ if (!r || typeof r !== 'object' || !Array.isArray(r.slides)) throw new Error('not a translation record (no "slides")');
238
+ if (r.version !== RECORD_VERSION) throw new Error(`a translation record of version ${r.version}, and this decklight reads ${RECORD_VERSION}`);
239
+ return { glossary: {}, deck: [], structure: [], ...r };
240
+ }
241
+
242
+ /**
243
+ * The record as it is written: one unit per line, so a re-translated sentence
244
+ * is a one-line diff. Stable key order.
245
+ */
246
+ export function formatRecord(r) {
247
+ const unit = (u) => ` ${JSON.stringify(u)}`;
248
+ const slides = r.slides.map((s) => (s.length ? ` [\n${s.map(unit).join(',\n')}\n ]` : ' []'));
249
+ return `{\n "version": ${r.version},\n "source": ${JSON.stringify(r.source)},\n "from": ${JSON.stringify(r.from)},\n "lang": ${JSON.stringify(r.lang)},\n`
250
+ + ` "glossary": ${JSON.stringify(r.glossary ?? {})},\n`
251
+ + ` "deck": [${(r.deck ?? []).map((u) => `\n ${JSON.stringify(u)}`).join(',')}${r.deck?.length ? '\n ' : ''}],\n`
252
+ + ` "structure": ${JSON.stringify(r.structure ?? [])},\n`
253
+ + (Array.isArray(r.overflow) ? ` "overflow": ${JSON.stringify(r.overflow)},\n` : '')
254
+ + ` "slides": [\n${slides.join(',\n')}\n ]\n}\n`;
255
+ }
256
+
257
+ const live = (p) => p && p.state !== 'pending';
258
+
259
+ /**
260
+ * Read back a person's corrections (TRANSLATION_RECORD): every unit of the
261
+ * translation whose text is no longer the record's `target` was edited by
262
+ * somebody, so the record takes the new text, `reviewed`. A slide whose shape
263
+ * is not the one the record wrote is a structural change, listed in
264
+ * `structure` and left alone. Returns `{ record, corrected, structure }`.
265
+ */
266
+ export function readBack(record, translationHtml) {
267
+ const next = { ...record, deck: [...(record.deck ?? [])], slides: record.slides.map((s) => s.map((u) => ({ ...u }))) };
268
+ const structure = [];
269
+ let corrected = 0;
270
+ if (!translationHtml) return { record: next, corrected, structure };
271
+ const bodies = bodiesOf(deckParts(translationHtml));
272
+ if (bodies.length !== next.slides.length) structure.push({ slide: null, why: `it has ${bodies.length} slides, and it was written with ${next.slides.length}` });
273
+ const take = (u, text) => {
274
+ if (u.target === text) return u;
275
+ corrected++;
276
+ return { kind: u.kind, state: 'reviewed', source: u.source, target: text };
277
+ };
278
+ bodies.forEach((body, i) => {
279
+ const R = next.slides[i];
280
+ if (!R) return;
281
+ if (next.structure?.[i] && slideShape(body) !== next.structure[i]) { structure.push({ slide: i + 1, why: 'it was changed in more than its words' }); return; }
282
+ const T = slideUnits(body);
283
+ if (T.length !== R.length || T.some((u, k) => u.kind !== R[k].kind)) { structure.push({ slide: i + 1, why: 'its words are not the ones it was written with' }); return; }
284
+ next.slides[i] = R.map((u, k) => take(u, T[k].text));
285
+ });
286
+ const title = deckTitle(translationHtml);
287
+ if (next.deck[0] && title && title !== next.deck[0].target) next.deck[0] = take(next.deck[0], title);
288
+ return { record: next, corrected, structure };
289
+ }
290
+
291
+ /**
292
+ * The source's units matched against the record (TRANSLATION_RECORD): each
293
+ * unit `current` (with the record's target and state), `changed` (with the
294
+ * previous version, which goes to the model) or `missing`. Slides are matched
295
+ * by what they say, a record slide claimed once; a unit not on its matched
296
+ * slide is looked up across the record. Pure.
297
+ *
298
+ * Returns `{ deck: [unit], slides: [[unit]] }`, each unit
299
+ * `{ kind, text, status, target, state, previous }`.
300
+ */
301
+ export function matchRecord(source, record) {
302
+ const R = record.slides ?? [];
303
+ const key = (kind, text) => `${kind}\u0000${text}`;
304
+ const global = new Map();
305
+ for (const slide of R) for (const p of slide) {
306
+ if (!live(p)) continue;
307
+ const k = key(p.kind, p.source);
308
+ const had = global.get(k);
309
+ if (!had || (had.state !== 'reviewed' && p.state === 'reviewed')) global.set(k, p);
310
+ }
311
+ for (const p of record.deck ?? []) if (live(p)) global.set(key(p.kind, p.source), p);
312
+ const inSource = new Set();
313
+ for (const s of source.slides) for (const u of s) inSource.add(key(u.kind, u.text));
314
+ for (const u of source.deck) inSource.add(key(u.kind, u.text));
315
+
316
+ const has = (slide, u) => slide.some((p) => live(p) && p.kind === u.kind && p.source === u.text);
317
+ const claimed = new Set();
318
+ const match = source.slides.map(() => -1);
319
+ const claim = (i, j) => { match[i] = j; claimed.add(j); };
320
+ // the same units, all of them; then most of them; then the slide in the same place
321
+ source.slides.forEach((S, i) => {
322
+ if (!S.length) return;
323
+ const j = R.findIndex((slide, jj) => !claimed.has(jj) && slide.length === S.length && S.every((u) => has(slide, u)));
324
+ if (j >= 0) claim(i, j);
325
+ });
326
+ source.slides.forEach((S, i) => {
327
+ if (match[i] >= 0 || !S.length) return;
328
+ let best = -1, score = 0;
329
+ R.forEach((slide, j) => {
330
+ if (claimed.has(j)) return;
331
+ const n = S.filter((u) => has(slide, u)).length;
332
+ if (n > score) { best = j; score = n; }
333
+ });
334
+ if (best >= 0) claim(i, best);
335
+ });
336
+ source.slides.forEach((S, i) => { if (match[i] < 0 && R[i] && !claimed.has(i)) claim(i, i); });
337
+
338
+ const resolve = (u, M, place) => {
339
+ const own = M?.find((p) => live(p) && p.kind === u.kind && p.source === u.text);
340
+ const found = own ?? global.get(key(u.kind, u.text));
341
+ if (found) return { ...u, status: 'current', target: found.target, state: found.state };
342
+ const there = M?.filter((p) => p.kind === u.kind)[place];
343
+ if (there?.state === 'pending' && there.was) return { ...u, status: 'changed', previous: there.was };
344
+ if (there && live(there) && !inSource.has(key(there.kind, there.source))) {
345
+ return { ...u, status: 'changed', previous: { source: there.source, target: there.target, state: there.state } };
346
+ }
347
+ return { ...u, status: 'missing' };
348
+ };
349
+ const placed = (units, M) => {
350
+ const seen = {};
351
+ return units.map((u) => { const place = seen[u.kind] = (seen[u.kind] ?? -1) + 1; return resolve(u, M, place); });
352
+ };
353
+ return {
354
+ deck: placed(source.deck, record.deck ?? []),
355
+ slides: source.slides.map((S, i) => placed(S, match[i] >= 0 ? R[match[i]] : null)),
356
+ };
357
+ }
358
+
359
+ /** A unit still behind, as the translation shows it: its previous translation, else the source's own text. */
360
+ export const placeholder = (u) => (u.status === 'changed' ? u.previous.target : u.text);
361
+
362
+ /** The text written into the translation for a matched unit. */
363
+ export const writtenText = (u) => (u.status === 'current' || u.status === 'translated' ? u.target : placeholder(u));
364
+
365
+ /** A matched unit as the record keeps it. */
366
+ export function recordUnit(u) {
367
+ if (u.status === 'current' || u.status === 'translated') return { kind: u.kind, state: u.state ?? 'machine', source: u.text, target: u.target };
368
+ return { kind: u.kind, state: 'pending', source: u.text, target: placeholder(u), ...(u.status === 'changed' ? { was: { source: u.previous.source, target: u.previous.target } } : {}) };
369
+ }
370
+
371
+ /** Is `lang` written right to left? From its likely script (Intl), so `ar`, `he`, `fa`, `ur` and their regions are. */
372
+ export function isRtl(lang) {
373
+ try { return ['Arab', 'Hebr', 'Thaa', 'Syrc', 'Nkoo', 'Adlm', 'Rohg'].includes(new Intl.Locale(lang).maximize().script); } catch { return false; }
374
+ }
375
+
376
+ /** `<html>` with `lang` set, and `dir="rtl"` for a language written right to left (a `dir` already there is replaced). */
377
+ export function withHtmlLang(html, lang) {
378
+ return String(html).replace(/<html\b([^>]*)>/i, (m, attrs) => {
379
+ let a = attrs.replace(/\s(?:lang|dir)\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/gi, '');
380
+ a += ` lang="${encAttr(lang)}"`;
381
+ if (isRtl(lang)) a += ' dir="rtl"';
382
+ return `<html${a}>`;
383
+ });
384
+ }
385
+
386
+ /**
387
+ * `html` with its languages linked in `<head>`: one `<link rel="alternate"
388
+ * hreflang href>` per language of the deck, the one on screen included, in
389
+ * place of any decklight wrote before. They are what the language switch
390
+ * reads in a translation (TRANSLATION_SWITCH), and what a search engine reads
391
+ * of a published one.
392
+ */
393
+ export function withAlternates(html, links) {
394
+ const s = String(html).replace(/[ \t]*<link\b[^>]*\bdata-decklight-lang\b[^>]*>\r?\n?/gi, '');
395
+ if (!links?.length) return s;
396
+ const head = /<head\b[^>]*>/i.exec(s);
397
+ if (!head) return s;
398
+ const at = head.index + head[0].length;
399
+ const indent = /\n([ \t]*)\S/.exec(s.slice(at))?.[1] ?? ' ';
400
+ const tags = links.map((l) => `\n${indent}<link rel="alternate" hreflang="${encAttr(l.lang)}" href="${encAttr(l.href)}" data-decklight-lang>`).join('');
401
+ return s.slice(0, at) + tags + s.slice(at);
402
+ }
403
+
404
+ /**
405
+ * The translation, written: the source with each unit's text replaced, its
406
+ * `<html lang>` (and `dir`), its title, and `translationOf` in its
407
+ * configuration (`languages` is the source's to keep). Returns `{ html,
408
+ * structure }`, `structure` each slide's shape as written, for the record.
409
+ */
410
+ export function renderTranslation(sourceHtml, matched, { lang, sourceName, alternates = null }) {
411
+ const parts = deckParts(sourceHtml);
412
+ let s = 0;
413
+ for (let i = 2; i < parts.length; i += 2) {
414
+ const units = matched.slides[s++] ?? [];
415
+ parts[i] = writeSlide(parts[i], units.map(writtenText));
416
+ }
417
+ let html = withHtmlLang(parts.join(''), lang);
418
+ if (matched.deck[0]) html = setDeckTitle(html, writtenText(matched.deck[0]));
419
+ html = withConfigKeys(html, { translationOf: sourceName, languages: null }) ?? html;
420
+ if (alternates) html = withAlternates(html, alternates);
421
+ return { html, structure: bodiesOf(deckParts(html)).map(slideShape) };
422
+ }
423
+
424
+ /** The record a run writes, from the matched (and translated) units. */
425
+ export function nextRecord(previous, matched, structure) {
426
+ return {
427
+ ...previous,
428
+ version: RECORD_VERSION,
429
+ deck: matched.deck.map(recordUnit),
430
+ slides: matched.slides.map((S) => S.map(recordUnit)),
431
+ structure,
432
+ };
433
+ }
434
+
435
+ /**
436
+ * How far behind a language is: units `current`, `changed`, `missing` and
437
+ * `reviewed` (current and read by a person), with the slides that are
438
+ * behind. Pure.
439
+ */
440
+ export function languageStatus(matched) {
441
+ const count = { current: 0, changed: 0, missing: 0, reviewed: 0, total: 0 };
442
+ const behind = [];
443
+ const tally = (u) => {
444
+ count.total++;
445
+ const st = u.status === 'translated' ? 'current' : u.status;
446
+ count[st]++;
447
+ if (st === 'current' && u.state === 'reviewed') count.reviewed++;
448
+ };
449
+ matched.deck.forEach(tally);
450
+ matched.slides.forEach((S, i) => {
451
+ S.forEach(tally);
452
+ if (S.some((u) => u.status === 'changed' || u.status === 'missing')) behind.push(i + 1);
453
+ });
454
+ return { ...count, behind, up: count.changed + count.missing === 0 };
455
+ }
456
+
457
+ /** The language a deck is written in, for the record's `from`. */
458
+ export const sourceLang = (html) => deckLang(html);
459
+
460
+ /** A language's name in its own language (`Français`), else the tag. */
461
+ export function languageName(tag, { in: where = tag } = {}) {
462
+ try {
463
+ const n = new Intl.DisplayNames([where], { type: 'language' }).of(tag);
464
+ return n ? n[0].toLocaleUpperCase(where) + n.slice(1) : tag;
465
+ } catch { return tag; }
466
+ }
@@ -0,0 +1,149 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ /**
5
+ * Where a deck's languages live, and what `decklight check` says about them
6
+ * (SPEC TRANSLATIONS). Kept apart from cli/translate.mjs so that check, which
7
+ * starts no agent, does not load the agent machinery to read a record.
8
+ *
9
+ * talk.html the source
10
+ * talk.fr.html the French, written by decklight translate
11
+ * talk.fr.translation.json the record it was written from
12
+ */
13
+
14
+ import { existsSync, readFileSync, readdirSync } from 'node:fs';
15
+ import { basename, dirname, join } from 'node:path';
16
+ import { deckConfig } from './runtime-link.mjs';
17
+ import { deckFamily } from '../tools/deck-family.mjs';
18
+ import { deckLang, sectionBodies, sectionInner, slideHeading, slideName } from '../tools/deck-html.mjs';
19
+ import { deckUnits, languageName, languageStatus, matchRecord, parseRecord, readBack } from './translate-core.mjs';
20
+
21
+ /** `talk.html` → `{ stem: 'talk', ext: '.html' }`. */
22
+ export const splitName = (name) => { const m = /^(.*?)(\.html?)$/i.exec(name); return m ? { stem: m[1], ext: m[2] } : { stem: name, ext: '.html' }; };
23
+
24
+ /** Where a language of `sourcePath` lives: its deck and its record. */
25
+ export function languageFiles(sourcePath, lang) {
26
+ const dir = dirname(sourcePath);
27
+ const { stem, ext } = splitName(basename(sourcePath));
28
+ return { deck: join(dir, `${stem}.${lang}${ext}`), record: join(dir, `${stem}.${lang}.translation.json`) };
29
+ }
30
+
31
+ /** A translation's own record: `talk.fr.html` → `talk.fr.translation.json`. */
32
+ export const recordOf = (translationPath) => join(dirname(translationPath), `${splitName(basename(translationPath)).stem}.translation.json`);
33
+
34
+ /** The languages a source has: its configuration's `languages`, and every record on disk beside it. */
35
+ export function knownLanguages(sourcePath, html, { list = (d) => readdirSync(d) } = {}) {
36
+ const cfg = deckConfig(html);
37
+ const named = Array.isArray(cfg?.languages) ? cfg.languages.filter((l) => typeof l === 'string') : [];
38
+ const { stem } = splitName(basename(sourcePath));
39
+ const esc = stem.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
40
+ const re = new RegExp(`^${esc}\\.([a-z]{2,3}(?:-[a-z0-9]{2,8})*)\\.translation\\.json$`, 'i');
41
+ let found = [];
42
+ try { found = list(dirname(sourcePath)).map((n) => re.exec(n)?.[1]).filter(Boolean); } catch { /* no folder */ }
43
+ const seen = new Set();
44
+ return [...named, ...found].filter((l) => { const k = l.toLowerCase(); if (seen.has(k)) return false; seen.add(k); return true; });
45
+ }
46
+
47
+ /**
48
+ * The source for a deck: itself, or, for a translation (a deck named for a
49
+ * language beside the deck it is the language of), that deck.
50
+ */
51
+ export function resolveSource(deckPath) {
52
+ const fam = deckFamily(deckPath);
53
+ if (!fam.lang) return { source: deckPath, given: null };
54
+ const src = fam.members.find((m) => m.lang === null);
55
+ return src ? { source: join(dirname(deckPath), src.name), given: fam.lang } : { source: deckPath, given: null };
56
+ }
57
+
58
+ const plural = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
59
+ const quote = (s) => { const t = String(s).replace(/\s+/g, ' ').trim(); return `"${t.length > 60 ? `${t.slice(0, 59)}…` : t}"`; };
60
+
61
+ /** "on "Pricing" and slide 7": the slides named the way decklight names slides. */
62
+ export function slidesPhrase(html, numbers) {
63
+ const bodies = sectionBodies(html);
64
+ const names = numbers.slice(0, 4).map((n) => slideName(bodies[n - 1] ?? '') || `slide ${n}`);
65
+ const more = numbers.length > 4 ? ` and ${plural(numbers.length - 4, 'other slide')}` : '';
66
+ return names.length ? `on ${names.join(', ')}${more}` : '';
67
+ }
68
+
69
+ /**
70
+ * A language of a source, read: the record and the translation as they are,
71
+ * matched against the source. `{ lang, files, exists, record, back, matched,
72
+ * status }`, or `{ error }` when the record cannot be read. No model.
73
+ */
74
+ export function readLanguage(sourcePath, sourceHtml, lang, { read = (p) => readFileSync(p, 'utf8'), exists = existsSync } = {}) {
75
+ const files = languageFiles(sourcePath, lang);
76
+ if (!exists(files.deck) || !exists(files.record)) return { lang, files, exists: false };
77
+ let record;
78
+ try { record = parseRecord(read(files.record)); } catch (e) { return { lang, files, exists: true, error: e.message }; }
79
+ const translation = read(files.deck);
80
+ const back = readBack(record, translation);
81
+ const base = back.structure.length ? { ...record, slides: [] } : back.record;
82
+ const matched = matchRecord(deckUnits(sourceHtml), base);
83
+ return { lang, files, exists: true, record, translation, back, matched, status: languageStatus(matched) };
84
+ }
85
+
86
+ /**
87
+ * What `decklight check` says about a deck's languages (SPEC
88
+ * TRANSLATION_RECORD). On a translation, errors: a piece made from words the
89
+ * source no longer has (`translation-stale`), a piece not translated
90
+ * (`translation-missing`), a slide changed in more than its words
91
+ * (`translation-structure`), a language that is not the record's
92
+ * (`translation-lang`), a record that cannot be read (`translation-record`).
93
+ * On the source, a warning per language that is behind (`translation-behind`):
94
+ * the source is not broken by having been edited. A deck with no languages
95
+ * gets nothing. `finding` is check's constructor.
96
+ */
97
+ export function translationFindings(path, html, { finding, read = (p) => readFileSync(p, 'utf8'), exists = existsSync } = {}) {
98
+ const out = [];
99
+ const bodies = sectionBodies(html);
100
+ const head = (n) => (n ? slideHeading(sectionInner(bodies[n - 1] ?? ''), n - 1) : 'head');
101
+ const fam = deckFamily(path);
102
+ const fix = (src) => `run decklight translate ${basename(src)}`;
103
+
104
+ if (fam.lang) {
105
+ const rec = recordOf(path);
106
+ if (!exists(rec)) return out;
107
+ const { source } = resolveSource(path);
108
+ if (source === path) return out;
109
+ let record;
110
+ try { record = parseRecord(read(rec)); } catch (e) {
111
+ out.push(finding('error', 'translation-record', null, 'head', `${basename(rec)} cannot be read — ${e.message}`));
112
+ return out;
113
+ }
114
+ const lang = deckLang(html);
115
+ if (record.lang && (lang ?? '').toLowerCase() !== record.lang.toLowerCase()) {
116
+ out.push(finding('error', 'translation-lang', null, 'head', `<html lang="${lang ?? ''}"> is not the language this file was translated into (${record.lang}): ${fix(source)} sets it`));
117
+ }
118
+ const back = readBack(record, html);
119
+ for (const s of back.structure) {
120
+ out.push(finding('error', 'translation-structure', s.slide, head(s.slide),
121
+ `${s.why}: a translation takes its structure from ${basename(source)}. Make the change there, or run decklight translate ${basename(source)} --discard-structure`));
122
+ }
123
+ let sourceHtml;
124
+ try { sourceHtml = read(source); } catch { return out; }
125
+ const matched = matchRecord(deckUnits(sourceHtml), back.structure.length ? { ...record, slides: [] } : back.record);
126
+ const say = (units, n) => {
127
+ const stale = units.filter((u) => u.status === 'changed');
128
+ const missing = units.filter((u) => u.status === 'missing');
129
+ if (stale.length) out.push(finding('error', 'translation-stale', n, head(n), `${plural(stale.length, 'piece')} translated from words ${basename(source)} no longer has, such as ${quote(stale[0].text)} (it shows its previous translation): ${fix(source)}`));
130
+ if (missing.length) out.push(finding('error', 'translation-missing', n, head(n), `${plural(missing.length, 'piece')} not translated, such as ${quote(missing[0].text)} (it shows the source's words): ${fix(source)}`));
131
+ };
132
+ if (!back.structure.length) {
133
+ say(matched.deck, null);
134
+ matched.slides.forEach((S, i) => say(S, i + 1));
135
+ }
136
+ return out;
137
+ }
138
+
139
+ for (const lang of knownLanguages(path, html)) {
140
+ const l = readLanguage(path, html, lang, { read, exists });
141
+ const name = `${languageName(lang, { in: 'en' })} (${basename(l.files.deck)})`;
142
+ if (l.error) { out.push(finding('warn', 'translation-behind', null, 'head', `${name}: its record cannot be read — ${l.error}`)); continue; }
143
+ if (!l.exists) { out.push(finding('warn', 'translation-behind', null, 'head', `${name} is listed in "languages" and not translated yet: ${fix(path)}`)); continue; }
144
+ if (l.back.structure.length) { out.push(finding('warn', 'translation-behind', null, 'head', `${name} was changed in more than its words; decklight check ${basename(l.files.deck)} says where`)); continue; }
145
+ const st = l.status;
146
+ if (!st.up) out.push(finding('warn', 'translation-behind', null, 'head', `${name} is ${plural(st.changed + st.missing, 'piece')} behind ${slidesPhrase(html, st.behind)}: ${fix(path)}`));
147
+ }
148
+ return out;
149
+ }