decklight 0.5.0 → 0.6.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.
package/cli/theme.mjs CHANGED
@@ -19,10 +19,11 @@
19
19
  // exactly what an older theme is missing.
20
20
 
21
21
  import { existsSync, readFileSync, writeFileSync } from 'node:fs';
22
+ import { escapeHtml } from '../tools/escape.mjs';
22
23
  import path, { resolve } from 'node:path';
23
24
  import { argReader, isMain } from '../tools/args.mjs';
24
25
  import { validateTheme, themeNameFrom, validThemeName, REQUIRED } from '../tools/theme-check.mjs';
25
- import { checkoutPath, classifySource, configHome, MarketplaceError } from './marketplace.mjs';
26
+ import { checkoutPath, classifySource, configHome, MarketplaceError, loadRegistry, loadCatalog, resolveEntry} from './marketplace.mjs';
26
27
 
27
28
  const USAGE = `usage: decklight theme <check|add> …
28
29
 
@@ -42,13 +43,37 @@ const USAGE = `usage: decklight theme <check|add> …
42
43
  a theme that does not pass is not installed — a deck cannot be made to carry
43
44
  something the shipped set would not be allowed to contain`;
44
45
 
45
- /** The <style> block an installed theme becomes, marked so the runtime groups it. */
46
- export function themeStyleBlock(name, css) {
46
+ /**
47
+ * The <style> block an installed theme becomes, marked so the runtime groups it.
48
+ *
49
+ * PROVENANCE TRAVELS WITH THE DECK, and it has to: a bundled deck opened on
50
+ * another machine has no `~/.decklight/marketplaces.json` to look a catalog up
51
+ * in, and the theme picker still has to draw a heading. So whatever the picker
52
+ * shows is written here, at install time, or it is not available at all.
53
+ *
54
+ * Two attributes, because identity and label are different things.
55
+ * `data-theme-marketplace` is the manifest's own kebab `name` — stable, and
56
+ * what a later dedup or upgrade would key on. `data-theme-source` is the
57
+ * catalog's human title, written only when it supplied one, and never derived
58
+ * from the name: stripping a prefix off `decklight-confluent` to guess
59
+ * "Confluent" breaks the moment a catalog is called `acme-themes`, and it puts
60
+ * decklight in the business of inventing names for other people's catalogs.
61
+ *
62
+ * `data-theme-added` stays on every installed block. Old decks keep working,
63
+ * and it remains what the runtime falls back to — the "never decklight's to
64
+ * begin with" distinction it was added for is untouched.
65
+ */
66
+ export function themeStyleBlock(name, css, { marketplace = null, title = null } = {}) {
47
67
  // </style> inside a theme's own comment would end the block early. Themes
48
68
  // are CSS and have no business containing one, but a downloaded file is
49
69
  // somebody else's, and "somebody else's" is exactly when to check.
50
70
  const safe = css.replace(/<\/(style)/gi, '<\\/$1');
51
- return `<style data-theme="${name}" data-theme-added media="not all">\n${safe.trim()}\n</style>`;
71
+ // Both values come out of a manifest somebody else wrote, and they land in a
72
+ // double-quoted attribute — so they are escaped, not trusted. A title of
73
+ // `"><script>` is the whole reason this is not a template hole.
74
+ const from = marketplace ? ` data-theme-marketplace="${escapeHtml(marketplace)}"` : '';
75
+ const label = title ? ` data-theme-source="${escapeHtml(title)}"` : '';
76
+ return `<style data-theme="${escapeHtml(name)}" data-theme-added${from}${label} media="not all">\n${safe.trim()}\n</style>`;
52
77
  }
53
78
 
54
79
  /** Where an existing block for this name starts and ends, or null. */
