decklight 0.1.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 (139) hide show
  1. package/LICENSE +202 -21
  2. package/README.md +105 -183
  3. package/SPEC.md +861 -74
  4. package/cli/agents.mjs +206 -0
  5. package/cli/associate.mjs +279 -0
  6. package/cli/audit.mjs +424 -0
  7. package/cli/bundle.mjs +210 -45
  8. package/cli/deckfile.mjs +233 -0
  9. package/cli/decklight.mjs +216 -5
  10. package/cli/dev.mjs +455 -0
  11. package/cli/edit.mjs +733 -63
  12. package/cli/extension.mjs +108 -0
  13. package/cli/git.mjs +141 -0
  14. package/cli/import.mjs +398 -0
  15. package/cli/init.mjs +465 -121
  16. package/cli/loader.mjs +263 -0
  17. package/cli/marketplace.mjs +730 -0
  18. package/cli/pdf.mjs +156 -0
  19. package/cli/pkg.mjs +69 -0
  20. package/cli/plugin.mjs +646 -0
  21. package/cli/port-conflict.mjs +94 -0
  22. package/cli/present.mjs +560 -0
  23. package/cli/publish.mjs +342 -0
  24. package/cli/qr.mjs +334 -0
  25. package/cli/rec.mjs +12 -8
  26. package/cli/remote.mjs +149 -0
  27. package/cli/report-bug.mjs +97 -0
  28. package/cli/restore.mjs +174 -0
  29. package/cli/serve.mjs +247 -0
  30. package/cli/sign.mjs +216 -0
  31. package/cli/skill-content.mjs +222 -0
  32. package/cli/skills.mjs +338 -0
  33. package/cli/supervise.mjs +57 -0
  34. package/cli/theme.mjs +201 -0
  35. package/cli/units.mjs +488 -0
  36. package/cli/upgrade.mjs +250 -0
  37. package/cli/util.mjs +90 -0
  38. package/cli/wizard.mjs +432 -0
  39. package/cli/zip.mjs +121 -0
  40. package/dist/decklight.css +949 -72
  41. package/dist/decklight.js +220 -103
  42. package/dist/decklight.js.map +4 -4
  43. package/docs/architecture.svg +1 -1
  44. package/package.json +9 -6
  45. package/themes/README.md +6 -4
  46. package/themes/aurora.css +4 -1
  47. package/themes/berry.css +4 -1
  48. package/themes/carbon.css +4 -1
  49. package/themes/citrus.css +4 -1
  50. package/themes/coastal.css +4 -1
  51. package/themes/cosmos.css +4 -1
  52. package/themes/dune.css +4 -1
  53. package/themes/eclipse.css +4 -1
  54. package/themes/ember.css +4 -1
  55. package/themes/fjord.css +4 -1
  56. package/themes/gallery.html +3 -11
  57. package/themes/glacier.css +4 -1
  58. package/themes/graphite.css +4 -1
  59. package/themes/harvest.css +4 -1
  60. package/themes/ibm-modern.css +4 -1
  61. package/themes/ink.css +4 -1
  62. package/themes/latte.css +4 -1
  63. package/themes/linen.css +4 -1
  64. package/themes/meadow.css +4 -1
  65. package/themes/metropolis.css +4 -1
  66. package/themes/midnight.css +4 -1
  67. package/themes/mint.css +4 -1
  68. package/themes/moss.css +4 -1
  69. package/themes/obsidian.css +4 -1
  70. package/themes/orchid.css +4 -1
  71. package/themes/packs.json +4 -31
  72. package/themes/paper.css +4 -1
  73. package/themes/peony.css +4 -1
  74. package/themes/porcelain.css +4 -1
  75. package/themes/reveal-beige.css +4 -1
  76. package/themes/reveal-black.css +4 -1
  77. package/themes/reveal-blood.css +4 -1
  78. package/themes/reveal-dracula.css +4 -1
  79. package/themes/reveal-league.css +4 -1
  80. package/themes/reveal-moon.css +4 -1
  81. package/themes/reveal-night.css +4 -1
  82. package/themes/reveal-serif.css +4 -1
  83. package/themes/reveal-simple.css +4 -1
  84. package/themes/reveal-sky.css +4 -1
  85. package/themes/reveal-solarized.css +4 -1
  86. package/themes/reveal-white.css +4 -1
  87. package/themes/sepia.css +4 -1
  88. package/themes/seriph.css +4 -1
  89. package/themes/slate.css +4 -1
  90. package/themes/storm.css +4 -1
  91. package/themes/synthwave.css +4 -1
  92. package/themes/velvet.css +4 -1
  93. package/themes/yamabuki.css +120 -0
  94. package/tools/args.mjs +32 -0
  95. package/tools/bridge.mjs +30 -0
  96. package/tools/chrome.mjs +52 -0
  97. package/tools/color.mjs +110 -0
  98. package/tools/deck-html.mjs +138 -0
  99. package/tools/elevenlabs-tts.mjs +248 -0
  100. package/tools/escape.mjs +40 -0
  101. package/tools/extension-check-runner.mjs +41 -0
  102. package/tools/extension-check.mjs +266 -0
  103. package/tools/gemini-tts.mjs +44 -4
  104. package/tools/lipsync-engines.mjs +81 -0
  105. package/tools/lipsync-server.mjs +290 -0
  106. package/tools/lipsync.mjs +181 -0
  107. package/tools/local-voice.mjs +209 -0
  108. package/tools/ooxml.mjs +151 -0
  109. package/tools/pptx.mjs +320 -0
  110. package/tools/publish-site-voices.mjs +5 -1
  111. package/tools/publish-targets.mjs +143 -0
  112. package/tools/publish-voices.mjs +230 -0
  113. package/tools/shot.mjs +129 -0
  114. package/tools/theme-check.mjs +139 -0
  115. package/tools/tts-engines.mjs +455 -0
  116. package/tools/tts-setup.mjs +257 -0
  117. package/tools/veo.mjs +204 -0
  118. package/tools/video.mjs +316 -0
  119. package/tools/visemes.mjs +26 -0
  120. package/tools/voiceover-server.mjs +0 -0
  121. package/tools/voiceover.mjs +73 -39
  122. package/tools/zip.mjs +143 -0
  123. package/docs/demo.svg +0 -124
  124. package/themes/aliens.css +0 -84
  125. package/themes/apple2.css +0 -126
  126. package/themes/blade-runner.css +0 -83
  127. package/themes/c64.css +0 -85
  128. package/themes/friends.css +0 -82
  129. package/themes/gameboy.css +0 -118
  130. package/themes/genesis.css +0 -84
  131. package/themes/godfather.css +0 -82
  132. package/themes/ibm-oldschool.css +0 -84
  133. package/themes/miami-vice.css +0 -84
  134. package/themes/pulp-fiction.css +0 -84
  135. package/themes/severance.css +0 -82
  136. package/themes/snes.css +0 -82
  137. package/themes/star-wars.css +0 -85
  138. package/themes/stranger-things.css +0 -84
  139. package/themes/terminator.css +0 -84
