decklight 0.2.0 → 0.4.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 (137) hide show
  1. package/README.md +69 -31
  2. package/SPEC.md +881 -80
  3. package/cli/agents.mjs +116 -10
  4. package/cli/associate.mjs +286 -0
  5. package/cli/audit.mjs +424 -0
  6. package/cli/bundle.mjs +174 -46
  7. package/cli/deckfile.mjs +233 -0
  8. package/cli/decklight.mjs +201 -8
  9. package/cli/dev.mjs +244 -55
  10. package/cli/edit.mjs +577 -107
  11. package/cli/extension.mjs +108 -0
  12. package/cli/git.mjs +141 -0
  13. package/cli/import.mjs +398 -0
  14. package/cli/init.mjs +421 -116
  15. package/cli/loader.mjs +263 -0
  16. package/cli/marketplace.mjs +911 -0
  17. package/cli/pdf.mjs +156 -0
  18. package/cli/pkg.mjs +69 -0
  19. package/cli/plugin.mjs +654 -0
  20. package/cli/port-conflict.mjs +94 -0
  21. package/cli/present.mjs +564 -0
  22. package/cli/publish.mjs +342 -0
  23. package/cli/qr.mjs +334 -0
  24. package/cli/rec.mjs +5 -8
  25. package/cli/remote.mjs +149 -0
  26. package/cli/report-bug.mjs +97 -0
  27. package/cli/restore.mjs +174 -0
  28. package/cli/serve.mjs +247 -0
  29. package/cli/sign.mjs +216 -0
  30. package/cli/skill-content.mjs +222 -0
  31. package/cli/skills.mjs +338 -0
  32. package/cli/supervise.mjs +57 -0
  33. package/cli/theme.mjs +219 -0
  34. package/cli/units.mjs +500 -0
  35. package/cli/upgrade.mjs +250 -0
  36. package/cli/util.mjs +90 -0
  37. package/cli/wizard.mjs +432 -0
  38. package/cli/zip.mjs +121 -0
  39. package/dist/decklight.css +716 -29
  40. package/dist/decklight.js +198 -125
  41. package/dist/decklight.js.map +4 -4
  42. package/docs/architecture.svg +1 -1
  43. package/package.json +7 -5
  44. package/themes/README.md +6 -4
  45. package/themes/aurora.css +1 -1
  46. package/themes/berry.css +1 -1
  47. package/themes/carbon.css +1 -1
  48. package/themes/citrus.css +1 -1
  49. package/themes/coastal.css +1 -1
  50. package/themes/cosmos.css +1 -1
  51. package/themes/dune.css +1 -1
  52. package/themes/eclipse.css +1 -1
  53. package/themes/ember.css +1 -1
  54. package/themes/fjord.css +1 -1
  55. package/themes/gallery.html +3 -11
  56. package/themes/glacier.css +1 -1
  57. package/themes/graphite.css +1 -1
  58. package/themes/harvest.css +1 -1
  59. package/themes/ibm-modern.css +1 -1
  60. package/themes/ink.css +1 -1
  61. package/themes/latte.css +1 -1
  62. package/themes/linen.css +1 -1
  63. package/themes/meadow.css +1 -1
  64. package/themes/metropolis.css +1 -1
  65. package/themes/midnight.css +1 -1
  66. package/themes/mint.css +1 -1
  67. package/themes/moss.css +1 -1
  68. package/themes/obsidian.css +1 -1
  69. package/themes/orchid.css +1 -1
  70. package/themes/packs.json +2 -30
  71. package/themes/paper.css +1 -1
  72. package/themes/peony.css +1 -1
  73. package/themes/porcelain.css +1 -1
  74. package/themes/reveal-beige.css +1 -1
  75. package/themes/reveal-black.css +1 -1
  76. package/themes/reveal-blood.css +1 -1
  77. package/themes/reveal-dracula.css +1 -1
  78. package/themes/reveal-league.css +1 -1
  79. package/themes/reveal-moon.css +1 -1
  80. package/themes/reveal-night.css +1 -1
  81. package/themes/reveal-serif.css +1 -1
  82. package/themes/reveal-simple.css +1 -1
  83. package/themes/reveal-sky.css +1 -1
  84. package/themes/reveal-solarized.css +1 -1
  85. package/themes/reveal-white.css +1 -1
  86. package/themes/sepia.css +1 -1
  87. package/themes/seriph.css +1 -1
  88. package/themes/slate.css +1 -1
  89. package/themes/storm.css +1 -1
  90. package/themes/synthwave.css +1 -1
  91. package/themes/velvet.css +1 -1
  92. package/themes/yamabuki.css +1 -1
  93. package/tools/args.mjs +32 -0
  94. package/tools/bridge.mjs +30 -0
  95. package/tools/chrome.mjs +46 -11
  96. package/tools/color.mjs +110 -0
  97. package/tools/deck-html.mjs +138 -0
  98. package/tools/elevenlabs-tts.mjs +248 -0
  99. package/tools/escape.mjs +40 -0
  100. package/tools/extension-check-runner.mjs +41 -0
  101. package/tools/extension-check.mjs +266 -0
  102. package/tools/gemini-tts.mjs +25 -3
  103. package/tools/lipsync-engines.mjs +81 -0
  104. package/tools/lipsync-server.mjs +78 -37
  105. package/tools/lipsync.mjs +36 -21
  106. package/tools/local-voice.mjs +209 -0
  107. package/tools/ooxml.mjs +151 -0
  108. package/tools/pptx.mjs +320 -0
  109. package/tools/publish-site-voices.mjs +2 -1
  110. package/tools/publish-targets.mjs +143 -0
  111. package/tools/publish-voices.mjs +230 -0
  112. package/tools/shot.mjs +91 -47
  113. package/tools/theme-check.mjs +144 -0
  114. package/tools/tts-engines.mjs +270 -41
  115. package/tools/tts-setup.mjs +257 -0
  116. package/tools/veo.mjs +204 -0
  117. package/tools/video.mjs +440 -0
  118. package/tools/voiceover-server.mjs +163 -54
  119. package/tools/voiceover.mjs +24 -7
  120. package/tools/zip.mjs +143 -0
  121. package/docs/demo.svg +0 -124
  122. package/themes/aliens.css +0 -87
  123. package/themes/apple2.css +0 -129
  124. package/themes/blade-runner.css +0 -86
  125. package/themes/c64.css +0 -88
  126. package/themes/friends.css +0 -85
  127. package/themes/gameboy.css +0 -121
  128. package/themes/genesis.css +0 -87
  129. package/themes/godfather.css +0 -85
  130. package/themes/ibm-oldschool.css +0 -87
  131. package/themes/miami-vice.css +0 -87
  132. package/themes/pulp-fiction.css +0 -87
  133. package/themes/severance.css +0 -85
  134. package/themes/snes.css +0 -85
  135. package/themes/star-wars.css +0 -88
  136. package/themes/stranger-things.css +0 -87
  137. package/themes/terminator.css +0 -87
