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,40 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ // The Node side's HTML escape. One function, deliberately.
5
+ //
6
+ // This file replaced four of them: `cli/serve.mjs` escaped `& < >`,
7
+ // `cli/bundle.mjs`'s escAttr escaped `& " <`, `tools/pptx.mjs` and
8
+ // `src/core/charts.js` escaped `& < > "` — two of them named `escapeHtml` and
9
+ // behaving differently. None of the call sites was wrong, which is exactly the
10
+ // problem: the next caller picks one by name, and the one whose name reads
11
+ // most general (`escapeHtml`, in serve.mjs) was the one that left quotes
12
+ // alone. `cli/init.mjs` already carried the comment "a prompt invites &, <
13
+ // and quotes" above a call that escaped two of those three.
14
+ //
15
+ // So the choice here is a single escape that is correct in BOTH places text
16
+ // can land — element content and a double-quoted attribute — rather than a
17
+ // pair the caller has to choose between correctly. Single quotes are left
18
+ // alone: every attribute decklight writes is double-quoted, and `&#39;` in a
19
+ // title is churn with no reader.
20
+ //
21
+ // `<!--` and `</script` are a different problem with a different answer —
22
+ // they are about what a SCRIPT body may contain, not what text may, and
23
+ // `scriptSafe` in cli/util.mjs owns them.
24
+ //
25
+ // The runtime has its own copy in src/core/escape.js, because src/ is bundled
26
+ // into a zero-dependency artifact and cannot import from tools/. A test pins
27
+ // the two against each other so "its own copy" cannot become "its own
28
+ // behaviour" (test/deck-html.test.mjs).
29
+
30
+ /**
31
+ * Escape `s` for HTML text or a double-quoted attribute value.
32
+ *
33
+ * Order matters: `&` first, or the ampersands introduced by the later
34
+ * replacements get escaped a second time.
35
+ */
36
+ export const escapeHtml = (s) => String(s)
37
+ .replace(/&/g, '&amp;')
38
+ .replace(/</g, '&lt;')
39
+ .replace(/>/g, '&gt;')
40
+ .replace(/"/g, '&quot;');
@@ -0,0 +1,41 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ // The child half of `extension check`'s process boundary (SPEC
5
+ // EXTENSIONS_CHECK) — the ONLY process in which the checked submission ever
6
+ // executes. Spawned by tools/extension-check.mjs under Node's permission
7
+ // model (reads limited to decklight's package and the submission's own
8
+ // directory, no writes, no child processes, no workers), with a replaced
9
+ // environment, a temp cwd and a wall-clock kill. Never run by hand.
10
+ //
11
+ // Protocol: argv[2] is the transform file; the fixture arrives in
12
+ // $DECKLIGHT_CHECK_FIXTURE (env, not argv — spawnSync replaces the whole
13
+ // environment, so this is also what proves nothing else crossed); the
14
+ // verdict leaves on stdout as one JSON object after RESULT_DELIM. After,
15
+ // because the submission shares this stdout and whatever it prints must not
16
+ // be mistaken for the verdict: the parent reads past the LAST marker, so a
17
+ // forged one is overwritten by the real one, and a submission that kills the
18
+ // process before the marker becomes a refusal, not a pass.
19
+
20
+ import path from 'node:path';
21
+ import { runTransformAt, LoaderError } from '../cli/loader.mjs';
22
+ import { RESULT_DELIM } from './extension-check.mjs';
23
+
24
+ const report = (verdict) => process.stdout.write(`${RESULT_DELIM}${JSON.stringify(verdict)}\n`);
25
+
26
+ const file = process.argv[2];
27
+ const fixture = process.env.DECKLIGHT_CHECK_FIXTURE;
28
+ if (!file || typeof fixture !== 'string') {
29
+ report({ ok: false, error: 'extension-check-runner: spawned without a file and a fixture'
30
+ + ' — this is tools/extension-check.mjs\'s child, not a command' });
31
+ process.exit(1);
32
+ }
33
+
34
+ try {
35
+ const html = await runTransformAt(path.resolve(file), fixture, path.basename(file));
36
+ report({ ok: true, html });
37
+ } catch (e) {
38
+ report({ ok: false, error: e instanceof LoaderError ? e.message
39
+ : `transform "${path.basename(file)}" failed: ${e.message}` });
40
+ process.exitCode = 1;
41
+ }
@@ -0,0 +1,266 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ // The marketplace admission gate for build-time code (MARKETPLACE.md
5
+ // EXTENSIONS#CHECK, SPEC EXTENSIONS_CHECK) — what `decklight extension check`
6
+ // runs. Lives under tools/, which ships, for the reason tools/theme-check.mjs
7
+ // already gives: test/ does not, so a marketplace's own CI needs this
8
+ // reachable from the installed package, not from a suite that never travels.
9
+ //
10
+ // Three phases, checking three different things:
11
+ //
12
+ // THE LINT IS ADVISORY, NOT A BOUNDARY. A shallow source-text scan for the
13
+ // reaches a build-time transform has no business making — the same kind
14
+ // `cli/plugin.mjs`'s `pluginLint` runs. It catches the honest mistake and
15
+ // states the bar in a sentence; it does not constrain a determined one. A
16
+ // static `import { execSync } from 'node:child_process'`, a `new
17
+ // Function('return fetch')()`, a `globalThis['fet' + 'ch']` all pass a
18
+ // regex unmatched, and no source-text scan closes that class.
19
+ //
20
+ // THE SUBMISSION ONLY EVER EXECUTES BEHIND A PROCESS BOUNDARY. This
21
+ // process never `import()`s the checked file: `runTransformIsolated` runs
22
+ // it in a separate Node process under the permission model, with reads
23
+ // limited to decklight's own package and the submission's directory, no
24
+ // filesystem writes, no child processes, no workers, a scrubbed
25
+ // environment, a temp working directory, and a wall-clock kill. What the
26
+ // boundary does NOT cover, stated plainly: Node's permission model does
27
+ // not restrict the network, so a hostile submission can still phone home
28
+ // during the check — the boundary protects the checking machine's files,
29
+ // processes and environment, not its network. And admission proves nothing
30
+ // about later: an installed transform runs as trusted, unsandboxed Node
31
+ // (EXTENSIONS_TRANSFORMS) — the installer bears that risk (MARKETPLACE.md
32
+ // EXTENSIONS). Admission screens; it does not absolve.
33
+ //
34
+ // THE HEADLESS LOAD CHECKS THE OUTPUT, NOT THE SOURCE. The transform runs
35
+ // against ONE small fixture this module owns — randomised per check, so a
36
+ // submission cannot recognise the fixture and behave only for the checker —
37
+ // never the submitter's own deck: proving the CONTRACT, not "does it
38
+ // handle some particular author's markup". Refused if the rendered result
39
+ // carries a <script> block or an inline event handler (`on…=` attribute):
40
+ // both are "the deck now carries executable code", the invariant
41
+ // "build-time transforms produce output, not code; nothing executable
42
+ // travels" (MARKETPLACE.md EXTENSIONS) exists to refuse.
43
+
44
+ import { mkdtempSync, writeFileSync, readFileSync, rmSync, realpathSync } from 'node:fs';
45
+ import { execFileSync, spawnSync } from 'node:child_process';
46
+ import { createHash, randomBytes } from 'node:crypto';
47
+ import { tmpdir } from 'node:os';
48
+ import path from 'node:path';
49
+ import { fileURLToPath } from 'node:url';
50
+ import { chromeBin, chromeArgs } from './chrome.mjs';
51
+
52
+ const here = path.dirname(fileURLToPath(import.meta.url));
53
+ const PKG_ROOT = path.resolve(here, '..');
54
+ const RUNNER = path.join(here, 'extension-check-runner.mjs');
55
+
56
+ /** Node's permission model grants on REAL paths — it resolves a symlink before
57
+ * it checks, so `--allow-fs-read` on a path that crosses one grants nothing.
58
+ * macOS makes that the common case, not the exotic one (`/tmp` is a symlink to
59
+ * `/private/tmp`, and `os.tmpdir()` is `/var/folders/…` → `/private/var/…`), so
60
+ * a submission checked from a temp directory was refused for the checker's own
61
+ * path handling — reported as the submission failing to load. Resolve before
62
+ * granting; fall back to the path as given when it does not exist yet, which
63
+ * `checkExtension` has already refused by name. */
64
+ const real = (p) => { try { return realpathSync(p); } catch { return p; } };
65
+
66
+ /** Extension kinds `extension check` knows how to validate. The import-adapter
67
+ * contract this would grow to is frozen (SPEC EXTENSIONS_ADAPTERS); an
68
+ * `importer` kind here is future work with its ticket still to file. */
69
+ export const TYPES = ['transform'];
70
+
71
+ /**
72
+ * The pin a passing submission's catalog entry carries (SPEC UNIT_PINNING) —
73
+ * the SHA-256 of the file's raw bytes, exactly as `sha256sum` prints it, so
74
+ * the gate that admits a transform also emits the digest `decklight
75
+ * transform add` will hold the fetched module to.
76
+ */
77
+ export const artifactSha256 = (file) =>
78
+ createHash('sha256').update(readFileSync(file)).digest('hex');
79
+
80
+ /** How long the submission gets, in each of its two executions (the transform
81
+ * run and the headless load of its output), before a hard kill. */
82
+ export const CHECK_TIMEOUT_MS = 15_000;
83
+
84
+ /** What the runner's verdict on stdout follows — AFTER whatever the transform
85
+ * itself printed, so the parent reads past the LAST occurrence and a forged
86
+ * marker is overwritten by the real one. */
87
+ export const RESULT_DELIM = '\n__decklight_extension_check_result__';
88
+
89
+ /**
90
+ * The fixture a check runs a transform against — small on purpose (SPEC
91
+ * EXTENSIONS_CHECK: this proves the calling convention, not any particular
92
+ * author's deck) and randomised per call, so a submission cannot recognise
93
+ * the fixture and behave only while being checked.
94
+ */
95
+ export function makeFixture() {
96
+ const nonce = randomBytes(8).toString('hex');
97
+ return `<!doctype html>\n<html><head><title>check ${nonce}</title></head>`
98
+ + `<body><section><h2>Check ${nonce}</h2><p>decklight extension check ${nonce}</p></section></body></html>\n`;
99
+ }
100
+
101
+ /**
102
+ * Reaches a build-time transform has no business making. Advisory (see the
103
+ * header): the boundary is `runTransformIsolated`, not this scan.
104
+ */
105
+ const LINT = [
106
+ [/\bfetch\s*\(/, 'calls fetch()'],
107
+ [/\beval\s*\(/, 'calls eval()'],
108
+ [/\bXMLHttpRequest\b/, 'uses XMLHttpRequest'],
109
+ [/\bimport\s*\(/, 'uses a dynamic import()'],
110
+ ];
111
+
112
+ /** `[{ line, why, text }]` for a transform's source — empty when nothing matched. */
113
+ export function extensionLint(js) {
114
+ const out = [];
115
+ js.split('\n').forEach((text, i) => {
116
+ for (const [re, why] of LINT) {
117
+ if (re.test(text)) out.push({ line: i + 1, why, text: text.trim().slice(0, 90) });
118
+ }
119
+ });
120
+ return out;
121
+ }
122
+
123
+ /** The permission-model flag this Node answers to (`--permission` from 22.13,
124
+ * `--experimental-permission` back to the `engines` floor of 20), probed once
125
+ * and cached — or null on a Node that has neither, which `checkExtension`
126
+ * turns into a named refusal, never a silent unsandboxed run. */
127
+ let cachedPermissionFlag;
128
+ function permissionFlag() {
129
+ if (cachedPermissionFlag !== undefined) return cachedPermissionFlag;
130
+ for (const flag of ['--permission', '--experimental-permission']) {
131
+ if (spawnSync(process.execPath, [flag, '-e', '0'], { stdio: 'ignore' }).status === 0) {
132
+ cachedPermissionFlag = flag;
133
+ return flag;
134
+ }
135
+ }
136
+ cachedPermissionFlag = null;
137
+ return null;
138
+ }
139
+
140
+ /**
141
+ * Run one transform file against `fixture` behind the process boundary the
142
+ * header describes, via tools/extension-check-runner.mjs. Returns `{ ok:
143
+ * true, html }`, or `{ ok: false, phase, error }` ready for `checkExtension`
144
+ * to hand back — `phase` is `'boundary'` when the boundary itself cannot be
145
+ * established, `'load'` for everything the submission did wrong.
146
+ *
147
+ * The env is REPLACED, not extended: the fixture is the only variable that
148
+ * crosses, so whatever secrets the checking machine's environment holds (a
149
+ * CI runner's tokens, say) never enter the process the submission runs in.
150
+ */
151
+ export function runTransformIsolated(file, fixture, { timeoutMs = CHECK_TIMEOUT_MS } = {}) {
152
+ const abs = path.resolve(file);
153
+ const flag = permissionFlag();
154
+ if (!flag) {
155
+ return { ok: false, phase: 'boundary', error: 'this Node has no permission model'
156
+ + ' (needs --permission or --experimental-permission, Node 20+) — refusing to run'
157
+ + ' an unvetted transform without the process boundary' };
158
+ }
159
+ const cwd = mkdtempSync(path.join(tmpdir(), 'decklight-extension-run-'));
160
+ try {
161
+ const realAbs = real(abs);
162
+ const res = spawnSync(process.execPath, [
163
+ flag,
164
+ `--allow-fs-read=${real(PKG_ROOT)}${path.sep}`,
165
+ `--allow-fs-read=${path.dirname(realAbs)}${path.sep}`,
166
+ RUNNER, realAbs,
167
+ ], {
168
+ cwd, encoding: 'utf8', maxBuffer: 8 * 1024 * 1024,
169
+ timeout: timeoutMs, killSignal: 'SIGKILL',
170
+ env: { DECKLIGHT_CHECK_FIXTURE: fixture },
171
+ stdio: ['ignore', 'pipe', 'ignore'],
172
+ });
173
+ if (res.error?.code === 'ETIMEDOUT' || res.signal) {
174
+ return { ok: false, phase: 'load', error: `the transform did not finish within ${Math.round(timeoutMs / 1000)}s`
175
+ + ' and was killed — a transform must return (an infinite loop, or waiting on something'
176
+ + ' that never comes)' };
177
+ }
178
+ if (res.error) {
179
+ return { ok: false, phase: 'load', error: `the transform could not be run — ${res.error.message}` };
180
+ }
181
+ const at = (res.stdout ?? '').lastIndexOf(RESULT_DELIM);
182
+ let verdict;
183
+ try {
184
+ verdict = at < 0 ? null : JSON.parse(res.stdout.slice(at + RESULT_DELIM.length));
185
+ } catch { verdict = null; }
186
+ if (!verdict) {
187
+ return { ok: false, phase: 'load', error: 'the transform exited without returning its output'
188
+ + ' (a process.exit(), or a crash) — a transform must return a string' };
189
+ }
190
+ if (!verdict.ok) return { ok: false, phase: 'load', error: verdict.error };
191
+ return { ok: true, html: verdict.html };
192
+ } finally {
193
+ rmSync(cwd, { recursive: true, force: true });
194
+ }
195
+ }
196
+
197
+ /**
198
+ * Headlessly render `html` and return the dumped DOM — a temp file, never
199
+ * the checked file itself, since what is being loaded is the OUTPUT.
200
+ *
201
+ * `timeout`/`killSignal` are load-bearing, not a courtesy: `--virtual-time-
202
+ * budget` bounds Chrome's own clock, but a synchronous `alert()`/`confirm()`
203
+ * in the OUTPUT opens a native dialog that blocks the render loop outside
204
+ * virtual time entirely, and an infinite loop blocks it the same way — and
205
+ * this command's whole job is loading output from code nobody has vetted
206
+ * yet. Without a hard wall-clock kill, one such submission hangs whatever is
207
+ * running the check (a marketplace's own CI) forever.
208
+ */
209
+ function headlessLoad(html) {
210
+ const dir = mkdtempSync(path.join(tmpdir(), 'decklight-extension-check-'));
211
+ try {
212
+ const file = path.join(dir, 'output.html');
213
+ writeFileSync(file, html);
214
+ return execFileSync(chromeBin('extension check'), chromeArgs(
215
+ '--virtual-time-budget=2000', '--dump-dom', `file://${file}`,
216
+ ), {
217
+ encoding: 'utf8', maxBuffer: 8 * 1024 * 1024,
218
+ timeout: CHECK_TIMEOUT_MS, killSignal: 'SIGKILL',
219
+ stdio: ['ignore', 'pipe', 'ignore'],
220
+ });
221
+ } finally {
222
+ rmSync(dir, { recursive: true, force: true });
223
+ }
224
+ }
225
+
226
+ /**
227
+ * Validate one transform source file. Returns `{ ok: true }` or `{ ok:
228
+ * false, phase, ... }` — `phase` is `'lint'` (with `lint`, the matches),
229
+ * `'boundary'` (the process boundary could not be established), `'load'`
230
+ * (with `error`, what the submission did wrong when run) or `'output'` (with
231
+ * `error`) — never a raw stack trace.
232
+ */
233
+ export async function checkExtension(file, { type = 'transform' } = {}) {
234
+ if (!TYPES.includes(type)) {
235
+ return { ok: false, phase: 'type', error: `--type ${type} is not implemented yet`
236
+ + ` — this decklight only checks: ${TYPES.join(', ')}` };
237
+ }
238
+
239
+ const abs = path.resolve(file);
240
+ const lint = extensionLint(readFileSync(abs, 'utf8'));
241
+ if (lint.length) return { ok: false, phase: 'lint', lint };
242
+
243
+ const run = runTransformIsolated(abs, makeFixture());
244
+ if (!run.ok) return run;
245
+
246
+ let dumped;
247
+ try {
248
+ dumped = headlessLoad(run.html);
249
+ } catch (e) {
250
+ if (e.signal || e.code === 'ETIMEDOUT') {
251
+ return { ok: false, phase: 'output', error: 'the headless load did not finish within 15s and was killed —'
252
+ + ' the output must never block the page (a synchronous alert()/confirm()/prompt(), or an infinite loop)' };
253
+ }
254
+ throw e;
255
+ }
256
+ if (/<script[\s>]/i.test(dumped)) {
257
+ return { ok: false, phase: 'output', error: 'the output contains a <script> block — a transform'
258
+ + ' must produce HTML only; nothing executable may travel (MARKETPLACE.md EXTENSIONS)' };
259
+ }
260
+ if (/<[a-z][^>]*\son[a-z]+\s*=/i.test(dumped)) {
261
+ return { ok: false, phase: 'output', error: 'the output carries an inline event handler (an on…= attribute)'
262
+ + ' — as executable as a <script> block, just waiting for a click; nothing executable'
263
+ + ' may travel (MARKETPLACE.md EXTENSIONS)' };
264
+ }
265
+ return { ok: true, sha256: artifactSha256(abs) };
266
+ }
@@ -42,6 +42,19 @@ export function gcloudToken() {
42
42
  { encoding: 'utf8' }).trim();
43
43
  }
44
44
 
45
+ /**
46
+ * Headers for a Vertex AI call made with ADC (a user credential): the Bearer
47
+ * token, JSON content-type, and x-goog-user-project so the call is billed and
48
+ * quota'd against the project, not whoever's gcloud is signed in. Every Vertex
49
+ * caller here already puts the project in the URL path; the header is what
50
+ * directs the *bill* there too.
51
+ */
52
+ export const authHeaders = (token, project) => ({
53
+ authorization: `Bearer ${token}`,
54
+ 'content-type': 'application/json',
55
+ 'x-goog-user-project': project,
56
+ });
57
+
45
58
  // Published Vertex AI list prices (USD per 1M tokens) — the API returns
46
59
  // token counts in usageMetadata, never dollars, so cost is an ESTIMATE.
47
60
  const PRICES = [
@@ -53,7 +66,12 @@ function estimateCost(model, usage) {
53
66
  return ((usage.promptTokenCount ?? 0) * p.input + (usage.candidatesTokenCount ?? 0) * p.output) / 1e6;
54
67
  }
55
68
 
56
- function wavFromPcm(pcm, rate) {
69
+ /**
70
+ * Wrap headerless 16-bit mono PCM in a RIFF/WAVE header. Every engine that
71
+ * gets raw samples back lands here (Gemini's audio/L16, ElevenLabs' pcm_24000)
72
+ * — WAV is what the deck's ⇧V stitching and the lip-sync bridge both read.
73
+ */
74
+ export function wavFromPcm(pcm, rate) {
57
75
  const h = Buffer.alloc(44);
58
76
  h.write('RIFF', 0); h.writeUInt32LE(36 + pcm.length, 4); h.write('WAVE', 8);
59
77
  h.write('fmt ', 12); h.writeUInt32LE(16, 16); h.writeUInt16LE(1, 20); h.writeUInt16LE(1, 22);
@@ -102,7 +120,7 @@ export function createSynth({ project, ttsModel, location } = {}) {
102
120
  const url = `https://${host}/v1/projects/${project}/locations/${loc}/publishers/google/models/${model}:generateContent`;
103
121
  const res = await fetch(url, {
104
122
  method: 'POST',
105
- headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },
123
+ headers: authHeaders(token, project),
106
124
  body: JSON.stringify({
107
125
  contents: [{ role: 'user', parts: [{ text }] }],
108
126
  generationConfig: {
@@ -134,8 +152,12 @@ export function createSynth({ project, ttsModel, location } = {}) {
134
152
  return async function synth(text, { voice = 'Alnilam', style = '' } = {}) {
135
153
  token ??= gcloudToken();
136
154
  const prompt = styledPrompt(style, text);
155
+ // An explicit --tts-model is a price ceiling: try only that model (both
156
+ // locations), never fall through to a different, costlier one. The
157
+ // pro/pro-preview pair is a fallback only when NO model was requested.
158
+ const models = ttsModel ? [ttsModel] : ['gemini-2.5-pro-tts', 'gemini-2.5-pro-preview-tts'];
137
159
  const routes = route ? [route]
138
- : [ttsModel ?? 'gemini-2.5-pro-tts', 'gemini-2.5-pro-preview-tts']
160
+ : models
139
161
  .flatMap((m) => [location ?? 'global', 'us-central1'].map((l) => ({ model: m, location: l })))
140
162
  .filter((r, i, a) => a.findIndex((x) => x.model === r.model && x.location === r.location) === i);
141
163
  let lastErr;
@@ -0,0 +1,81 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ // The external programs that turn a wav into a mouth: rhubarb (visemes),
5
+ // Wav2Lip and SadTalker (a talking head), and ffmpeg (mute + faststart). The
6
+ // batch tool (lipsync.mjs) and the bridge (lipsync-server.mjs) each drove all
7
+ // four, and the argv had already started to drift (a timeout here, not there).
8
+ //
9
+ // This is the invocation ONLY — each caller still owns its own temp-file names,
10
+ // disk cache, dedup, and GPU queue, and the cache KEYS stay per-tool on purpose
11
+ // (unifying them would invalidate every user's cached clips). Everything is
12
+ // async: the batch tool was execFileSync in a loop, but it runs under a
13
+ // top-level await, so awaiting a shared runner is the same sequential work.
14
+ //
15
+ // COVERAGE: runRhubarb is exercised by test/lipsync.test.mjs (bridge) and
16
+ // test/lipsync-batch.test.mjs (batch) against a stub rhubarb. runWav2lip /
17
+ // runSadtalker need a GPU + model checkpoints and run in neither, so they are
18
+ // preserved argv-for-argv from the two call sites rather than re-derived.
19
+
20
+ import { execFile } from 'node:child_process';
21
+ import { promisify } from 'node:util';
22
+ import { readFileSync, writeFileSync, rmSync, mkdirSync, readdirSync, statSync, renameSync } from 'node:fs';
23
+ import { resolve, join } from 'node:path';
24
+ import { normalizeRhubarb } from './visemes.mjs';
25
+
26
+ const run = promisify(execFile);
27
+
28
+ // captured (not inherited) so the tool's own progress lines aren't drowned; a
29
+ // GPU job the batch tool wants to watch live passes inherit:true instead.
30
+ const bufOpts = (timeout, inherit) => ({
31
+ ...(timeout ? { timeout } : {}),
32
+ ...(inherit ? { stdio: 'inherit' } : { maxBuffer: 64 * 1024 * 1024 }),
33
+ });
34
+
35
+ /** rhubarb: `wav` (+ optional `dialogFile`) → normalized viseme timeline. */
36
+ export async function runRhubarb(rhubarb, { wav, dialogFile, out, timeout } = {}) {
37
+ const dialog = dialogFile ? ['--dialogFile', dialogFile] : [];
38
+ await run(rhubarb, ['-f', 'json', '-o', out, '--machineReadable', ...dialog, wav],
39
+ timeout ? { timeout } : {});
40
+ return normalizeRhubarb(JSON.parse(readFileSync(out, 'utf8')));
41
+ }
42
+
43
+ /**
44
+ * Wav2Lip: `face` (a still, or a veo motion clip) + `wav` → mp4 at `out`.
45
+ * `smallBatches` when the face is a multi-frame clip — the default batch size
46
+ * OOMs an 8 GB card ("Image too big to run face detection on GPU").
47
+ */
48
+ export async function runWav2lip(python, { dir, checkpoint, face, wav, out, smallBatches, inherit, timeout } = {}) {
49
+ const batches = smallBatches ? ['--face_det_batch_size', '4', '--wav2lip_batch_size', '32'] : [];
50
+ await run(python, ['inference.py', '--checkpoint_path', resolve(checkpoint),
51
+ '--face', face, '--audio', wav, '--outfile', out, ...batches],
52
+ { cwd: resolve(dir), ...bufOpts(timeout, inherit) });
53
+ }
54
+
55
+ /**
56
+ * SadTalker: `still` + `wav` → mp4 at `out`. It writes `<timestamp>/….mp4`
57
+ * into `resultDir`; take the newest and move it to `out`. (SadTalker makes its
58
+ * own head motion, so it always gets the still, never a veo clip.)
59
+ */
60
+ export async function runSadtalker(python, { dir, still, wav, out, resultDir, inherit, timeout } = {}) {
61
+ mkdirSync(resultDir, { recursive: true });
62
+ await run(python, ['inference.py', '--driven_audio', wav, '--source_image', still, '--result_dir', resultDir],
63
+ { cwd: resolve(dir), ...bufOpts(timeout, inherit) });
64
+ const found = [];
65
+ const walk = (d) => {
66
+ for (const f of readdirSync(d)) {
67
+ const p = join(d, f); const s = statSync(p);
68
+ if (s.isDirectory()) walk(p); else if (f.endsWith('.mp4')) found.push([s.mtimeMs, p]);
69
+ }
70
+ };
71
+ walk(resultDir);
72
+ if (!found.length) throw new Error('sadtalker produced no mp4');
73
+ renameSync(found.sort((a, b) => b[0] - a[0])[0][1], out);
74
+ }
75
+
76
+ /** Strip the audio track (playback is muted — narrAudio is the voice) and
77
+ * front-load the moov atom so the player can start instantly. */
78
+ export async function muteFaststart(src, out, { timeout } = {}) {
79
+ await run('ffmpeg', ['-y', '-i', src, '-an', '-movflags', '+faststart', '-c:v', 'copy', out],
80
+ timeout ? { timeout } : {});
81
+ }