@@ -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
+ }
@@ -1,3 +1,6 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
1
4
  // Shared Gemini TTS synthesis (Vertex AI) — used by tools/voiceover.mjs
2
5
  // (batch pre-render) and tools/voiceover-server.mjs (live bridge for the
3
6
  // player). generateContent with responseModalities AUDIO returns base64 raw
@@ -8,6 +11,15 @@
8
11
 
9
12
  import { execFileSync } from 'node:child_process';
10
13
 
14
+ /**
15
+ * GCP project ids: 6–30 chars, lowercase, leading letter, no trailing hyphen.
16
+ * Worth checking rather than letting Vertex answer, because `project` is
17
+ * interpolated straight into the request path — punctuation dragged in from a
18
+ * copy-paste comes back as an opaque 403 on a project that "doesn't exist",
19
+ * and a stray slash would rewrite the URL outright.
20
+ */
21
+ export const validProjectId = (id) => /^[a-z][a-z0-9-]{4,28}[a-z0-9]$/.test(id ?? '');
22
+
11
23
  // The prebuilt voice roster (docs' flavor words) — the player shows this
12
24
  // same list, keep the two in sync (engine.js GEMINI_VOICES).
13
25
  export const GEMINI_VOICES = [
@@ -23,11 +35,26 @@ export const GEMINI_VOICES = [
23
35
  ['Sadachbia', 'lively'], ['Sadaltager', 'knowledgeable'], ['Sulafat', 'warm'],
24
36
  ];
25
37
 
26
- function gcloudToken() {
38
+ // ADC, not `gcloud auth login` — a separate credential store, and the one every
39
+ // Google client library reads. Shared with the Chirp engine (tools/tts-engines.mjs).
40
+ export function gcloudToken() {
27
41
  return execFileSync('gcloud', ['auth', 'application-default', 'print-access-token'],
28
42
  { encoding: 'utf8' }).trim();
29
43
  }
30
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
+
31
58
  // Published Vertex AI list prices (USD per 1M tokens) — the API returns
32
59
  // token counts in usageMetadata, never dollars, so cost is an ESTIMATE.
33
60
  const PRICES = [
@@ -39,7 +66,12 @@ function estimateCost(model, usage) {
39
66
  return ((usage.promptTokenCount ?? 0) * p.input + (usage.candidatesTokenCount ?? 0) * p.output) / 1e6;
40
67
  }
41
68
 
42
- 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) {
43
75
  const h = Buffer.alloc(44);
44
76
  h.write('RIFF', 0); h.writeUInt32LE(36 + pcm.length, 4); h.write('WAVE', 8);
45
77
  h.write('fmt ', 12); h.writeUInt32LE(16, 16); h.writeUInt16LE(1, 20); h.writeUInt16LE(1, 22);
@@ -79,6 +111,7 @@ export function styledPrompt(style, text) {
79
111
  */
80
112
  export function createSynth({ project, ttsModel, location } = {}) {
81
113
  if (!project) throw new Error('Gemini TTS needs a GCP project — pass { project } (CLI: --project <id> or set GOOGLE_CLOUD_PROJECT)');
114
+ if (!validProjectId(project)) throw new Error(`not a GCP project id: ${JSON.stringify(project)} — expected 6-30 chars, lowercase letters, digits and hyphens, starting with a letter (stray punctuation from a copy-paste?)`);
82
115
  let token = null;
83
116
  let route = null;
84
117
 
@@ -87,7 +120,7 @@ export function createSynth({ project, ttsModel, location } = {}) {
87
120
  const url = `https://${host}/v1/projects/${project}/locations/${loc}/publishers/google/models/${model}:generateContent`;
88
121
  const res = await fetch(url, {
89
122
  method: 'POST',
90
- headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },
123
+ headers: authHeaders(token, project),
91
124
  body: JSON.stringify({
92
125
  contents: [{ role: 'user', parts: [{ text }] }],
93
126
  generationConfig: {
@@ -108,6 +141,9 @@ export function createSynth({ project, ttsModel, location } = {}) {
108
141
  model,
109
142
  promptTokens: um.promptTokenCount ?? 0,
110
143
  audioTokens: um.candidatesTokenCount ?? 0,
144
+ chars: text.length,
145
+ // every engine reports a `note`, so the bridge logs one line for all
146
+ note: `${um.promptTokenCount ?? 0}+${um.candidatesTokenCount ?? 0} tokens`,
111
147
  cost: estimateCost(model, um),
112
148
  },
113
149
  };
@@ -116,8 +152,12 @@ export function createSynth({ project, ttsModel, location } = {}) {
116
152
  return async function synth(text, { voice = 'Alnilam', style = '' } = {}) {
117
153
  token ??= gcloudToken();
118
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'];
119
159
  const routes = route ? [route]
120
- : [ttsModel ?? 'gemini-2.5-pro-tts', 'gemini-2.5-pro-preview-tts']
160
+ : models
121
161
  .flatMap((m) => [location ?? 'global', 'us-central1'].map((l) => ({ model: m, location: l })))
122
162
  .filter((r, i, a) => a.findIndex((x) => x.model === r.model && x.location === r.location) === i);
123
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
+ }