@@ -0,0 +1,230 @@
1
+ #!/usr/bin/env node
2
+ // Copyright 2026 Gilles Philippart
3
+ // SPDX-License-Identifier: Apache-2.0
4
+
5
+ // Put a recorded voice track in a bucket and sign it, so the megabytes of
6
+ // audio stop travelling with the deck.
7
+ //
8
+ // node tools/publish-voices.mjs voices/algenib \
9
+ // --bucket gs://decklight-voices/showcase --sign 7d
10
+ //
11
+ // What ships next to the deck afterwards is manifest.signed.json — a few KB of
12
+ // JSON naming one URL per slide. The runtime plays those URLs verbatim, which
13
+ // is the entire reason this exists: a presigned URL carries its signature in
14
+ // the query string, and the older `dir:` form has nowhere to put one. A PUBLIC
15
+ // bucket never needed this and still doesn't (`dir: 'https://storage.googleapis.com/…'`
16
+ // has always worked) — signing is for audio that should not be world-readable.
17
+ //
18
+ // Signing is `gcloud storage sign-url`, not our own node:crypto. V4 signing is
19
+ // twenty lines, but it means a service-account private key passing through a
20
+ // repo tool; gcloud already owns those credentials and should keep owning them.
21
+ // Same posture as tools/publish-site-voices.mjs shelling out to `gh`.
22
+
23
+ import { execFileSync } from 'node:child_process';
24
+ import { existsSync, readFileSync, writeFileSync, statSync } from 'node:fs';
25
+ import { basename, join, resolve } from 'node:path';
26
+ import { argReader, isMain } from './args.mjs';
27
+
28
+ const USAGE = `usage: node tools/publish-voices.mjs <voice-dir> --bucket gs://bucket/prefix [--sign 7d]
29
+ uploads a recorded track's audio to Cloud Storage and writes a manifest of
30
+ per-slide URLs to deploy next to the deck
31
+
32
+ --bucket gs://… destination; the track's own folder name is appended
33
+ --sign <dur> mint V4 signed URLs valid this long (max 7d, the V4 cap)
34
+ omit for a public bucket — plain object URLs, no expiry
35
+ --all re-upload every file, not just the ones whose hash moved
36
+ --dry-run print what would happen; touch nothing
37
+
38
+ needs gcloud on PATH, authenticated for the bucket`;
39
+
40
+ /** GCS caps V4 signatures at seven days. Not our rule, but ours to enforce. */
41
+ export const V4_MAX_SECONDS = 7 * 24 * 3600;
42
+
43
+ const VALUE_FLAGS = new Set(['--bucket', '--sign']);
44
+
45
+ /**
46
+ * The bare words in argv — the voice directory, here. Skipping each value
47
+ * flag's argument by name is what keeps `--sign 7d` from being mistaken for a
48
+ * directory called `7d`.
49
+ */
50
+ export function positional(argv) {
51
+ const out = [];
52
+ for (let i = 0; i < argv.length; i += 1) {
53
+ if (VALUE_FLAGS.has(argv[i])) { i += 1; continue; }
54
+ if (argv[i].startsWith('-')) continue;
55
+ out.push(argv[i]);
56
+ }
57
+ return out;
58
+ }
59
+
60
+ /**
61
+ * `7d`, `12h`, `30m`, `3600s`, or bare seconds → seconds.
62
+ * Returns null for anything else, so a typo is a message and not a surprise.
63
+ */
64
+ export function parseDuration(text) {
65
+ const m = /^(\d+(?:\.\d+)?)\s*([smhd]?)$/.exec(String(text ?? '').trim());
66
+ if (!m) return null;
67
+ const n = Number(m[1]);
68
+ if (!(n > 0)) return null;
69
+ return Math.round(n * ({ s: 1, m: 60, h: 3600, d: 86400 }[m[2]] ?? 1));
70
+ }
71
+
72
+ /**
73
+ * Split `gs://bucket/some/prefix` into its parts. A destination that is not a
74
+ * gs:// URL is worth catching here rather than inside gcloud's error text.
75
+ */
76
+ export function parseBucket(dest) {
77
+ const m = /^gs:\/\/([a-z0-9][a-z0-9._-]*)(?:\/(.*))?$/i.exec(String(dest ?? '').trim());
78
+ if (!m) return null;
79
+ return { bucket: m[1], prefix: (m[2] ?? '').replace(/\/+$/, '') };
80
+ }
81
+
82
+ /** The gs:// path a track's files live under — the dir's own name, appended. */
83
+ export const trackPrefix = ({ bucket, prefix }, dirName) =>
84
+ `gs://${bucket}/${[prefix, dirName].filter(Boolean).join('/')}`;
85
+
86
+ /**
87
+ * Which files this run has to upload.
88
+ *
89
+ * The track's manifest already carries a content hash per slide — that is how
90
+ * the pre-render tool skips regenerating unchanged audio — so a previous
91
+ * manifest.signed.json is a record of exactly which bytes are already up
92
+ * there. No bucket listing, no re-hashing: files whose hash moved, plus any
93
+ * the last publish never saw.
94
+ */
95
+ export function changedFiles(manifest, previous, { all = false } = {}) {
96
+ const was = new Map((previous?.slides ?? []).filter(Boolean).map((s) => [s.file, s.hash]));
97
+ return (manifest?.slides ?? [])
98
+ .filter(Boolean)
99
+ .filter((s) => all || was.get(s.file) !== s.hash);
100
+ }
101
+
102
+ /**
103
+ * The manifest that ships with the deck: the source manifest, plus a URL per
104
+ * slide and the facts a lapsed deck needs to name its own fix.
105
+ */
106
+ export function signedManifest(manifest, {
107
+ urls, expires, source, bucket, signDuration,
108
+ }) {
109
+ return {
110
+ ...manifest,
111
+ ...(expires ? { expires } : {}),
112
+ source,
113
+ bucket,
114
+ ...(signDuration ? { signDuration } : {}),
115
+ slides: (manifest.slides ?? []).map((s) => (s ? { ...s, url: urls.get(s.file) ?? s.url } : null)),
116
+ };
117
+ }
118
+
119
+ /**
120
+ * `gcloud storage sign-url --format=json` has answered with a bare object and
121
+ * with a list across versions, and has spelled the field both ways. Read all
122
+ * of them rather than pinning a gcloud release.
123
+ */
124
+ export function signedUrlFrom(json) {
125
+ const one = Array.isArray(json) ? json[0] : json;
126
+ return one?.signed_url ?? one?.signedUrl ?? one?.signed_uri ?? null;
127
+ }
128
+
129
+ const gcloud = (argv) => execFileSync('gcloud', argv, { encoding: 'utf8', maxBuffer: 1 << 26 });
130
+
131
+ export async function publishVoicesMain(args = []) {
132
+ if (!args.length || args.includes('--help') || args.includes('-h')) { console.log(USAGE); return args.length ? 0 : 1; }
133
+ const { opt } = argReader(args);
134
+ const [dir] = positional(args);
135
+ if (!dir) { console.error(`publish-voices: needs a voice directory\n\n${USAGE}`); return 1; }
136
+ const src = resolve(dir);
137
+ const manifestPath = join(src, 'manifest.json');
138
+ if (!existsSync(manifestPath)) {
139
+ console.error(`publish-voices: ${dir}/manifest.json not found`);
140
+ console.error(' generate the track first: node tools/voiceover.mjs deck.html --engine gemini -o ' + dir);
141
+ return 1;
142
+ }
143
+
144
+ const dest = parseBucket(opt('--bucket'));
145
+ if (!dest) { console.error(`publish-voices: --bucket must be a gs:// URL\n\n${USAGE}`); return 1; }
146
+
147
+ const signArg = opt('--sign');
148
+ let signSeconds = null;
149
+ if (args.includes('--sign') && (signArg === undefined || signArg.startsWith('-'))) {
150
+ console.error(`publish-voices: --sign needs a duration (try 7d)\n\n${USAGE}`);
151
+ return 1;
152
+ }
153
+ if (signArg !== undefined) {
154
+ signSeconds = parseDuration(signArg);
155
+ if (signSeconds === null) {
156
+ console.error(`publish-voices: --sign ${signArg} is not a duration (try 7d, 12h, 30m)`);
157
+ return 1;
158
+ }
159
+ if (signSeconds > V4_MAX_SECONDS) {
160
+ console.error(`publish-voices: --sign ${signArg} is longer than 7d`);
161
+ console.error(' V4 signatures cannot outlive seven days — that is the signing scheme\'s own');
162
+ console.error(' limit, not ours. For audio that must stay reachable indefinitely, use a');
163
+ console.error(' public bucket and point the deck at it with dir: instead of signing.');
164
+ return 1;
165
+ }
166
+ }
167
+
168
+ const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'));
169
+ const outPath = join(src, 'manifest.signed.json');
170
+ let previous = null;
171
+ try { previous = JSON.parse(readFileSync(outPath, 'utf8')); } catch { /* first publish */ }
172
+
173
+ const dirName = basename(src);
174
+ const at = trackPrefix(dest, dirName);
175
+ const dry = args.includes('--dry-run');
176
+ const changed = changedFiles(manifest, previous, { all: args.includes('--all') });
177
+ const missing = changed.filter((s) => !existsSync(join(src, s.file)));
178
+ if (missing.length) {
179
+ console.error(`publish-voices: ${missing.length} file(s) in the manifest are not on disk:`);
180
+ for (const s of missing.slice(0, 5)) console.error(` ${s.file}`);
181
+ console.error(' regenerate the track, or delete manifest.json to start clean');
182
+ return 1;
183
+ }
184
+
185
+ if (!changed.length) console.log(`nothing to upload — every slide's audio is already at ${at}`);
186
+ else {
187
+ const bytes = changed.reduce((n, s) => n + statSync(join(src, s.file)).size, 0);
188
+ console.log(`${dry ? 'would upload' : 'uploading'} ${changed.length} changed file(s)`
189
+ + ` (${(bytes / 1048576).toFixed(1)} MB) → ${at}`);
190
+ if (!dry) {
191
+ for (const s of changed) gcloud(['storage', 'cp', join(src, s.file), `${at}/${s.file}`]);
192
+ }
193
+ }
194
+
195
+ // EVERY slide is signed, not only the changed ones: signatures expire on
196
+ // their own schedule, so a re-sign that skipped the untouched files would
197
+ // publish a manifest where most slides had already lapsed.
198
+ const all = (manifest.slides ?? []).filter(Boolean);
199
+ const urls = new Map();
200
+ let expires = null;
201
+ if (signSeconds === null) {
202
+ for (const s of all) urls.set(s.file, `https://storage.googleapis.com/${dest.bucket}/${[dest.prefix, dirName, s.file].filter(Boolean).join('/')}`);
203
+ console.log(`wrote ${all.length} public URL(s) — no signature, no expiry`);
204
+ } else if (dry) {
205
+ console.log(`would sign ${all.length} slide URL(s) for ${signArg}`);
206
+ } else {
207
+ for (const s of all) {
208
+ const out = gcloud(['storage', 'sign-url', `${at}/${s.file}`,
209
+ `--duration=${signSeconds}s`, '--format=json']);
210
+ const url = signedUrlFrom(JSON.parse(out));
211
+ if (!url) { console.error(`publish-voices: gcloud signed nothing for ${s.file}`); return 1; }
212
+ urls.set(s.file, url);
213
+ }
214
+ expires = new Date(Date.now() + signSeconds * 1000).toISOString();
215
+ console.log(`signed ${all.length} slide URL(s) · valid until ${expires}`
216
+ + (signSeconds === V4_MAX_SECONDS ? ' (7 days — the V4 maximum)' : ''));
217
+ }
218
+
219
+ if (dry) { console.log(`would write ${outPath}`); return 0; }
220
+ const out = signedManifest(manifest, {
221
+ urls, expires, source: dir, bucket: opt('--bucket'),
222
+ signDuration: signSeconds === null ? null : signArg,
223
+ });
224
+ writeFileSync(outPath, JSON.stringify(out, null, 1));
225
+ console.log(`wrote ${outPath} — deploy it next to the deck`);
226
+ console.log(` narration: { files: [{ label: '${manifest.voice ?? dirName}', manifest: '${dir}/manifest.signed.json' }] }`);
227
+ return 0;
228
+ }
229
+
230
+ if (isMain(import.meta.url)) process.exit(await publishVoicesMain(process.argv.slice(2)));
package/tools/shot.mjs CHANGED
@@ -7,6 +7,7 @@
7
7
  // node tools/shot.mjs <deck.html> -o shot.png
