decklight 0.8.1 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. package/PLATFORM.md +666 -0
  2. package/README.md +224 -150
  3. package/SPEC.md +732 -886
  4. package/cli/agent-review.mjs +245 -0
  5. package/cli/agents.mjs +25 -5
  6. package/cli/associate.mjs +12 -12
  7. package/cli/audit.mjs +42 -10
  8. package/cli/banner.mjs +41 -17
  9. package/cli/bundle-audio.mjs +183 -0
  10. package/cli/bundle.mjs +383 -31
  11. package/cli/cast.mjs +7 -7
  12. package/cli/check.mjs +961 -0
  13. package/cli/clone-deck.mjs +179 -0
  14. package/cli/commands.mjs +345 -0
  15. package/cli/comments.mjs +64 -18
  16. package/cli/commit-flow.mjs +44 -19
  17. package/cli/commit-message.mjs +51 -74
  18. package/cli/commit-split.mjs +601 -0
  19. package/cli/deck-refs.mjs +59 -0
  20. package/cli/deck-routes.mjs +67 -0
  21. package/cli/deckfile.mjs +3 -5
  22. package/cli/decklight.mjs +68 -289
  23. package/cli/design-system-deps.mjs +209 -0
  24. package/cli/design-system-edit.mjs +194 -0
  25. package/cli/design-system-refs.mjs +409 -0
  26. package/cli/design-system.mjs +429 -0
  27. package/cli/doctor.mjs +115 -0
  28. package/cli/edit-git.mjs +353 -0
  29. package/cli/edit-handover.mjs +445 -0
  30. package/cli/edit-look.mjs +388 -0
  31. package/cli/edit-slides.mjs +683 -0
  32. package/cli/edit.mjs +2126 -842
  33. package/cli/enhance.mjs +483 -0
  34. package/cli/extension.mjs +10 -10
  35. package/cli/font-refs.mjs +273 -0
  36. package/cli/font.mjs +246 -0
  37. package/cli/git-tree.mjs +1 -1
  38. package/cli/git.mjs +65 -11
  39. package/cli/import.mjs +56 -10
  40. package/cli/init.mjs +400 -234
  41. package/cli/library.mjs +127 -0
  42. package/cli/loader.mjs +3 -1
  43. package/cli/marketplace.mjs +215 -21
  44. package/cli/narrate.mjs +176 -0
  45. package/cli/open-browser.mjs +63 -0
  46. package/cli/open.mjs +943 -0
  47. package/cli/pdf.mjs +41 -13
  48. package/cli/pkg.mjs +44 -2
  49. package/cli/plugin.mjs +43 -41
  50. package/cli/port-conflict.mjs +53 -23
  51. package/cli/pptx-export.mjs +57 -24
  52. package/cli/publish.mjs +8 -4
  53. package/cli/qr.mjs +1 -1
  54. package/cli/record.mjs +14 -12
  55. package/cli/remote.mjs +11 -11
  56. package/cli/restore.mjs +11 -4
  57. package/cli/review-ref.mjs +125 -0
  58. package/cli/review-remote.mjs +92 -48
  59. package/cli/review-routes.mjs +254 -0
  60. package/cli/review-store.mjs +47 -7
  61. package/cli/review-submit.mjs +47 -57
  62. package/cli/runtime-link.mjs +560 -0
  63. package/cli/serve.mjs +235 -44
  64. package/cli/setup.mjs +112 -0
  65. package/cli/sign.mjs +1 -1
  66. package/cli/skill-content.mjs +190 -33
  67. package/cli/skills.mjs +107 -24
  68. package/cli/start.mjs +110 -0
  69. package/cli/supervise.mjs +6 -6
  70. package/cli/theme-refs.mjs +515 -0
  71. package/cli/theme.mjs +181 -137
  72. package/cli/trust.mjs +83 -0
  73. package/cli/units.mjs +39 -42
  74. package/cli/update-check.mjs +1 -5
  75. package/cli/upgrade.mjs +194 -28
  76. package/cli/upstream.mjs +4 -3
  77. package/cli/util.mjs +4 -4
  78. package/cli/wizard.mjs +6 -6
  79. package/dist/build-info.json +1 -1
  80. package/dist/decklight.css +1126 -49
  81. package/dist/decklight.js +212 -115
  82. package/dist/decklight.js.map +4 -4
  83. package/docs/GLOSSARY.md +141 -0
  84. package/docs/architecture.svg +17 -17
  85. package/package.json +4 -2
  86. package/themes/README.md +9 -8
  87. package/themes/reveal-solarized.css +10 -0
  88. package/tools/args.mjs +20 -0
  89. package/tools/atomic-write.mjs +48 -0
  90. package/tools/brand-palette.mjs +717 -0
  91. package/tools/bridge.mjs +1 -1
  92. package/tools/build-groups.mjs +42 -0
  93. package/tools/color.mjs +48 -0
  94. package/tools/deck-html.mjs +396 -11
  95. package/tools/design-system-format.mjs +753 -0
  96. package/tools/elevenlabs-tts.mjs +110 -17
  97. package/tools/exec.mjs +1 -1
  98. package/tools/extension-check.mjs +31 -7
  99. package/tools/font-format.mjs +190 -0
  100. package/tools/font-stacks.mjs +24 -0
  101. package/tools/gemini-tts.mjs +3 -0
  102. package/tools/lipsync-config.mjs +103 -0
  103. package/tools/lipsync-engines.mjs +205 -2
  104. package/tools/lipsync-server.mjs +264 -41
  105. package/tools/lipsync.mjs +37 -18
  106. package/tools/local-voice.mjs +32 -42
  107. package/tools/narration-manifest.mjs +196 -0
  108. package/tools/narration-synth.mjs +416 -0
  109. package/tools/pptx.mjs +776 -19
  110. package/tools/publish-targets.mjs +1 -1
  111. package/tools/publish-voices.mjs +3 -3
  112. package/tools/recording-impact.mjs +7 -3
  113. package/tools/render-theme.mjs +33 -0
  114. package/tools/review-anchor.mjs +28 -12
  115. package/tools/semver.mjs +40 -0
  116. package/tools/sentences.mjs +180 -0
  117. package/tools/shot.mjs +14 -7
  118. package/tools/site-voices.mjs +232 -0
  119. package/tools/template-theme.mjs +1 -1
  120. package/tools/test-impact.mjs +17 -10
  121. package/tools/theme-check.mjs +30 -3
  122. package/tools/tts-cache.mjs +4 -3
  123. package/tools/tts-engines.mjs +38 -20
  124. package/tools/tts-setup.mjs +7 -7
  125. package/tools/video-options.mjs +34 -0
  126. package/tools/video.mjs +461 -48
  127. package/tools/voiceover-server.mjs +185 -104
  128. package/tools/voiceover.mjs +119 -261
  129. package/tools/zip.mjs +1 -1
  130. package/cli/dev.mjs +0 -623
  131. package/cli/present.mjs +0 -853
  132. package/cli/review.mjs +0 -361
  133. package/tools/publish-site-voices.mjs +0 -75
