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,911 @@
1
+ #!/usr/bin/env node
2
+ // Copyright 2026 Gilles Philippart
3
+ // SPDX-License-Identifier: Apache-2.0
4
+
5
+ // decklight marketplace — register catalogs; never fetch unless asked to.
6
+ //
7
+ // decklight marketplace add <owner/repo | git url | path> [--name x]
8
+ // decklight marketplace list
9
+ // decklight marketplace update <name>
10
+ // decklight marketplace remove <name>
11
+ //
12
+ // A marketplace is a git repo (or a local directory) with
13
+ // `.decklight/marketplace.json` at its root, mirroring Claude Code's layout
14
+ // (MARKETPLACE.md MARKETPLACES). Registration lives under `~/.decklight/`:
15
+ // one registry file (`marketplaces.json`) plus a `marketplaces/` directory
16
+ // holding, per marketplace, its cached manifest (`<name>.json`) and the
17
+ // CHECKOUT that manifest came with (`<name>/`) — the boring layout the engine
18
+ // wizard shares.
19
+ //
20
+ // A remote marketplace is read by CLONING it (MARKETPLACES#CLONE), never by
21
+ // fetching one file at a time off a raw-content host. That is what lets a
22
+ // private marketplace work at all — a clone uses the caller's own git
23
+ // credentials, an anonymous fetch has none — and it is also what makes an
24
+ // entry's files provably come from the same commit as the manifest that
25
+ // offered them.
26
+ //
27
+ // The invariant this module exists to keep (SPEC MARKETPLACE_REGISTRY): the
28
+ // network is touched ONLY by an explicit `add` or `update` of a remote
29
+ // source. Registering is a filesystem write; `list` reads only the cache;
30
+ // installing an entry reads the checkout; nothing on the deck-load or
31
+ // presenting path imports this module at all. A deck on conference wifi, on a
32
+ // plane, or air-gapped behaves identically to one at a desk, marketplace or
33
+ // no marketplace.
34
+
35
+ import {
36
+ existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync,
37
+ } from 'node:fs';
38
+ import { execFileSync } from 'node:child_process';
39
+ import { homedir } from 'node:os';
40
+ import { join, resolve } from 'node:path';
41
+ import { argReader, isMain } from '../tools/args.mjs';
42
+ import { oneline } from './git.mjs';
43
+
44
+ export const MANIFEST_PATH = '.decklight/marketplace.json';
45
+ export const NAME_RE = /^[A-Za-z0-9_-]+$/;
46
+
47
+ /**
48
+ * Every kind of entry this decklight recognises, and how you install one.
49
+ *
50
+ * It lives here rather than in units.mjs because this module owns the manifest
51
+ * vocabulary and units.mjs is the layer above it — the other direction would
52
+ * be a cycle. A `null` hint means the kind is real but nothing installs it
53
+ * here yet, which `marketplace list` prints as its own state: "not yet" and
54
+ * "typo" must not look alike.
55
+ */
56
+ export const INSTALL_HINT = {
57
+ theme: 'decklight theme add <source> <deck>',
58
+ plugin: 'decklight plugin add <name>',
59
+ template: 'decklight template add <name>',
60
+ skill: 'decklight skills add <name>',
61
+ importer: 'decklight importer add <name>',
62
+ engine: 'decklight engine add <name>', // ENGINE_UNITS — the wizard then configures it
63
+ agent: 'decklight agent add <name>', // AGENT_UNITS — a descriptor, never code
64
+ transform: 'decklight transform add <name>', // EXTENSIONS#LOADER — installs; bundle --transform <name> runs it
65
+ voice: 'decklight voice add <name>',
66
+ 'publish-target': null,
67
+ };
68
+
69
+ export const KNOWN_TYPES = Object.keys(INSTALL_HINT);
70
+
71
+ /** The catalog every install registers, and no install ever fetches. */
72
+ export const FIRST_PARTY = { name: 'decklight', source: 'decklight/decklight-plugins-official' };
73
+
74
+ /** A failure with a message for a human — the mains print it, never a stack. */
75
+ export class MarketplaceError extends Error {}
76
+
77
+ // ── where everything lives ─────────────────────────────────────────────────
78
+
79
+ /** The decklight config home (ENGINES decided `~/.decklight/`). */
80
+ export const configHome = (env = process.env) =>
81
+ env.DECKLIGHT_HOME || join(homedir(), '.decklight');
82
+
83
+ const registryPath = (home) => join(home, 'marketplaces.json');
84
+ const cachePath = (home, name) => join(home, 'marketplaces', `${name}.json`);
85
+
86
+ /**
87
+ * The CHECKOUT a remote marketplace keeps beside its cached manifest
88
+ * (MARKETPLACES#CLONE): `~/.decklight/marketplaces/<name>/`, the working tree
89
+ * of the shallow clone `add`/`update` made, with its `.git` removed.
90
+ *
91
+ * It exists because an entry's `source` is repo-relative, and the two ways to
92
+ * turn that into bytes are not equivalent. A second unauthenticated fetch of
93
+ * `raw.githubusercontent.com` cannot see a private repo at all, and reads a
94
+ * ref that may have moved since the manifest was read; a file in the checkout
95
+ * came from the same clone as the manifest, over the caller's own git
96
+ * credentials. So the clone is what an install reads, and the network is not
97
+ * on the install path at all.
98
+ *
99
+ * A LOCAL marketplace has none — its directory already is the checkout, and
100
+ * copying somebody's working tree into the config home would give them a stale
101
+ * second copy of files they are editing.
102
+ */
103
+ export const checkoutPath = (home, name) => join(home, 'marketplaces', name);
104
+
105
+ export function loadRegistry(home = configHome()) {
106
+ const p = registryPath(home);
107
+ if (!existsSync(p)) return { version: 1, marketplaces: {} };
108
+ try {
109
+ const data = JSON.parse(readFileSync(p, 'utf8'));
110
+ return { version: 1, marketplaces: {}, ...data };
111
+ } catch (e) {
112
+ throw new MarketplaceError(`${p} is not valid JSON (${parseMsg(e)}) — fix or delete it`);
113
+ }
114
+ }
115
+
116
+ export function saveRegistry(reg, home = configHome()) {
117
+ mkdirSync(join(home, 'marketplaces'), { recursive: true });
118
+ writeFileSync(registryPath(home), JSON.stringify(reg, null, 2) + '\n');
119
+ }
120
+
121
+ /**
122
+ * Register the first-party marketplace on first run — REGISTERED, not
123
+ * fetched: this writes two files and touches nothing else, so first run
124
+ * offline is silent and instant. First run means "no registry file yet";
125
+ * once one exists this never fires again, so removing the first-party
126
+ * marketplace is respected rather than undone on the next command.
127
+ */
128
+ export function ensureFirstPartyRegistered(home = configHome()) {
129
+ if (existsSync(registryPath(home))) return false;
130
+ saveRegistry({
131
+ version: 1,
132
+ marketplaces: { [FIRST_PARTY.name]: { source: FIRST_PARTY.source, firstParty: true } },
133
+ }, home);
134
+ return true;
135
+ }
136
+
137
+ // ── the manifest, validated with line numbers ──────────────────────────────
138
+
139
+ /** "Unexpected token } in JSON at position 47" minus the part we say better. */
140
+ const parseMsg = (e) => String(e.message)
141
+ .replace(/ in JSON.*$/, '')
142
+ .replace(/,\s*(?:\.\.\.)?"[\s\S]*"(?:\.\.\.)? is not valid JSON$/, '')
143
+ .replace(/^JSON\.parse: /, '');
144
+
145
+ const lineAt = (raw, idx) => raw.slice(0, idx).split('\n').length;
146
+
147
+ // V8's snippet-style parse error ('Unexpected token X, ..."<context>"... is
148
+ // not valid JSON') carries no position — but the context starts a fixed 10
149
+ // characters before the error, so finding the snippet in the raw text
150
+ // recovers it. The other two message forms name the position outright.
151
+ const V8_SNIPPET_BEFORE = 10;
152
+
153
+ /** The line a JSON.parse SyntaxError points at, from any V8 message form. */
154
+ export function parseErrorLine(raw, e) {
155
+ const lc = /line (\d+) column \d+/.exec(e.message);
156
+ if (lc) return Number(lc[1]);
157
+ const pos = /position (\d+)/.exec(e.message);
158
+ if (pos) return lineAt(raw, Number(pos[1]));
159
+ const snip = /^Unexpected token '(.*?)', (\.\.\.)?"([\s\S]*)"(?:\.\.\.)? is not valid JSON$/.exec(e.message);
160
+ if (snip) {
161
+ const [, token, clipped, escaped] = snip;
162
+ const context = escaped.replace(/\\n/g, '\n').replace(/\\r/g, '\r').replace(/\\t/g, '\t').replace(/\\\\/g, '\\');
163
+ const start = raw.indexOf(context.slice(0, V8_SNIPPET_BEFORE + 2));
164
+ if (start >= 0) {
165
+ const offset = clipped ? V8_SNIPPET_BEFORE : Math.max(0, context.indexOf(token));
166
+ return lineAt(raw, start + offset);
167
+ }
168
+ }
169
+ return 1;
170
+ }
171
+
172
+ /**
173
+ * Path → line for every key and array element in a VALID JSON text
174
+ * (`entries[2].type` → the line that key sits on), so a field error can name
175
+ * the line the way a parse error does. Only ever called after JSON.parse
176
+ * succeeded, which is what keeps this walk simple.
177
+ */
178
+ export function jsonLineMap(raw) {
179
+ const lines = new Map();
180
+ let i = 0;
181
+ const ws = () => { while (i < raw.length && /\s/.test(raw[i])) i++; };
182
+ const str = () => {
183
+ const s = i; i++;
184
+ while (raw[i] !== '"') i += raw[i] === '\\' ? 2 : 1;
185
+ i++;
186
+ return JSON.parse(raw.slice(s, i));
187
+ };
188
+ const value = (path) => {
189
+ ws();
190
+ const c = raw[i];
191
+ if (c === '{') {
192
+ i++; ws();
193
+ if (raw[i] === '}') { i++; return; }
194
+ for (;;) {
195
+ ws();
196
+ const keyStart = i;
197
+ const key = str();
198
+ const p = path ? `${path}.${key}` : key;
199
+ lines.set(p, lineAt(raw, keyStart));
200
+ ws(); i++; // the ':'
201
+ value(p);
202
+ ws();
203
+ if (raw[i] === ',') { i++; continue; }
204
+ i++; return; // '}'
205
+ }
206
+ }
207
+ if (c === '[') {
208
+ i++; ws();
209
+ if (raw[i] === ']') { i++; return; }
210
+ for (let idx = 0; ; idx++) {
211
+ ws();
212
+ lines.set(`${path}[${idx}]`, lineAt(raw, i));
213
+ value(`${path}[${idx}]`);
214
+ ws();
215
+ if (raw[i] === ',') { i++; continue; }
216
+ i++; return; // ']'
217
+ }
218
+ }
219
+ if (c === '"') { str(); return; }
220
+ while (i < raw.length && !/[\s,\]}]/.test(raw[i])) i++; // number/true/false/null
221
+ };
222
+ try { value(''); } catch { /* a walk bug never outranks the real report */ }
223
+ return lines;
224
+ }
225
+
226
+ /**
227
+ * The extra fields a given kind of entry must carry (`UNITS`).
228
+ *
229
+ * A type NOT in this table is accepted rather than refused, and that is
230
+ * deliberate: a catalog is a file someone else wrote, quite possibly against a
231
+ * newer decklight than the one reading it, and rejecting a manifest wholesale
232
+ * because one entry names a kind we have not shipped yet would make every
233
+ * catalog un-addable the day it adds an entry. The unknown kind is surfaced by
234
+ * `marketplace list` instead, where it is information rather than a wall.
235
+ */
236
+ /**
237
+ * The build-time transform invocation contract's own version (SPEC
238
+ * `UNIT_COMPAT`, `OPEN` 2 in MARKETPLACE.md).
239
+ *
240
+ * Deliberately NOT decklight's package version: `src/core/engine.js` has been
241
+ * split apart repeatedly (four modules pulled out in #147 alone) without that
242
+ * ever being a promise to anyone outside the repo, so checking a transform's
243
+ * compatibility against decklight's package.json would tie every installed
244
+ * extension to churn it never touches. This number instead tracks only the
245
+ * narrow "HTML in, HTML out" calling convention `EXTENSIONS#TRANSFORMS`
246
+ * declares, and moves the way `CAST_FORMAT`'s `decklightCast` does: additive
247
+ * only, bumped only when that calling convention itself would break an
248
+ * existing transform, never for an internal reorganisation. A transform
249
+ * declares the lowest version it needs; this decklight is compatible with
250
+ * anything at or below `TRANSFORM_API_VERSION`.
251
+ */
252
+ export const TRANSFORM_API_VERSION = 1;
253
+
254
+ /**
255
+ * The import-adapter invocation contract's own version (SPEC
256
+ * `EXTENSIONS_ADAPTERS`, `EXTENSIONS#ADAPTEREXEC`).
257
+ *
258
+ * A separate counter from `TRANSFORM_API_VERSION`, deliberately: the two are
259
+ * different calling conventions (`html, opts → html` vs `bytes, opts →
260
+ * html`) that will each grow a field on their own schedule, so sharing one
261
+ * number would bump every installed transform's compatibility the day the
262
+ * *importer* contract changed something a transform never touched — the same
263
+ * churn-isolation argument `TRANSFORM_API_VERSION` itself makes against
264
+ * decklight's own package version. Additive-only, the same way: bumped only
265
+ * when the import-adapter calling convention itself would break an existing
266
+ * adapter, never for an internal reorganisation.
267
+ */
268
+ export const IMPORTER_API_VERSION = 1;
269
+
270
+ /**
271
+ * The speech-engine invocation contract's own version (SPEC `ENGINE_UNITS`,
272
+ * `ENGINES#TTS`).
273
+ *
274
+ * A third counter beside the two above, for the third reason they are
275
+ * separate: an engine's convention is not `input → string` at all. It is a
276
+ * FACTORY — `opts → {name, voices, stylable, synth}` — and `synth` returns
277
+ * audio plus a usage record rather than text, so the day either of the other
278
+ * two grows a field, an engine's contract is untouched and must not be
279
+ * invalidated along with them. Additive-only on the same terms: bumped only
280
+ * when the factory or `synth` convention itself would break an installed
281
+ * engine, never for an internal reorganisation of `tools/tts-engines.mjs`
282
+ * (whose six built-ins are not units and are not versioned by this at all).
283
+ */
284
+ export const ENGINE_API_VERSION = 1;
285
+
286
+ /**
287
+ * What an installed engine's `capability` may say, and this decklight runs.
288
+ *
289
+ * `lipsync` joined `tts` with ENGINES#LIPSYNC: the loader's contract is the
290
+ * same factory either way, and what differs is the PREREQUISITES an engine
291
+ * declares (SPEC ENGINE_PREREQUISITES) — a binary and a checkout rather than
292
+ * only a pasted key.
293
+ */
294
+ export const ENGINE_CAPABILITIES = ['tts', 'lipsync'];
295
+
296
+ /**
297
+ * The pin a code-carrying entry installs against (SPEC `UNIT_PINNING`): the
298
+ * SHA-256 of the module file's bytes, lowercase hex, as `sha256sum` prints it
299
+ * and `decklight extension check` emits it on success.
300
+ *
301
+ * Validated for SHAPE when present, like everything else in `ENTRY_SHAPES` —
302
+ * but its ABSENCE is refused at install time (`cli/units.mjs`), not here.
303
+ * Requiring it at the manifest level would invalidate a whole catalog over
304
+ * one unpinned transform, costing its theme entries too — the same
305
+ * blast-radius reasoning that leaves an unknown `type` accepted. The refusal
306
+ * instead lands at the one moment the risk does: installing the executable
307
+ * entry.
308
+ */
309
+ const sha256Shape = (v) => (typeof v === 'string' && /^[0-9a-f]{64}$/.test(v)
310
+ ? null
311
+ : 'must be 64 lowercase hex characters — the SHA-256 of the module file\'s bytes (SPEC UNIT_PINNING)');
312
+
313
+ /** Fields a kind MAY carry, checked only when present — see `sha256Shape`. */
314
+ const ENTRY_SHAPES_OPTIONAL = {
315
+ importer: { sha256: sha256Shape },
316
+ transform: { sha256: sha256Shape },
317
+ // An engine entry wears one `type` for two jobs, and only one of them
318
+ // carries code. `{name, type: 'engine', source, wizard}` DECLARES a wizard
319
+ // for an engine decklight already ships (ENGINES#WIZARD) — it installs
320
+ // nothing, so it has no contract version and no capability to name. An
321
+ // engine UNIT (SPEC ENGINE_UNITS) is a module the loader runs, and needs
322
+ // both. Requiring them here would invalidate every catalog of the first
323
+ // kind, so they are shape-checked when present and their ABSENCE is
324
+ // refused at install (`cli/units.mjs`) — exactly where `sha256`'s is, for
325
+ // exactly the same blast-radius reason.
326
+ engine: {
327
+ sha256: sha256Shape,
328
+ apiVersion: (v) => (Number.isInteger(v) && v >= 1
329
+ ? null
330
+ : 'must be a positive integer — the ENGINE_UNITS contract version this engine needs, not a decklight version'),
331
+ capability: (v) => (typeof v === 'string' && /^[a-z][a-z0-9-]*$/.test(v)
332
+ ? null
333
+ : 'must name the affordance this engine answers for, e.g. "tts"'),
334
+ },
335
+ };
336
+
337
+ const ENTRY_SHAPES = {
338
+ // `import` has to name the adapter for a `.marp` file from the CACHE, with
339
+ // no network — so which extensions an adapter claims is a fact the catalog
340
+ // must carry, not something discoverable by installing it and looking.
341
+ // `apiVersion` is the same shape-only check `transform` gets below, against
342
+ // its own contract (SPEC EXTENSIONS_ADAPTERS) — an adapter is Node code
343
+ // running an installed unit, exactly like a transform is.
344
+ importer: {
345
+ extensions: (v) => (Array.isArray(v) && v.length && v.every((x) => typeof x === 'string' && /^\.?[A-Za-z0-9]+$/.test(x))
346
+ ? null
347
+ : 'must be a non-empty array of file extensions the adapter reads, e.g. [".marp"]'),
348
+ apiVersion: (v) => (Number.isInteger(v) && v >= 1
349
+ ? null
350
+ : 'must be a positive integer — the EXTENSIONS_ADAPTERS contract version this adapter needs, not a decklight version'),
351
+ },
352
+ // A transform is Node code, so it declares the invocation-contract version
353
+ // it needs rather than pinning decklight's own package version (OPEN 2) —
354
+ // see TRANSFORM_API_VERSION above. Any positive integer validates here
355
+ // regardless of what THIS decklight currently implements: a catalog written
356
+ // against a newer contract must stay addable, the same reasoning that
357
+ // leaves an unknown `type` accepted rather than refused (below).
358
+ transform: {
359
+ apiVersion: (v) => (Number.isInteger(v) && v >= 1
360
+ ? null
361
+ : 'must be a positive integer — the EXTENSIONS#TRANSFORMS contract version this transform needs, not a decklight version'),
362
+ },
363
+ // An agent entry is a DESCRIPTOR (SPEC AGENT_UNITS): the binary you already
364
+ // installed, and the argv of its headless mode. Deliberately not code — the
365
+ // three shapes the built-in roster already covers (`-p …`, `exec
366
+ // --full-auto …`, `run -t …`) are a small closed vocabulary a template
367
+ // expresses completely, so teaching decklight a new agent never means
368
+ // downloading and running someone's module (which is why `agent` is in
369
+ // REFERENCE_ONLY below and carries no `sha256`).
370
+ agent: {
371
+ bin: (v) => (typeof v === 'string' && /^[A-Za-z0-9][\w.-]*$/.test(v)
372
+ ? null
373
+ : "must be the agent's executable name, e.g. \"claude\" — a bare command, never a path or a shell line"),
374
+ args: (v) => (Array.isArray(v) && v.length && v.every((x) => typeof x === 'string')
375
+ ? (v.some((x) => x.includes('{prompt}'))
376
+ ? null
377
+ : 'must include {prompt} in one of its arguments — otherwise the agent is handed no instruction')
378
+ : 'must be the argv of the agent\'s headless mode, as an array of strings, e.g. ["-p", "{prompt}"]'),
379
+ },
380
+ // A voice entry is a POINTER (SPEC VOICE_UNITS): which engine, and which of
381
+ // that engine's voices. Both are needed for the roster to be filtered to the
382
+ // engine actually running — a reference to an ElevenLabs voice is not an
383
+ // answer when the bridge is speaking piper.
384
+ voice: {
385
+ engine: (v) => (typeof v === 'string' && /^[a-z][a-z0-9-]*$/.test(v)
386
+ ? null
387
+ : 'must name the TTS engine the voice belongs to, e.g. "elevenlabs"'),
388
+ voiceId: (v) => (typeof v === 'string' && v.trim()
389
+ ? null
390
+ : "must be the engine's own identifier for the voice"),
391
+ },
392
+ };
393
+
394
+ /**
395
+ * Kinds that NAME a thing rather than carrying it (SPEC VOICE_UNITS).
396
+ *
397
+ * A voice is distributed as a reference and never as a payload — no model
398
+ * weights, no sample audio, nothing that reproduces a person offline. The
399
+ * enforcement is this set, and it works by SUBTRACTION: an entry listed here
400
+ * has no `source`, so the code path that fetches bytes is never entered and
401
+ * there is no field through which a cloned voice could arrive.
402
+ *
403
+ * That is deliberately a shape, not an attestation. A `consent: true` field
404
+ * would be one boolean an uploader types and nobody can check — the same
405
+ * defeatable green mark the ingredients label refuses to print (SPEC
406
+ * PRESENTING). Distributing only references puts the consent relationship
407
+ * where it can actually be enforced and revoked: the provider account whose
408
+ * terms governed the cloning, and which can unshare the voice.
409
+ */
410
+ export const REFERENCE_ONLY = new Set(['voice', 'agent']);
411
+
412
+ function shapeErrors(entry, p, err) {
413
+ // NOT an early return when a type declares no required fields: a kind can be
414
+ // all-optional (`engine`, whose two fields are enforced at install instead —
415
+ // ENTRY_SHAPES_OPTIONAL above), and bailing here would skip its shape checks
416
+ // entirely, silently accepting `capability: 42`.
417
+ for (const [field, check] of Object.entries(ENTRY_SHAPES[entry.type] ?? {})) {
418
+ if (entry[field] === undefined) {
419
+ err(`${p}.${field}`, `missing — ${entry.type} entries must declare it: ${check(undefined) ?? 'see UNITS'}`);
420
+ continue;
421
+ }
422
+ const why = check(entry[field]);
423
+ if (why) err(`${p}.${field}`, why);
424
+ }
425
+ for (const [field, check] of Object.entries(ENTRY_SHAPES_OPTIONAL[entry.type] ?? {})) {
426
+ if (entry[field] === undefined) continue;
427
+ const why = check(entry[field]);
428
+ if (why) err(`${p}.${field}`, why);
429
+ }
430
+ }
431
+
432
+ /**
433
+ * Validate a manifest text. Returns `{ ok, manifest, errors }`; every error
434
+ * carries the LINE and the FIELD it is about — a typo in somebody's catalog
435
+ * is met with "line 7: entries[1].type — missing", never a stack trace.
436
+ */
437
+ export function validateManifest(raw) {
438
+ let data;
439
+ try { data = JSON.parse(raw); } catch (e) {
440
+ return { ok: false, manifest: null, errors: [{ line: parseErrorLine(raw, e), field: '(json)', msg: parseMsg(e) }] };
441
+ }
442
+ if (typeof data !== 'object' || data === null || Array.isArray(data)) {
443
+ return { ok: false, manifest: null, errors: [{ line: 1, field: '(top level)', msg: 'must be a JSON object' }] };
444
+ }
445
+ const lines = jsonLineMap(raw);
446
+ const errors = [];
447
+ // a missing key has no line of its own; its container's line is the honest one
448
+ const at = (path) => lines.get(path) ?? lines.get(path.replace(/\.[^.[\]]+$/, '')) ?? 1;
449
+ const err = (path, msg) => errors.push({ line: at(path), field: path, msg });
450
+
451
+ if (data.name === undefined) err('name', 'missing — the marketplace needs a name');
452
+ else if (typeof data.name !== 'string' || !NAME_RE.test(data.name)) {
453
+ err('name', `${JSON.stringify(data.name)} — letters, digits, - and _ only (it names every entry: entry@${typeof data.name === 'string' ? data.name : 'name'})`);
454
+ }
455
+ if (data.entries === undefined) err('entries', 'missing — an array of { name, type, source, description? }');
456
+ else if (!Array.isArray(data.entries)) err('entries', 'must be an array');
457
+ else {
458
+ const seen = new Map();
459
+ data.entries.forEach((entry, idx) => {
460
+ const p = `entries[${idx}]`;
461
+ if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) { err(p, 'must be an object'); return; }
462
+ if (entry.name === undefined) err(`${p}.name`, 'missing — the name an install asks for');
463
+ else if (typeof entry.name !== 'string' || !NAME_RE.test(entry.name)) {
464
+ err(`${p}.name`, `${JSON.stringify(entry.name)} — letters, digits, - and _ only`);
465
+ } else if (seen.has(entry.name)) {
466
+ err(`${p}.name`, `"${entry.name}" already used by entries[${seen.get(entry.name)}] — entry names are unique within a marketplace`);
467
+ } else seen.set(entry.name, idx);
468
+ if (entry.type === undefined) err(`${p}.type`, 'missing — what kind of thing this is (theme, template, skill, importer, engine, transform, …)');
469
+ else if (typeof entry.type !== 'string' || !/^[a-z][a-z0-9-]*$/.test(entry.type)) {
470
+ err(`${p}.type`, `${JSON.stringify(entry.type)} — a lowercase word (theme, template, skill, importer, engine, transform, …)`);
471
+ } else shapeErrors(entry, p, err);
472
+ if (REFERENCE_ONLY.has(entry.type)) {
473
+ // Refused, not ignored. A `source` on a reference-only entry is the one
474
+ // field through which a voice could arrive as bytes, and an ignored
475
+ // field would let a catalog carry a model that merely never loads.
476
+ if (entry.source !== undefined) {
477
+ err(`${p}.source`, `a ${entry.type} entry names a ${entry.type}, it does not carry one`
478
+ + ' — no source, no model, no sample (SPEC VOICE_UNITS)');
479
+ }
480
+ } else if (entry.source === undefined) {
481
+ err(`${p}.source`, 'missing — the repo-relative path or URL the entry is fetched from');
482
+ } else if (typeof entry.source !== 'string' || !entry.source) err(`${p}.source`, 'must be a non-empty string');
483
+ if (entry.description !== undefined && typeof entry.description !== 'string') {
484
+ err(`${p}.description`, 'must be a string');
485
+ }
486
+ });
487
+ }
488
+ return { ok: errors.length === 0, manifest: errors.length ? null : data, errors };
489
+ }
490
+
491
+ // ── sources: owner/repo, git URL, local path ───────────────────────────────
492
+
493
+ /**
494
+ * What kind of source a spec names. A path that exists always wins.
495
+ *
496
+ * `github` is a shorthand for a CLONE, not for a raw-content host: it carries
497
+ * the owner and repo so a message can name the SSH form, and `cloneUrl` below
498
+ * is what it is actually read through.
499
+ */
500
+ export function classifySource(spec, { exists = existsSync } = {}) {
501
+ const gh = /^https:\/\/github\.com\/([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/.exec(spec);
502
+ if (gh) return { kind: 'github', owner: gh[1], repo: gh[2], spec };
503
+ // `file://` is a git transport like any other (a bare mirror on a share, a
504
+ // fixture in a test) — and unlike a bare path, writing it means "clone this",
505
+ // not "read this directory in place".
506
+ if (/^(git@|ssh:\/\/|git:\/\/|file:\/\/|https?:\/\/)/.test(spec)) return { kind: 'git', url: spec, spec };
507
+ if (/^[\w.-]+\/[\w.-]+$/.test(spec) && !spec.startsWith('.') && !exists(spec)) {
508
+ const [owner, repo] = spec.split('/');
509
+ return { kind: 'github', owner, repo, spec };
510
+ }
511
+ return { kind: 'local', root: resolve(spec), spec };
512
+ }
513
+
514
+ /** The URL git is handed for a remote source. */
515
+ export const cloneUrl = (src) =>
516
+ (src.kind === 'github' ? `https://github.com/${src.owner}/${src.repo}.git` : src.url);
517
+
518
+ /**
519
+ * What to say when git could not clone a marketplace.
520
+ *
521
+ * The HTTPS form of a private repo fails here rather than 404ing somewhere
522
+ * unauthenticated, which is already the improvement — but "Repository not
523
+ * found" from a repo the user can see in their browser needs the missing half
524
+ * spelled out: decklight clones with the CALLER's git credentials, so the
525
+ * usual answer is that git has none for that host.
526
+ *
527
+ * Which it does not GUESS at. The setup instructions are printed when the
528
+ * machine actually needs them and withheld when it does not (`hasGitCredential`
529
+ * below), because advice that is wrong half the time is what teaches people to
530
+ * skim past the last line of an error. When git does have a credential, saying
531
+ * so is the more useful sentence: it means the name or the access is the
532
+ * problem, not the setup.
533
+ */
534
+ function cloneFailure(src, e, exec) {
535
+ const why = `git clone ${cloneUrl(src)} failed — ${oneline(e)}`;
536
+ // Offline is not an auth problem, and must not be answered as one: a plane
537
+ // is a first-class place to run decklight, and the cache is still there.
538
+ if (/could not resolve host|unable to access|connection (refused|timed out)|network is unreachable|SIGTERM/i.test(oneline(e))) {
539
+ return `${why}\n offline? the cached copy, if any, still serves \`marketplace list\``
540
+ + ' — and an already-cloned marketplace still installs.';
541
+ }
542
+ // Named for GitHub only, because that is the only host whose SSH URL can be
543
+ // derived rather than guessed at.
544
+ const ssh = src.kind === 'github'
545
+ ? `\n Or add it by its SSH URL, which uses your keys instead of a helper:`
546
+ + `\n decklight marketplace add git@github.com:${src.owner}/${src.repo}.git`
547
+ : '';
548
+ const url = cloneUrl(src);
549
+ if (!/^https?:\/\//i.test(url)) {
550
+ // An SSH or git:// URL never consults a credential helper — the key is the
551
+ // credential, so pointing at helper setup here would be a wrong turn.
552
+ return `${why}\n decklight clones with your own git credentials; for an SSH URL that means`
553
+ + ' your key — `ssh -T git@github.com` says whether GitHub accepts it.';
554
+ }
555
+ const host = new URL(url).host;
556
+ if (hasGitCredential(url, exec)) {
557
+ return `${why}\n git does have a credential for ${host}, so this is not a setup problem:`
558
+ + '\n check the spelling, and that the account that credential belongs to can see'
559
+ + ` the repo.${ssh}`;
560
+ }
561
+ return `${why}\n git has no credential for ${host}, so this clone was anonymous — and a`
562
+ + '\n private repo answers an anonymous clone exactly as a missing one does.'
563
+ + '\n Configure a credential helper, then try again:'
564
+ + '\n gh auth setup-git (or the macOS Keychain, or git-credential-store)'
565
+ + ssh;
566
+ }
567
+
568
+ /**
569
+ * Does git already have a usable credential for this URL's host?
570
+ *
571
+ * `git credential fill` is the only honest way to ask. Reading
572
+ * `credential.helper` out of the config answers a different question and gets
573
+ * it wrong exactly where it matters: macOS ships a global `osxkeychain`
574
+ * helper, so "a helper is configured" is true on a machine that has never
575
+ * stored a GitHub credential in its life — the precise state that fails.
576
+ *
577
+ * Prompts are disabled on every axis (terminal, askpass), so this cannot hang
578
+ * or pop a dialog, and it is bounded by its own timeout. The credential it
579
+ * fills is DISCARDED unread: only the exit status is used, nothing is logged,
580
+ * nothing is returned. This runs only after a clone has already failed.
581
+ */
582
+ export function hasGitCredential(url, exec = execFileSync) {
583
+ const { GIT_ASKPASS, SSH_ASKPASS, ...env } = process.env;
584
+ try {
585
+ const u = new URL(url);
586
+ exec('git', ['credential', 'fill'], {
587
+ input: `protocol=${u.protocol.replace(':', '')}\nhost=${u.host}\n\n`,
588
+ stdio: ['pipe', 'pipe', 'pipe'], encoding: 'utf8', timeout: 5000,
589
+ env: { ...env, GIT_TERMINAL_PROMPT: '0' },
590
+ });
591
+ return true;
592
+ } catch {
593
+ return false;
594
+ }
595
+ }
596
+
597
+ /**
598
+ * Clone a remote marketplace into a fresh directory under `stagingIn` and read
599
+ * its manifest. Returns the working tree for the caller to ADOPT (see
600
+ * `adoptCheckout`) or discard — it is never left behind on a failure.
601
+ *
602
+ * `.git` is dropped once the commit is recorded: what decklight keeps is a
603
+ * checkout, not a repository. Nothing ever pulls into it — `update` re-clones
604
+ * — which is what keeps decklight out of the credential-helper trap a
605
+ * background `git pull` walks into, and keeps `~/.decklight/` from filling up
606
+ * with nested repositories.
607
+ */
608
+ function cloneMarketplace(src, { exec, timeoutMs, stagingIn }) {
609
+ mkdirSync(stagingIn, { recursive: true });
610
+ const dir = mkdtempSync(join(stagingIn, '.staging-'));
611
+ const opts = { stdio: ['ignore', 'pipe', 'pipe'], timeout: timeoutMs * 4, encoding: 'utf8' };
612
+ try {
613
+ exec('git', ['clone', '--quiet', '--depth', '1', cloneUrl(src), dir], {
614
+ ...opts,
615
+ // never a password prompt: an unreachable private repo is an answer, not a hang
616
+ env: { ...process.env, GIT_TERMINAL_PROMPT: '0' },
617
+ });
618
+ } catch (e) {
619
+ rmSync(dir, { recursive: true, force: true });
620
+ throw new MarketplaceError(cloneFailure(src, e, exec));
621
+ }
622
+ try {
623
+ const p = join(dir, MANIFEST_PATH);
624
+ if (!existsSync(p)) throw new MarketplaceError(`${src.spec} has no ${MANIFEST_PATH} — is it a marketplace repo?`);
625
+ const raw = readFileSync(p, 'utf8');
626
+ let commit = null;
627
+ try { commit = String(exec('git', ['rev-parse', 'HEAD'], { ...opts, cwd: dir })).trim(); } catch { /* not fatal */ }
628
+ rmSync(join(dir, '.git'), { recursive: true, force: true });
629
+ return { raw, checkout: dir, commit };
630
+ } catch (e) {
631
+ rmSync(dir, { recursive: true, force: true });
632
+ throw e;
633
+ }
634
+ }
635
+
636
+ /**
637
+ * A source's manifest, and the files it came with — the only network in the
638
+ * subsystem, reached only by an explicit `add` or `update`.
639
+ *
640
+ * Returns `{ raw, checkout, commit }`. `checkout` is a directory the caller
641
+ * must adopt or remove, and is null for a local source (whose own directory
642
+ * serves that role). It fails FAST and says why: git is told never to prompt,
643
+ * the clone carries a timeout, and offline is an answer, not a hang (a plane
644
+ * is a first-class place to run decklight).
645
+ */
646
+ export async function fetchManifest(src, { exec = execFileSync, timeoutMs = 8000, stagingIn } = {}) {
647
+ if (src.kind === 'local') {
648
+ if (!existsSync(src.root)) throw new MarketplaceError(`no such directory: ${src.spec}`);
649
+ const p = join(src.root, MANIFEST_PATH);
650
+ if (!existsSync(p)) throw new MarketplaceError(`${src.spec} has no ${MANIFEST_PATH} — is it a marketplace repo?`);
651
+ return { raw: readFileSync(p, 'utf8'), checkout: null, commit: null };
652
+ }
653
+ // staged beside the destination by default, so adopting it is a rename
654
+ return cloneMarketplace(src, { exec, timeoutMs, stagingIn: stagingIn ?? join(configHome(), 'marketplaces') });
655
+ }
656
+
657
+ /**
658
+ * Put a freshly cloned working tree in place as `name`'s checkout, replacing
659
+ * whatever was there. A rename, not a copy, and the staging directory is a
660
+ * sibling of the destination — so the swap is one filesystem operation on one
661
+ * filesystem, and a half-written checkout is not a state that exists.
662
+ */
663
+ export function adoptCheckout(home, name, checkout) {
664
+ const dest = checkoutPath(home, name);
665
+ mkdirSync(join(home, 'marketplaces'), { recursive: true });
666
+ rmSync(dest, { recursive: true, force: true });
667
+ if (checkout === null) return null; // a local marketplace keeps none
668
+ renameSync(checkout, dest);
669
+ return dest;
670
+ }
671
+
672
+ // ── the cache, and names ───────────────────────────────────────────────────
673
+
674
+ /** The cached manifest for `name`: null when never fetched, else a validation. */
675
+ export function loadCatalog(name, home = configHome()) {
676
+ const p = cachePath(home, name);
677
+ if (!existsSync(p)) return null;
678
+ return validateManifest(readFileSync(p, 'utf8'));
679
+ }
680
+
681
+ /**
682
+ * Resolve an entry reference against every cached catalog. `name@marketplace`
683
+ * is exact; a bare name resolves only when it exists in exactly ONE
684
+ * registered marketplace — two is reported as ambiguous with the qualified
685
+ * forms to say instead, never silently resolved to either. This is the seam
686
+ * every install surface (theme browse, engine wizard, `init --from`) goes
687
+ * through; nothing in THIS command installs anything.
688
+ */
689
+ export function resolveEntry(ref, catalogs) {
690
+ const q = /^(.+)@([^@]+)$/.exec(ref);
691
+ if (q) {
692
+ const [, entryName, market] = q;
693
+ const cat = catalogs[market];
694
+ if (!cat) throw new MarketplaceError(`no marketplace "${market}" is registered (decklight marketplace list)`);
695
+ const entry = (cat.entries ?? []).find((e) => e.name === entryName);
696
+ if (!entry) throw new MarketplaceError(`no "${entryName}" in ${market}`);
697
+ return { entry, marketplace: market, qualified: `${entryName}@${market}` };
698
+ }
699
+ const hits = [];
700
+ for (const [market, cat] of Object.entries(catalogs)) {
701
+ for (const e of cat?.entries ?? []) {
702
+ if (e.name === ref) hits.push({ entry: e, marketplace: market, qualified: `${ref}@${market}` });
703
+ }
704
+ }
705
+ if (hits.length === 0) throw new MarketplaceError(`no "${ref}" in any registered marketplace`);
706
+ if (hits.length > 1) {
707
+ throw new MarketplaceError(`"${ref}" is ambiguous — it exists in ${hits.length} marketplaces:`
708
+ + ` ${hits.map((h) => h.qualified).join(', ')} — say which`);
709
+ }
710
+ return hits[0];
711
+ }
712
+
713
+ // ── the command ────────────────────────────────────────────────────────────
714
+
715
+ const USAGE = `usage: decklight marketplace <add|list|update|remove> …
716
+
717
+ decklight marketplace add <owner/repo | git url | path> [--name <name>]
718
+ clone the source, read ${MANIFEST_PATH} at its root, and register
719
+ the catalog under ~/.decklight/ — a local path never touches the network
720
+ EXAMPLE: decklight marketplace add decklight/decklight-plugins-official
721
+ EXAMPLE: decklight marketplace add ../my-marketplace
722
+
723
+ the clone uses YOUR git credentials, so a private marketplace works the
724
+ way git clone does in your terminal — and its entries install from that
725
+ clone, at the commit the manifest came from
726
+
727
+ decklight marketplace list
728
+ every registered marketplace and its cached entries (as name@marketplace),
729
+ read from the cache alone — list works on a plane
730
+
731
+ decklight marketplace update <name>
732
+ re-clone a marketplace, refreshing the cached manifest and the checkout
733
+ its entries install from; for a registered-not-fetched marketplace this is
734
+ the FIRST fetch it ever gets
735
+
736
+ decklight marketplace remove <name>
737
+ unregister a marketplace and drop its cached manifest and checkout
738
+
739
+ registering is not fetching: the network is touched only by an explicit add
740
+ or update, never when a deck loads or presents (SPEC MARKETPLACE_REGISTRY).
741
+ DECKLIGHT_HOME overrides ~/.decklight/.`;
742
+
743
+ const printManifestErrors = (cmd, spec, errors) => {
744
+ console.error(`decklight marketplace ${cmd}: ${spec} — ${MANIFEST_PATH} is not a valid marketplace manifest:`);
745
+ for (const e of errors) console.error(` line ${e.line}: ${e.field} — ${e.msg}`);
746
+ };
747
+
748
+ const entriesSummary = (name, entries) => {
749
+ const shown = entries.slice(0, 6).map((e) => `${e.name}@${name}`);
750
+ if (entries.length > shown.length) shown.push(`… ${entries.length - shown.length} more`);
751
+ return `${entries.length} ${entries.length === 1 ? 'entry' : 'entries'}${entries.length ? `: ${shown.join(', ')}` : ''}`;
752
+ };
753
+
754
+ async function addMain(args, home) {
755
+ const { opt } = argReader(args);
756
+ const [spec] = args.filter((a, i) => !a.startsWith('-') && args[i - 1] !== '--name');
757
+ if (!spec) { console.error(`decklight marketplace add: needs an owner/repo, a git url, or a path\n\n${USAGE}`); return 1; }
758
+
759
+ const src = classifySource(spec);
760
+ let got;
761
+ try { got = await fetchManifest(src, { stagingIn: join(home, 'marketplaces') }); } catch (e) {
762
+ console.error(`decklight marketplace add: ${e.message}`);
763
+ return 1;
764
+ }
765
+ // Everything below either adopts the clone or drops it — a staging directory
766
+ // must not survive a refusal, so every early return passes through here.
767
+ try {
768
+ const v = validateManifest(got.raw);
769
+ if (!v.ok) { printManifestErrors('add', spec, v.errors); return 1; }
770
+
771
+ const name = opt('--name') ?? v.manifest.name;
772
+ if (!NAME_RE.test(name)) { console.error(`decklight marketplace add: "${name}" is not a usable marketplace name`); return 1; }
773
+
774
+ const reg = loadRegistry(home);
775
+ const existing = reg.marketplaces[name];
776
+ if (existing && existing.source !== spec) {
777
+ console.error(`decklight marketplace add: "${name}" is already registered from ${existing.source}`);
778
+ console.error(` remove it first, or register this one under another name with --name`);
779
+ return 1;
780
+ }
781
+ reg.marketplaces[name] = { ...(existing ?? {}), source: spec, commit: got.commit ?? undefined };
782
+ writeCache(home, name, got.raw);
783
+ const at = adoptCheckout(home, name, got.checkout);
784
+ got.checkout = null;
785
+ saveRegistry(reg, home);
786
+ console.log(`${existing ? 'refreshed' : 'registered'} ${name} from ${spec} — ${entriesSummary(name, v.manifest.entries)}`);
787
+ if (at) console.log(` cloned to ${at}${got.commit ? ` (${got.commit.slice(0, 7)})` : ''} — installing an entry reads it, not the network`);
788
+ return 0;
789
+ } finally {
790
+ if (got.checkout) rmSync(got.checkout, { recursive: true, force: true });
791
+ }
792
+ }
793
+
794
+ function writeCache(home, name, raw) {
795
+ mkdirSync(join(home, 'marketplaces'), { recursive: true });
796
+ writeFileSync(cachePath(home, name), raw);
797
+ }
798
+
799
+ function listMain(home) {
800
+ const reg = loadRegistry(home);
801
+ const names = Object.keys(reg.marketplaces).sort();
802
+ if (!names.length) {
803
+ console.log('no marketplaces registered — decklight marketplace add <owner/repo | git url | path>');
804
+ return 0;
805
+ }
806
+ for (const name of names) {
807
+ const m = reg.marketplaces[name];
808
+ // The commit is what the manifest AND every entry's files came from — one
809
+ // clone, so there is a single answer to "which version of this catalog is
810
+ // installed", and it is worth printing.
811
+ const head = `${name}${m.firstParty ? ' (first-party)' : ''} ${m.source}`
812
+ + `${m.commit ? ` @${m.commit.slice(0, 7)}` : ''}`;
813
+ const cached = loadCatalog(name, home);
814
+ if (cached === null) {
815
+ console.log(`${head} — registered, not fetched (decklight marketplace update ${name})`);
816
+ } else if (!cached.ok) {
817
+ console.log(`${head} — cached copy unreadable (decklight marketplace update ${name})`);
818
+ } else {
819
+ // Grouped by KIND rather than listed flat (UNITS): a catalog's entries
820
+ // are not one undifferentiated bag of names — what you can do with an
821
+ // entry depends entirely on what kind it is, and the install command
822
+ // differs per kind. A kind this decklight does not know is shown as
823
+ // exactly that, so a catalog written against a newer version reads as
824
+ // "not yet" rather than as a typo.
825
+ const entries = cached.manifest.entries;
826
+ console.log(`${head} — ${entries.length} ${entries.length === 1 ? 'entry' : 'entries'}`);
827
+ const kinds = [...new Set(entries.map((e) => e.type))].sort();
828
+ for (const kind of kinds) {
829
+ const known = KNOWN_TYPES.includes(kind);
830
+ const how = INSTALL_HINT[kind];
831
+ console.log(` ${kind}${known ? '' : ' (this decklight does not install this kind)'}`
832
+ + `${how ? ` — ${how}` : ''}`);
833
+ for (const e of entries.filter((x) => x.type === kind)) {
834
+ console.log(` ${e.name}@${name}${e.description ? ` — ${e.description}` : ''}`);
835
+ }
836
+ }
837
+ }
838
+ }
839
+ return 0;
840
+ }
841
+
842
+ async function updateMain(args, home) {
843
+ const [name] = args.filter((a) => !a.startsWith('-'));
844
+ if (!name) { console.error(`decklight marketplace update: which one?\n\n${USAGE}`); return 1; }
845
+ const reg = loadRegistry(home);
846
+ const m = reg.marketplaces[name];
847
+ if (!m) { console.error(`decklight marketplace update: no marketplace "${name}" (decklight marketplace list)`); return 1; }
848
+
849
+ const first = loadCatalog(name, home) === null;
850
+ let got;
851
+ try { got = await fetchManifest(classifySource(m.source), { stagingIn: join(home, 'marketplaces') }); } catch (e) {
852
+ console.error(`decklight marketplace update: ${name}: ${e.message}`);
853
+ // The clone lands in staging and is adopted only once it validates, so a
854
+ // failed update leaves BOTH halves of what is on disk untouched — the
855
+ // cached manifest and the checkout its entries install from.
856
+ if (!first) console.error(` the cached copy is untouched — list still works`);
857
+ return 1;
858
+ }
859
+ try {
860
+ const v = validateManifest(got.raw);
861
+ if (!v.ok) { printManifestErrors('update', m.source, v.errors); return 1; }
862
+ writeCache(home, name, got.raw);
863
+ const at = adoptCheckout(home, name, got.checkout);
864
+ got.checkout = null;
865
+ const reg2 = loadRegistry(home);
866
+ if (reg2.marketplaces[name]) {
867
+ reg2.marketplaces[name] = { ...reg2.marketplaces[name], commit: got.commit ?? undefined };
868
+ saveRegistry(reg2, home);
869
+ }
870
+ console.log(`${first ? 'fetched' : 'updated'} ${name} — ${entriesSummary(name, v.manifest.entries)}`);
871
+ if (at) console.log(` cloned to ${at}${got.commit ? ` (${got.commit.slice(0, 7)})` : ''}`);
872
+ return 0;
873
+ } finally {
874
+ if (got.checkout) rmSync(got.checkout, { recursive: true, force: true });
875
+ }
876
+ }
877
+
878
+ function removeMain(args, home) {
879
+ const [name] = args.filter((a) => !a.startsWith('-'));
880
+ if (!name) { console.error(`decklight marketplace remove: which one?\n\n${USAGE}`); return 1; }
881
+ const reg = loadRegistry(home);
882
+ const m = reg.marketplaces[name];
883
+ if (!m) { console.error(`decklight marketplace remove: no marketplace "${name}" (decklight marketplace list)`); return 1; }
884
+ delete reg.marketplaces[name];
885
+ saveRegistry(reg, home);
886
+ rmSync(cachePath(home, name), { force: true });
887
+ rmSync(checkoutPath(home, name), { recursive: true, force: true });
888
+ console.log(`removed ${name} — re-add any time with: decklight marketplace add ${m.source}`);
889
+ return 0;
890
+ }
891
+
892
+ export async function marketplaceMain(args = []) {
893
+ const sub = args[0];
894
+ if (!sub || sub === '--help' || sub === '-h' || sub === 'help') { console.log(USAGE); return sub ? 0 : 1; }
895
+ const rest = args.slice(1);
896
+ if (rest.includes('--help') || rest.includes('-h')) { console.log(USAGE); return 0; }
897
+ const home = configHome();
898
+ try {
899
+ if (sub === 'add') return await addMain(rest, home);
900
+ if (sub === 'list') return listMain(home);
901
+ if (sub === 'update') return await updateMain(rest, home);
902
+ if (sub === 'remove') return removeMain(rest, home);
903
+ } catch (e) {
904
+ if (e instanceof MarketplaceError) { console.error(`decklight marketplace ${sub}: ${e.message}`); return 1; }
905
+ throw e;
906
+ }
907
+ console.error(`decklight marketplace: unknown subcommand "${sub}"\n\n${USAGE}`);
908
+ return 1;
909
+ }
910
+
911
+ if (isMain(import.meta.url)) process.exit(await marketplaceMain(process.argv.slice(2)));