8
8
  // [--size 1280x720] [--wait 1500] [--theme eclipse]
9
9
  // [--slide N] [--drive <file.mjs>] [--keys "g,ArrowRight"]
10
+ // [--query "print=handout"]
10
11
  //
11
12
  // --drive runs a snippet INSIDE the page after Decklight.init, so a feature can
12
13
  // be exercised before the shutter: the deck is on `window.__deck`, and `press(k)`
@@ -16,70 +17,113 @@
16
17
  // // shots/solo.mjs
17
18
  // press('/'); for (const c of 'solo') press(c); await sleep(100); press('Enter');
18
19
  //
20
+ // The deck is served over http://127.0.0.1 under the `present` CSP — NOT opened
21
+ // over file:// with --allow-file-access-from-files (#229). That flag let a
22
+ // deck's own JS read any local file it could name (.git/config, tokens, keys)
23
+ // and exfiltrate it, and shot runs on decks you have not vetted — a repro deck
24
+ // off an issue, or one you screenshot before presenting it. An http origin
25
+ // cannot touch file://, and the read is confined to the served directory.
26
+ //
19
27
  // Headless Chrome renders it; no puppeteer, no node_modules, nothing to install
20
28
  // that CI does not already have.
21
29
 
22
- import { execFileSync } from 'node:child_process';
23
- import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
24
- import { dirname, resolve } from 'node:path';
30
+ import { execFile } from 'node:child_process';
31
+ import { existsSync, mkdirSync, readFileSync } from 'node:fs';
32
+ import { dirname, relative, resolve, sep } from 'node:path';
33
+ import { promisify } from 'node:util';
25
34
  import { chromeBin, chromeArgs } from './chrome.mjs';