package/cli/check.mjs ADDED
@@ -0,0 +1,961 @@
1
+ #!/usr/bin/env node
2
+ // Copyright 2026 Gilles Philippart
3
+ // SPDX-License-Identifier: Apache-2.0
4
+
5
+ /**
6
+ * decklight check — one headless lint of one deck, with one exit code.
7
+ *
8
+ * decklight check <deck.html> [--no-render] [--json] [--wait <ms>]
9
+ *
10
+ * The promise this repo makes (README, SPEC PRESENTING: the overflow guardrail
11
+ * is assertable headlessly) is that an agent can verify its own work without
12
+ * eyes. The signals to verify it WITH were real but scattered: `pdf` names the
13
+ * clipped slides on stderr while writing a PDF nobody asked for, `present
14
+ * --check` prints the ingredients label, a missing image is a 404 only a human
15
+ * with a browser open ever sees, and a ⟨CLICK⟩ that does not line up with a
16
+ * build step is discovered while presenting. Each of those is a different
17
+ * command, a different output shape, and a different exit code.
18
+ *
19
+ * So this is the one command whose whole job is to REPORT, per slide, what an
20
+ * author or an agent would otherwise only find by looking — and to exit 1 when
21
+ * something is actually wrong. Nothing here writes a file, starts a server, or
22
+ * changes the deck.
23
+ *
24
+ * TWO HALVES, AND WHY THEY ARE SEPARATE FUNCTIONS. `staticFindings` is pure
25
+ * over the file text (with `exists` injected, it touches no disk at all) and
26
+ * `renderFindings` is pure over one dumped DOM string. Everything decidable is
27
+ * therefore unit-testable without a browser, and `--no-render` is a real mode
28
+ * rather than a degraded one: on a machine with no Chrome the static half still
29
+ * runs and says so in one line, instead of refusing to run at all.
30
+ *
31
+ * WHAT IT IS NOT. Not a style critic and not a verdict on the deck — the same
32
+ * position cli/audit.mjs takes about the ingredients label. Every finding names
33
+ * something checkable: a file that is not on disk, a section that never closes,
34
+ * a count that disagrees with another count, a slide the browser measured as
35
+ * clipped.
36
+ */
37
+
38
+ import { existsSync, readFileSync } from 'node:fs';
39
+ import { basename, dirname, resolve } from 'node:path';
40
+
41
+ import { argReader, firstPositional, isMain } from '../tools/args.mjs';
42
+ import { computeGroups, orderItem } from '../tools/build-groups.mjs';
43
+ import { findChrome, chromeArgs } from '../tools/chrome.mjs';
44
+ import { runAsync, CODEC_MS } from '../tools/exec.mjs';
45
+ import {
46
+ NOTES_ASIDE, cleanNotes, readNotes, indexOfCI, readAttrs, sectionBodies, sectionCloseIndex,
47
+ sectionInner, slideHeading, splitOpenTag,
48
+ } from '../tools/deck-html.mjs';
49
+ import { CLICK_MARK } from '../tools/sentences.mjs';
50
+ import { isTemplateRef, parseTemplateRef } from '../tools/design-system-format.mjs';
51
+ import { auditDeck } from './audit.mjs';
52
+ import { designSystemRefs, packageVerdict, resolveDesignSystemRef } from './design-system-refs.mjs';
53
+ import { markedSources } from './theme-refs.mjs';
54
+ import { parseColor, toOklab } from '../tools/color.mjs';
55
+ import { ON_PALETTE_DISTANCE, offRoleColours, nearestRole, resolveTokenColours } from '../tools/brand-palette.mjs';
56
+ import { printUrl } from './pdf.mjs';
57
+ import { runMain } from './util.mjs';
58
+
59
+ /**
60
+ * One finding. `slide` is null for anything outside a section (the head), and
61
+ * `rule` is there for the `--json` reader: an agent filters on a stable name,
62
+ * never on the wording of a message a human reads.
63
+ */
64
+ const finding = (level, rule, slide, title, message) => ({ level, rule, slide, title, message });
65
+
66
+ // ── a deck as a tree, just enough of one ─────────────────────────────────────
67
+ // Both static halves need the same two things — which element carries which
68
+ // attribute, and how many ELEMENT CHILDREN it has — and neither is answerable
69
+ // with a flat regex sweep. tools/deck-html.mjs walks elements for its own
70
+ // slide-splicing (`sectionChildRanges`), but only ever at one level of one
71
+ // section; this is the same shape generalised, and it stays here because that
72
+ // is the file's job and the runtime never needs it.
73
+
74
+ const VOID_ELEMENTS = new Set([
75
+ 'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input',
76
+ 'link', 'meta', 'param', 'source', 'track', 'wbr',
77
+ ]);
78
+ /** Bodies that are not markup: a chart's JSON spec is not a tag soup. */
79
+ const OPAQUE_ELEMENTS = new Set(['script', 'style']);
80
+ /**
81
+ * Tags HTML lets an author leave open, and what a new one closes. Decks are
82
+ * hand-written, and `<li>a<li>b` is legal HTML that a naive stack would read
83
+ * as one li nested in another — which would then report one build step where
84
+ * the browser will show two, i.e. a warning about a deck that is correct.
85
+ */
86
+ const IMPLIED_CLOSE = {
87
+ li: ['li'], dt: ['dt', 'dd'], dd: ['dt', 'dd'], p: ['p'], option: ['option'],
88
+ tr: ['tr'], td: ['td', 'th'], th: ['td', 'th'],
89
+ thead: ['thead', 'tbody', 'tfoot'], tbody: ['thead', 'tbody', 'tfoot'], tfoot: ['thead', 'tbody', 'tfoot'],
90
+ };
91
+
92
+ const TAG = /<!--[\s\S]*?-->|<(\/)?([a-zA-Z][\w:.-]*)((?:"[^"]*"|'[^']*'|[^>"'])*)>/g;
93
+
94
+ /**
95
+ * `html` as a tree of `{ tag, attrs, start, children }`, best-effort.
96
+ *
97
+ * Best-effort is the contract: this reads a file somebody is mid-edit on, so a
98
+ * stray `</div>` is ignored rather than thrown on, and an unclosed tag simply
99
+ * ends with the document. A lint that crashes on the deck it was asked about
100
+ * is worse than one that reports a little less.
101
+ */
102
+ export function parseTree(html) {
103
+ const root = { tag: '#root', attrs: '', start: 0, children: [] };
104
+ const stack = [root];
105
+ const re = new RegExp(TAG.source, 'g');
106
+ let m;
107
+ while ((m = re.exec(html))) {
108
+ if (m[0].startsWith('<!--')) continue;
109
+ const [, closing, rawName, rawAttrs] = m;
110
+ const tag = rawName.toLowerCase();
111
+ if (closing) {
112
+ const at = stack.findLastIndex((n) => n.tag === tag);
113
+ if (at > 0) stack.length = at; // a close with no open is somebody's typo, not a nesting level
114
+ continue;
115
+ }
116
+ const selfClosed = /\/\s*$/.test(rawAttrs);
117
+ const node = { tag, attrs: rawAttrs.replace(/\/\s*$/, ''), start: m.index, children: [] };
118
+ for (const implied of IMPLIED_CLOSE[tag] ?? []) {
119
+ if (stack.at(-1).tag === implied) stack.pop();
120
+ }
121
+ stack.at(-1).children.push(node);
122
+ if (selfClosed || VOID_ELEMENTS.has(tag)) continue;
123
+ if (OPAQUE_ELEMENTS.has(tag)) {
124
+ const close = indexOfCI(html, `</${tag}`, re.lastIndex);
125
+ re.lastIndex = close === -1 ? html.length : close;
126
+ continue;
127
+ }
128
+ stack.push(node);
129
+ }
130
+ return root;
131
+ }
132
+
133
+ /** Every node under `root`, itself excluded, in document order. */
134
+ function* descendants(root) {
135
+ for (const child of root.children) {
136
+ yield child;
137
+ yield* descendants(child);
138
+ }
139
+ }
140
+
141
+ /**
142
+ * Each slide's byte range in the file, so a finding found at an offset can be
143
+ * given a slide number.
144
+ *
145
+ * The end matters as much as the start: `sectionBodies` cuts at the NEXT
146
+ * `<section`, so the last slide's piece carries the whole tail of the document
147
+ * — `</div>`, the inlined runtime, `</body>`. Bounding each range at the
148
+ * section's own `</section>` (deck-html's `sectionCloseIndex`, which knows
149
+ * about `</section>` shown inside a code block) is what keeps a `<script src>`
150
+ * in the page's tail from being reported as a fault of the last slide.
151
+ */
152
+ export function sectionRanges(html) {
153
+ const bodies = sectionBodies(html);
154
+ const opens = [...String(html).matchAll(/<section\b/g)].map((m) => m.index);
155
+ return bodies.map((body, i) => {
156
+ const start = opens[i];
157
+ const close = sectionCloseIndex(body);
158
+ const end = close === -1
159
+ ? (opens[i + 1] ?? html.length)
160
+ : start + '<section'.length + close + '</section>'.length;
161
+ return { slide: i + 1, start, end, body };
162
+ });
163
+ }
164
+
165
+ /** The 1-based slide an offset falls in, or null for the head and the tail. */
166
+ const slideAt = (ranges, at) => ranges.find((r) => at >= r.start && at < r.end)?.slide ?? null;
167
+
168
+ // ── local assets ─────────────────────────────────────────────────────────────
169
+
170
+ /**
171
+ * Attributes a browser fetches, per tag. `link` is conditional (only a
172
+ * stylesheet is a local asset worth resolving) and the background trio is
173
+ * read by the runtime rather than the browser (SPEC DECK_ANATOMY), which makes
174
+ * no difference to the author: a path that is not there shows nothing either
175
+ * way, and shows it silently.
176
+ */
177
+ const ASSET_ATTRS = {
178
+ img: ['src'], script: ['src'], source: ['src'], video: ['src'], audio: ['src'],
179
+ track: ['src'], embed: ['src'], iframe: ['src'], object: ['data'],
180
+ };
181
+ /**
182
+ * Paths the RUNTIME loads rather than the browser (SPEC DECK_ANATOMY,
183
+ * TERMINAL_RECORDINGS). The distinction is invisible to an author: a
184
+ * background photo or a cast that is not there shows nothing, and shows it
185
+ * silently. `data-cast-inline="#id"` names an embedded block, not a file, and
186
+ * falls out by itself — `localAsset` refuses an anchor.
187
+ */
188
+ const LOADED_ATTRS = [
189
+ 'data-background-image', 'data-background-video', 'data-background-poster', 'data-cast',
190
+ ];
191
+
192
+ /**
193
+ * The local file an attribute value points at, or null when it points
194
+ * somewhere this check cannot follow.
195
+ *
196
+ * ANY scheme means not-local, not merely the four common ones: `file:`,
197
+ * `mailto:` and a Windows-style `C:` are all things a resolve-against-the-deck
198
+ * would turn into a confident, wrong "missing asset". Same for a
199
+ * protocol-relative `//cdn/x.js` and an in-page `#anchor`. What is left is a
200
+ * relative or root-relative path, and THAT is the class of mistake worth
201
+ * reporting: `%20`-encoded, because a browser decodes before it opens a file
202
+ * and so must this, and stripped of `?query#hash`, because a cache-buster is
203
+ * not part of the filename.
204
+ */
205
+ export function localAsset(value) {
206
+ const raw = String(value ?? '').trim();
207
+ if (!raw || raw.startsWith('#')) return null;
208
+ if (raw.startsWith('//') || /^[a-z][a-z0-9+.-]*:/i.test(raw)) return null;
209
+ const bare = raw.split(/[?#]/)[0];
210
+ if (!bare) return null;
211
+ try { return decodeURIComponent(bare); } catch { return bare; } // a lone % is a filename, not an escape
212
+ }
213
+
214
+ /** Every (tag, attribute, value, offset) in the file that names a local file. */
215
+ function assetReferences(tree) {
216
+ const out = [];
217
+ for (const node of descendants(tree)) {
218
+ const attrs = readAttrs(node.attrs);
219
+ const named = [...(ASSET_ATTRS[node.tag] ?? [])];
220
+ // a <link> is only an asset when it is the deck's CSS; rel="canonical" and
221
+ // friends name a document, not a file beside the deck
222
+ if (node.tag === 'link' && /\bstylesheet\b/i.test(attrs.rel ?? '')) named.push('href');
223
+ for (const attr of [...named, ...LOADED_ATTRS]) {
224
+ const path = localAsset(attrs[attr]);
225
+ if (path) out.push({ tag: node.tag, attr, value: attrs[attr], path, at: node.start });
226
+ }
227
+ }
228
+ return out;
229
+ }
230
+
231
+ // ── ⟨CLICK⟩ segments vs build steps ──────────────────────────────────────────
232
+
233
+ const SVG_SKIP = new Set(['defs', 'title', 'desc', 'style', 'metadata']);
234
+ const CONTAINER_TAGS = new Set(['ul', 'ol', 'table', 'tbody', 'dl', 'svg']);
235
+ /** The SVG shapes a concept recolours (src/core/svg.js's SHAPES). */
236
+ const SHAPE_TAGS = new Set(['rect', 'circle', 'ellipse', 'polygon', 'polyline', 'path']);
237
+
238
+ /** src/core/builds.js `eligibleChildren`, over the file instead of the DOM. */
239
+ function eligibleChildren(node) {
240
+ return node.children.filter((c) => {
241
+ if (SVG_SKIP.has(c.tag)) return false;
242
+ if (c.tag === 'aside') return false;
243
+ return !('data-build-stay' in readAttrs(c.attrs));
244
+ });
245
+ }
246
+
247
+ /** src/core/builds.js `isContainer` — the "one g is a leaf" resolution included. */
248
+ function isContainer(node) {
249
+ if ('data-build-self' in readAttrs(node.attrs)) return false;
250
+ if (CONTAINER_TAGS.has(node.tag)) return true;
251
+ if (node.tag === 'div' || node.tag === 'g') return eligibleChildren(node).length >= 2;
252
+ return false;
253
+ }
254
+
255
+ /** src/core/builds.js `stepSource`: a table steps by ROW, not by its tbody. */
256
+ function stepSource(node) {
257
+ if (node.tag !== 'table') return eligibleChildren(node);
258
+ const tbody = node.children.find((c) => c.tag === 'tbody');
259
+ return tbody ? eligibleChildren(tbody) : eligibleChildren(node).filter((c) => c.tag === 'tr');
260
+ }
261
+
262
+ /**
263
+ * A STATIC estimate of a slide's build steps — the file-reading twin of
264
+ * `scanSlide` (SPEC BUILDS, BUILD_SEMANTICS).
265
+ *
266
+ * An estimate, and named as one: a container's children each become a step and
267
+ * their own subtrees are then claimed (so a nested `data-build` inside a
268
+ * counted child adds nothing), which this reproduces — but build PROVIDERS
269
+ * (BUILD_PROVIDER_API) contribute steps that exist only once the runtime has
270
+ * read a cast or parsed `data-lines`, and no file reader can count those.
271
+ * `hasProvider` below is why the caller does not compare on such a slide at
272
+ * all: a guess against a number nobody can know is a warning about nothing.
273
+ */
274
+ export function buildSteps(node) {
275
+ return buildItems(node).length;
276
+ }
277
+
278
+ /**
279
+ * The slide's build steps as the order items `computeGroups` takes — the
280
+ * static twin of `scanSlide`'s `push`: a container's children each one step
281
+ * keyed by their own `data-build-order`, a leaf one step keyed by its own; a
282
+ * stroke drawing in stages (`data-draw-stops`, #522) one step per stop, since
283
+ * its count is right there in the attribute, unlike a provider's.
284
+ */
285
+ function buildItems(node) {
286
+ const items = [];
287
+ let auto = 0;
288
+ const push = (orderAttr) => { items.push(orderItem(orderAttr, auto)); auto++; };
289
+ const stops = (n) => parseDrawStops(readAttrs(n.attrs)['data-draw-stops']).length;
290
+ const stepsOf = (n) => {
291
+ const attrs = readAttrs(n.attrs);
292
+ if ('data-draw-stops' in attrs && stops(n)) {
293
+ // its stops count up from its data-build-order, when it has one (#524)
294
+ const base = parseInt(attrs['data-build-order'] ?? '', 10);
295
+ for (let i = 0; i < stops(n); i++) push(Number.isFinite(base) ? String(base + i) : null);
296
+ return;
297
+ }
298
+ push(attrs['data-build-order']);
299
+ };
300
+ const walk = (parent) => {
301
+ for (const child of parent.children) {
302
+ if (child.tag === 'aside' || OPAQUE_ELEMENTS.has(child.tag)) continue;
303
+ const attrs = readAttrs(child.attrs);
304
+ if ('data-build' in attrs) {
305
+ if (isContainer(child)) { for (const c of stepSource(child)) stepsOf(c); continue; }
306
+ stepsOf(child); // a leaf is one step, and the engine keeps walking into it
307
+ } else if ('data-draw-stops' in attrs && stops(child)) {
308
+ stepsOf(child); // a staged stroke outside any build container is its own provider
309
+ continue;
310
+ }
311
+ walk(child);
312
+ }
313
+ };
314
+ walk(node);
315
+ return items;
316
+ }
317
+
318
+ /**
319
+ * How many CLICKS the slide's builds take — steps tied by a shared explicit
320
+ * `data-build-order` advance together (SPEC BUILD_SEMANTICS), so a slide with
321
+ * three steps in two ties takes two clicks, and its notes want three segments,
322
+ * not four (#526). The same `computeGroups` the runtime applies to the DOM.
323
+ */
324
+ export function buildClicks(node) {
325
+ return computeGroups(buildItems(node)).length;
326
+ }
327
+
328
+ /** The stop count a `data-draw-stops` attribute declares (the runtime's `parseDrawStops`, without a length to clamp to). */
329
+ function parseDrawStops(attr) {
330
+ const raw = String(attr ?? '').trim().split(/[\s,]+/).filter(Boolean);
331
+ const nums = raw.map((s) => parseFloat(s));
332
+ return nums.length && nums.every((n) => Number.isFinite(n) && n >= 0) ? nums : [];
333
+ }
334
+
335
+ /**
336
+ * Does this slide contain a widget whose step count only the runtime knows?
337
+ *
338
+ * Code stepping (`data-lines`) and a terminal cast register build providers
339
+ * (BUILD_PROVIDER_API), so their steps are a count parsed at load. A chart is
340
+ * the same shape without the API: `initCharts` MOVES the authored `data-build`
341
+ * off the wrapper onto the `<svg>` it generates, whose series groups are then
342
+ * the steps — a file reader sees an empty div and would report one step for a
343
+ * slide that has one per series. On any of these the comparison is skipped
344
+ * rather than guessed at: a warning about a number nobody can know is noise,
345
+ * and noise is how a check gets turned off.
346
+ */
347
+ const hasProvider = (node) => [...descendants(node)].some((n) => {
348
+ const attrs = readAttrs(n.attrs);
349
+ return 'data-lines' in attrs || 'data-cast' in attrs || 'data-cast-inline' in attrs || 'data-chart' in attrs;
350
+ });
351
+
352
+ /**
353
+ * How many ⟨CLICK⟩ segments a slide's notes have, by the RUNTIME's rule.
354
+ *
355
+ * `notesSegsOf` (src/core/narration.js) keeps every part of the split, empties
356
+ * included, because segment k must line up with build step k — so segments are
357
+ * clicks + 1, always. `notesSegments` in deck-html drops empties, because it is
358
+ * naming files; using it here would make a ⟨CLICK⟩ at the very start of a note
359
+ * read as one fewer beat than the deck will actually play.
360
+ */
361
+ export function clickSegments(notesHtml) {
362
+ const text = readNotes(notesHtml);
363
+ if (!cleanNotes(text)) return 0; // no notes at all is not a disagreement
364
+ return text.split(CLICK_MARK).length;
365
+ }
366
+
367
+ // ── design systems ───────────────────────────────────────────────────────────
368
+
369
+ /**
370
+ * The deck's design systems as `check` needs them (SPEC DESIGN_SYSTEMS):
371
+ * name → `{ ref, templates: Map<id, slots> }`, or `{ ref, missing }` when this
372
+ * machine cannot read one. From the checkouts and the cache only — never a
373
+ * fetch — and through the same check every server makes, so a package that
374
+ * no longer passes it is as unreadable here as it is on stage. The default
375
+ * `designSystems` of `staticFindings`, which a test replaces with a fixture.
376
+ */
377
+ export function deckDesignSystems(html) {
378
+ const sources = markedSources(html);
379
+ const out = new Map();
380
+ for (const ref of designSystemRefs(html)) {
381
+ const r = resolveDesignSystemRef(ref, undefined, { source: sources[ref.marketplace] ?? null });
382
+ const verdict = r.dir ? packageVerdict(r.dir) : null;
383
+ const missing = r.missing ?? (verdict.ok ? null : verdict.why);
384
+ out.set(ref.name, missing ? { ref: ref.ref, missing } : checkEntry(ref.ref, verdict));
385
+ }
386
+ return out;
387
+ }
388
+
389
+ /** What `check` keeps of a design system that passed its gate: its templates, and its palette and roles when it has them. */
390
+ export function checkEntry(ref, verdict) {
391
+ const brand = verdict?.summary?.brand;
392
+ return {
393
+ ref, templates: new Map((verdict?.summary?.templates ?? []).map((l) => [l.id, l.slots])),
394
+ // component classes its base styles also give a plain element (SPEC DESIGN_SYSTEMS)
395
+ components: verdict?.summary?.baseStyles?.components ?? {},
396
+ // a palette of scales and its own themes (SPEC BRAND_PALETTE): what off-palette-literal holds slides to
397
+ ...(brand ? { palette: brand.palette.map((e) => ({ ref: e.ref, hex: e.hex, token: e.token })), themes: brand.themes.length, themeNames: brand.themes.map((t) => t.name) } : {}),
398
+ // its roles (SPEC DESIGN_SYSTEM_ROLES): what off-role holds slides to, with each theme's values to name the nearest
399
+ ...(brand?.roles ? {
400
+ prefix: verdict.summary.prefix, roles: brand.roles, contract: brand.contract ?? {}, tokenValues: verdict.summary.tokenValues ?? {},
401
+ themeRoles: Object.fromEntries(brand.themes.map((t) => [t.name, { roles: t.roleValues ?? {}, tokens: t.tokens ?? {} }])),
402
+ } : {}),
403
+ };
404
+ }
405
+
406
+ // ── the brand's palette (SPEC BRAND_PALETTE) ─────────────────────────────────
407
+
408
+ /** Colour literals a slide's markup writes: in a fill/stroke/color attribute or a style. */
409
+ const LITERAL = /#[0-9a-f]{6}\b|#[0-9a-f]{3}\b|rgba?\([^)]*\)/gi;
410
+ const COLOUR_ATTRS = ['fill', 'stroke', 'color', 'bgcolor', 'stop-color'];
411
+ const COLOUR_DECL = /(?:^|;)\s*(color|background(?:-color)?|fill|stroke|border(?:-(?:top|right|bottom|left))?(?:-color)?|outline(?:-color)?|stop-color)\s*:\s*([^;]+)/gi;
412
+ /** A shorthand whose value also holds widths, images, styles: a token read there is a colour only if it resolves to one. */
413
+ const SHORTHAND = /^(?:background|border(?:-(?:top|right|bottom|left))?|outline)$/i;
414
+
415
+ /** `{ swatches: [{ ref, lab }] }` when the deck is held to a brand palette — its own themes, not unlocked — else null. */
416
+ function brandHold(src, systems) {
417
+ const config = (() => { try { return JSON.parse(/<script[^>]*data-decklight-config[^>]*>([\s\S]*?)<\/script>/i.exec(src)?.[1] ?? 'null'); } catch { return null; } })();
418
+ if (config?.brandThemesOnly === false) return null;
419
+ const swatches = [];
420
+ let themes = 0;
421
+ for (const sys of systems.values()) {
422
+ themes += sys.themes ?? 0;
423
+ for (const e of sys.palette ?? []) swatches.push({ ref: e.ref, lab: toOklab(parseColor(e.hex)) });
424
+ }
425
+ return themes && swatches.length ? { swatches } : null;
426
+ }
427
+
428
+ /**
429
+ * The deck's roles when it is held to a design system that declares them
430
+ * (SPEC DESIGN_SYSTEM_ROLES): what off-role reads, at their values in the
431
+ * theme the deck opens on (its own `theme` when that is one of the brand's,
432
+ * else the brand's first, as the runtime does — theme-off-brand says so). Null when the deck is unlocked or no design system has roles.
433
+ */
434
+ function roleHold(src, systems) {
435
+ const config = (() => { try { return JSON.parse(/<script[^>]*data-decklight-config[^>]*>([\s\S]*?)<\/script>/i.exec(src)?.[1] ?? 'null'); } catch { return null; } })();
436
+ if (config?.brandThemesOnly === false) return null;
437
+ for (const sys of systems.values()) {
438
+ if (!sys.roles?.length || !sys.prefix) continue;
439
+ const names = Object.keys(sys.themeRoles ?? {});
440
+ const theme = sys.themeRoles[names.includes(config?.theme) ? config.theme : names[0]] ?? { roles: {}, tokens: {} };
441
+ const scales = {};
442
+ for (const e of sys.palette ?? []) {
443
+ const m = /^([a-z][a-z0-9-]*)-(\d{3,4})$/.exec(e.ref ?? '');
444
+ if (m) ((scales[m[1]] ??= { weights: {} }).weights[Number(m[2])] = e.hex);
445
+ }
446
+ const ctx = { prefix: sys.prefix, scales, roles: Object.fromEntries(sys.roles.map((r) => [r.id, r])), contractHex: theme.tokens };
447
+ // its own other tokens (an alias of a swatch, kept for older decks) are not roles either: each at the colour it resolves to here
448
+ ctx.tokens = resolveTokenColours(sys.tokenValues ?? {}, { ...ctx, roleValues: theme.roles });
449
+ return { ctx, values: theme.roles, contract: sys.contract ?? {} };
450
+ }
451
+ return null;
452
+ }
453
+
454
+ /**
455
+ * A deck held to its brand whose configuration names a theme outside it
456
+ * (SPEC BRAND_PALETTE): `{ theme, brand: [names] }`, else null. The runtime
457
+ * opens such a deck on the brand's first theme instead, so the configured one
458
+ * is never what it shows — said here, where an author reads it, rather than
459
+ * only by a toast on load.
460
+ */
461
+ function themeOffBrand(src, systems) {
462
+ const config = (() => { try { return JSON.parse(/<script[^>]*data-decklight-config[^>]*>([\s\S]*?)<\/script>/i.exec(src)?.[1] ?? 'null'); } catch { return null; } })();
463
+ if (config?.brandThemesOnly === false || typeof config?.theme !== 'string' || !config.theme) return null;
464
+ const brand = [...systems.values()].flatMap((sys) => sys.themeNames ?? []);
465
+ return brand.length && !brand.includes(config.theme) ? { theme: config.theme, brand } : null;
466
+ }
467
+
468
+ /** The palette swatch nearest a literal, and how far (OKLab). */
469
+ function nearestOf(hold, literal) {
470
+ const c = parseColor(literal);
471
+ if (!c) return null;
472
+ const lab = toOklab(c.slice(0, 3));
473
+ let best = null;
474
+ for (const s of hold.swatches) {
475
+ const d = Math.hypot(lab[0] - s.lab[0], lab[1] - s.lab[1], lab[2] - s.lab[2]);
476
+ if (!best || d < best.d) best = { ref: s.ref, d };
477
+ }
478
+ return best;
479
+ }
480
+
481
+ const slotList = (slots) => `${slots.map((s) => `${s.name}${s.required ? '*' : ''}`).join(', ')}${slots.some((s) => s.required) ? '; * = required' : ''}`;
482
+
483
+ /**
484
+ * A slide that names a slide template, against what the design system
485
+ * defines. Every mistake here renders — the engine shows the content plainly
486
+ * or in the unslotted box rather than losing it — so each is a warning that
487
+ * names what was written and what the design system offers instead.
488
+ */
489
+ function designSystemFindings(value, tree, systems, configured, push) {
490
+ // the slots the engine reads: the slide's direct children, as written
491
+ const slotted = tree.children.map((n) => readAttrs(n.attrs)['data-slot']).filter((v) => v !== undefined);
492
+ const ref = parseTemplateRef(value);
493
+ const sys = ref ? systems.get(ref.system) : null;
494
+ const slots = sys?.templates?.get(ref.template) ?? null;
495
+ // a slot filled twice is decidable from the file alone — except the layout's
496
+ // default slot, which is MEANT to take everything else
497
+ const fallback = slots?.find((s) => s.default)?.name;
498
+ const seen = new Set();
499
+ for (const name of slotted) {
500
+ if (seen.has(name) && name !== fallback) {
501
+ push('ds-slot-twice', `data-slot="${name}" is filled twice on this slide — a slot is one place in the layout; put both elements in one wrapper, or one of them in another slot`);
502
+ }
503
+ seen.add(name);
504
+ }
505
+ if (!ref) {
506
+ push('ds-unknown-template', `data-template="${value}" is not a slide template — it is written <design system>/<template>`);
507
+ return;
508
+ }
509
+ if (!sys) {
510
+ push('ds-unknown-system', `data-template="${value}" — the deck uses no design system called "${ref.system}"`
511
+ + ` (it uses: ${configured.length ? configured.join(', ') : 'none'}); decklight design-system add ${ref.system}@<marketplace> <deck> references one`);
512
+ return;
513
+ }
514
+ if (sys.missing) return; // said once, in the head; nothing here can be known
515
+ if (!slots) {
516
+ push('ds-unknown-template', `data-template="${value}" — ${sys.ref} has no template "${ref.template}" (its templates: ${[...sys.templates.keys()].join(', ') || 'none'})`);
517
+ return;
518
+ }
519
+ const names = new Set(slots.map((s) => s.name));
520
+ for (const name of new Set(slotted)) {
521
+ if (!names.has(name)) push('ds-unknown-slot', `data-slot="${name}" — the ${ref.template} template has no such slot (its slots: ${slotList(slots)})`);
522
+ }
523
+ for (const s of slots) {
524
+ if (s.required && !seen.has(s.name)) push('ds-required-empty', `the ${ref.template} template needs its "${s.name}" slot filled — no element here carries data-slot="${s.name}" (its slots: ${slotList(slots)})`);
525
+ }
526
+ }
527
+
528
+ // ── A. the static half ───────────────────────────────────────────────────────
529
+
530
+ // ── whether a slide's diagram builds ─────────────────────────────────────────
531
+
532
+ const hasClass = (node, cls) => new RegExp(`(?:^|\\s)${cls}(?:\\s|$)`).test(readAttrs(node.attrs).class ?? '');
533
+ /** Generated, not drawn: a chart or a terminal cast has nothing an author would build. */
534
+ const generated = (node) => hasClass(node, 'chart') || hasClass(node, 'terminal');
535
+
536
+ /** Every authored `<svg>` on the slide that is a diagram: three drawn shapes or more and a label, outside anything generated. */
537
+ function diagramsIn(tree) {
538
+ const out = [];
539
+ const walk = (node) => {
540
+ for (const child of node.children) {
541
+ if (child.tag === 'aside' || generated(child)) continue;
542
+ if (child.tag === 'svg') {
543
+ // shapes AND words: an illustration (a trophy, a logo) is drawn but says nothing to build up
544
+ const inside = [...descendants(child)];
545
+ const shapes = inside.filter((n) => SHAPE_TAGS.has(n.tag) || n.tag === 'line').length;
546
+ if (shapes >= 3 && inside.some((n) => n.tag === 'text')) out.push(child);
547
+ continue;
548
+ }
549
+ walk(child);
550
+ }
551
+ };
552
+ walk(tree);
553
+ return out;
554
+ }
555
+
556
+ /** Does the diagram reveal itself in steps: a build on the svg, or on anything drawn inside it. */
557
+ function diagramBuilds(svg) {
558
+ const attrs = readAttrs(svg.attrs);
559
+ return 'data-build' in attrs || 'data-draw-stops' in attrs || buildItems(svg).length > 0;
560
+ }
561
+
562
+
563
+ /**
564
+ * Everything decidable from the file text. Pure when `exists` is injected:
565
+ * nothing here reads a file, spawns anything, or looks at the clock.
566
+ *
567
+ * `dir` is what a relative asset path resolves against — the deck's own
568
+ * directory, exactly as the browser would resolve it from the deck's URL.
569
+ */
570
+ export function staticFindings(html, { dir = '.', exists = existsSync, designSystems = deckDesignSystems } = {}) {
571
+ const src = String(html ?? '');
572
+ const out = [];
573
+ const ranges = sectionRanges(src);
574
+ // Design systems (SPEC DESIGN_SYSTEMS): resolved only when the deck names
575
+ // one — a deck without any attempts nothing — and one this machine cannot
576
+ // read is said once, its slides' layouts and slots skipped, not guessed.
577
+ const configured = designSystemRefs(src);
578
+ const systems = configured.length ? designSystems(src) : new Map();
579
+ const hold = brandHold(src, systems);
580
+ const roles = roleHold(src, systems);
581
+ const offBrand = themeOffBrand(src, systems);
582
+ if (offBrand) {
583
+ out.push(finding('warn', 'theme-off-brand', null, 'head',
584
+ `"theme": "${offBrand.theme}" is not one of the brand's themes (${offBrand.brand.join(', ')}) — a deck held to its brand opens on ${offBrand.brand[0]} instead: `
585
+ + `name one of them, or set "brandThemesOnly": false to wear ${offBrand.theme}`));
586
+ }
587
+ for (const [, sys] of systems) {
588
+ if (sys.missing) {
589
+ out.push(finding('warn', 'ds-unresolved', null, 'head',
590
+ `design system ${sys.ref} cannot be read on this machine — ${sys.missing}; its slides' templates and slots go unchecked`));
591
+ }
592
+ }
593
+ // `sectionInner`, never the raw body: a body begins mid-open-tag, so a slide
594
+ // with no heading to fall back on would be titled ` data-markdown>` — the
595
+ // remnant of its own tag, read as the slide's opening words.
596
+ const title = (slide) => (slide ? slideHeading(sectionInner(ranges[slide - 1].body), slide - 1) : 'head');
597
+ const at = (offset) => {
598
+ const slide = slideAt(ranges, offset);
599
+ return { slide, title: title(slide) };
600
+ };
601
+
602
+ for (const range of ranges) {
603
+ const { slide, body } = range;
604
+ const attrs = readAttrs(splitOpenTag(body).attrs);
605
+ const head = title(slide);
606
+ const inner = sectionInner(body);
607
+
608
+ // An unclosed section swallows every slide after it: the browser nests
609
+ // them, the deck shows one slide where the file has five, and nothing else
610
+ // in this file can be trusted about that slide either.
611
+ if (sectionCloseIndex(body) === -1) {
612
+ out.push(finding('error', 'unclosed-section', slide, head,
613
+ 'this <section> is never closed — every slide after it is swallowed into this one'));
614
+ }
615
+
616
+ // Markdown slides were removed in 0.3.0 (SPEC DECK_ANATOMY). The runtime
617
+ // stamps data-markdown-removed and warns, but only once the deck is open;
618
+ // in a file it is silent, and the slide comes up empty on stage.
619
+ if ('data-markdown' in attrs) {
620
+ out.push(finding('error', 'markdown-slide', slide, head,
621
+ 'markdown slides are not rendered — data-markdown was removed in 0.3.0, so this slide comes up '
622
+ + 'empty; author it in HTML (SPEC DECK_ANATOMY)'));
623
+ }
624
+
625
+ const tree = parseTree(inner);
626
+ const push = (rule, message) => out.push(finding('warn', rule, slide, head, message));
627
+ // a slashed data-layout was how a slide named a template before 0.9.0
628
+ if (isTemplateRef(attrs['data-layout'])) {
629
+ push('ds-layout-attr', `data-layout="${attrs['data-layout']}" — a slide template is named by data-template now: write data-template="${attrs['data-layout']}" (data-layout is for the built-in layouts, L)`);
630
+ }
631
+ // a concept shape with its own fill (SVG_DIAGRAMS, #718): the concept
632
+ // repaints the fill on every load, so the hand-set one is never seen
633
+ for (const node of descendants(tree)) {
634
+ if (!SHAPE_TAGS.has(node.tag)) continue;
635
+ const a = readAttrs(node.attrs);
636
+ if (!a['data-concept']) continue;
637
+ const own = a.fill && a.fill !== 'none' ? `fill="${a.fill}"` : /(?:^|;)\s*fill\s*:\s*(?!none\b)[^;]+/i.test(a.style ?? '') ? 'a fill in its style' : null;
638
+ if (own) push('concept-fill', `<${node.tag} data-concept="${a['data-concept']}"> also carries ${own} — the concept colours it, and the fill is painted over; pin the concept's slot (Concept colors…) or take the concept off (Colors… → Detach from concept)`);
639
+ }
640
+ // a deck on a design system with roles: every colour its slides name is a role (SPEC DESIGN_SYSTEM_ROLES)
641
+ if (roles) {
642
+ const off = [];
643
+ for (const node of descendants(tree)) {
644
+ const a = readAttrs(node.attrs);
645
+ const values = [...COLOUR_ATTRS.map((k) => [k, a[k]]).filter(([, v]) => v), ...[...(a.style ?? '').matchAll(COLOUR_DECL)].map((m) => [m[1], m[2]])];
646
+ for (const [prop, v] of values) {
647
+ for (const o of offRoleColours(v, roles.ctx)) {
648
+ if (off.some((x) => x.name === o.name)) continue;
649
+ // `border: var(--acme-rule-width) solid …`: a design-system token that is no colour is the width, not off-role
650
+ if (o.kind === 'token' && !o.hex && SHORTHAND.test(prop)) continue;
651
+ off.push({ ...o, near: (o.kind === 'contract' && roles.contract[o.name]) || nearestRole(roles.values, o.hex) });
652
+ }
653
+ }
654
+ }
655
+ if (off.length) {
656
+ const what = (o) => `${o.name}${o.kind === 'contract' ? ' (the theme contract)' : o.kind === 'swatch' ? ' (a swatch)' : o.kind === 'token' ? ' (a design-system token)' : ''}${o.near ? ` (nearest role ${o.near})` : ''}`;
657
+ push('off-role', `${off.slice(0, 3).map(what).join(', ')}${off.length > 3 ? ` and ${off.length - 3} more` : ''}`
658
+ + ` ${off.length === 1 ? 'is' : 'are'} not one of the design system's roles — this deck colours through them, so every theme recolours it: pick a role in Colors…, or set "brandThemesOnly": false`);
659
+ }
660
+ } else if (hold) {
661
+ // a deck held to its brand: every colour its slides write by hand is a palette colour
662
+ const off = [];
663
+ for (const node of descendants(tree)) {
664
+ const a = readAttrs(node.attrs);
665
+ const values = [...COLOUR_ATTRS.map((k) => a[k]).filter(Boolean), ...[...(a.style ?? '').matchAll(COLOUR_DECL)].map((m) => m[2])];
666
+ for (const v of values) {
667
+ for (const lit of String(v).match(LITERAL) ?? []) {
668
+ const n = nearestOf(hold, lit);
669
+ if (n && n.d > ON_PALETTE_DISTANCE && !off.some((o) => o.lit === lit)) off.push({ lit, near: n.ref });
670
+ }
671
+ }
672
+ }
673
+ if (off.length) {
674
+ push('off-palette-literal', `${off.slice(0, 3).map((o) => `${o.lit} (nearest ${o.near})`).join(', ')}${off.length > 3 ? ` and ${off.length - 3} more` : ''}`
675
+ + ` ${off.length === 1 ? 'is' : 'are'} not in the brand's palette — this deck keeps to it: pick a swatch in Colors…, or set "brandThemesOnly": false`);
676
+ }
677
+ }
678
+ // a design system's component class on a part plain markup already gets it on (SPEC DESIGN_SYSTEMS)
679
+ const plainWouldDo = [];
680
+ for (const [, sys] of systems) {
681
+ for (const node of descendants(tree)) {
682
+ const cls = String(readAttrs(node.attrs).class ?? '').split(/\s+/).filter(Boolean);
683
+ for (const c of cls) {
684
+ const tags = sys.components?.[c];
685
+ if (!tags?.length || plainWouldDo.some((x) => x.c === c)) continue;
686
+ plainWouldDo.push({ c, tag: node.tag, tags });
687
+ }
688
+ }
689
+ }
690
+ if (plainWouldDo.length) {
691
+ const say = ({ c, tag, tags }) => {
692
+ const part = { h1: 'title', h2: 'title', h3: 'title', ul: 'points', ol: 'points', blockquote: 'quote', table: 'table', pre: 'code', figcaption: 'caption' }[tags[0]];
693
+ return `<${tag} class="${c}">: a plain <${tags[0]}>${part ? ` (or a template's ${part} slot)` : ''} gets this component from the design system`;
694
+ };
695
+ out.push(finding('hint', 'ds-plain-markup', slide, head, `${plainWouldDo.map(say).join('; ')} — plain markup keeps the slide readable without it`));
696
+ }
697
+ if (attrs['data-template']) {
698
+ designSystemFindings(attrs['data-template'], tree, systems, configured.map((r) => r.ref),
699
+ (rule, message) => out.push(finding('warn', rule, slide, head, message)));
700
+ }
701
+ const segments = clickSegments(NOTES_ASIDE.exec(inner)?.[1]);
702
+ const steps = buildSteps(tree);
703
+ const clicks = buildClicks(tree);
704
+ // segments = clicks + 1, so a slide with one segment has no ⟨CLICK⟩ at all
705
+ // and is making no claim about the builds.
706
+ if (segments > 1 && segments - 1 !== clicks && !hasProvider(tree)) {
707
+ const tied = clicks !== steps ? ` (${steps} build steps, tied by data-build-order)` : '';
708
+ out.push(finding('warn', 'clicks-vs-builds', slide, head,
709
+ `${segments} [click] segment${segments === 1 ? '' : 's'} but ${clicks} build click${clicks === 1 ? '' : 's'}${tied}`
710
+ + ` — ${clicks} click${clicks === 1 ? '' : 's'} take${clicks === 1 ? 's' : ''} ${clicks} [click] marker${clicks === 1 ? '' : 's'}`
711
+ + ` in the notes (${clicks + 1} segments: one before the first click, one per click), and this slide has`
712
+ + ` ${segments - 1}, so the narration and the builds drift apart here`));
713
+ }
714
+
715
+
716
+ // A diagram that lands all at once (SVG_DIAGRAMS, BUILDS): a HINT per
717
+ // svg with no build on it or in it. A deliberate still says so with
718
+ // data-static-ok on the svg or the section.
719
+ if (!('data-static-ok' in attrs)) {
720
+ const still = diagramsIn(tree).filter((svg) => !diagramBuilds(svg) && !('data-static-ok' in readAttrs(svg.attrs)));
721
+ if (still.length) {
722
+ out.push(finding('hint', 'static-diagram', slide, head,
723
+ `${still.length === 1 ? 'an SVG diagram' : `${still.length} SVG diagrams`} with no build: ${still.length === 1 ? 'it lands' : 'they land'} all at once,`
724
+ + ' so the audience reads the whole picture before you have said its first part; reveal it in steps'
725
+ + ' (data-build="draw" on the svg, or data-build on the groups inside it, BUILDS), or mark it data-static-ok if it is meant'));
726
+ }
727
+ }
728
+ }
729
+
730
+ // An asset that is not on disk is the failure with no symptom: the deck
731
+ // renders, the image is a blank box, and whoever exported the PDF finds out
732
+ // afterwards. Resolved the way the browser would, against the deck's folder.
733
+ for (const ref of assetReferences(parseTree(src))) {
734
+ if (exists(resolve(dir, ref.path))) continue;
735
+ const where = at(ref.at);
736
+ out.push(finding('error', 'missing-asset', where.slide, where.title,
737
+ `missing asset: ${ref.value} — <${ref.tag} ${ref.attr}> points at nothing on disk`));
738
+ }
739
+
740
+ // The ingredients label (cli/audit.mjs), per item and per slide. A WARNING,
741
+ // not an error: a deck may legitimately carry its own script, and this
742
+ // command has no more standing than the label does to call that wrong — it
743
+ // says what will happen to it. `installed: null` keeps this half pure; the
744
+ // runtime hash is the label's business, not this one's.
745
+ const report = auditDeck(src, { installed: null });
746
+ for (const block of report.unaccounted) {
747
+ const where = at(block.start);
748
+ out.push(finding('warn', 'unaccounted-script', where.slide, where.title,
749
+ `line ${block.line}: unaccounted script block (${block.src ? `src=${block.src}` : `${block.bytes} B`})`
750
+ + ' — --no-trust --strict would strip this'));
751
+ }
752
+ for (const h of report.handlers) {
753
+ const where = at(h.start);
754
+ out.push(finding('warn', 'executable-attribute', where.slide, where.title,
755
+ `line ${h.line}: ${h.kind} on <${h.tag}> (${h.attr}) — --no-trust --strict would strip this`));
756
+ }
757
+
758
+ return sortFindings(out);
759
+ }
760
+
761
+ /** Head first, then slides in order; within a slide, the order they were found. */
762
+ const sortFindings = (findings) => findings
763
+ .map((f, i) => [f, i])
764
+ .sort((a, b) => (a[0].slide ?? 0) - (b[0].slide ?? 0) || a[1] - b[1])
765
+ .map(([f]) => f);
766
+
767
+ // ── B. the render half ───────────────────────────────────────────────────────
768
+
769
+ /**
770
+ * Everything only a browser can say, read back off one `--dump-dom` of the
771
+ * deck's `?print` view (SPEC PRESENTING): every slide rendered, every build
772
+ * complete, so a slide that only clips once its last build lands is measured
773
+ * like all the others.
774
+ *
775
+ * Pure over the dumped string. `slides` is what the FILE said, so the two
776
+ * counts can be compared — a runtime that never mounted produces a page whose
777
+ * sections are still there but whose measurements are all clean, which is the
778
+ * one failure that reads exactly like a healthy deck.
779
+ */
780
+ export function renderFindings(domHtml, { slides = 0 } = {}) {
781
+ const dom = String(domHtml ?? '');
782
+ const out = [];
783
+ const tags = [...dom.matchAll(/<section\b[^>]*>/g)];
784
+ const bodies = sectionBodies(dom);
785
+
786
+ if (slides && tags.length !== slides) {
787
+ out.push(finding('error', 'not-rendered', null, 'head',
788
+ `the deck did not render: ${slides} section${slides === 1 ? '' : 's'} in the file, `
789
+ + `${tags.length} on the page`));
790
+ }
791
+
792
+ // Labels that recur across slides in different colours (SVG_DIAGRAMS): the
793
+ // runtime stamps them on the root as it lays the print view out
794
+ // (concepts.js markConceptHints). A HINT: advice that never fails the run.
795
+ const hints = /data-concept-hints="([^"]*)"/.exec(dom)?.[1];
796
+ for (const entry of hints ? hints.replace(/&amp;/g, '&').split('|') : []) {
797
+ const [rawLabel, slideList, name, colours] = entry.split('~');
798
+ let label = rawLabel;
799
+ try { label = decodeURIComponent(rawLabel); } catch { /* shown as it came */ }
800
+ const at = String(slideList ?? '').split(',').map(Number).filter((n) => n > 0);
801
+ if (!label || !name || !at.length) continue;
802
+ const said = at.length === 1 ? `slide ${at[0]}` : `slides ${at.slice(0, -1).join(', ')} and ${at.at(-1)}`;
803
+ out.push(finding('hint', 'concept-suggestion', null, 'head',
804
+ `"${label}" is on ${said} in ${colours} colours — one idea, one colour: data-concept="${name}" on those shapes `
805
+ + '(or Concept colors… in the deck), SPEC SVG_DIAGRAMS'));
806
+ }
807
+
808
+ tags.forEach((m, i) => {
809
+ const slide = i + 1; // print never re-orders: position IS the slide number
810
+ const head = slideHeading(sectionInner(bodies[i] ?? ''), i);
811
+ const attrs = readAttrs(m[0].slice('<section'.length).replace(/>$/, ''));
812
+ if ('data-overflow' in attrs) {
813
+ // The guardrail is a boolean today (engine.js `checkOverflow` toggles the
814
+ // attribute), so the px figure is reported only if a future one writes it
815
+ // — better than printing a number this file made up.
816
+ const by = Number(attrs['data-overflow-by']);
817
+ out.push(finding('error', 'overflow', slide, head,
818
+ Number.isFinite(by) && by > 0
819
+ ? `content is clipped (${Math.round(by)} px over)`
820
+ : 'content is clipped — it does not fit the slide, and the audience never sees the rest'));
821
+ }
822
+ // crowded past SLIDE_DENSITY: the runtime counts it as it lays the deck
823
+ // out (src/core/density.js) and marks the section, like data-overflow
824
+ if (attrs['data-dense']) {
825
+ out.push(finding('warn', 'dense', slide, head,
826
+ `crowded: ${attrs['data-dense']} (~3–4 bullets or ~2 short paragraphs per column, SPEC SLIDE_DENSITY)`
827
+ + ' — split the slide rather than shrink it, or mark it data-dense-ok if it is meant'));
828
+ }
829
+ if ('data-split-conflict' in attrs) {
830
+ out.push(finding('warn', 'split-conflict', slide, head,
831
+ 'data-layout="split" is fighting this slide\'s own column flexbox — two layout systems, '
832
+ + 'drop one (SPEC COMPARISON_SLIDES)'));
833
+ }
834
+ // data-markdown-removed is deliberately not reported here: the static half
835
+ // already names that slide from the file, and saying it twice would make a
836
+ // machine with Chrome disagree with one without about how many findings a
837
+ // deck has.
838
+ });
839
+
840
+ return sortFindings(out);
841
+ }
842
+
843
+ // ── output ───────────────────────────────────────────────────────────────────
844
+
845
+ /**
846
+ * The findings as lines, grouped by slide. Pure, and marks are words rather
847
+ * than colours or symbols, so a CI log and a terminal read the same.
848
+ */
849
+ export function formatFindings(findings, { color = false, slides = 0 } = {}) {
850
+ const RED = '\x1b[31m', YELLOW = '\x1b[33m', BOLD = '\x1b[1m', DIM = '\x1b[2m', RESET = '\x1b[0m';
851
+ const paint = (s, c) => (color ? `${c}${s}${RESET}` : s);
852
+ const errors = findings.filter((f) => f.level === 'error').length;
853
+ const hints = findings.filter((f) => f.level === 'hint').length;
854
+ const warnings = findings.length - errors - hints;
855
+ if (!findings.length) return [`no findings — ${slides} slide${slides === 1 ? '' : 's'} checked`];
856
+
857
+ const groups = new Map();
858
+ for (const f of sortFindings(findings)) {
859
+ const key = f.slide ?? 0;
860
+ if (!groups.has(key)) groups.set(key, []);
861
+ groups.get(key).push(f);
862
+ }
863
+
864
+ const lines = [];
865
+ for (const [slide, list] of groups) {
866
+ // `slideHeading` falls back to the slide's own number when a slide has no
867
+ // heading and no words to borrow — printing that back as `slide 5 "slide 5"`
868
+ // says nothing twice, so the quoted half is dropped instead.
869
+ const title = list.find((f) => f.title)?.title ?? '';
870
+ const named = title && title !== `slide ${slide}`;
871
+ lines.push(slide === 0
872
+ ? paint('head', BOLD)
873
+ : paint(`slide ${slide}`, BOLD) + (named ? ` ${paint(`"${title}"`, DIM)}` : ''));
874
+ for (const f of list) {
875
+ lines.push(` ${f.level === 'error' ? paint('error', RED) : f.level === 'hint' ? paint('hint ', DIM) : paint('warn ', YELLOW)} ${f.message}`);
876
+ }
877
+ lines.push('');
878
+ }
879
+ lines.push(`${errors} error${errors === 1 ? '' : 's'}, ${warnings} warning${warnings === 1 ? '' : 's'}`
880
+ + (hints ? `, ${hints} hint${hints === 1 ? '' : 's'}` : ''));
881
+ return lines;
882
+ }
883
+
884
+ const USAGE = `usage: decklight check <deck.html> [--no-render] [--json] [--wait <ms>]
885
+ lints one deck and says, per slide, what you would otherwise only find by
886
+ looking — for an AI agent after every edit, and for a human before a talk
887
+
888
+ what it reports
889
+ from the file a <section> that is never closed · an image, video, cast
890
+ or stylesheet that is not on disk · a data-markdown slide
891
+ (removed in 0.3.0) · [click] segments that do not line up
892
+ with the slide's build steps · script blocks and inline
893
+ handlers --no-trust --strict would strip
894
+ from a render slides the overflow guardrail measured as clipped, slides
895
+ crowded past SLIDE_DENSITY (~3–4 bullets or ~2 short
896
+ paragraphs per column; a warning, and data-dense-ok on a
897
+ section says it is meant), split layouts fighting their
898
+ own flexbox, and a deck whose runtime never mounted
899
+ hints the same words on boxes on several slides in different
900
+ colours: one idea, worth one concept (SVG_DIAGRAMS) · an
901
+ SVG diagram with no build, landing all at once
902
+ (data-static-ok says it is meant)
903
+
904
+ --no-render the file half only — no Chrome, no render (a machine without
905
+ Chrome skips that half by itself, and says so)
906
+ --json the findings as a JSON array: level, rule, slide, title, message
907
+ --wait <ms> render budget for heavy decks [8000]
908
+
909
+ exit 1 if anything is an error, 0 otherwise — warnings and hints never fail the run`;
910
+
911
+ export async function checkMain(args = []) {
912
+ if (args.includes('--help') || args.includes('-h')) { console.log(USAGE); return 0; }
913
+ const { opt } = argReader(args);
914
+ const deck = firstPositional(args, ['--wait']);
915
+ if (!deck) { console.error(`decklight check: needs a deck\n\n${USAGE}`); return 1; }
916
+ const src = resolve(deck);
917
+ if (!existsSync(src)) { console.error(`decklight check: no such deck: ${deck}`); return 1; }
918
+
919
+ const html = readFileSync(src, 'utf8');
920
+ const slides = sectionBodies(html).length;
921
+ const findings = staticFindings(html, { dir: dirname(src) });
922
+
923
+ // The render half is skipped rather than failed when there is no browser:
924
+ // `findChrome` and never `chromeBin`, which exits the process — half a lint
925
+ // is the useful answer on a machine that cannot run the other half.
926
+ const json = args.includes('--json');
927
+ const bin = args.includes('--no-render') ? null : findChrome();
928
+ const notes = [];
929
+ if (args.includes('--no-render')) notes.push('check: --no-render — the file half only, nothing was rendered');
930
+ else if (!bin) notes.push('check: no Chrome found — the file half only; clipped slides go unreported (point $CHROME at one)');
931
+
932
+ if (bin) {
933
+ const wait = Number(opt('--wait', 8000));
934
+ try {
935
+ const dom = await runAsync(bin, [
936
+ ...chromeArgs('--allow-file-access-from-files', `--virtual-time-budget=${wait}`),
937
+ '--dump-dom', printUrl(src),
938
+ ], {
939
+ encoding: 'utf8', maxBuffer: 64 * 1024 * 1024, timeout: CODEC_MS,
940
+ why: 'Chrome did not finish rendering — a slide is probably waiting on a resource it cannot reach',
941
+ });
942
+ findings.push(...renderFindings(dom, { slides }));
943
+ } catch (e) {
944
+ findings.push(finding('error', 'render-failed', null, 'head',
945
+ `the deck could not be rendered — ${String(e.message ?? e).split('\n')[0]}`));
946
+ }
947
+ }
948
+
949
+ const ordered = sortFindings(findings);
950
+ const errors = ordered.filter((f) => f.level === 'error').length;
951
+ if (json) {
952
+ console.log(JSON.stringify(ordered, null, 2));
953
+ } else {
954
+ for (const note of notes) console.error(note);
955
+ console.error(`check: ${basename(src)} — ${slides} slide${slides === 1 ? '' : 's'}`);
956
+ console.log(formatFindings(ordered, { color: !!process.stdout.isTTY, slides }).join('\n'));
957
+ }
958
+ return errors ? 1 : 0;
959
+ }
960
+
961
+ if (isMain(import.meta.url)) process.exit(await runMain('check', () => checkMain(process.argv.slice(2))));