@@ -64,8 +89,8 @@ export function findThemeBlock(html, name) {
64
89
  * last in <head> so an active added theme wins the cascade over the deck's
65
90
  * link or inline base theme.
66
91
  */
67
- export function installTheme(html, name, css) {
68
- const block = themeStyleBlock(name, css);
92
+ export function installTheme(html, name, css, provenance = {}) {
93
+ const block = themeStyleBlock(name, css, provenance);
69
94
  const existing = findThemeBlock(html, name);
70
95
  if (existing) {
71
96
  return { html: html.slice(0, existing.start) + block + html.slice(existing.end), replaced: true };
@@ -172,17 +197,59 @@ async function addMain(args) {
172
197
  const [source, deck] = positional;
173
198
  if (!source || !deck) { console.error(`decklight theme add: needs a theme and a deck\n\n${USAGE}`); return 1; }
174
199
 
175
- const name = opt('--name') ?? themeNameFrom(source);
200
+ const deckPath = resolve(deck);
201
+ if (!existsSync(deckPath)) { console.error(`decklight theme add: no such deck: ${deck}`); return 1; }
202
+
203
+ // A marketplace ref (`confluent@decklight-confluent`, or a bare entry name)
204
+ // resolves through the registry; a file or a URL is taken as it was typed.
205
+ // Without this the CLI could not install from a catalog at all — Browse was
206
+ // the only door — and provenance would only ever reach half the decks.
207
+ let src = source;
208
+ let provenance = {};
209
+ let entryName = null;
210
+ if (!/^https?:\/\//i.test(source) && !existsSync(resolve(source))) {
211
+ const reg = loadRegistry();
212
+ const catalogs = {};
213
+ for (const mkt of Object.keys(reg.marketplaces ?? {})) {
214
+ const c = loadCatalog(mkt);
215
+ if (c?.ok) catalogs[mkt] = c.manifest;
216
+ }
217
+ let hit;
218
+ try { hit = resolveEntry(source, catalogs); }
219
+ catch (e) {
220
+ console.error(`decklight theme add: ${e.message}`);
221
+ return 1;
222
+ }
223
+ if (hit.entry.type !== 'theme') {
224
+ console.error(`decklight theme add: ${hit.qualified} is a ${hit.entry.type}, not a theme`);
225
+ return 1;
226
+ }
227
+ try {
228
+ src = resolveSource(hit.entry.source, {
229
+ name: hit.marketplace, source: reg.marketplaces[hit.marketplace]?.source,
230
+ });
231
+ } catch (e) {
232
+ console.error(`decklight theme add: ${e.message}`);
233
+ return 1;
234
+ }
235
+ // The catalog's own title, captured HERE because the deck may be opened on
236
+ // a machine where this marketplace was never registered.
237
+ provenance = { marketplace: hit.marketplace, title: catalogs[hit.marketplace]?.title?.trim() || null };
238
+ entryName = hit.entry.name;
239
+ }
240
+
241
+ // The name is settled AFTER resolution: `confluent@decklight-confluent` is a
242
+ // reference, not a filename, and deriving a theme name from it would refuse
243
+ // every marketplace install for containing an `@`.
244
+ const name = opt('--name') ?? entryName ?? themeNameFrom(source);
176
245
  if (!validThemeName(name)) {
177
246
  console.error(`decklight theme add: "${name}" is not a usable theme name`);
178
247
  console.error(' the runtime only resolves names matching [A-Za-z0-9_-]+ — pass --name to choose one');
179
248
  return 1;
180
249
  }
181
- const deckPath = resolve(deck);
182
- if (!existsSync(deckPath)) { console.error(`decklight theme add: no such deck: ${deck}`); return 1; }
183
250
 
184
251
  let css;
185
- try { css = await fetchTheme(source); } catch (e) { console.error(`decklight theme add: ${e.message}`); return 1; }
252
+ try { css = await fetchTheme(src); } catch (e) { console.error(`decklight theme add: ${e.message}`); return 1; }
186
253
 
187
254
  const result = validateTheme(css);
188
255
  for (const line of reportLines(name, result)) console.log(line);
@@ -192,7 +259,7 @@ async function addMain(args) {
192
259
  }
193
260
 
194
261
  const html = readFileSync(deckPath, 'utf8');
195
- const { html: next, replaced } = installTheme(html, name, css);
262
+ const { html: next, replaced } = installTheme(html, name, css, provenance);
196
263
  if (next === null) { console.error(`decklight theme add: ${deck} has no </head> to install into`); return 1; }
197
264
 
198
265
  if (args.includes('--dry-run')) {
@@ -0,0 +1,256 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ /**
5
+ * `present`'s upstream check — SPEC PRESENTING (`PRESENT#UPSTREAM`).
6
+ *
7
+ * A deck cloned before a talk goes stale silently: `present` reads the file
8
+ * once and serves those bytes, so a fix the author pushed an hour ago is
9
+ * invisible. This asks the upstream, and — with `--upstream-pull` — lets the
10
+ * deck fast-forward to it.
11
+ *
12
+ * ## What makes this safe, in one place
13
+ *
14
+ * The feature is UNREACHABLE for the deck the rest of `present` is written
15
+ * against. A deck you were emailed is a single file with no repository, no
16
+ * remote and no upstream, so `resolveUpstream` returns `no-repo` and nothing —
17
+ * not the routes, not the timer — is ever registered.
18
+ *
19
+ * The gate that matters most is `untracked`, and it is not obvious: anyone
20
+ * whose $HOME is a git repository (yadm, chezmoi, a dotfiles clone) has every
21
+ * deck in ~/Downloads "inside a clone". Requiring the deck to be a file that
22
+ * repository actually VERSIONS is the honest reading of "the deck lives in a
23
+ * git clone" — without it, presenting a downloaded deck would offer to
24
+ * fast-forward somebody's home directory.
25
+ *
26
+ * ## Never a hang, never a false pass
27
+ *
28
+ * Every git call is async (`execFile`): a synchronous child would block the
29
+ * event loop of the server serving the talk, and a 15-second fetch would be a
30
+ * 15-second black slide. Every one runs with prompts disabled — the env from
31
+ * cli/git.mjs, which covers ssh as well as https — and a timeout, so an
32
+ * unreachable remote is an answer rather than a stall.
33
+ *
34
+ * And a fetch that FAILED is never reported as up to date. The comparison
35
+ * against a stale remote-tracking ref is simply not made; the state is the
36
+ * failure, `checkedAt` stays null, and "unchecked" is its own answer — the same
37
+ * rule signature verification already follows (SPEC PRESENTING: when it cannot
38
+ * be done here, that is said as its own state and never as a pass).
39
+ */
40
+
41
+ import { execFile } from 'node:child_process';
42
+ import { realpathSync } from 'node:fs';
43
+ import { homedir } from 'node:os';
44
+ import { basename, dirname, parse, resolve } from 'node:path';
45
+ import { classifyRemoteError, noPromptEnv, oneline, parseAheadBehind } from './git.mjs';
46
+
47
+ /** Every answer this can give. Frozen so a typo is a crash, not a silent miss. */
48
+ export const UPSTREAM_STATES = Object.freeze([
49
+ 'no-repo', 'untracked', 'detached', 'no-upstream',
50
+ 'up-to-date', 'behind', 'ahead', 'diverged',
51
+ 'offline', 'no-credential', 'timeout', 'error', 'disabled',
52
+ ]);
53
+
54
+ /** git, asynchronously, with prompts off and a bound. Never throws. */
55
+ export function runGit(args, { cwd, timeoutMs = 8000, exec = execFile } = {}) {
56
+ return new Promise((done) => {
57
+ exec('git', args, { cwd, encoding: 'utf8', timeout: timeoutMs, env: noPromptEnv() },
58
+ (err, stdout, stderr) => done({
59
+ ok: !err, stdout: (stdout ?? '').trim(), stderr: (stderr ?? '').trim(), err,
60
+ }));
61
+ });
62
+ }
63
+
64
+ /**
65
+ * The `-c` overrides every invocation carries.
66
+ *
67
+ * `core.hooksPath` points at a directory that does not exist and is never
68
+ * created: decklight is not the presenter typing `git pull`, and it must not
69
+ * run arbitrary local scripts in the middle of a talk. The rest keep a
70
+ * background maintenance task, a filesystem monitor or a submodule walk from
71
+ * starting behind a slide.
72
+ */
73
+ export const SAFE_CONFIG = Object.freeze([
74
+ '-c', 'gc.auto=0', '-c', 'maintenance.auto=false',
75
+ '-c', 'core.fsmonitor=false', '-c', 'submodule.recurse=false',
76
+ '-c', 'credential.interactive=false',
77
+ ]);
78
+
79
+ /** Why a git failure happened, as one of this module's states. */
80
+ export function classifyFailure({ err, stderr }) {
81
+ if (err?.killed || err?.signal) return 'timeout';
82
+ const kind = classifyRemoteError({ stderr, message: err?.message });
83
+ if (kind === 'denied') return 'no-credential';
84
+ if (kind === 'offline') return 'offline';
85
+ return 'error';
86
+ }
87
+
88
+ /**
89
+ * Is the check even a question here? Resolved once, before anything is served.
90
+ *
91
+ * Returns `{ state, repoRoot, branch, upstream }`. Anything but `ok` means the
92
+ * feature is absent — no routes, no timer, no line in the label.
93
+ */
94
+ export async function resolveUpstream(deckPath, { run = runGit, home = homedir() } = {}) {
95
+ // REALPATH FIRST. `git rev-parse --show-toplevel` answers with symlinks
96
+ // resolved, and on macOS /tmp and /var are symlinks — so comparing it against
97
+ // an unresolved deck path makes `relative()` produce a ../../.. escape, the
98
+ // tracked check fails, and the feature silently never activates for anyone
99
+ // whose deck lives under a symlinked path. It fails CLOSED, which is why it
100
+ // would have gone unnoticed rather than gone wrong.
101
+ let full;
102
+ try { full = realpathSync(resolve(deckPath)); } catch { full = resolve(deckPath); }
103
+ const cwd = dirname(full);
104
+ const no = (state) => ({ state, repoRoot: null, branch: null, upstream: null });
105
+
106
+ const top = await run(['rev-parse', '--show-toplevel'], { cwd });
107
+ if (!top.ok || !top.stdout) return no('no-repo');
108
+ // resolve() because git answers in FORWARD SLASHES on every platform,
109
+ // including Windows — so `C:/Users/x` has to become `C:\Users\x` before it
110
+ // can be compared with a path Node produced, or the tracked check below
111
+ // compares two spellings of the same directory and refuses every deck.
112
+ const repoRoot = resolve(top.stdout);
113
+
114
+ // A repository whose root is $HOME or a filesystem root is somebody's whole
115
+ // machine, not a deck's home. Belt and braces behind the tracked check below.
116
+ if (repoRoot === resolve(home) || repoRoot === parse(repoRoot).root) return no('untracked');
117
+
118
+ // THE GATE THAT MATTERS: the deck must be a file this repository versions.
119
+ // Without it, every deck in ~/Downloads is "inside a clone" for anyone whose
120
+ // home directory is one.
121
+ // Asked from the DECK'S OWN DIRECTORY, by basename — git resolves it against
122
+ // the repository itself. Computing the relative path here instead means
123
+ // comparing two absolute paths, and two absolute paths for the same file
124
+ // disagree more often than they look: git answers in forward slashes on every
125
+ // platform, macOS resolves /tmp and /var through symlinks, and a Windows temp
126
+ // directory is an 8.3 short name (RUNNER~1) that realpath may or may not
127
+ // expand. Every one of those made this refuse a deck it should have accepted.
128
+ const tracked = await run(['ls-files', '--error-unmatch', '--', basename(full)], { cwd });
129
+ if (!tracked.ok) return no('untracked');
130
+
131
+ const branch = await run(['symbolic-ref', '--quiet', '--short', 'HEAD'], { cwd: repoRoot });
132
+ if (!branch.ok || !branch.stdout) return { ...no('detached'), repoRoot };
133
+
134
+ const up = await run(['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{upstream}'], { cwd: repoRoot });
135
+ if (!up.ok || !up.stdout) return { ...no('no-upstream'), repoRoot, branch: branch.stdout };
136
+
137
+ return { state: 'ok', repoRoot, branch: branch.stdout, upstream: up.stdout };
138
+ }
139
+
140
+ /**
141
+ * One check cycle: fetch, then compare. Returns the status the routes serve.
142
+ *
143
+ * The fetch carries no refspec and no remote name — `git fetch` with no
144
+ * arguments fetches whatever the current branch tracks, and `@{upstream}` is a
145
+ * constant git resolves itself. NOTHING derived from anything reaches a git
146
+ * argument, which is a property worth stating because it is the one that makes
147
+ * the route safe by construction rather than by validation.
148
+ */
149
+ export async function checkUpstream(ctx, { run = runGit, now = () => Date.now() } = {}) {
150
+ const { repoRoot, branch, upstream } = ctx;
151
+ const base = { branch, upstream, behind: 0, ahead: 0, dirty: false, commits: [], checkedAt: null };
152
+
153
+ const fetched = await run([...SAFE_CONFIG, 'fetch', '--quiet', '--no-tags', '--no-recurse-submodules'],
154
+ { cwd: repoRoot, timeoutMs: 15000 });
155
+ if (!fetched.ok) {
156
+ // The comparison against a STALE ref is deliberately not made: "I could not
157
+ // ask" must never come out as "up to date".
158
+ const state = classifyFailure(fetched);
159
+ return { ...base, state, message: FAILURE_MESSAGE[state](upstream, oneline(fetched.stderr || fetched.err)) };
160
+ }
161
+
162
+ const counts = parseAheadBehind(
163
+ (await run(['rev-list', '--left-right', '--count', '@{upstream}...HEAD'], { cwd: repoRoot })).stdout,
164
+ );
165
+ if (!counts) return { ...base, state: 'error', message: 'could not count against ' + upstream };
166
+
167
+ const dirty = Boolean((await run(['status', '--porcelain', '--untracked-files=no'], { cwd: repoRoot })).stdout);
168
+ const log = await run(['log', '--format=%h\x01%s', '-n', '5', 'HEAD..@{upstream}'], { cwd: repoRoot });
169
+ const commits = log.ok && log.stdout
170
+ ? log.stdout.split('\n').map((l) => { const [hash, subject] = l.split('\x01'); return { hash, subject }; })
171
+ : [];
172
+
173
+ const state = counts.behind && counts.ahead ? 'diverged'
174
+ : counts.behind ? 'behind'
175
+ : counts.ahead ? 'ahead'
176
+ : 'up-to-date';
177
+ return { ...base, ...counts, dirty, commits, state, checkedAt: now(), message: describe(state, { ...counts, upstream, dirty }) };
178
+ }
179
+
180
+ const FAILURE_MESSAGE = {
181
+ offline: (up) => `could not reach ${up.split('/')[0]} — unchecked, NOT up to date`,
182
+ 'no-credential': (up) => `${up.split('/')[0]} refused an anonymous fetch — unchecked, NOT up to date`,
183
+ timeout: (up) => `${up.split('/')[0]} did not answer in 15s — unchecked, not up to date`,
184
+ error: (up, why) => `git said: ${why}`,
185
+ };
186
+
187
+ /** The sentence for a state that was actually determined. */
188
+ export function describe(state, { behind = 0, ahead = 0, upstream = '', dirty = false } = {}) {
189
+ const s = {
190
+ 'up-to-date': `up to date with ${upstream}`,
191
+ behind: `${behind} commit${behind === 1 ? '' : 's'} behind ${upstream}`,
192
+ ahead: `${ahead} commit${ahead === 1 ? '' : 's'} ahead of ${upstream} — nothing to pull`,
193
+ diverged: `diverged from ${upstream} (${ahead} ahead, ${behind} behind) — a fast-forward is not possible`,
194
+ }[state] ?? state;
195
+ return dirty && state === 'behind' ? `${s} · uncommitted changes here` : s;
196
+ }
197
+
198
+ /**
199
+ * May this status be pulled? Pure, and re-asked against a FRESH check
200
+ * immediately before the merge rather than trusted from the cached one.
201
+ */
202
+ export function canPull(status, { offered = false } = {}) {
203
+ if (!offered) return { ok: false, state: 'not-offered', message: 'the update control is off' };
204
+ if (!status) return { ok: false, state: 'error', message: 'nothing has been checked yet' };
205
+ if (status.state === 'up-to-date') return { ok: false, state: 'up-to-date', message: 'already up to date' };
206
+ if (status.state === 'ahead') return { ok: false, state: 'ahead', message: 'nothing to pull' };
207
+ if (status.state === 'diverged') {
208
+ return { ok: false, state: 'diverged', message: 'diverged — a fast-forward is not possible' };
209
+ }
210
+ if (status.state !== 'behind') {
211
+ return { ok: false, state: status.state, message: status.message ?? 'not in a state that can be pulled' };
212
+ }
213
+ // A checkout over uncommitted work is how somebody loses an edit they made in
214
+ // the ten minutes before a talk.
215
+ if (status.dirty) {
216
+ return { ok: false, state: 'dirty', message: 'uncommitted changes here — commit or stash them first' };
217
+ }
218
+ return { ok: true, state: 'behind' };
219
+ }
220
+
221
+ /**
222
+ * Why this run is not checking at all, as a reason string, or false.
223
+ *
224
+ * The `suppressed()` shape from cli/update-check.mjs, so a test reads like the
225
+ * rule. Deliberately NOT suppressed on a non-TTY: the answer here reaches a
226
+ * route as well as a terminal, and gating on a TTY would make the feature
227
+ * untestable and invisible to the deck.
228
+ */
229
+ export function upstreamSuppressed({ args = [], env = process.env } = {}) {
230
+ if (args.includes('--no-upstream')) return '--no-upstream';
231
+ if (args.includes('--check')) return '--check';
232
+ if (env.DECKLIGHT_NO_UPSTREAM_CHECK) return 'DECKLIGHT_NO_UPSTREAM_CHECK is set';
233
+ if (env.CI) return 'CI';
234
+ return false;
235
+ }
236
+
237
+ /**
238
+ * How often to look, or 0 for "only when asked".
239
+ *
240
+ * `0` turns off the TIMER, not the feature: the manual check and the update
241
+ * control stay, which is what somebody who does not want background network
242
+ * during a talk actually wants. `--no-upstream` is how you turn it all off, and
243
+ * the two being different is the point.
244
+ *
245
+ * A typo falls back to the default rather than disabling anything —
246
+ * resolveGitMode's rule: a mistyped flag must not silently cost you the thing
247
+ * you were configuring.
248
+ */
249
+ export function resolveInterval(args = []) {
250
+ const i = args.indexOf('--upstream-every');
251
+ if (i < 0) return 10 * 60_000;
252
+ const raw = Number(args[i + 1]);
253
+ if (raw === 0) return 0;
254
+ const minutes = Number.isFinite(raw) && raw > 0 ? raw : 10;
255
+ return Math.max(60_000, minutes * 60_000);
256
+ }