35
+ import { argReader, isMain } from './args.mjs';
36
+ import { injectBeforeBodyEnd } from './deck-html.mjs';
37
+ import { serveForRender } from '../cli/present.mjs';
38
+
39
+ const run = promisify(execFile);
40
+
41
+ const USAGE = 'usage: shot.mjs <deck.html> -o shot.png [--size 1280x720] [--wait 1500]'
42
+ + ' [--theme name] [--slide N] [--drive file.mjs] [--keys "a,b"] [--query "print=handout"]';
26
43
 
27
- const args = process.argv.slice(2);
28
- const opt = (flag, dflt) => { const i = args.indexOf(flag); return i >= 0 ? args[i + 1] : dflt; };
29
- const page = args.find((a) => !a.startsWith('-') && /\.html?$/i.test(a));
30
- if (!page || args.includes('--help')) {
31
- console.error('usage: shot.mjs <deck.html> -o shot.png [--size 1280x720] [--wait 1500]'
32
- + ' [--theme name] [--slide N] [--drive file.mjs] [--keys "a,b"]');
33
- process.exit(page ? 0 : 1);
44
+ // The default renderer: one async headless Chrome. Async is not incidental —
45
+ // the deck is served by an in-process server (serveForRender), and a SYNC child
46
+ // (execFileSync) would block the event loop so that server never answers.
47
+ // Injectable so a test can capture the argv without launching a browser.
48
+ async function chromeShot(bin, chromeArgv) {
49
+ await run(bin, chromeArgv, { maxBuffer: 32 * 1024 * 1024 });
34
50
  }
35
51
 
52
+ export async function shotMain(argv, { render = chromeShot } = {}) {
53
+ const { opt } = argReader(argv);
54
+ const page = argv.find((a) => !a.startsWith('-') && /\.html?$/i.test(a));
55
+ if (!page || argv.includes('--help')) {
56
+ console.error(USAGE);
57
+ process.exit(page ? 0 : 1);
58
+ }
36
59
 
37
- const out = resolve(opt('-o', 'shot.png'));
38
- const size = opt('--size', '1280x720');
39
- const wait = Number(opt('--wait', 1500));
40
- const theme = opt('--theme');
41
- const slide = opt('--slide');
42
- const keys = (opt('--keys') ?? '').split(',').map((k) => k.trim()).filter(Boolean);
43
- const drive = opt('--drive');
60
+ const out = resolve(opt('-o', 'shot.png'));
61
+ const size = opt('--size', '1280x720');
62
+ const wait = Number(opt('--wait', 1500));
63
+ const theme = opt('--theme');
64
+ const slide = opt('--slide');
65
+ const keys = (opt('--keys') ?? '').split(',').map((k) => k.trim()).filter(Boolean);
66
+ const drive = opt('--drive');
67
+ const query = opt('--query'); // deck URL query string, e.g. "print=handout"
44
68
 
45
- // The driver runs in the page, so the shot can show a FEATURE and not just a
46
- // title card. Injected by writing a sibling copy of the deck — a sibling so that
47
- // every relative href in it (dist/, themes/, voices/) still resolves.
48
- const src = resolve(page);
49
- const driver = drive ? readFileSync(resolve(drive), 'utf8') : '';
50
- const boot = `
69
+ // The served root is the directory you run from — the deck must sit inside it,
70
+ // so a source deck's `../dist/decklight.js` and `themes/…` still resolve as
71
+ // relative URLs off the loopback origin. This is exactly `present`'s rule and
72
+ // for the same reason: exposure is chosen by where you run the command, and a
73
+ // read cannot escape the served tree. `cd` to a directory containing the deck.
74
+ const root = process.cwd();
75
+ const src = resolve(page);
76
+ if (!existsSync(src)) { console.error(`shot: no such deck: ${src}`); process.exit(1); }
77
+ if (src !== root && !src.startsWith(root + sep)) {
78
+ console.error(`shot: the deck must live under the current directory (${root}) — cd there first`);
79
+ process.exit(1);
80
+ }
81
+
82
+ // The driver runs in the page, so the shot can show a FEATURE and not just a
83
+ // title card. Injected into the deck's response in memory (no temp file): the
84
+ // deck is served at its own path, so every relative href in it still resolves.
85
+ const driver = drive ? readFileSync(resolve(drive), 'utf8') : '';
86
+ const boot = `
51
87
  <script type="module">
52
88
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
53
89
  const press = (k, opts = {}) => document.body.dispatchEvent(
54
90
  new KeyboardEvent('keydown', { key: k, bubbles: true, cancelable: true, ...opts }));
55
- window.__deck = window.Decklight?.instances?.[0] ?? window.__decklight ?? null;
91
+ window.__deck = window.Decklight?.instances?.[0] ?? window.__decklight
92
+ ?? document.querySelector('.decklight')?.__decklight ?? null;
56
93
  ${keys.length ? `for (const k of ${JSON.stringify(keys)}) { press(k); await sleep(120); }` : ''}
57
94
  ${driver}
58
95
  </script>`;
59
96
 
60
- const tmp = src.replace(/\.html?$/i, `.__shot-${process.pid}.html`);
61
- let html = readFileSync(src, 'utf8');
62
- if (theme) html = html.replace(/(<\/head>)/i, `<link rel="stylesheet" href="themes/${theme}.css">$1`);
63
- html = html.replace(/(<\/body>)/i, `${boot}$1`);
64
- writeFileSync(tmp, html);
97
+ // Only the deck itself gets the theme link and the driver; every other html
98
+ // asset under the root is served untouched.
99
+ const inject = (text, file) => {
100
+ if (file !== src) return text;
101
+ let h = theme ? text.replace(/(<\/head>)/i, `<link rel="stylesheet" href="themes/${theme}.css">$1`) : text;
102
+ return injectBeforeBodyEnd(h, boot) ?? h + boot;
103
+ };
65
104
 
66
- mkdirSync(dirname(out), { recursive: true });
67
- try {
68
- execFileSync(chromeBin('shot'), chromeArgs(
69
- '--hide-scrollbars',
70
- '--allow-file-access-from-files',
71
- '--autoplay-policy=no-user-gesture-required',
72
- `--window-size=${size.replace('x', ',')}`,
73
- `--virtual-time-budget=${wait}`,
74
- `--screenshot=${out}`,
75
- `file://${tmp}${slide ? `#/${slide}/0` : ''}`,
76
- ), { stdio: ['ignore', 'ignore', 'ignore'] });
77
- } finally {
78
- rmSync(tmp, { force: true });
79
- }
105
+ mkdirSync(dirname(out), { recursive: true });
106
+ const server = await serveForRender(root, { html: inject });
107
+ try {
108
+ const deckPath = '/' + relative(root, src).split(sep).join('/');
109
+ const url = `${server.origin}${deckPath}${query ? `?${query}` : ''}${slide ? `#/${slide}/0` : ''}`;
110
+ await render(chromeBin('shot'), chromeArgs(
111
+ '--hide-scrollbars',
112
+ '--autoplay-policy=no-user-gesture-required',
113
+ `--window-size=${size.replace('x', ',')}`,
114
+ `--virtual-time-budget=${wait}`,
115
+ `--screenshot=${out}`,
116
+ url,
117
+ ), { out, size, wait, url });
118
+ } finally {
119
+ await server.close();
120
+ }
80
121
 
