decklight 0.8.0 → 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 +71 -26
  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 +35 -2
  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 +19 -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,560 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ /**
5
+ * A deck as data (#520): slides plus one JSON configuration block, and no
6
+ * runtime in the file — no `<script src="decklight.js">`, no embedded engine,
7
+ * no `Decklight.init(…)` call. The server adds the engine on the way out
8
+ * (`linkRuntime`, applied by `staticFiles` to every html response and by
9
+ * `--no-trust` to the deck it serves from memory); `bundle` embeds it at
10
+ * hand-over through the same function, and then flattens the references it
11
+ * just added exactly as it flattens a deck that wrote them itself.
12
+ *
13
+ * The configuration block is
14
+ *
15
+ * <script type="application/json" data-decklight-config>
16
+ * { "decklight": "0.8.1", "theme": "aurora", "transition": "fade" }
17
+ * </script>
18
+ *
19
+ * inert to every browser (JSON is not executed), read by the runtime when it
20
+ * boots — `Decklight.init()` with no argument takes its options from it, and
21
+ * the engine boots itself once the document is parsed when a deck calls no
22
+ * `init` of its own. Two keys are the file's, not the engine's: `decklight`
23
+ * is the version the deck was written for (what --no-trust --audit compares
24
+ * against the runtime this install serves), `theme` names the theme the
25
+ * server links (default `aurora`).
26
+ *
27
+ * One module, used by every command that has to know whether a file carries
28
+ * a runtime, so that "no runtime at all" is the normal case everywhere and no
29
+ * classifier is left assuming a deck must load an engine to be a deck.
30
+ */
31
+
32
+ import { existsSync } from 'node:fs';
33
+ import path from 'node:path';
34
+ import { PKG, THEMES_DIR } from './pkg.mjs';
35
+
36
+ export const DEFAULT_THEME = 'aurora';
37
+ export const CONFIG_ATTR = 'data-decklight-config';
38
+
39
+ const maskComments = (html) => html.replace(/<!--[\s\S]*?-->/g, (m) => m.replace(/[^\n]/g, ' '));
40
+
41
+ /** Is there a deck in this document at all? The one marker of deckness (DECK_ANATOMY). */
42
+ export const isDeck = (html) =>
43
+ /<[a-z][^>]*\bclass=["'](?:[^"']*\s)?decklight(?:\s[^"']*)?["']/i.test(maskComments(html));
44
+
45
+ /**
46
+ * Does the document load or carry the engine? True for a `<script src>`
47
+ * naming `decklight.js`, a block marked `data-decklight-runtime="js"`, or an
48
+ * unmarked block defining `Decklight` (the bundle output of every version).
49
+ */
50
+ export function hasRuntime(html) {
51
+ const masked = maskComments(html);
52
+ for (const m of masked.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)) {
53
+ const [, attrs, inner] = m;
54
+ if (/\bsrc\s*=\s*["'][^"']*(?:^|\/)?decklight(?:\.min)?\.js(?:[?#][^"']*)?["']/i.test(attrs)) return true;
55
+ if (/\bdata-decklight-runtime\s*=\s*["']js["']/i.test(attrs)) return true;
56
+ if (/(?:\bvar\s+|\bwindow\.)Decklight\s*=/.test(inner) || /\/\*!\s*Decklight v\d/.test(inner)) return true;
57
+ }
58
+ return false;
59
+ }
60
+
61
+ /**
62
+ * Is the engine IN the file — a bundle, an `init --inline` deck — as opposed
63
+ * to referenced or absent? What `bundle` and `publish` ask before flattening.
64
+ */
65
+ export function hasEmbeddedRuntime(html) {
66
+ const masked = maskComments(html);
67
+ for (const m of masked.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)) {
68
+ const [, attrs, inner] = m;
69
+ if (/\bsrc\s*=/i.test(attrs)) continue;
70
+ if (/\bdata-decklight-runtime\s*=\s*["']js["']/i.test(attrs)) return true;
71
+ if (/(?:\bvar\s+|\bwindow\.)Decklight\s*=/.test(inner) || /\/\*!\s*Decklight v\d/.test(inner)) return true;
72
+ }
73
+ return false;
74
+ }
75
+
76
+ /** Does the document carry the runtime stylesheet — by reference or embedded? */
77
+ const hasRuntimeCss = (html) =>
78
+ /<link\b[^>]*\bhref\s*=\s*["'][^"']*decklight(?:\.min)?\.css(?:[?#][^"']*)?["']/i.test(html)
79
+ || /<style\b[^>]*\bdata-decklight-runtime\s*=\s*["']css["']/i.test(html);
80
+
81
+ /**
82
+ * Does the document carry a theme of its OWN — a `themes/<name>.css` link or a
83
+ * `<style data-theme>` block? An added theme (`data-theme-added`, inline or
84
+ * linked) is not one: it is an extra the picker offers over the deck's base
85
+ * theme, and a deck carrying only extras still needs that base linked.
86
+ */
87
+ function hasTheme(html) {
88
+ for (const [, tag, attrs] of html.matchAll(/<(link|style)\b([^>]*)>/gi)) {
89
+ if (/\bdata-theme-added\b/i.test(attrs)) continue;
90
+ if (tag.toLowerCase() === 'style' ? /\bdata-theme\b/i.test(attrs)
91
+ : /\bhref\s*=\s*["'][^"']*themes\/[\w-]+\.css(?:[?#][^"']*)?["']/i.test(attrs)) return true;
92
+ }
93
+ return false;
94
+ }
95
+
96
+ /**
97
+ * The configuration block, with its offsets: `start`/`end` span the whole
98
+ * `<script>` element, `innerStart`/`innerEnd` its text. `config` is the
99
+ * parsed object, or null with `error` set when the text is not JSON — a
100
+ * deck with a broken block is still a deck, and the caller says what is
101
+ * wrong rather than treating it as absent. Null when there is no block.
102
+ */
103
+ export function configBlock(html) {
104
+ const masked = maskComments(html);
105
+ const re = /<script\b([^>]*)>([\s\S]*?)<\/script>/gi;
106
+ let m;
107
+ while ((m = re.exec(masked))) {
108
+ const [tag, attrs, inner] = m;
109
+ if (!/\bdata-decklight-config\b/i.test(attrs)) continue;
110
+ const innerStart = m.index + tag.length - inner.length - '</script>'.length;
111
+ const block = { start: m.index, end: m.index + tag.length, attrs, inner, innerStart, innerEnd: innerStart + inner.length, config: null, error: null };
112
+ try {
113
+ const parsed = JSON.parse(inner);
114
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) block.config = parsed;
115
+ else block.error = 'the configuration block is not a JSON object';
116
+ } catch (e) {
117
+ block.error = `the configuration block is not valid JSON — ${e.message}`;
118
+ }
119
+ return block;
120
+ }
121
+ return null;
122
+ }
123
+
124
+ /** The parsed configuration, or null (no block, or not JSON). */
125
+ export const deckConfig = (html) => configBlock(html)?.config ?? null;
126
+
127
+ /** The version the block says the deck was written for, or null. */
128
+ export function configVersion(html) {
129
+ const v = deckConfig(html)?.decklight;
130
+ return typeof v === 'string' && v ? v : null;
131
+ }
132
+
133
+ /** The theme the block names, or the default. */
134
+ export function configTheme(html) {
135
+ const t = deckConfig(html)?.theme;
136
+ return typeof t === 'string' && /^[\w-]+$/.test(t) ? t : DEFAULT_THEME;
137
+ }
138
+
139
+ /**
140
+ * The theme a server LINKS as the deck's base: the configured one, unless it
141
+ * names a theme the deck marks from a marketplace (`markedThemes`, SPEC
142
+ * THEME_DISTRIBUTION). That one is not a file in `themes/`; it arrives as an
143
+ * added theme and the runtime applies it over the default linked here.
144
+ */
145
+ export function baseTheme(html) {
146
+ const t = configTheme(html);
147
+ const marked = deckConfig(html)?.markedThemes;
148
+ // marketplace references only: a marked SHIPPED theme is a file in themes/
149
+ const names = Array.isArray(marked) ? marked.filter((r) => String(r).includes('@')).map((r) => String(r).split('@')[0]) : [];
150
+ if (names.includes(t)) return DEFAULT_THEME;
151
+ // a design system's own theme (SPEC BRAND_PALETTE) is a block the server
152
+ // adds with the design system, not a file in themes/: the page opens on the
153
+ // default and the runtime applies the configured one, as for a marked theme
154
+ const usesSystems = Array.isArray(deckConfig(html)?.designSystems) && deckConfig(html).designSystems.length > 0;
155
+ if (usesSystems && t && !existsSync(path.join(THEMES_DIR, `${t}.css`))) return DEFAULT_THEME;
156
+ return t;
157
+ }
158
+
159
+ /**
160
+ * The block's text with `decklight` recorded as `version` — edited in place
161
+ * (the value swapped, or the key added first) so the author's own formatting
162
+ * of the rest survives. Null when there is no block.
163
+ */
164
+ export function withConfigVersion(html, version = PKG.version) {
165
+ const block = configBlock(html);
166
+ if (!block) return null;
167
+ const keyRe = /("decklight"\s*:\s*)"[^"]*"/;
168
+ let inner;
169
+ if (keyRe.test(block.inner)) inner = block.inner.replace(keyRe, `$1"${version}"`);
170
+ else {
171
+ const open = block.inner.indexOf('{');
172
+ if (open === -1) return null;
173
+ const rest = block.inner.slice(open + 1);
174
+ const empty = /^\s*}/.test(rest);
175
+ inner = `${block.inner.slice(0, open + 1)} "decklight": "${version}"${empty ? ' ' : ', '}${rest.replace(/^\s+/, empty ? '' : '')}`;
176
+ }
177
+ return html.slice(0, block.innerStart) + inner + html.slice(block.innerEnd);
178
+ }
179
+
180
+ /**
181
+ * The block's text with `theme` set — the value swapped, or the key added
182
+ * after `decklight` (or first), so the author's own formatting survives.
183
+ * Null when there is no block.
184
+ */
185
+ export function withConfigTheme(html, name) {
186
+ const block = configBlock(html);
187
+ if (!block) return null;
188
+ const keyRe = /("theme"\s*:\s*)"[^"]*"/;
189
+ let inner;
190
+ if (keyRe.test(block.inner)) inner = block.inner.replace(keyRe, `$1"${name}"`);
191
+ else {
192
+ const afterVersion = /("decklight"\s*:\s*"[^"]*")/;
193
+ if (afterVersion.test(block.inner)) inner = block.inner.replace(afterVersion, `$1, "theme": "${name}"`);
194
+ else {
195
+ const open = block.inner.indexOf('{');
196
+ if (open === -1) return null;
197
+ const rest = block.inner.slice(open + 1);
198
+ const empty = /^\s*}/.test(rest);
199
+ inner = `${block.inner.slice(0, open + 1)} "theme": "${name}"${empty ? ' ' : ', '}${rest.replace(/^\s+/, empty ? '' : '')}`;
200
+ }
201
+ }
202
+ return html.slice(0, block.innerStart) + inner + html.slice(block.innerEnd);
203
+ }
204
+
205
+ /**
206
+ * Where a top-level `key` sits in an object literal — JSON, or a JS literal
207
+ * with bare keys and single quotes — as `{ keyStart, valueEnd, open, close }`
208
+ * (`open`/`close` the outer braces); `keyStart`/`valueEnd` null when the key
209
+ * is absent. Null when `text` holds no object. Strings are skipped whole, so
210
+ * a brace inside one never counts.
211
+ */
212
+ function keySpan(text, key) {
213
+ const open = text.indexOf('{');
214
+ if (open === -1) return null;
215
+ let depth = 0; let i = open; let keyStart = null; let valueEnd = null; let pendingKey = null; let close = -1;
216
+ const skipString = (q) => { for (i++; i < text.length && text[i] !== q; i++) if (text[i] === '\\') i++; };
217
+ // the value ends where its last character does, not where the comma or brace sits
218
+ const trimmedEnd = (at) => { let e = at; while (e > 0 && /\s/.test(text[e - 1])) e--; return e; };
219
+ for (; i < text.length; i++) {
220
+ const c = text[i];
221
+ if (c === '"' || c === "'" || c === '`') {
222
+ const from = i; skipString(c);
223
+ if (depth === 1 && pendingKey === null) pendingKey = { name: text.slice(from + 1, i), start: from };
224
+ continue;
225
+ }
226
+ if (c === '{' || c === '[') { depth++; continue; }
227
+ if (c === '}' || c === ']') {
228
+ depth--;
229
+ if (depth === 0) { close = i; if (keyStart !== null && valueEnd === null) valueEnd = trimmedEnd(i); break; }
230
+ continue;
231
+ }
232
+ if (depth !== 1) continue;
233
+ if (/[A-Za-z_$]/.test(c) && pendingKey === null) {
234
+ const m = /^[A-Za-z_$][\w$]*/.exec(text.slice(i));
235
+ pendingKey = { name: m[0], start: i }; i += m[0].length - 1; continue;
236
+ }
237
+ if (c === ':' && pendingKey) {
238
+ if (pendingKey.name === key) keyStart = pendingKey.start;
239
+ pendingKey = { name: null, start: -1, value: true };
240
+ continue;
241
+ }
242
+ if (c === ',') {
243
+ if (keyStart !== null && valueEnd === null) valueEnd = trimmedEnd(i);
244
+ pendingKey = null;
245
+ }
246
+ }
247
+ if (close === -1) return null;
248
+ return { open, close, keyStart, valueEnd };
249
+ }
250
+
251
+ /** `text` with top-level `key` set to `valueText` (or removed, null), spliced in place: nothing else moves. */
252
+ function withObjectKey(text, key, valueText) {
253
+ const span = keySpan(text, key);
254
+ if (!span) return null;
255
+ const { open, close, keyStart, valueEnd } = span;
256
+ if (keyStart !== null) {
257
+ if (valueText !== null) return text.slice(0, keyStart) + `"${key}": ${valueText}` + text.slice(valueEnd);
258
+ // off: the key, its value, and the comma that joined it to a neighbour
259
+ let a = keyStart; let b = valueEnd;
260
+ const after = /^\s*,\s*/.exec(text.slice(b));
261
+ if (after) b += after[0].length;
262
+ else { const before = /,\s*$/.exec(text.slice(open + 1, a)); if (before) a = open + 1 + before.index; }
263
+ return text.slice(0, a) + text.slice(b);
264
+ }
265
+ if (valueText === null) return text;
266
+ const inner = text.slice(open + 1, close);
267
+ const empty = /^\s*$/.test(inner);
268
+ const indent = /\n([ \t]*)\S/.exec(inner)?.[1] ?? (empty ? ' ' : ' ');
269
+ const lastLine = /\n([ \t]*)$/.exec(inner)?.[1] ?? '';
270
+ const nl = inner.includes('\n');
271
+ const sep = empty ? (nl ? '' : ' ') : (nl ? `,\n${indent}` : ', ');
272
+ const body = inner.replace(/\s+$/, '');
273
+ return text.slice(0, open + 1) + (empty && nl ? `\n${indent}` : '') + body + sep + `"${key}": ${valueText}` + (nl ? `\n${lastLine}` : (empty ? ' ' : ' ')) + text.slice(close);
274
+ }
275
+
276
+ /**
277
+ * The deck's concept colours (SVG_DIAGRAMS, #718), written the way the deck
278
+ * carries its configuration: the configuration block's `concepts` key for a
279
+ * deck that is data, or the `concepts` key of a plain-data `Decklight.init`
280
+ * literal for a bundle. `concepts` is `{ name: slot (1-6) | css colour }`;
281
+ * an empty map takes the key off. The key is spliced in place and nothing
282
+ * else in the block moves. Null when the deck carries its configuration in
283
+ * neither way (an init call that is code is the author's, not this server's),
284
+ * or when a name or a value is not one the runtime reads.
285
+ */
286
+ export function setDeckConcepts(html, concepts) {
287
+ const clean = {};
288
+ for (const [name, v] of Object.entries(concepts ?? {})) {
289
+ if (!/^[a-z][a-z0-9-]{0,40}$/i.test(name)) return null;
290
+ if (typeof v === 'number' ? !(Number.isInteger(v) && v >= 1 && v <= 6) : (typeof v !== 'string' || !/^(?:var\(--[a-z][a-z0-9-]{0,40}\)|#[0-9a-f]{3,8})$/i.test(v))) return null;
291
+ clean[name] = v;
292
+ }
293
+ const valueText = Object.keys(clean).length ? '{ ' + Object.entries(clean).map(([k, v]) => `"${k}": ${JSON.stringify(v)}`).join(', ') + ' }' : null;
294
+ const block = configBlock(html);
295
+ if (block) {
296
+ if (!block.config) return null;
297
+ const inner = withObjectKey(block.inner, 'concepts', valueText);
298
+ if (inner === null) return null;
299
+ return html.slice(0, block.innerStart) + inner + html.slice(block.innerEnd);
300
+ }
301
+ const boot = bootCall(html);
302
+ if (!boot) return null;
303
+ const lit = parseLiteral(boot.arg);
304
+ if (!lit || typeof lit !== 'object' || Array.isArray(lit)) return null;
305
+ const call = html.slice(boot.start, boot.end);
306
+ const argStart = call.indexOf(boot.arg);
307
+ if (argStart === -1) return null;
308
+ const arg = withObjectKey(boot.arg, 'concepts', valueText);
309
+ if (arg === null) return null;
310
+ return html.slice(0, boot.start) + call.slice(0, argStart) + arg + call.slice(argStart + boot.arg.length) + html.slice(boot.end);
311
+ }
312
+
313
+ /**
314
+ * Whether the theme picker holds the deck to its design systems' own themes
315
+ * (SPEC BRAND_PALETTE): on unless the configuration says `"brandThemesOnly":
316
+ * false`, so `only` true takes the key off and false writes it. Written in a
317
+ * deck that is data only, the configuration block; null otherwise.
318
+ */
319
+ export function setDeckBrandThemesOnly(html, only) {
320
+ const block = configBlock(html);
321
+ if (!block?.config) return null;
322
+ const inner = withObjectKey(block.inner, 'brandThemesOnly', only ? null : 'false');
323
+ if (inner === null) return null;
324
+ return html.slice(0, block.innerStart) + inner + html.slice(block.innerEnd);
325
+ }
326
+
327
+ /**
328
+ * The deck's theme, written the way this deck carries it (PRESENTING): the
329
+ * configuration block's `theme` for a deck that is data; for a bundle, the
330
+ * active one among its embedded `<style data-theme>` blocks (`media="all"`
331
+ * on the chosen, `not all` on the rest — the shape `bundle` and `upgrade`
332
+ * write); for a source deck, the `themes/<name>.css` link. Null when the
333
+ * deck carries its theme in none of those ways, or does not have `name`.
334
+ */
335
+ export function setDeckTheme(html, name) {
336
+ if (!/^[\w-]+$/.test(name)) return null;
337
+ if (configBlock(html)) return withConfigTheme(html, name);
338
+ const styles = [...html.matchAll(/<style\b([^>]*\bdata-theme\s*=\s*["']([\w-]+)["'][^>]*)>/gi)];
339
+ if (styles.length) {
340
+ if (!styles.some((m) => m[2] === name)) return null;
341
+ let out = html;
342
+ for (const m of styles) {
343
+ const attrs = m[1].replace(/\s*\bmedia\s*=\s*["'][^"']*["']/i, '');
344
+ const tag = `<style${attrs}${m[2] === name ? '' : ' media="not all"'}>`;
345
+ out = out.replace(m[0], tag);
346
+ }
347
+ return out;
348
+ }
349
+ const link = /(<link\b[^>]*\bhref\s*=\s*["'][^"']*themes\/)([\w-]+)(\.css(?:[?#][^"']*)?["'][^>]*>)/i;
350
+ if (link.test(html)) return html.replace(link, `$1${name}$3`);
351
+ return null;
352
+ }
353
+
354
+ /** JSON text that is safe inside a `<script>`: a `</script` in a string value cannot end the block early. */
355
+ const jsonSafe = (text) => text.replace(/<\/(script)/gi, '<\\/$1').replace(/<!--/g, '<\\u0021--');
356
+
357
+ /**
358
+ * The configuration block as markup, `indent` in front of each line. The
359
+ * keys the file owns (`decklight`, `theme`) lead, so the version is on the
360
+ * first line whoever reads the file.
361
+ */
362
+ export function configBlockHtml(config = {}, { indent = ' ', version = PKG.version } = {}) {
363
+ const { decklight: _v, theme, ...rest } = config;
364
+ const ordered = { decklight: version, ...(theme ? { theme } : {}), ...rest };
365
+ const json = Object.keys(rest).length
366
+ ? JSON.stringify(ordered, null, 2).split('\n').map((l) => indent + l).join('\n')
367
+ : `${indent}{ ${Object.entries(ordered).map(([k, v]) => `${JSON.stringify(k)}: ${JSON.stringify(v)}`).join(', ')} }`;
368
+ return `${indent}<script type="application/json" ${CONFIG_ATTR}>\n${jsonSafe(json)}\n${indent}</script>`;
369
+ }
370
+
371
+ /** The first executable `<script>` — no type, or a JavaScript one — and its offset; null when there is none. */
372
+ export function firstExecutableScript(html) {
373
+ const masked = maskComments(html);
374
+ for (const m of masked.matchAll(/<script\b([^>]*)>/gi)) {
375
+ const type = /\btype\s*=\s*["']([^"']*)["']/i.exec(m[1])?.[1]?.trim().toLowerCase();
376
+ if (!type || type === 'module' || /^(text|application)\/(javascript|ecmascript)$/.test(type)) return m.index;
377
+ }
378
+ return null;
379
+ }
380
+
381
+ /**
382
+ * The document with the runtime referenced — and unchanged when it already
383
+ * is, or when it is not a deck. Idempotent and ordered: the stylesheet and
384
+ * the theme go at the end of `<head>` (each only when the document has none
385
+ * of its own), the engine before the first script that executes — an
386
+ * author's own script, or a `Decklight.init` call kept as the JS API's
387
+ * escape hatch, must find `Decklight` defined — or else before `</body>`.
388
+ * Every reference is a sibling path the servers answer from the installed
389
+ * package (`packageAsset`), the same ones `init` used to write (#517).
390
+ */
391
+ export function linkRuntime(html, { theme = null } = {}) {
392
+ if (!isDeck(html) || hasRuntime(html)) return html;
393
+ const head = [];
394
+ if (!hasRuntimeCss(html)) head.push('<link rel="stylesheet" href="decklight.css" data-decklight-runtime="css">');
395
+ if (!hasTheme(html)) head.push(`<link rel="stylesheet" href="themes/${theme ?? baseTheme(html)}.css">`);
396
+ let out = html;
397
+ if (head.length) {
398
+ const masked = maskComments(out);
399
+ const headEnd = masked.search(/<\/head>/i);
400
+ const bodyAt = masked.search(/<body\b/i);
401
+ const at = headEnd !== -1 ? headEnd : bodyAt !== -1 ? bodyAt : 0;
402
+ out = `${out.slice(0, at)}${head.join('\n')}\n${out.slice(at)}`;
403
+ }
404
+ const engine = '<script src="decklight.js" data-decklight-runtime="js"></script>';
405
+ const scriptAt = firstExecutableScript(out);
406
+ if (scriptAt !== null) return `${out.slice(0, scriptAt)}${engine}\n${out.slice(scriptAt)}`;
407
+ const bodyEnd = maskComments(out).toLowerCase().lastIndexOf('</body>');
408
+ return bodyEnd === -1 ? `${out}\n${engine}\n` : `${out.slice(0, bodyEnd)}${engine}\n${out.slice(bodyEnd)}`;
409
+ }
410
+
411
+ /**
412
+ * A JavaScript object literal as data — the argument of a `Decklight.init(…)`
413
+ * call, which `upgrade` turns into the configuration block. Accepts what an
414
+ * author writes by hand: unquoted keys, single- or double-quoted strings,
415
+ * numbers, booleans, null, nested arrays and objects, trailing commas, and
416
+ * comments. Refuses anything that is code — an identifier, a call, an
417
+ * expression — by returning null, so the call stays as it is: the JS API is
418
+ * the escape hatch, and a guess at what an expression evaluates to is not.
419
+ */
420
+ export function parseLiteral(src) {
421
+ let i = 0;
422
+ const s = String(src ?? '');
423
+ const ws = () => {
424
+ for (;;) {
425
+ while (i < s.length && /\s/.test(s[i])) i++;
426
+ if (s.startsWith('//', i)) { const nl = s.indexOf('\n', i); i = nl === -1 ? s.length : nl + 1; continue; }
427
+ if (s.startsWith('/*', i)) { const end = s.indexOf('*/', i + 2); if (end === -1) throw 0; i = end + 2; continue; }
428
+ return;
429
+ }
430
+ };
431
+ const string = () => {
432
+ const q = s[i++];
433
+ let out = '';
434
+ while (i < s.length && s[i] !== q) {
435
+ if (s[i] === '\n' && q !== '`') throw 0;
436
+ if (s[i] === '\\') {
437
+ const c = s[++i];
438
+ const map = { n: '\n', t: '\t', r: '\r', b: '\b', f: '\f', v: '\v', 0: '\0', '\n': '' };
439
+ if (c === 'u' && s[i + 1] === '{') { const end = s.indexOf('}', i); out += String.fromCodePoint(parseInt(s.slice(i + 2, end), 16)); i = end + 1; continue; }
440
+ if (c === 'u') { out += String.fromCharCode(parseInt(s.slice(i + 1, i + 5), 16)); i += 5; continue; }
441
+ if (c === 'x') { out += String.fromCharCode(parseInt(s.slice(i + 1, i + 3), 16)); i += 3; continue; }
442
+ out += c in map ? map[c] : c;
443
+ i++;
444
+ continue;
445
+ }
446
+ if (q === '`' && s.startsWith('${', i)) throw 0;
447
+ out += s[i++];
448
+ }
449
+ if (s[i] !== q) throw 0;
450
+ i++;
451
+ return out;
452
+ };
453
+ const value = () => {
454
+ ws();
455
+ const c = s[i];
456
+ if (c === '{') {
457
+ i++;
458
+ const obj = {};
459
+ for (;;) {
460
+ ws();
461
+ if (s[i] === '}') { i++; return obj; }
462
+ let key;
463
+ if (s[i] === '"' || s[i] === "'") key = string();
464
+ else {
465
+ const m = /^[A-Za-z_$][\w$]*/.exec(s.slice(i));
466
+ if (!m) throw 0;
467
+ key = m[0];
468
+ i += key.length;
469
+ }
470
+ ws();
471
+ if (s[i] !== ':') throw 0;
472
+ i++;
473
+ obj[key] = value();
474
+ ws();
475
+ if (s[i] === ',') { i++; continue; }
476
+ if (s[i] === '}') { i++; return obj; }
477
+ throw 0;
478
+ }
479
+ }
480
+ if (c === '[') {
481
+ i++;
482
+ const arr = [];
483
+ for (;;) {
484
+ ws();
485
+ if (s[i] === ']') { i++; return arr; }
486
+ arr.push(value());
487
+ ws();
488
+ if (s[i] === ',') { i++; continue; }
489
+ if (s[i] === ']') { i++; return arr; }
490
+ throw 0;
491
+ }
492
+ }
493
+ if (c === '"' || c === "'" || c === '`') return string();
494
+ const num = /^[+-]?(?:\d+\.?\d*(?:e[+-]?\d+)?|\.\d+(?:e[+-]?\d+)?|0x[0-9a-f]+)/i.exec(s.slice(i));
495
+ if (num) { i += num[0].length; return Number(num[0]); }
496
+ for (const [word, v] of [['true', true], ['false', false], ['null', null]]) {
497
+ if (s.startsWith(word, i) && !/[\w$]/.test(s[i + word.length] ?? '')) { i += word.length; return v; }
498
+ }
499
+ throw 0;
500
+ };
501
+ try {
502
+ ws();
503
+ if (i >= s.length) return { value: {} };
504
+ const v = value();
505
+ ws();
506
+ if (s[i] === ';') { i++; ws(); }
507
+ if (i !== s.length) return null;
508
+ return v && typeof v === 'object' && !Array.isArray(v) ? { value: v } : null;
509
+ } catch {
510
+ return null;
511
+ }
512
+ }
513
+
514
+ /**
515
+ * The deck's own `Decklight.init(…)` boot script, when it has one: the
516
+ * `<script>` whose whole body is that one call (an optional `const deck =`
517
+ * in front, at most a semicolon after), with the call's argument text.
518
+ * `upgrade` turns the argument into the configuration block when
519
+ * `parseLiteral` accepts it. Null when the deck boots some other way.
520
+ */
521
+ export function bootCall(html) {
522
+ const masked = maskComments(html);
523
+ for (const m of masked.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)) {
524
+ const [tag, attrs, inner] = m;
525
+ if (/\bsrc\s*=/i.test(attrs) || /\btype\s*=/i.test(attrs) && !/\btype\s*=\s*["'](?:text\/javascript|module)["']/i.test(attrs)) continue;
526
+ const bare = inner.replace(/\/\*[\s\S]*?\*\//g, ' ').replace(/(^|[^:])\/\/[^\n]*/g, '$1 ').trim();
527
+ const head = /^(?:(?:const|let|var)\s+[A-Za-z_$][\w$]*\s*=\s*)?Decklight\s*\.\s*init\s*\(/.exec(bare);
528
+ if (!head) continue;
529
+ let depth = 0;
530
+ for (let i = head[0].length - 1; i < bare.length; i++) {
531
+ const c = bare[i];
532
+ if (c === '"' || c === "'" || c === '`') {
533
+ for (i++; i < bare.length && bare[i] !== c; i++) if (bare[i] === '\\') i++;
534
+ continue;
535
+ }
536
+ if (c === '(') depth++;
537
+ else if (c === ')' && --depth === 0) {
538
+ if (!/^\s*;?\s*$/.test(bare.slice(i + 1))) break;
539
+ return { start: m.index, end: m.index + tag.length, arg: bare.slice(head[0].length, i) };
540
+ }
541
+ }
542
+ }
543
+ return null;
544
+ }
545
+
546
+ /**
547
+ * The span of an element widened to the whole line it sits on — the
548
+ * indentation before it when nothing else is on the line, and the line
549
+ * break after — so that removing the element removes its line, not just its
550
+ * tag, and the author's surrounding text closes up as if it was never there.
551
+ */
552
+ export function lineSpan(html, start, end) {
553
+ let from = start;
554
+ while (from > 0 && (html[from - 1] === ' ' || html[from - 1] === '\t')) from--;
555
+ if (from > 0 && html[from - 1] !== '\n') from = start;
556
+ let to = end;
557
+ if (html[to] === '\r') to++;
558
+ if (html[to] === '\n') to++;
559
+ return { start: from, end: to };
560
+ }