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
package/cli/rec.mjs CHANGED
@@ -3,7 +3,7 @@
3
3
  // SPDX-License-Identifier: Apache-2.0
4
4
 
5
5
  /**
6
- * decklight-rec — record truthful terminal casts for Decklight decks (SPEC §7.1/§7.2).
6
+ * decklight-rec — record truthful terminal casts for Decklight decks (SPEC RECORDER_CLI/CAST_FORMAT).
7
7
  *
8
8
  * decklight rec <script.term.yaml> [-o out.cast.json] [--allow-fail] [--quiet]
9
9
  * decklight refresh <dir | cast.json…> [--allow-fail]
@@ -25,7 +25,8 @@ import fs from 'node:fs';
25
25
  import path from 'node:path';
26
26
  import os from 'node:os';
27
27
  import { createRequire } from 'node:module';
28
- import { fileURLToPath } from 'node:url';
28
+ import { makeFail, runMain } from './util.mjs';
29
+ import { isMain } from '../tools/args.mjs';
29
30
 
30
31
  const require = createRequire(import.meta.url);
31
32
 
@@ -40,10 +41,7 @@ const READY_MARK = `${GS}DECKLIGHT-READY${GS}`;
40
41
 
41
42
  // ---------------------------------------------------------------- utilities
42
43
 
43
- function fail(msg) {
44
- process.stderr.write(`decklight rec: ${msg}\n`);
45
- process.exit(1);
46
- }
44
+ const fail = makeFail('rec');
47
45
 
48
46
  function loadDeps() {
49
47
  let yaml, pty;
@@ -541,5 +539,4 @@ export async function recMain(argv = process.argv.slice(2)) {
541
539
 
542
540
  // Import-safe: only run the CLI when executed directly (recordScript and
543
541
  // exportAsciicast are importable for tests/tooling).
544
- const isMain = process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url);
545
- if (isMain) recMain().catch(e => fail(e.message));
542
+ if (isMain(import.meta.url)) process.exitCode = await runMain('rec', recMain);
package/cli/remote.mjs ADDED
@@ -0,0 +1,149 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ // The phone remote (#39): the controller page, its QR, and the relay — two
5
+ // one-way channels deliberately kept apart from the deck's own SSE stream: a
6
+ // phone has no business receiving `reload` or `agent`, and the deck has no
7
+ // business receiving position echoes of its own movement.
8
+ //
9
+ // The relay is mounted by whichever server owns the deck (edit today;
10
+ // `present` after PRESENT#REMOTE in MARKETPLACE.md) and never touches the
11
+ // deck file: the phone asks the deck to move, it never edits.
12
+
13
+ import { qrSvg } from './qr.mjs';
14
+ import { escapeHtml, isLoopback, sseChannel } from './serve.mjs';
15
+
16
+ /**
17
+ * The phone controller page (#39): a clicker, NOT a second screen — SPEC NON_GOALS
18
+ * rules out multiplex/follow-along, so this renders no slides, only two big
19
+ * targets and the position readout. Self-contained by necessity: the phone is
20
+ * off-loopback, and every asset it could reference is one more thing the token
21
+ * would have to guard. It carries the token it was opened with into both its
22
+ * POSTs and its SSE subscription.
23
+ */
24
+ export function remoteControllerHtml(deckName) {
25
+ return `<!doctype html>
26
+ <html lang="en">
27
+ <head>
28
+ <meta charset="utf-8">
29
+ <meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
30
+ <title>${escapeHtml(deckName)} — remote</title>
31
+ <style>
32
+ :root { color-scheme: dark; }
33
+ * { box-sizing: border-box; -webkit-tap-highlight-color: transparent; }
34
+ body { margin: 0; height: 100dvh; display: flex; flex-direction: column;
35
+ font: 600 16px/1.3 system-ui, -apple-system, sans-serif; background: #111; color: #eee; }
36
+ header { padding: .9rem 1rem; text-align: center; border-bottom: 1px solid #333; }
37
+ .deck { font-weight: 400; opacity: .6; font-size: .8rem; }
38
+ .pos { font-size: 1.6rem; font-variant-numeric: tabular-nums; }
39
+ main { flex: 1; display: grid; grid-template-rows: 1fr 1fr; gap: .6rem; padding: .6rem; }
40
+ button { font: inherit; font-size: 2rem; border: 0; border-radius: 1rem; color: #eee;
41
+ background: #26262b; touch-action: manipulation; }
42
+ button:active { background: #3a3a44; }
43
+ footer { padding: .5rem; text-align: center; font-size: .7rem; opacity: .5; }
44
+ </style>
45
+ </head>
46
+ <body>
47
+ <header>
48
+ <div class="deck">${escapeHtml(deckName)}</div>
49
+ <div class="pos" id="pos">—</div>
50
+ </header>
51
+ <main>
52
+ <button id="next" aria-label="next">▼ next</button>
53
+ <button id="prev" aria-label="previous">▲ prev</button>
54
+ </main>
55
+ <footer id="state">connecting…</footer>
56
+ <script>
57
+ var t = new URLSearchParams(location.search).get('t') || '';
58
+ var q = t ? '?t=' + encodeURIComponent(t) : '';
59
+ var pos = document.getElementById('pos');
60
+ var state = document.getElementById('state');
61
+ function send(key) {
62
+ return fetch('/remote/key' + q, {
63
+ method: 'POST', headers: { 'content-type': 'application/json' },
64
+ body: JSON.stringify({ key: key }),
65
+ }).catch(function () { state.textContent = 'offline'; });
66
+ }
67
+ document.getElementById('next').onclick = function () { send('next'); };
68
+ document.getElementById('prev').onclick = function () { send('prev'); };
69
+ var es = new EventSource('/remote/events' + q);
70
+ es.addEventListener('pos', function (e) {
71
+ try { var p = JSON.parse(e.data); pos.textContent = p.i + ' / ' + p.n; } catch (err) {}
72
+ });
73
+ es.onopen = function () { state.textContent = 'connected'; };
74
+ es.onerror = function () { state.textContent = 'reconnecting…'; };
75
+ </script>
76
+ </body>
77
+ </html>`;
78
+ }
79
+
80
+ /**
81
+ * The relay. handle(req, res, url[, body]) answers every /remote/* route and
82
+ * returns whether it did. GET routes need no body; the mounting server hands
83
+ * POST bodies in after its own read. A bad payload throws — the mounting
84
+ * server's error path answers 400, exactly as when this lived inline.
85
+ *
86
+ * deckName what the controller page shows
87
+ * token the per-run token (null when --remote is off — QR refuses)
88
+ * remoteUrl () => the LAN URL the QR encodes (port known only after bind)
89
+ * relayToDeck (event, data) => broadcast into the deck's own SSE stream
90
+ * deckCount () => how many decks are listening (the /remote/key echo)
91
+ * CORS the mounting server's CORS headers
92
+ */
93
+ export function createRemoteRelay({ deckName, token, remoteUrl, relayToDeck, deckCount, CORS }) {
94
+ const phones = sseChannel(); // phones watching /remote/events
95
+ let lastPos = null; // the last position the deck reported
96
+ const pushPos = () => { if (lastPos) phones.raw(`event: pos\ndata: ${JSON.stringify(lastPos)}\n\n`); };
97
+ return {
98
+ handle(req, res, url, body) {
99
+ const json = (code, obj) => {
100
+ res.writeHead(code, { ...CORS, 'content-type': 'application/json' });
101
+ res.end(JSON.stringify(obj));
102
+ return true;
103
+ };
104
+ if (req.method === 'GET' && url.pathname === '/remote') {
105
+ res.writeHead(200, { ...CORS, 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-cache' });
106
+ res.end(remoteControllerHtml(deckName));
107
+ return true;
108
+ }
109
+ if (req.method === 'GET' && url.pathname === '/remote/qr.svg') {
110
+ // Only meaningful with --remote: without it there is no LAN URL to
111
+ // scan, and a QR encoding 127.0.0.1 would be a lie a phone can't use.
112
+ if (!token) return json(404, { ok: false, error: 'the remote is off — start with --remote' });
113
+ res.writeHead(200, { ...CORS, 'content-type': 'image/svg+xml', 'cache-control': 'no-cache' });
114
+ res.end(qrSvg(remoteUrl()));
115
+ return true;
116
+ }
117
+ if (req.method === 'GET' && url.pathname === '/remote/events') {
118
+ const sub = phones.add(req, res, CORS);
119
+ // a phone joining mid-talk should show the right number immediately,
120
+ // not stay blank until the presenter happens to advance
121
+ if (lastPos) sub.write(`event: pos\ndata: ${JSON.stringify(lastPos)}\n\n`);
122
+ return true;
123
+ }
124
+ if (req.method === 'POST' && url.pathname === '/remote/key') {
125
+ const { key } = JSON.parse(body);
126
+ if (key !== 'next' && key !== 'prev') throw new Error('bad payload');
127
+ // relayed as a named event on the stream the deck ALREADY listens to —
128
+ // no second socket, no WebSockets anywhere in this codebase
129
+ relayToDeck('remote', { key });
130
+ return json(200, { ok: true, key, decks: deckCount() });
131
+ }
132
+ if (req.method === 'POST' && url.pathname === '/remote/pos') {
133
+ // The deck→phones direction, and only that. The deck reporting its
134
+ // position is a loopback caller; a phone — or anyone who obtained the
135
+ // QR token — has no business posting here, and accepting it would let
136
+ // one fabricated {i,n} desync the readout every other phone shows.
137
+ if (!isLoopback(req.socket?.remoteAddress)) {
138
+ return json(403, { ok: false, error: 'position reports come from the deck, not the phone' });
139
+ }
140
+ const { i, n } = JSON.parse(body);
141
+ if (!Number.isInteger(i) || !Number.isInteger(n)) throw new Error('bad payload');
142
+ lastPos = { i, n };
143
+ pushPos();
144
+ return json(200, { ok: true });
145
+ }
146
+ return false;
147
+ },
148
+ };
149
+ }
@@ -0,0 +1,97 @@
1
+ #!/usr/bin/env node
2
+ // Copyright 2026 Gilles Philippart
3
+ // SPDX-License-Identifier: Apache-2.0
4
+
5
+ /**
6
+ * decklight report-bug — the mechanical half of a good bug report.
7
+ *
8
+ * decklight report-bug
9
+ *
10
+ * Prints a ready-to-paste environment block and the new-issue URL, then exits.
11
+ * That is the whole command: it makes NO network requests, files nothing,
12
+ * opens nothing, and sends nothing anywhere. Everything it prints is on your
13
+ * screen first, which is the only honest way to collect facts about somebody's
14
+ * machine.
15
+ *
16
+ * The conversational half — what happened, what you expected, the smallest
17
+ * repro, and an optional screenshot — belongs to the `decklight-report-bug`
18
+ * agent skill, which drives this command and then asks. Keeping the command
19
+ * print-and-exit is what makes it scriptable and testable; the agent is the
20
+ * wizard, not the CLI.
21
+ */
22
+
23
+ import os from 'node:os';
24
+ import { createRequire } from 'node:module';
25
+ import { isMain } from '../tools/args.mjs';
26
+ import { findChrome } from '../tools/chrome.mjs';
27
+ import { PKG } from './skill-content.mjs';
28
+
29
+ /** Is an optional dependency actually installed? Resolution only — never loaded. */
30
+ export function resolves(name, req = createRequire(import.meta.url)) {
31
+ try { req.resolve(name); return true; } catch { return false; }
32
+ }
33
+
34
+ /**
35
+ * The facts a triager asks for first, gathered from this machine. Pure inputs
36
+ * are injectable so the block itself is testable without pretending to be a
37
+ * different operating system.
38
+ */
39
+ export function probe({ platform = os.platform(), release = os.release(), arch = os.arch(),
40
+ node = process.version, chrome = findChrome(), pty = resolves('node-pty'),
41
+ version = PKG.version } = {}) {
42
+ return {
43
+ decklight: version,
44
+ node,
45
+ os: `${platform} ${release} (${arch})`,
46
+ chrome: chrome ? `yes (${chrome})` : 'not found',
47
+ pty: pty ? 'installed' : 'not installed (terminal recording unavailable)',
48
+ };
49
+ }
50
+
51
+ /** The paste-ready markdown. Pure — `probe()` supplies the facts. */
52
+ export function environmentBlock(facts) {
53
+ return [
54
+ '## Environment',
55
+ '',
56
+ `- decklight: ${facts.decklight}`,
57
+ `- node: ${facts.node}`,
58
+ `- os: ${facts.os}`,
59
+ `- headless Chrome: ${facts.chrome}`,
60
+ `- node-pty: ${facts.pty}`,
61
+ ].join('\n');
62
+ }
63
+
64
+ /** The issues URL, taken from package.json rather than hardcoded twice. */
65
+ export function issuesUrl(pkg = PKG) {
66
+ return typeof pkg.bugs === 'string' ? pkg.bugs : pkg.bugs?.url ?? '';
67
+ }
68
+
69
+ const HELP = `decklight report-bug — gather the facts a Decklight bug report needs
70
+
71
+ Usage:
72
+ decklight report-bug
73
+
74
+ Prints a paste-ready environment block and the new-issue URL. It makes no
75
+ network requests and sends nothing anywhere — copy what you see, click the
76
+ link, paste.
77
+
78
+ A good report also needs three things this command cannot know: what happened
79
+ (verbatim output if there was any), what you expected instead, and the
80
+ smallest deck and keypresses that reproduce it.`;
81
+
82
+ export async function reportBugMain(argv = process.argv.slice(2)) {
83
+ if (argv.includes('--help') || argv.includes('-h')) { console.log(HELP); return 0; }
84
+
85
+ console.log(environmentBlock(probe()));
86
+ console.log();
87
+ console.log('Also say, in the issue:');
88
+ console.log(' - what happened (paste any error verbatim)');
89
+ console.log(' - what you expected instead');
90
+ console.log(' - the smallest deck + keypresses that reproduce it');
91
+ console.log();
92
+ console.log(`File it at: ${issuesUrl()}/new`);
93
+ console.log('(nothing has been sent — this command only printed the above)');
94
+ return 0;
95
+ }
96
+
97
+ if (isMain(import.meta.url)) process.exit(await reportBugMain());
@@ -0,0 +1,174 @@
1
+ #!/usr/bin/env node
2
+ // Copyright 2026 Gilles Philippart
3
+ // SPDX-License-Identifier: Apache-2.0
4
+
5
+ /**
6
+ * decklight restore — a deck's durable history, and the way back to any of it.
7
+ *
8
+ * decklight restore <deck.html> list the commits that touched it
9
+ * decklight restore <deck.html> <ref> put the deck back to that commit
10
+ *
11
+ * This is the git-level sibling of the in-memory Z/⇧Z stack (SPEC PRESENTING): it
12
+ * survives a restart and spans whole agent sessions, so it is what you reach
13
+ * for to undo a run rather than a keystroke.
14
+ *
15
+ * Restoring is NON-DESTRUCTIVE. Commit N's content is written as a NEW commit
16
+ * on top; history is never rewritten and `git reset --hard` is never run. So
17
+ * overshooting costs nothing — restore forward again and the round trip is
18
+ * two more commits, not a lost afternoon. And because a restore only ever
19
+ * ADDS, the deck you were on a moment ago is itself still in the list.
20
+ *
21
+ * Only the deck file is touched, matching the autocommit's single-file
22
+ * staging: a restore is not a checkout of somebody's whole tree.
23
+ */
24
+
25
+ import { execFileSync } from 'node:child_process';
26
+ import { existsSync, writeFileSync } from 'node:fs';
27
+ import { resolve, dirname, relative, basename } from 'node:path';
28
+ import { isMain } from '../tools/args.mjs';
29
+ import { git, inGitRepo, isIdentityError, oneline } from './git.mjs';
30
+
31
+ // A control character, written as an escape so no editor can silently strip
32
+ // it: a commit subject may contain any printable character, so a printable
33
+ // separator would corrupt the row the first time someone used it in a message.
34
+ const SEP = '\x01';
35
+
36
+ /**
37
+ * The commits that touched this deck, newest first: `{ hash, when, subject }`.
38
+ * `run` is the git invoker, injected so this is testable without a repo.
39
+ * Returns [] for a file git has never seen.
40
+ */
41
+ export function deckHistory(deckPath, cwd, run = git) {
42
+ const rel = relative(cwd, deckPath) || basename(deckPath);
43
+ const out = run(['log', `--format=%h${SEP}%ar${SEP}%s`, '--', rel], cwd);
44
+ if (!out) return [];
45
+ return out.split('\n').filter(Boolean).map((line) => {
46
+ const [hash, when, subject] = line.split(SEP);
47
+ return { hash, when, subject };
48
+ });
49
+ }
50
+
51
+ /** One list row, aligned enough to scan: `a1b2c3d · 2 hours ago · subject`. */
52
+ export function formatEntry({ hash, when, subject }, pad = 14) {
53
+ return `${hash} ${String(when).padEnd(pad)} ${subject}`;
54
+ }
55
+
56
+ /**
57
+ * Read the deck's content AT `ref` without going through git()'s trim — a
58
+ * deck's trailing newline is content, and a restore that quietly reformats
59
+ * the file is not a restore.
60
+ */
61
+ function showAt(ref, rel, cwd, exec = execFileSync) {
62
+ return exec('git', ['show', `${ref}:./${rel}`], { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
63
+ }
64
+
65
+ /**
66
+ * The deck exactly as it was at `ref` — what the restore overlay previews
67
+ * before you commit to going back (#129). Throws on an unknown ref.
68
+ */
69
+ export function deckAt(deckPath, ref, cwd, exec = execFileSync) {
70
+ const rel = relative(cwd, deckPath) || basename(deckPath);
71
+ return showAt(ref, rel, cwd, exec);
72
+ }
73
+
74
+ /**
75
+ * Give a previewed deck a root `<base>`, because it is served from `/edit/`
76
+ * rather than the root and every relative `../dist` and `./casts` path in it
77
+ * would otherwise resolve one directory too deep — a preview with no runtime.
78
+ *
79
+ * `<head>` is optional in HTML, so a deck can perfectly well not have one:
80
+ * fall through to `<html>`, then to the front of the document, rather than
81
+ * silently doing nothing. An author's own `<base>` is left alone.
82
+ */
83
+ export function withBaseHref(html, href = '/') {
84
+ const tag = `<base href="${href}">`;
85
+ if (/<base\b/i.test(html)) return html;
86
+ if (/<head(\s[^>]*)?>/i.test(html)) return html.replace(/<head(\s[^>]*)?>/i, (m) => m + tag);
87
+ if (/<html(\s[^>]*)?>/i.test(html)) return html.replace(/<html(\s[^>]*)?>/i, (m) => `${m}<head>${tag}</head>`);
88
+ return tag + html;
89
+ }
90
+
91
+ /** Commit just the deck, falling back to a decklight identity like autocommit. */
92
+ function commitDeck(rel, cwd, message, run = git) {
93
+ run(['add', '--', rel], cwd);
94
+ try {
95
+ run(['commit', '-m', message, '--', rel], cwd);
96
+ } catch (e) {
97
+ if (!isIdentityError(e)) throw e;
98
+ run(['-c', 'user.name=decklight', '-c', 'user.email=decklight@localhost',
99
+ 'commit', '-m', message, '--', rel], cwd);
100
+ }
101
+ }
102
+
103
+ /**
104
+ * Put `deckPath` back to `ref`, as a new commit on top.
105
+ *
106
+ * Uncommitted work is never silently discarded: if the deck has unsaved
107
+ * changes they are committed first, so the state you were in is itself
108
+ * recoverable from the list afterwards. Content is read BEFORE anything is
109
+ * written, so an unknown ref cannot leave a half-restored file.
110
+ */
111
+ export function restoreDeck(deckPath, ref, cwd, { run = git, exec = execFileSync } = {}) {
112
+ const rel = relative(cwd, deckPath) || basename(deckPath);
113
+ const content = showAt(ref, rel, cwd, exec); // throws on an unknown ref — before any write
114
+ const short = run(['rev-parse', '--short', ref], cwd);
115
+
116
+ const dirty = !!run(['status', '--porcelain', '--', rel], cwd);
117
+ if (dirty) commitDeck(rel, cwd, `decklight: save before restoring ${short}`, run);
118
+
119
+ writeFileSync(deckPath, content);
120
+ const changed = !!run(['status', '--porcelain', '--', rel], cwd);
121
+ if (changed) commitDeck(rel, cwd, `decklight: restore ${short}`, run);
122
+ return { short, savedFirst: dirty, changed };
123
+ }
124
+
125
+ const HELP = `decklight restore — a deck's history, and the way back to any of it
126
+
127
+ Usage:
128
+ decklight restore <deck.html> list the commits that touched the deck
129
+ decklight restore <deck.html> <ref> restore the deck to that commit
130
+
131
+ Restoring writes that version as a NEW commit on top — history is never
132
+ rewritten, so overshooting is free: restore forward again. Only the deck file
133
+ is touched, and uncommitted changes are committed first rather than lost.`;
134
+
135
+ export async function restoreMain(argv = process.argv.slice(2)) {
136
+ if (argv.includes('--help') || argv.includes('-h')) { console.log(HELP); return 0; }
137
+ const [deckArg, ref] = argv.filter((a) => !a.startsWith('-'));
138
+ if (!deckArg) { console.error('decklight restore: name the deck to restore\n\n' + HELP); return 1; }
139
+
140
+ const deckPath = resolve(deckArg);
141
+ if (!existsSync(deckPath)) { console.error(`decklight restore: no such file: ${deckArg}`); return 1; }
142
+ const cwd = dirname(deckPath);
143
+ if (!inGitRepo(cwd)) {
144
+ console.error(`decklight restore: ${basename(deckPath)} is not in a git repository — there is no history to restore`);
145
+ return 1;
146
+ }
147
+
148
+ let entries;
149
+ try { entries = deckHistory(deckPath, cwd); }
150
+ catch (e) { console.error(`decklight restore: could not read the history: ${oneline(e)}`); return 1; }
151
+ if (!entries.length) {
152
+ console.error(`decklight restore: git has no record of ${basename(deckPath)} — commit it once and this becomes useful`);
153
+ return 1;
154
+ }
155
+
156
+ if (!ref) {
157
+ const pad = Math.max(...entries.map((e) => e.when.length));
158
+ console.log(`${basename(deckPath)} — ${entries.length} commit${entries.length === 1 ? '' : 's'}, newest first:\n`);
159
+ for (const e of entries) console.log(' ' + formatEntry(e, pad));
160
+ console.log(`\nRestore one with: decklight restore ${deckArg} ${entries[Math.min(1, entries.length - 1)].hash}`);
161
+ return 0;
162
+ }
163
+
164
+ let result;
165
+ try { result = restoreDeck(deckPath, ref, cwd); }
166
+ catch (e) { console.error(`decklight restore: cannot restore ${ref}: ${oneline(e)}`); return 1; }
167
+
168
+ if (result.savedFirst) console.log(` uncommitted changes committed first — they are in the list too`);
169
+ if (!result.changed) { console.log(`${basename(deckPath)} was already at ${result.short} — nothing to do`); return 0; }
170
+ console.log(`${basename(deckPath)} restored to ${result.short} — as a new commit, so you can restore forward again`);
171
+ return 0;
172
+ }
173
+
174
+ if (isMain(import.meta.url)) process.exit(await restoreMain());