decklight 0.2.0 → 0.3.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 +855 -80
  3. package/cli/agents.mjs +113 -9
  4. package/cli/associate.mjs +279 -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 +564 -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 +730 -0
  17. package/cli/pdf.mjs +156 -0
  18. package/cli/pkg.mjs +69 -0
  19. package/cli/plugin.mjs +646 -0
  20. package/cli/port-conflict.mjs +94 -0
  21. package/cli/present.mjs +560 -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 +201 -0
  34. package/cli/units.mjs +488 -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 +5 -4
  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 +11 -2
  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 +139 -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 +316 -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
package/cli/theme.mjs ADDED
@@ -0,0 +1,201 @@
1
+ #!/usr/bin/env node
2
+ // Copyright 2026 Gilles Philippart
3
+ // SPDX-License-Identifier: Apache-2.0
4
+
5
+ // decklight theme — install and validate themes that came from somewhere else.
6
+ //
7
+ // decklight theme check <file|url>
8
+ // decklight theme add <file|url> <deck.html> [--name x] [--dry-run]
9
+ //
10
+ // The distribution mechanism already half-existed: a theme is ONE portable CSS
11
+ // file, `⌃⇧T` already downloads a shareable one, `decklight bundle` already
12
+ // embeds whatever the deck carries. What was missing is the last mile in both
13
+ // directions — a way to prove a file satisfies the contract before sharing it,
14
+ // and a way to put someone else's file into a deck without hand-editing HTML.
15
+ //
16
+ // There is no registry and no version number. The distribution unit is the
17
+ // file — a repo, a gist, a download — and compatibility with a runtime IS
18
+ // passing that runtime's check. When the contract grows a token, `check` names
19
+ // exactly what an older theme is missing.
20
+
21
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs';
22
+ import path, { resolve } from 'node:path';
23
+ import { argReader, isMain } from '../tools/args.mjs';
24
+ import { validateTheme, themeNameFrom, validThemeName, REQUIRED } from '../tools/theme-check.mjs';
25
+
26
+ const USAGE = `usage: decklight theme <check|add> …
27
+
28
+ decklight theme check <file|url>
29
+ run the SPEC THEMING token contract and the WCAG contrast gates on a theme file
30
+ EXAMPLE: decklight theme check nord-deep.css
31
+
32
+ decklight theme add <file|url> <deck.html> [--name <name>] [--dry-run]
33
+ validate a theme, then install it into the deck — it then behaves like a
34
+ shipped one: in the picker under "Added", reachable by , / . and ?theme=,
35
+ and carried by decklight bundle
36
+ EXAMPLE: decklight theme add https://gist.../nord-deep.css talk.html
37
+
38
+ --name <name> install under this name [the file's, minus .css]
39
+ --dry-run validate and report; touch nothing
40
+
41
+ a theme that does not pass is not installed — a deck cannot be made to carry
42
+ something the shipped set would not be allowed to contain`;
43
+
44
+ /** The <style> block an installed theme becomes, marked so the runtime groups it. */
45
+ export function themeStyleBlock(name, css) {
46
+ // </style> inside a theme's own comment would end the block early. Themes
47
+ // are CSS and have no business containing one, but a downloaded file is
48
+ // somebody else's, and "somebody else's" is exactly when to check.
49
+ const safe = css.replace(/<\/(style)/gi, '<\\/$1');
50
+ return `<style data-theme="${name}" data-theme-added media="not all">\n${safe.trim()}\n</style>`;
51
+ }
52
+
53
+ /** Where an existing block for this name starts and ends, or null. */
54
+ export function findThemeBlock(html, name) {
55
+ const re = new RegExp(`<style[^>]*\\bdata-theme=["']${name}["'][^>]*>[\\s\\S]*?<\\/style>`, 'i');
56
+ const m = re.exec(html);
57
+ return m ? { start: m.index, end: m.index + m[0].length, text: m[0] } : null;
58
+ }
59
+
60
+ /**
61
+ * Put the block in the deck: replacing the theme's previous block if it has
62
+ * one (re-adding IS the update path — there is no auto-update), otherwise
63
+ * last in <head> so an active added theme wins the cascade over the deck's
64
+ * link or inline base theme.
65
+ */
66
+ export function installTheme(html, name, css) {
67
+ const block = themeStyleBlock(name, css);
68
+ const existing = findThemeBlock(html, name);
69
+ if (existing) {
70
+ return { html: html.slice(0, existing.start) + block + html.slice(existing.end), replaced: true };
71
+ }
72
+ const head = /<\/head>/i.exec(html);
73
+ if (!head) return { html: null, replaced: false };
74
+ return {
75
+ html: html.slice(0, head.index) + block + '\n' + html.slice(head.index),
76
+ replaced: false,
77
+ };
78
+ }
79
+
80
+ /**
81
+ * Where a catalog entry's `source` actually lives.
82
+ *
83
+ * A manifest says `./themes/nord-deep.css`, which is relative to the
84
+ * MARKETPLACE — and by the time the catalog is a cached JSON file, the repo it
85
+ * came from is not the cwd of whoever is installing. The registry records each
86
+ * marketplace's source, so that is what a relative entry resolves against:
87
+ * a local path joins, `owner/repo` becomes a raw URL on the default branch.
88
+ *
89
+ * This lives in theme.mjs rather than in the author server on purpose. Fetching
90
+ * an ARTIFACT on an explicit install is fine anywhere; fetching a CATALOG is
91
+ * what `registered, not fetched` forbids on a deck-serving path, and keeping the
92
+ * two in different files is what keeps the sweep in test/marketplace.test.mjs
93
+ * able to tell them apart.
94
+ */
95
+ export function resolveSource(source, marketplaceSource) {
96
+ if (/^https?:\/\//i.test(source)) return source; // absolute already
97
+ const rel = source.replace(/^\.\//, '');
98
+ if (!marketplaceSource) return source; // nothing to resolve against
99
+ if (/^https?:\/\//i.test(marketplaceSource)) {
100
+ return `${marketplaceSource.replace(/\.git$/, '').replace(/\/$/, '')}/raw/HEAD/${rel}`;
101
+ }
102
+ if (/^[\w.-]+\/[\w.-]+$/.test(marketplaceSource)) {
103
+ // owner/repo — GitHub's raw host, HEAD so a marketplace is not pinned to a
104
+ // branch name we guessed at.
105
+ return `https://raw.githubusercontent.com/${marketplaceSource}/HEAD/${rel}`;
106
+ }
107
+ return path.resolve(marketplaceSource, rel); // a local marketplace
108
+ }
109
+
110
+ /** Read a theme from disk or over https. */
111
+ export async function fetchTheme(source, { fetchImpl = fetch, read = readFileSync } = {}) {
112
+ if (/^https?:\/\//i.test(source)) {
113
+ const r = await fetchImpl(source);
114
+ if (!r.ok) throw new Error(`${source} — HTTP ${r.status}`);
115
+ return await r.text();
116
+ }
117
+ const p = resolve(source);
118
+ if (!existsSync(p)) throw new Error(`no such file: ${source}`);
119
+ return read(p, 'utf8');
120
+ }
121
+
122
+ /** The validation report, as the lines to print. */
123
+ export function reportLines(name, result) {
124
+ const out = [];
125
+ if (result.ok) {
126
+ out.push(`✔ ${name} — all ${REQUIRED.length} tokens present, contrast gates pass`);
127
+ const ex = Object.entries(result.exceptions ?? {});
128
+ for (const [rule, why] of ex) out.push(` ○ ${rule} waived — ${why}`);
129
+ return out;
130
+ }
131
+ out.push(`✘ ${name}`);
132
+ for (const e of result.errors) out.push(` ${e}`);
133
+ if (result.missing.length && !result.empty) {
134
+ out.push(` ${result.missing.length} of ${REQUIRED.length} tokens missing`
135
+ + ' — a theme written against an older contract needs the new ones added (SPEC THEMING)');
136
+ }
137
+ return out;
138
+ }
139
+
140
+ async function checkMain(args) {
141
+ const [source] = args.filter((a) => !a.startsWith('-'));
142
+ if (!source) { console.error(`decklight theme check: needs a theme file or url\n\n${USAGE}`); return 1; }
143
+ let css;
144
+ try { css = await fetchTheme(source); } catch (e) { console.error(`decklight theme check: ${e.message}`); return 1; }
145
+ const name = themeNameFrom(source) || 'theme';
146
+ const result = validateTheme(css);
147
+ for (const line of reportLines(name, result)) console.log(line);
148
+ return result.ok ? 0 : 1;
149
+ }
150
+
151
+ async function addMain(args) {
152
+ const { opt } = argReader(args);
153
+ const positional = args.filter((a, i) => !a.startsWith('-') && args[i - 1] !== '--name');
154
+ const [source, deck] = positional;
155
+ if (!source || !deck) { console.error(`decklight theme add: needs a theme and a deck\n\n${USAGE}`); return 1; }
156
+
157
+ const name = opt('--name') ?? themeNameFrom(source);
158
+ if (!validThemeName(name)) {
159
+ console.error(`decklight theme add: "${name}" is not a usable theme name`);
160
+ console.error(' the runtime only resolves names matching [A-Za-z0-9_-]+ — pass --name to choose one');
161
+ return 1;
162
+ }
163
+ const deckPath = resolve(deck);
164
+ if (!existsSync(deckPath)) { console.error(`decklight theme add: no such deck: ${deck}`); return 1; }
165
+
166
+ let css;
167
+ try { css = await fetchTheme(source); } catch (e) { console.error(`decklight theme add: ${e.message}`); return 1; }
168
+
169
+ const result = validateTheme(css);
170
+ for (const line of reportLines(name, result)) console.log(line);
171
+ if (!result.ok) {
172
+ console.error(`\ndecklight theme add: ${name} was NOT installed — fix the report above and try again`);
173
+ return 1;
174
+ }
175
+
176
+ const html = readFileSync(deckPath, 'utf8');
177
+ const { html: next, replaced } = installTheme(html, name, css);
178
+ if (next === null) { console.error(`decklight theme add: ${deck} has no </head> to install into`); return 1; }
179
+
180
+ if (args.includes('--dry-run')) {
181
+ console.log(`would ${replaced ? 'replace' : 'install'} ${name} in ${deck} (${(css.length / 1024).toFixed(1)} KB)`);
182
+ return 0;
183
+ }
184
+ writeFileSync(deckPath, next);
185
+ console.log(`${replaced ? 'replaced' : 'installed'} ${name} in ${deck}`
186
+ + ` — press T and look under "Added"${replaced ? '' : ', or open it with ?theme=' + name}`);
187
+ return 0;
188
+ }
189
+
190
+ export async function themeMain(args = []) {
191
+ const sub = args[0];
192
+ if (!sub || sub === '--help' || sub === '-h' || sub === 'help') { console.log(USAGE); return sub ? 0 : 1; }
193
+ const rest = args.slice(1);
194
+ if (rest.includes('--help') || rest.includes('-h')) { console.log(USAGE); return 0; }
195
+ if (sub === 'check') return checkMain(rest);
196
+ if (sub === 'add') return addMain(rest);
197
+ console.error(`decklight theme: unknown subcommand "${sub}"\n\n${USAGE}`);
198
+ return 1;
199
+ }
200
+
201
+ if (isMain(import.meta.url)) process.exit(await themeMain(process.argv.slice(2)));
package/cli/units.mjs ADDED
@@ -0,0 +1,488 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ /**
5
+ * The unit library — one install seam for everything a marketplace
6
+ * distributes that is not a theme or a plugin (MARKETPLACE.md `UNITS`).
7
+ *
8
+ * `MARKETPLACES#CORE` registers catalogs and resolves a name to an entry;
9
+ * `THEME_BROWSE#UI` and `PRESENT#PLUGINS` each installed one kind of thing on
10
+ * top of it. This is the rest — deck templates, agent skills, import adapters
11
+ * — and it is deliberately ONE implementation with a type table rather than
12
+ * three commands that each grew their own copy of resolve-fetch-validate-write.
13
+ * `decklight template add` and `decklight importer add` are the same function
14
+ * with a different row.
15
+ *
16
+ * THE INVARIANT THAT OUTRANKS CONVENIENCE (SPEC MARKETPLACE_REGISTRY):
17
+ * registering is not fetching. Everything here reads the catalog CACHE; the
18
+ * only network call is `fetchArtifact`, reached only from an explicit `add`.
19
+ * `unitFor` and `listUnits` — the lookups on the `init` and `import` paths —
20
+ * cannot reach the network at all, so a deck on a plane behaves exactly like a
21
+ * deck at a desk.
22
+ *
23
+ * WHAT IS DELIBERATELY NOT HERE: running an installed unit. A template is
24
+ * HTML and a skill is Markdown, so both are just files. An import adapter and
25
+ * a build-time transform are both **Node code**, and executing either is one
26
+ * shared capability rather than two copies of resolve-fetch-validate-load —
27
+ * `cli/loader.mjs` (`EXTENSIONS#LOADER`) is that shared loader. `bundle
28
+ * --transform <name>` calls it once a transform is installed by the seam
29
+ * below, and `cli/import.mjs` calls the same loader's `runImporter` the
30
+ * moment an installed adapter matches the extension in hand
31
+ * (`EXTENSIONS#ADAPTEREXEC`, SPEC `EXTENSIONS_ADAPTERS`).
32
+ */
33
+
34
+ import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs';
35
+ import { createHash } from 'node:crypto';
36
+ import { join, resolve } from 'node:path';
37
+ import { configHome, loadRegistry, loadCatalog, resolveEntry, MarketplaceError } from './marketplace.mjs';
38
+
39
+ /** A failure with a message for a human — the mains print it, never a stack. */
40
+ export class UnitError extends Error {}
41
+
42
+ /**
43
+ * The unit types this decklight installs, and the shape each one takes.
44
+ *
45
+ * `files` is what an entry's `source` must yield. A single-file unit names its
46
+ * one file and `source` points straight at it; a multi-file unit's `source` is
47
+ * a DIRECTORY and each name is fetched from inside it. `required` names the
48
+ * catalog fields beyond the universal `{name, type, source}` — `extensions`
49
+ * for an importer is not decoration: it is what lets `decklight import` find
50
+ * the adapter for a `.marp` file **offline**, from the cache alone.
51
+ */
52
+ export const UNIT_TYPES = {
53
+ template: {
54
+ dir: 'templates',
55
+ single: 'html',
56
+ label: 'deck template',
57
+ use: 'decklight init --from <name>',
58
+ example: 'startup-pitch',
59
+ required: [],
60
+ },
61
+ skill: {
62
+ dir: 'skills',
63
+ files: ['SKILL.md'],
64
+ optional: ['reference.md'],
65
+ label: 'agent skill',
66
+ use: 'decklight skills add <name>',
67
+ example: 'conference-cfp',
68
+ required: [],
69
+ },
70
+ // `pinned` marks the kinds that are Node code the loader runs unsandboxed
71
+ // at author privilege (EXTENSIONS#LOADER): their `source` resolves against
72
+ // a moving ref (`resolveSource` deliberately fetches HEAD), so an entry
73
+ // installs only against the `sha256` its catalog admitted — refused before
74
+ // any fetch without one, refused before any write on a mismatch (SPEC
75
+ // UNIT_PINNING). Data kinds stay unpinned: a theme re-passes its whole
76
+ // contract at `theme add`, and nothing in a template or skill executes.
77
+ importer: {
78
+ dir: 'importers',
79
+ files: ['importer.mjs'],
80
+ label: 'import adapter',
81
+ use: 'decklight import <file>',
82
+ example: 'marp-import',
83
+ required: ['extensions'],
84
+ pinned: true,
85
+ },
86
+ // Node code, like an importer — but this one DOES run (EXTENSIONS#LOADER):
87
+ // `bundle --transform <name>` loads it through cli/loader.mjs. `apiVersion`
88
+ // is not persisted onto the installed file (there is nowhere on an .mjs to
89
+ // put it); the loader re-reads it from the catalog cache at run time, the
90
+ // same way `adapterFor` re-reads an importer's `extensions` rather than
91
+ // duplicating it into the library.
92
+ transform: {
93
+ dir: 'transforms',
94
+ single: 'mjs',
95
+ label: 'build-time transform',
96
+ use: 'decklight bundle --transform <name>',
97
+ example: 'grammar-check',
98
+ required: ['apiVersion'],
99
+ pinned: true,
100
+ },
101
+ // Node code that runs at AUTHOR time like a transform, and pinned for the
102
+ // same reason — but it is the first unit whose module is a FACTORY rather
103
+ // than a `(input) → string` pass (SPEC ENGINE_UNITS). What it returns is
104
+ // spoken with, so a malformed one has to be caught on the way out of the
105
+ // import rather than at the first sentence, mid-talk. Like a transform,
106
+ // `apiVersion` is not persisted onto the installed .mjs — the loader
107
+ // re-reads it, and `capability`, from the catalog cache.
108
+ engine: {
109
+ dir: 'engines',
110
+ single: 'mjs',
111
+ label: 'speech engine',
112
+ use: 'decklight tts --engine <name>, then the N picker',
113
+ example: 'azure-tts',
114
+ required: ['apiVersion', 'capability'],
115
+ pinned: true,
116
+ },
117
+ // A reference kind like `voice` below, but for a different reason: not
118
+ // consent, blast radius (SPEC AGENT_UNITS). An agent descriptor names a
119
+ // binary the user installed THEMSELVES and the argv of its headless mode,
120
+ // so teaching decklight a new agent downloads nothing and runs nothing of
121
+ // the catalog's — which is what keeps an open roster out of UNIT_PINNING's
122
+ // risk class entirely, unlike the engine directly above.
123
+ agent: {
124
+ dir: 'agents',
125
+ single: 'json',
126
+ reference: true,
127
+ label: 'AI agent',
128
+ use: 'A, author mode',
129
+ example: 'my-agent',
130
+ note: 'An agent unit is a DESCRIPTOR — which command to run and how to run it\n headlessly. Installing one fetches nothing; you install the agent itself the\n way its own docs say, and this only teaches decklight how to call it.',
131
+ required: ['bin', 'args'],
132
+ },
133
+ // The one kind that carries NOTHING. `reference: true` means the install is
134
+ // the catalog entry itself, written to disk as a pointer — no source to
135
+ // resolve, no bytes to fetch (SPEC VOICE_UNITS). Two consequences fall out
136
+ // of that and both are the point: `voice add` is the only add that works
137
+ // OFFLINE, and there is no code path by which a voice model could land in
138
+ // the library, because the fetch is not skipped conditionally — it is not
139
+ // reachable.
140
+ voice: {
141
+ dir: 'voices',
142
+ single: 'json',
143
+ reference: true,
144
+ label: 'voice',
145
+ use: 'the N picker, author mode',
146
+ example: 'narrator-anna',
147
+ note: 'A voice is a REFERENCE — which engine, which of its voices. Installing\n one writes a pointer and fetches nothing, so this is the one add that works\n offline; speaking through it still needs that engine and your own credential.',
148
+ required: ['engine', 'voiceId'],
149
+ },
150
+ };
151
+
152
+ const typeOf = (type) => {
153
+ const t = UNIT_TYPES[type];
154
+ if (!t) throw new UnitError(`"${type}" is not a unit type this decklight installs`);
155
+ return t;
156
+ };
157
+
158
+ /** Where a type's units live: `~/.decklight/templates/`, `…/skills/`, … */
159
+ export const unitDir = (type, home = configHome()) => join(home, typeOf(type).dir);
160
+
161
+ /** Where ONE unit lives — a file for a single-file type, a directory otherwise. */
162
+ export const unitPath = (type, name, home = configHome()) => {
163
+ const t = typeOf(type);
164
+ return join(unitDir(type, home), t.single ? `${name}.${t.single}` : name);
165
+ };
166
+
167
+ // ── reading the library, always offline ────────────────────────────────────
168
+
169
+ /** Installed units of a type, by name. Never touches the network. */
170
+ export function listUnits(type, home = configHome()) {
171
+ const t = typeOf(type);
172
+ const dir = unitDir(type, home);
173
+ if (!existsSync(dir)) return [];
174
+ const out = [];
175
+ for (const entry of readdirSync(dir).sort()) {
176
+ const full = join(dir, entry);
177
+ if (t.single) {
178
+ const suffix = `.${t.single}`;
179
+ if (!entry.endsWith(suffix) || !statSync(full).isFile()) continue;
180
+ out.push({ name: entry.slice(0, -suffix.length), path: full });
181
+ } else {
182
+ if (!statSync(full).isDirectory()) continue;
183
+ out.push({ name: entry, path: full });
184
+ }
185
+ }
186
+ return out;
187
+ }
188
+
189
+ /** One installed unit, or null. Never touches the network. */
190
+ export function findUnit(type, name, home = configHome()) {
191
+ const p = unitPath(type, name, home);
192
+ return existsSync(p) ? { name, path: p } : null;
193
+ }
194
+
195
+ /**
196
+ * Every entry in every CACHED catalog, flattened. The lookup that `init` and
197
+ * `import` use to name something they cannot find installed — reading a JSON
198
+ * file that is already on disk, which is exactly as offline-identical as not
199
+ * reading it at all.
200
+ */
201
+ export function catalogEntries(home = configHome()) {
202
+ const reg = loadRegistry(home);
203
+ const out = [];
204
+ for (const marketplace of Object.keys(reg.marketplaces).sort()) {
205
+ const cached = loadCatalog(marketplace, home);
206
+ if (!cached?.ok) continue;
207
+ for (const entry of cached.manifest.entries) {
208
+ out.push({ ...entry, marketplace, qualified: `${entry.name}@${marketplace}` });
209
+ }
210
+ }
211
+ return out;
212
+ }
213
+
214
+ /** Catalog entries of one type, cache-only — "what templates could I install?" */
215
+ export const catalogEntriesOfType = (type, home = configHome()) =>
216
+ catalogEntries(home).filter((e) => e.type === type);
217
+
218
+ /**
219
+ * The import adapter a file extension would need, from the cache alone.
220
+ *
221
+ * This is what makes the offer at the point of failure possible without a
222
+ * setup step nobody performs in advance (the ENGINES pattern): `import
223
+ * talk.marp` can name `marp-import` because the catalog it already fetched
224
+ * said which extensions that adapter handles. With no catalog cached it
225
+ * returns nothing and `import` says what it always said — never a hang, never
226
+ * a fetch.
227
+ */
228
+ export function adapterFor(ext, home = configHome()) {
229
+ const want = String(ext ?? '').toLowerCase();
230
+ if (!want) return null;
231
+ return catalogEntriesOfType('importer', home).find((e) =>
232
+ (e.extensions ?? []).some((x) => String(x).toLowerCase().replace(/^\.?/, '.') === want)) ?? null;
233
+ }
234
+
235
+ /**
236
+ * Installed voice references for one engine (SPEC VOICE_UNITS).
237
+ *
238
+ * Filtered by engine because a reference is only an answer on the engine it
239
+ * names: an ElevenLabs voice id means nothing to piper, and offering it while
240
+ * piper is live would put a row in the picker that can only fail. Unreadable
241
+ * or half-written files are skipped rather than thrown — one bad pointer must
242
+ * not cost the roster the bridge is otherwise able to report.
243
+ */
244
+ export function installedVoices(engine, home = configHome()) {
245
+ const want = String(engine ?? '').toLowerCase();
246
+ if (!want) return [];
247
+ const out = [];
248
+ for (const { name, path } of listUnits('voice', home)) {
249
+ let ref;
250
+ try { ref = JSON.parse(readFileSync(path, 'utf8')); } catch { continue; }
251
+ if (String(ref?.engine ?? '').toLowerCase() !== want) continue;
252
+ if (!ref.voiceId) continue;
253
+ out.push({ name, voiceId: String(ref.voiceId), label: ref.label || name, marketplace: ref.marketplace });
254
+ }
255
+ return out;
256
+ }
257
+
258
+ // ── installing, the one place that reaches the network ─────────────────────
259
+
260
+ /** Read one artifact file from a resolved source (a URL or a local path). */
261
+ async function fetchArtifact(at, { fetchImpl = fetch, timeoutMs = 8000 } = {}) {
262
+ if (/^https?:\/\//i.test(at)) {
263
+ let r;
264
+ try { r = await fetchImpl(at, { signal: AbortSignal.timeout(timeoutMs), redirect: 'follow' }); } catch (e) {
265
+ const why = e.name === 'TimeoutError' || e.code === 'ABORT_ERR'
266
+ ? `no response after ${timeoutMs / 1000}s` : String(e.cause?.code ?? e.message);
267
+ throw new UnitError(`could not fetch ${at} — ${why}`);
268
+ }
269
+ if (!r.ok) throw new UnitError(`${at} — HTTP ${r.status}`);
270
+ return await r.text();
271
+ }
272
+ if (!existsSync(at)) throw new UnitError(`no such file: ${at}`);
273
+ return readFileSync(at, 'utf8');
274
+ }
275
+
276
+ const joinSource = (base, file) => (/^https?:\/\//i.test(base)
277
+ ? `${base.replace(/\/$/, '')}/${file}`
278
+ : join(resolve(base), file));
279
+
280
+ /**
281
+ * Install one unit by catalog reference (`name` or `name@marketplace`).
282
+ *
283
+ * Everything is fetched and checked BEFORE anything is written, so a refusal
284
+ * or a dropped connection leaves the library exactly as it was — the rule
285
+ * `theme add` keeps, for the same reason: a half-installed unit is worse than
286
+ * an uninstalled one, because it looks present.
287
+ */
288
+ export async function installUnit(type, ref, home = configHome(), { fetchImpl = fetch } = {}) {
289
+ const t = typeOf(type);
290
+ const reg = loadRegistry(home);
291
+ const catalogs = {};
292
+ for (const name of Object.keys(reg.marketplaces)) {
293
+ const c = loadCatalog(name, home);
294
+ if (c?.ok) catalogs[name] = c.manifest;
295
+ }
296
+ if (!Object.keys(catalogs).length) {
297
+ throw new UnitError('no marketplace has been fetched yet'
298
+ + ' — decklight marketplace update <name> (registering is not fetching)');
299
+ }
300
+
301
+ let hit;
302
+ try { hit = resolveEntry(ref, catalogs); } catch (e) {
303
+ if (e instanceof MarketplaceError) throw new UnitError(e.message);
304
+ throw e;
305
+ }
306
+ if (hit.entry.type !== type) {
307
+ throw new UnitError(`${hit.qualified} is a ${hit.entry.type}, not a ${type}`
308
+ + `${UNIT_TYPES[hit.entry.type] ? ` — try: decklight ${hit.entry.type} add ${ref}` : ''}`);
309
+ }
310
+
311
+ // A reference-only kind is fully installed by the catalog entry it resolved
312
+ // to: write the pointer and return, before anything can be fetched.
313
+ if (t.reference) {
314
+ const dest = unitPath(type, hit.entry.name, home);
315
+ const { name, type: _t, source: _s, ...rest } = hit.entry;
316
+ mkdirSync(unitDir(type, home), { recursive: true });
317
+ writeFileSync(dest, `${JSON.stringify({ name, ...rest, marketplace: hit.marketplace }, null, 2)}\n`);
318
+ return { name, qualified: hit.qualified, entry: hit.entry, path: dest, files: [] };
319
+ }
320
+
321
+ // A pinned kind with no pin is refused HERE, before the network is touched:
322
+ // its source resolves against a moving ref, so without a digest there is no
323
+ // fact to hold the fetched bytes to (SPEC UNIT_PINNING).
324
+ if (t.pinned && !hit.entry.sha256) {
325
+ throw new UnitError(`${hit.qualified} carries no sha256 — a ${t.label} is Node code decklight`
326
+ + ` runs unsandboxed, so it installs only pinned to the digest its catalog admitted`
327
+ + ` (SPEC UNIT_PINNING). Ask the marketplace to pin the entry; decklight extension check`
328
+ + ` prints the digest to use`);
329
+ }
330
+
331
+ // Same placement, same reason: an `engine` entry may legitimately carry
332
+ // neither field, because the type is also how a catalog declares a wizard
333
+ // for an engine decklight already SHIPS (ENGINES#WIZARD) — no module, no
334
+ // contract version, nothing installed. Only an entry actually being
335
+ // installed as a unit has to answer for both (SPEC ENGINE_UNITS).
336
+ for (const field of t.required ?? []) {
337
+ if (t.reference || hit.entry[field] !== undefined) continue;
338
+ throw new UnitError(`${hit.qualified} declares no ${field}, which installing a ${t.label} needs`
339
+ + (type === 'engine'
340
+ ? ' (SPEC ENGINE_UNITS). An entry that only declares a wizard for an engine decklight'
341
+ + ' already ships carries neither field, and is not installed this way — the wizard'
342
+ + ' reaches it through the palette instead'
343
+ : ''));
344
+ }
345
+
346
+ const { resolveSource } = await import('./theme.mjs');
347
+ const base = resolveSource(hit.entry.source, reg.marketplaces[hit.marketplace]?.source);
348
+
349
+ // Fetch first, write second.
350
+ const fetched = [];
351
+ if (t.single) {
352
+ fetched.push(['', await fetchArtifact(base, { fetchImpl })]);
353
+ } else {
354
+ for (const file of t.files) fetched.push([file, await fetchArtifact(joinSource(base, file), { fetchImpl })]);
355
+ for (const file of t.optional ?? []) {
356
+ try { fetched.push([file, await fetchArtifact(joinSource(base, file), { fetchImpl })]); } catch { /* optional */ }
357
+ }
358
+ }
359
+
360
+ // The pin covers the MODULE — the file the loader will import() — and it is
361
+ // checked between fetch and write, so a mismatch leaves the library exactly
362
+ // as it was, like every other refusal here.
363
+ if (hit.entry.sha256) {
364
+ const moduleFile = t.single ? '' : t.files[0];
365
+ const got = createHash('sha256').update(fetched.find(([f]) => f === moduleFile)[1]).digest('hex');
366
+ const want = String(hit.entry.sha256).toLowerCase();
367
+ if (got !== want) {
368
+ throw new UnitError(`${hit.qualified}: the fetched ${t.single ? `.${t.single} file` : t.files[0]}`
369
+ + ` does not match the catalog's pin (SPEC UNIT_PINNING)\n`
370
+ + ` pinned sha256 ${want}\n`
371
+ + ` fetched sha256 ${got}\n`
372
+ + ` the file changed since this catalog was cached — nothing was installed. If the`
373
+ + ` marketplace re-pinned it, decklight marketplace update ${hit.marketplace} and try again`);
374
+ }
375
+ }
376
+
377
+ const dest = unitPath(type, hit.entry.name, home);
378
+ if (t.single) {
379
+ mkdirSync(unitDir(type, home), { recursive: true });
380
+ writeFileSync(dest, fetched[0][1]);
381
+ } else {
382
+ mkdirSync(dest, { recursive: true });
383
+ for (const [file, text] of fetched) writeFileSync(join(dest, file), text);
384
+ }
385
+ return { name: hit.entry.name, qualified: hit.qualified, entry: hit.entry, path: dest, files: fetched.map(([f]) => f).filter(Boolean) };
386
+ }
387
+
388
+ /** Delete an installed unit. */
389
+ export function removeUnit(type, name, home = configHome()) {
390
+ const p = unitPath(type, name, home);
391
+ if (!existsSync(p)) throw new UnitError(`no ${type} "${name}" installed (decklight ${type} list)`);
392
+ rmSync(p, { recursive: true, force: true });
393
+ return p;
394
+ }
395
+
396
+ // ── the command every unit type shares ─────────────────────────────────────
397
+
398
+ export const unitUsage = (type) => {
399
+ const t = typeOf(type);
400
+ return `usage: decklight ${type} <add|list|remove> …
401
+
402
+ decklight ${type} add <name[@marketplace]>
403
+ install a ${t.label} from a registered marketplace into ~/.decklight/${t.dir}/
404
+ EXAMPLE: decklight ${type} add ${t.example}${t.note ? `\n\n ${t.note}` : ''}
405
+
406
+ decklight ${type} list
407
+ what is installed, and what the registered catalogs offer that is not
408
+
409
+ decklight ${type} remove <name>
410
+ delete it from your library
411
+
412
+ used by: ${t.use}
413
+
414
+ Registering a marketplace is not fetching it (SPEC MARKETPLACE_REGISTRY):
415
+ \`list\` reads only the cache and works on a plane, and the network is touched
416
+ only by an explicit \`add\`. DECKLIGHT_HOME overrides ~/.decklight/.`;
417
+ };
418
+
419
+ async function addMain(type, args, home) {
420
+ const [ref] = args.filter((a) => !a.startsWith('-'));
421
+ if (!ref) { console.error(`decklight ${type} add: needs a name\n\n${unitUsage(type)}`); return 1; }
422
+ let done;
423
+ try { done = await installUnit(type, ref, home); } catch (e) {
424
+ if (!(e instanceof UnitError)) throw e;
425
+ console.error(`decklight ${type} add: ${e.message}`);
426
+ return 1;
427
+ }
428
+ console.log(`installed ${done.name} from ${done.qualified} — ${UNIT_TYPES[type].use}`);
429
+ if (done.entry.description) console.log(` ${done.entry.description}`);
430
+ return 0;
431
+ }
432
+
433
+ function listMain(type, home) {
434
+ const t = UNIT_TYPES[type];
435
+ const installed = listUnits(type, home);
436
+ const offered = catalogEntriesOfType(type, home);
437
+ const have = new Set(installed.map((u) => u.name));
438
+
439
+ if (!installed.length && !offered.length) {
440
+ console.log(`no ${t.label}s installed, and no registered marketplace offers one`);
441
+ console.log(' decklight marketplace add <owner/repo>, then decklight marketplace update <name>');
442
+ return 0;
443
+ }
444
+ for (const u of installed) {
445
+ const from = offered.find((e) => e.name === u.name);
446
+ console.log(`${u.name}${from ? ` ${from.qualified}` : ''}${from?.description ? ` — ${from.description}` : ''}`);
447
+ }
448
+ const rest = offered.filter((e) => !have.has(e.name));
449
+ if (rest.length) {
450
+ console.log(installed.length ? `\navailable (decklight ${type} add <name>):` : `available (decklight ${type} add <name>):`);
451
+ for (const e of rest) console.log(` ${e.qualified}${e.description ? ` — ${e.description}` : ''}`);
452
+ }
453
+ return 0;
454
+ }
455
+
456
+ function removeMain(type, args, home) {
457
+ const [name] = args.filter((a) => !a.startsWith('-'));
458
+ if (!name) { console.error(`decklight ${type} remove: which one?\n\n${unitUsage(type)}`); return 1; }
459
+ try { removeUnit(type, name, home); } catch (e) {
460
+ if (!(e instanceof UnitError)) throw e;
461
+ console.error(`decklight ${type} remove: ${e.message}`);
462
+ return 1;
463
+ }
464
+ console.log(`removed ${name}`);
465
+ return 0;
466
+ }
467
+
468
+ /** `decklight <type> <add|list|remove>` — one implementation, three commands. */
469
+ export async function unitMain(type, args = []) {
470
+ const sub = args[0];
471
+ if (!sub || sub === '--help' || sub === '-h' || sub === 'help') { console.log(unitUsage(type)); return sub ? 0 : 1; }
472
+ const rest = args.slice(1);
473
+ if (rest.includes('--help') || rest.includes('-h')) { console.log(unitUsage(type)); return 0; }
474
+ const home = configHome();
475
+ try {
476
+ if (sub === 'add') return await addMain(type, rest, home);
477
+ if (sub === 'list') return listMain(type, home);
478
+ if (sub === 'remove') return removeMain(type, rest, home);
479
+ } catch (e) {
480
+ if (e instanceof UnitError || e instanceof MarketplaceError) {
481
+ console.error(`decklight ${type} ${sub}: ${e.message}`);
482
+ return 1;
483
+ }
484
+ throw e;
485
+ }
486
+ console.error(`decklight ${type}: unknown subcommand "${sub}"\n\n${unitUsage(type)}`);
487
+ return 1;
488
+ }