81
- if (!existsSync(out)) {
82
- console.error('shot: chrome produced no image');
83
- process.exit(1);
122
+ if (!existsSync(out)) {
123
+ console.error('shot: chrome produced no image');
124
+ process.exit(1);
125
+ }
126
+ console.log(`${out} (${(Buffer.byteLength(readFileSync(out)) / 1024).toFixed(0)} KB)`);
84
127
  }
85
- console.log(`${out} (${(Buffer.byteLength(readFileSync(out)) / 1024).toFixed(0)} KB)`);
128
+
129
+ if (isMain(import.meta.url)) await shotMain(process.argv.slice(2));
@@ -0,0 +1,144 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ // The theme contract, as a function.
5
+ //
6
+ // A Decklight theme is one CSS file declaring the SPEC THEMING tokens, and whether
7
+ // a given file IS one has always been decidable — test/contrast.mjs has
8
+ // decided it for the 65 shipped themes since the beginning. What it could not
9
+ // do is answer the question for anybody else's file: `test/` does not ship in
10
+ // the npm package, so a theme author outside this repo had no way to run the
11
+ // gates their theme would be judged by.
12
+ //
13
+ // So the rules live here, under tools/, which ships. test/contrast.mjs is now
14
+ // a loop over this, and `decklight theme check` is the same loop over one file.
15
+ //
16
+ // There is no version number in a theme, deliberately. Compatibility with a
17
+ // runtime IS passing that runtime's check — and when the contract grows a
18
+ // token, the report names exactly what an older theme is missing.
19
+
20
+ import { colorsIn, contrast, parseTheme } from './color.mjs';
21
+
22
+ /**
23
+ * Every token a theme must declare (SPEC THEMING). Presence is checked separately
24
+ * from contrast, because a missing token and an unreadable one are different
25
+ * problems with different fixes.
26
+ */
27
+ export const REQUIRED = [
28
+ 'bg', 'bg-accent', 'fg', 'muted',
29
+ 'font-body', 'font-heading', 'font-mono', 'heading-color', 'heading-weight', 'link',
30
+ 'accent', 'accent-contrast',
31
+ 'block-bg', 'block-border', 'block-radius', 'shadow',
32
+ 'code-bg', 'code-fg', 'hl-keyword', 'hl-string', 'hl-number', 'hl-comment', 'hl-function', 'hl-type', 'hl-punct',
33
+ 'd-stroke', 'd-text', 'd-muted', 'd-accent', 'd-fill-1', 'd-fill-2', 'd-fill-3', 'd-fill-4', 'd-fill-5', 'd-fill-6',
34
+ 'term-bg', 'term-fg', 'term-prompt', 'term-cursor', 'term-selection',
35
+ 'ansi-black', 'ansi-red', 'ansi-green', 'ansi-yellow', 'ansi-blue', 'ansi-magenta', 'ansi-cyan', 'ansi-white',
36
+ 'ansi-bright-black', 'ansi-bright-red', 'ansi-bright-green', 'ansi-bright-yellow',
37
+ 'ansi-bright-blue', 'ansi-bright-magenta', 'ansi-bright-cyan', 'ansi-bright-white',
38
+ ];
39
+
40
+ const ANSI = ['black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white'];
41
+
42
+ /**
43
+ * Every contrast gate, as data: [foreground, background, minimum].
44
+ *
45
+ * `✦` gates in the original comment are presentation-quality rather than WCAG
46
+ * proper; they are not distinguished here because a theme has to pass all of
47
+ * them either way. Diagram ink is checked against every PANEL and not only the
48
+ * canvas — the gameboy lesson: every canvas gate passed while the boxes were
49
+ * unreadable.
50
+ */
51
+ export const GATES = [
52
+ ['fg', 'bg', 4.5],
53
+ ['muted', 'bg', 3.0],
54
+ ['heading-color', 'bg', 3.0],
55
+ ['link', 'bg', 3.0],
56
+ ['d-text', 'bg', 3.0],
57
+ ...[1, 2, 3, 4, 5, 6].flatMap((i) => [
58
+ ['d-text', `d-fill-${i}`, 3.0],
59
+ ['d-muted', `d-fill-${i}`, 2.6],
60
+ ['d-accent', `d-fill-${i}`, 2.6],
61
+ ]),
62
+ ['accent-contrast', 'accent', 4.5],
63
+ ['code-fg', 'code-bg', 4.5],
64
+ ...['keyword', 'string', 'number', 'function', 'type', 'punct'].map((h) => [`hl-${h}`, 'code-bg', 4.5]),
65
+ ['hl-comment', 'code-bg', 3.0],
66
+ ['term-fg', 'term-bg', 3.0],
67
+ ['term-prompt', 'term-bg', 3.0],
68
+ ...ANSI.flatMap((a) => [[`ansi-${a}`, 'term-bg', 3.0], [`ansi-bright-${a}`, 'term-bg', 3.0]]),
69
+ ];
70
+
71
+ /**
72
+ * A foreground's contrast against a background that may be a GRADIENT: every
73
+ * stop has to clear the bar, because the text sits over all of them.
74
+ */
75
+ export function minContrast(fgValue, bgValue) {
76
+ const fg = colorsIn(fgValue)[0];
77
+ const stops = colorsIn(bgValue);
78
+ if (!fg || stops.length === 0) return null;
79
+ return Math.min(...stops.map((s) => contrast(fg, s)));
80
+ }
81
+
82
+ /**
83
+ * Judge one theme file.
84
+ *
85
+ * Returns `{ ok, tokens, missing, failures, errors }` — `missing` lists absent
86
+ * token names, `failures` the gates that did not clear (each with its measured
87
+ * ratio), and `errors` the human-readable lines. A file with no tokens at all
88
+ * is reported as such rather than as 56 separate missing tokens: it is almost
89
+ * certainly not a theme, and 56 lines would bury that.
90
+ */
91
+ export function validateTheme(css) {
92
+ const { tokens, exceptions } = parseTheme(css ?? '');
93
+ const declared = Object.keys(tokens).length;
94
+ const missing = REQUIRED.filter((t) => !(t in tokens));
95
+ const failures = [];
96
+ const errors = [];
97
+
98
+ if (declared === 0) {
99
+ return {
100
+ ok: false, tokens, exceptions, missing, failures,
101
+ errors: ['no CSS custom properties found — is this a Decklight theme? '
102
+ + '(a theme declares its tokens on .decklight, see SPEC THEMING)'],
103
+ empty: true,
104
+ };
105
+ }
106
+
107
+ for (const t of missing) errors.push(`missing token --${t}`);
108
+
109
+ for (const [fg, bg, min] of GATES) {
110
+ if (!(fg in tokens) || !(bg in tokens)) continue; // already reported as missing
111
+ const ratio = minContrast(tokens[fg], tokens[bg]);
112
+ if (ratio === null) {
113
+ failures.push({ fg, bg, min, ratio: null });
114
+ errors.push(`--${fg} on --${bg}: unparseable color`);
115
+ continue;
116
+ }
117
+ if (ratio < min) {
118
+ failures.push({ fg, bg, min, ratio });
119
+ errors.push(`--${fg} (${tokens[fg].slice(0, 28)}) on --${bg}: ${ratio.toFixed(2)} < ${min}`);
120
+ }
121
+ }
122
+
123
+ return { ok: errors.length === 0, tokens, exceptions, missing, failures, errors, empty: false };
124
+ }
125
+
126
+ /** A theme name from a path or URL: the basename, minus .css. */
127
+ export function themeNameFrom(source) {
128
+ // Both separators, because `source` is either a URL (always `/`) or a local
129
+ // path (`\` on Windows). Splitting on `/` alone made the whole path the
130
+ // name there — `decklight theme check C:\themes\aurora.css` reported
131
+ // `✔ C:\themes\aurora`, and `theme add` would then have tried to install
132
+ // under a name validThemeName refuses, from a file that was perfectly fine.
133
+ const last = String(source ?? '').split(/[?#]/)[0].split(/[/\\]/).filter(Boolean).pop() ?? '';
134
+ return last.replace(/\.css$/i, '');
135
+ }
136
+
137
+ /**
138
+ * Whether a name is usable as a theme name.
139
+ *
140
+ * The runtime's applyTheme silently ignores anything outside `[\w-]+`, so a
141
+ * name it would refuse has to be refused HERE, loudly, or the theme installs
142
+ * and then does nothing when picked.
143
+ */
144
+ export const validThemeName = (name) => /^[\w-]+$/.test(String(name ?? ''));