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,108 @@
1
+ #!/usr/bin/env node
2
+ // Copyright 2026 Gilles Philippart
3
+ // SPDX-License-Identifier: Apache-2.0
4
+
5
+ /**
6
+ * `decklight extension` — the marketplace admission gate for build-time code
7
+ * (MARKETPLACE.md `EXTENSIONS#CHECK`, SPEC `EXTENSIONS_CHECK`).
8
+ *
9
+ * decklight extension check <file> [--type transform]
10
+ *
11
+ * Validates a bare source FILE, not an installed, catalog-backed unit —
12
+ * `bundle`, `import` and `publish` run an already-installed transform and
13
+ * never re-check it (`EXTENSIONS#LOADER` already settled that). This is what
14
+ * a marketplace repo's own CI runs on every PR that adds or updates a
15
+ * `transform` entry; a failing check blocks that PR from merging — the
16
+ * extension's admission to a catalog, never `decklight publish`ing a deck.
17
+ *
18
+ * Named `extension`, not `transform`: `decklight plugin check` already gates
19
+ * presenter-library plugins (a different risk — a stranger's code on the
20
+ * presenter's own machine). This is the gate for build-time code
21
+ * specifically, and `--type` leaves room for an `importer` check later. The
22
+ * adapter calling convention that check would gate is frozen (SPEC
23
+ * `EXTENSIONS_ADAPTERS`, landed with `EXTENSIONS#ADAPTEREXEC`); the check
24
+ * itself is its own ticket, not a hidden mode of this one.
25
+ */
26
+
27
+ import { existsSync } from 'node:fs';
28
+ import { isMain, argReader } from '../tools/args.mjs';
29
+ import { checkExtension, TYPES } from '../tools/extension-check.mjs';
30
+
31
+ const USAGE = `usage: decklight extension check <file> [--type transform]
32
+
33
+ decklight extension check <file>
34
+ lints the source — refuses fetch(), eval(), XMLHttpRequest or a dynamic
35
+ import() anywhere in it — then runs it against a randomised fixture in a
36
+ SEPARATE Node process under the permission model (no filesystem writes,
37
+ no child processes, no workers; a scrubbed environment; a temp working
38
+ directory; a 15s kill) and headlessly loads the OUTPUT, refusing any
39
+ <script> block or inline event handler (on…=) in it. Exits non-zero on
40
+ a refusal, so a marketplace's own CI can gate admission on it.
41
+ On a pass it prints the file's sha256 — the pin the catalog entry carries,
42
+ which installs are held to (SPEC UNIT_PINNING)
43
+ EXAMPLE: decklight extension check grammar-check.mjs
44
+
45
+ --type transform what kind of extension this is (default, and the only
46
+ kind implemented — the import-adapter contract is frozen
47
+ (SPEC EXTENSIONS_ADAPTERS), so an "importer" type can
48
+ follow as its own ticket)
49
+
50
+ This is not part of bundle, import or publish — those run an
51
+ already-installed unit and never re-check it (EXTENSIONS#LOADER). It is
52
+ the gate a marketplace's own CI runs before admitting an entry to a
53
+ catalog: "failure blocks publish" means blocking that admission, not
54
+ decklight's own publish command.
55
+
56
+ The lint is advisory: a source-text scan catches the honest mistake, not a
57
+ determined one (a static child_process import sails right past it). What
58
+ constrains the submission DURING the check is the process boundary — which
59
+ does not cover the network; Node's permission model stops files, processes
60
+ and env, not fetch. And past admission, an installed transform runs as
61
+ trusted, unsandboxed Node: the installer bears that risk (MARKETPLACE.md
62
+ EXTENSIONS). Admission screens; it does not absolve. Needs a real Chrome
63
+ to run the headless phase, the same way \`npm run verify\`'s render
64
+ harnesses do.`;
65
+
66
+ /** The validation report, as the lines to print. */
67
+ export function reportLines(name, result) {
68
+ if (result.ok) {
69
+ return [`✔ ${name} — lints clean, output carries no <script> or inline handler`,
70
+ // The pin the entry carries once admitted (SPEC UNIT_PINNING):
71
+ // `transform add` refuses to install without it, or past a mismatch.
72
+ ` sha256: ${result.sha256} — the catalog entry pins the file to this digest`];
73
+ }
74
+ if (result.phase === 'lint') {
75
+ return [`✘ ${name}`, ...result.lint.map((l) => ` line ${l.line}: ${l.why}\n ${l.text}`)];
76
+ }
77
+ return [`✘ ${name}`, ` ${result.error}`];
78
+ }
79
+
80
+ async function checkMain(args) {
81
+ const { opt } = argReader(args);
82
+ const [file] = args.filter((a, i) => !a.startsWith('-') && args[i - 1] !== '--type');
83
+ if (!file) { console.error(`decklight extension check: needs a file\n\n${USAGE}`); return 1; }
84
+ if (!existsSync(file)) { console.error(`decklight extension check: no such file: ${file}`); return 1; }
85
+
86
+ const type = opt('--type') ?? 'transform';
87
+ if (!TYPES.includes(type)) {
88
+ console.error(`decklight extension check: --type ${type} is not implemented`
89
+ + ` — this decklight only checks: ${TYPES.join(', ')}`);
90
+ return 1;
91
+ }
92
+
93
+ const result = await checkExtension(file, { type });
94
+ for (const line of reportLines(file, result)) console.log(line);
95
+ return result.ok ? 0 : 1;
96
+ }
97
+
98
+ export async function extensionMain(args = []) {
99
+ const sub = args[0];
100
+ if (!sub || sub === '--help' || sub === '-h' || sub === 'help') { console.log(USAGE); return sub ? 0 : 1; }
101
+ const rest = args.slice(1);
102
+ if (rest.includes('--help') || rest.includes('-h')) { console.log(USAGE); return 0; }
103
+ if (sub === 'check') return checkMain(rest);
104
+ console.error(`decklight extension: unknown subcommand "${sub}"\n\n${USAGE}`);
105
+ return 1;
106
+ }
107
+
108
+ if (isMain(import.meta.url)) process.exit(await extensionMain(process.argv.slice(2)));
package/cli/git.mjs ADDED
@@ -0,0 +1,141 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ // The git plumbing decklight reaches for when it keeps the durable record —
5
+ // repo creation, the autosave commit, "am I in a repo?". It was hand-rolled in
6
+ // edit, dev and init, and the identity-missing regex had already drifted apart
7
+ // between them (init learned `auto-detect`, edit never did). One home now.
8
+
9
+ import { execFileSync } from 'node:child_process';
10
+ import { existsSync, writeFileSync } from 'node:fs';
11
+ import { resolve, basename } from 'node:path';
12
+
13
+ /** Run git in `cwd`, return trimmed stdout; throws on failure (stderr on e.stderr). */
14
+ export const git = (args, cwd, exec = execFileSync) =>
15
+ exec('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
16
+
17
+ /** Is `dir` inside a git work tree? (exec injectable for tests) */
18
+ export function inGitRepo(dir, exec = execFileSync) {
19
+ try { return git(['rev-parse', '--is-inside-work-tree'], dir, exec) === 'true'; } catch { return false; }
20
+ }
21
+
22
+ /**
23
+ * A git error that means "no identity configured" — the one failure decklight
24
+ * handles rather than surfaces, because the commit is the player's, not a
25
+ * human's. The superset of what edit and init each used to test for.
26
+ */
27
+ export const isIdentityError = (e) =>
28
+ /user\.(name|email)|tell me who you are|auto-detect/i.test(String(e.stderr || e));
29
+
30
+ /** A git error squeezed onto one line, for a note that never becomes an exit. */
31
+ export const oneline = (e) => String(e.stderr || e.message || e).replace(/\s+/g, ' ').trim().slice(0, 160);
32
+
33
+ // The starter .gitignore a decklight-created repository begins with: generated
34
+ // artifacts (screenshot evidence, OS junk, narration audio) stay out of the
35
+ // autocommit loop and out of a hasty `git add -A`. Three entries, one comment —
36
+ // a starter the player owns from the first commit, not an ignore database.
37
+ export const STARTER_GITIGNORE = `.shots/
38
+ .DS_Store
39
+
40
+ # narration audio is bulky — but cloud-generated narration costs money to regenerate; delete this line to version yours
41
+ voiceover/
42
+ `;
43
+
44
+ /**
45
+ * Create a git repository in `dir` — the one shared seam for every place
46
+ * decklight creates a repo (`edit`/`dev` with --git today, init's offer per
47
+ * #50). Runs `git init`, then writes the starter .gitignore — after init and
48
+ * before any initial commit the caller makes, so a `git add -A` opening
49
+ * commit picks it up. The repo-creation moment is the only time decklight
50
+ * touches ignore rules: an existing .gitignore is never appended to or
51
+ * merged, and a repository decklight didn't create never gets one. Returns
52
+ * true when the starter file was written. Throws when `git init` fails.
53
+ */
54
+ export function createRepo(dir) {
55
+ git(['init'], dir);
56
+ const ignorePath = resolve(dir, '.gitignore');
57
+ if (existsSync(ignorePath)) return false;
58
+ writeFileSync(ignorePath, STARTER_GITIGNORE);
59
+ return true;
60
+ }
61
+
62
+ /** Commit the deck if it changed. Returns true when a commit was made. */
63
+ // ── when to commit (#71) ───────────────────────────────────────────────────
64
+ // A timer is the wrong boundary for agent-authored edits: the commits land on
65
+ // a five-minute clock that lines up with nothing the agent did, and every one
66
+ // of them says `autosave`. After a long session you get a wall of identical
67
+ // messages and no way to see what changed when. `agent` mode commits per
68
+ // completed agent edit instead, with the agent's own summary as the subject.
69
+
70
+ export const GIT_MODES = ['timer', 'agent', 'off'];
71
+
72
+ /**
73
+ * Which commit policy is in force. `--no-git` still means off; the default is
74
+ * `agent`, which is a SUPERSET of `timer` — the cadence still runs underneath
75
+ * (see shouldCommit), so defaulting to it adds real commit messages for agent
76
+ * edits without taking the periodic safety net away from anyone. Anything
77
+ * unrecognised falls back to the default rather than failing: a typo should
78
+ * not cost you the safety net.
79
+ */
80
+ export function resolveGitMode(args = [], fallback = 'agent') {
81
+ if (args.includes('--no-git')) return 'off';
82
+ const i = args.indexOf('--git-mode');
83
+ const v = i >= 0 ? args[i + 1] : null;
84
+ return GIT_MODES.includes(v) ? v : fallback;
85
+ }
86
+
87
+ /**
88
+ * Should this moment produce a commit? Pure, so the whole decision table is
89
+ * testable without a repository or an agent (the planServices idiom).
90
+ *
91
+ * `ev.kind` is 'timer' (the cadence fired), 'agent' (a job finished — with
92
+ * `ok` and `changed`), or 'bookend' (start/stop of a session).
93
+ */
94
+ export function shouldCommit(mode, ev = {}) {
95
+ if (mode === 'off') return false;
96
+ // The cadence runs in agent mode too — it is the backstop for everything an
97
+ // agent job cannot see: your own edits, and any agent driven from outside the
98
+ // A flow. Suppressing it there would mean a crashed session loses hand edits
99
+ // entirely, which is the one thing autocommit exists to prevent. It is only
100
+ // held back WHILE a job is in flight, so no commit ever captures a
101
+ // half-finished agent run. (Two commits cannot race: gitAutocommit no-ops on
102
+ // a clean tree.)
103
+ if (ev.kind === 'timer') return !ev.agentBusy;
104
+ // a failed or cancelled job leaves the tree alone; an edit that changed
105
+ // nothing is not worth a commit that says it did
106
+ if (ev.kind === 'agent') return mode === 'agent' && ev.ok === true && ev.changed === true;
107
+ return true; // bookends: a session's first and last commit, in any live mode
108
+ }
109
+
110
+ /**
111
+ * A commit subject from text an AGENT wrote — untrusted, and heading for a
112
+ * command line. Collapse it to one line (a subject is one line by definition),
113
+ * cap it, and refuse to let it start with `-` so it can never be read as an
114
+ * option by anything downstream. Empty or unusable falls back.
115
+ */
116
+ export function commitSubject(raw, fallback) {
117
+ const one = String(raw ?? '').replace(/\s+/g, ' ').trim();
118
+ if (!one) return fallback;
119
+ const capped = one.length > 72 ? one.slice(0, 71) + '…' : one;
120
+ return /^-/.test(capped) ? `agent: ${capped}` : capped;
121
+ }
122
+
123
+ export function gitAutocommit(deckPath, cwd, message = `decklight: autosave ${basename(deckPath)}`) {
124
+ try {
125
+ if (!git(['status', '--porcelain', '--', deckPath], cwd)) return false;
126
+ git(['add', '--', deckPath], cwd);
127
+ try {
128
+ git(['commit', '-m', message, '--', deckPath], cwd);
129
+ } catch (e) {
130
+ // a fresh machine has no git identity — commit anyway rather than
131
+ // silently dropping the safety net, without touching global config
132
+ if (!isIdentityError(e)) throw e;
133
+ git(['-c', 'user.name=decklight', '-c', 'user.email=decklight@localhost',
134
+ 'commit', '-m', message, '--', deckPath], cwd);
135
+ }
136
+ return true;
137
+ } catch (e) {
138
+ console.error(` git autocommit failed: ${oneline(e)}`);
139
+ return false;
140
+ }
141
+ }
package/cli/import.mjs ADDED
@@ -0,0 +1,398 @@
1
+ #!/usr/bin/env node
2
+ // Copyright 2026 Gilles Philippart
3
+ // SPDX-License-Identifier: Apache-2.0
4
+
5
+ // decklight import — bring an existing deck across.
6
+ //
7
+ // decklight import "Q3 Review.pptx"
8
+ // decklight import keynote-deck.key (macOS: converted via Keynote)
9
+ // decklight import https://docs.google.com/presentation/d/<id>/edit
10
+ //
11
+ // THREE FRONT DOORS, ONE PARSER. PowerPoint's .pptx is the only one of the
12
+ // three that is a readable format: .key is an undocumented binary archive
13
+ // (Apple ships no schema and there is no honest way to parse it), and a Google
14
+ // Slides deck is not a local file at all. Both, however, can *become* a .pptx —
15
+ // Keynote exports one on the machine that owns it, and Google serves one from
16
+ // /export/pptx. So the importer speaks one format and meets you where you are.
17
+ //
18
+ // It is a CONTENT importer, not a pixel renderer: the original template's look
19
+ // is replaced by decklight theming. Anything that cannot cross is dropped and
20
+ // NAMED, per slide, because a chart that quietly vanishes from slide 14 gets
21
+ // discovered on stage.
22
+
23
+ import { execFileSync } from 'node:child_process';
24
+ import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
25
+ import { tmpdir } from 'node:os';
26
+ import { basename, join, resolve } from 'node:path';
27
+ import { argReader, isMain } from '../tools/args.mjs';
28
+ import { THEMES_DIR, themeCss as shippedThemeCss, runtimeCss, runtimeJs } from './pkg.mjs';
29
+ import { unzip } from '../tools/zip.mjs';
30
+ import { decodeEntities } from '../tools/ooxml.mjs';
31
+ import { parseRels, resolvePart, slideOrder, parseSlide, notesText, slideSection, mimeOf } from '../tools/pptx.mjs';
32
+
33
+
34
+ const USAGE = `usage: decklight import <deck.pptx | deck.key | google-slides-url> [options]
35
+ convert an existing presentation into a self-contained decklight deck
36
+
37
+ -o <file> output path [the source's, with .html]
38
+ --theme <name> theme to open in [midnight]
39
+ --build all|none|auto
40
+ which lists step in [auto]
41
+ auto follows PowerPoint's own per-paragraph build list
42
+ --force overwrite an existing output file
43
+ -v, --verbose print every slide's line, not just the ones with drops
44
+
45
+ content crosses over — titles, bullets (nested), paragraphs, tables, images
46
+ and speaker notes. The template's LOOK does not: the result is themed by
47
+ decklight. Anything that cannot cross is named on stderr with its slide
48
+ number, so you know what to rebuild by hand.
49
+
50
+ .key needs Keynote (macOS): it is converted to .pptx by Keynote itself.
51
+ A Google Slides URL is fetched as .pptx — the deck must be link-shared.
52
+
53
+ A format decklight cannot read itself runs through an installed import
54
+ adapter instead, if one is installed for that extension: decklight importer
55
+ add <name>, then this command again. -v/--build/drop reporting are the
56
+ built-in PowerPoint path's own; a third-party adapter has no equivalent yet.`;
57
+
58
+ /**
59
+ * The deck name a source implies: the file's, or the URL's document id.
60
+ *
61
+ * Strips ANY trailing extension, not only `.pptx`/`.key`/`.ppt`: a source an
62
+ * installed import adapter reads (`.marp`, say) is just as much "the file's
63
+ * name minus its format" as the three built-in ones — `talk.marp` importing
64
+ * to `talk-marp.html` would be the format's name doubling into the deck's,
65
+ * for every extension `EXTENSIONS#ADAPTEREXEC` newly makes importable.
66
+ */
67
+ export function outPath(source, oFlag) {
68
+ if (oFlag) return resolve(oFlag);
69
+ const base = /^https?:/i.test(source)
70
+ ? (slidesId(source) ?? 'imported-deck')
71
+ : basename(source).replace(/\.[A-Za-z0-9]+$/, '');
72
+ return resolve(slug(base) + '.html');
73
+ }
74
+
75
+ export const slug = (s) => String(s).trim().toLowerCase()
76
+ .replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '') || 'deck';
77
+
78
+ /** The document id in a Google Slides URL, or null if it is not one. */
79
+ export function slidesId(url) {
80
+ const m = /docs\.google\.com\/presentation\/d\/(?:e\/)?([A-Za-z0-9_-]{8,})/.exec(String(url ?? ''));
81
+ return m ? m[1] : null;
82
+ }
83
+
84
+ /** Google serves any presentation it will show you as a .pptx at this URL. */
85
+ export const slidesExportUrl = (id) => `https://docs.google.com/presentation/d/${id}/export/pptx`;
86
+
87
+ /**
88
+ * What kind of source this is. Deciding up front keeps the three doors'
89
+ * error messages specific: "that is not a Google Slides link" beats a 404.
90
+ */
91
+ export function sourceKind(source) {
92
+ const s = String(source ?? '');
93
+ if (/^https?:/i.test(s)) return slidesId(s) ? 'gslides' : 'url';
94
+ if (/\.pptx$/i.test(s)) return 'pptx';
95
+ if (/\.key$/i.test(s)) return 'keynote';
96
+ if (/\.ppt$/i.test(s)) return 'ppt';
97
+ return 'unknown';
98
+ }
99
+
100
+ /**
101
+ * Turn a .key into a .pptx by asking Keynote to export it.
102
+ *
103
+ * There is no parser here and there should not be: iWork's format is
104
+ * undocumented, versioned with the app, and a snappy-compressed protobuf
105
+ * archive in current versions. Keynote already exports PowerPoint perfectly
106
+ * well; the only thing missing was someone to ask. Off macOS, the honest
107
+ * answer is instructions.
108
+ */
109
+ export function keynoteScript(src, outDir) {
110
+ // `save ... as` is scriptable export; the file name follows the document's
111
+ return `tell application "Keynote"
112
+ set d to open POSIX file ${JSON.stringify(src)}
113
+ export d to POSIX file ${JSON.stringify(outDir)} as Microsoft PowerPoint
114
+ close d saving no
115
+ end tell`;
116
+ }
117
+
118
+ function convertKeynote(src, { platform = process.platform, exec = execFileSync } = {}) {
119
+ if (platform !== 'darwin') {
120
+ throw new Error(
121
+ `.key files can only be read by Keynote, and Keynote only runs on macOS.\n`
122
+ + ` On a Mac, either run this same command there, or export by hand:\n`
123
+ + ` Keynote → File → Export To → PowerPoint… → save as .pptx\n`
124
+ + ` then: decklight import that-file.pptx`);
125
+ }
126
+ const dir = mkdtempSync(join(tmpdir(), 'decklight-key-'));
127
+ try {
128
+ exec('osascript', ['-e', keynoteScript(resolve(src), dir)], { stdio: ['ignore', 'ignore', 'pipe'] });
129
+ } catch (e) {
130
+ rmSync(dir, { recursive: true, force: true });
131
+ throw new Error(
132
+ `Keynote could not export ${basename(src)} (${String(e.stderr ?? e.message).trim().split('\n')[0]}).\n`
133
+ + ` Keynote must be installed, and the first run needs you to allow automation\n`
134
+ + ` (System Settings → Privacy & Security → Automation). Or export by hand:\n`
135
+ + ` Keynote → File → Export To → PowerPoint…`);
136
+ }
137
+ const made = readdirSync(dir).find((f) => /\.pptx$/i.test(f));
138
+ if (!made) { rmSync(dir, { recursive: true, force: true }); throw new Error('Keynote exported no .pptx'); }
139
+ return { file: join(dir, made), cleanup: () => rmSync(dir, { recursive: true, force: true }) };
140
+ }
141
+
142
+ async function fetchSlides(url, { fetchImpl = fetch } = {}) {
143
+ const id = slidesId(url);
144
+ const r = await fetchImpl(slidesExportUrl(id));
145
+ if (!r.ok) {
146
+ throw new Error(
147
+ `Google would not export that presentation (HTTP ${r.status}).\n`
148
+ + ` decklight downloads it as .pptx, which only works if the deck is shared:\n`
149
+ + ` Share → General access → "Anyone with the link"\n`
150
+ + ` Otherwise download it yourself (File → Download → Microsoft PowerPoint)\n`
151
+ + ` and run: decklight import that-file.pptx`);
152
+ }
153
+ const buf = Buffer.from(await r.arrayBuffer());
154
+ // an unshared deck answers 200 with a sign-in page, not an archive
155
+ if (buf.length < 4 || buf[0] !== 0x50 || buf[1] !== 0x4b) {
156
+ throw new Error(
157
+ 'Google returned a web page instead of a presentation — the deck is probably not shared.\n'
158
+ + ' Share → General access → "Anyone with the link", or download it as .pptx yourself.');
159
+ }
160
+ return buf;
161
+ }
162
+
163
+ /**
164
+ * The whole conversion, from archive bytes to sections and a report.
165
+ * Pure apart from the parsing, so the mapping is testable without a CLI.
166
+ */
167
+ export function convert(zip, { build = 'auto' } = {}) {
168
+ const part = (name) => zip.get(name)?.toString('utf8');
169
+ const order = slideOrder(part('ppt/presentation.xml'), part('ppt/_rels/presentation.xml.rels'));
170
+ if (!order.length) throw new Error('no slides found — is this really a PowerPoint file?');
171
+
172
+ const sections = [];
173
+ const report = [];
174
+ let n = 0;
175
+ for (const slidePath of order) {
176
+ const xml = part(slidePath);
177
+ if (!xml) continue;
178
+ const rels = parseRels(part(`${slidePath.replace(/([^/]+)$/, '_rels/$1')}.rels`));
179
+ const slide = parseSlide(xml, {
180
+ rels,
181
+ mediaOf: (target) => {
182
+ const p = resolvePart(slidePath, target);
183
+ const bytes = zip.get(p);
184
+ return bytes ? { bytes, mime: mimeOf(p) } : null;
185
+ },
186
+ });
187
+ n += 1;
188
+ if (slide.hidden) { report.push({ n, hidden: true, title: slide.title }); continue; }
189
+
190
+ const notesRel = [...rels.values()].find((r) => r.type.endsWith('/notesSlide'));
191
+ const notes = notesRel
192
+ ? notesText(part(resolvePart(slidePath, notesRel.target)), { rels })
193
+ : [];
194
+ const { html, did } = slideSection(slide, notes, { build });
195
+ sections.push(html);
196
+ report.push({ n, title: slide.title, did, drops: slide.drops });
197
+ }
198
+ if (!sections.length) throw new Error('every slide in this file is hidden — nothing to import');
199
+ return { sections, report };
200
+ }
201
+
202
+ /** The self-contained deck, runtime and theme inlined — the `init` output shape. */
203
+ export function deckHtml(sections, { title, theme }) {
204
+ const css = runtimeCss();
205
+ const theme_ = shippedThemeCss(theme);
206
+ // runtimeJs() applies the SAME transform init/upgrade/bundle use and audit
207
+ // recomputes. This used to be a local escape that missed `<!--`, which made
208
+ // every imported deck audit as "runtime DIFFERS from this install's build".
209
+ const js = runtimeJs();
210
+ const safe = (s) => s.replace(/<\/(script|style)/gi, '<\\/$1');
211
+ return `<!doctype html>
212
+ <html lang="en">
213
+ <head>
214
+ <meta charset="utf-8">
215
+ <title>${title.replace(/[<&]/g, (c) => (c === '<' ? '&lt;' : '&amp;'))}</title>
216
+ <style data-decklight-runtime="css">
217
+ ${safe(css)}
218
+ </style>
219
+ <style data-theme="${theme}">
220
+ ${safe(theme_)}
221
+ </style>
222
+ </head>
223
+ <body>
224
+ <div class="decklight">
225
+
226
+ ${sections.join('\n\n')}
227
+
228
+ </div>
229
+ <script data-decklight-runtime="js">${js}</script>
230
+ <script>Decklight.init({});</script>
231
+ </body>
232
+ </html>
233
+ `;
234
+ }
235
+
236
+ /**
237
+ * What to say about a file this importer cannot read AND has no installed
238
+ * adapter for.
239
+ *
240
+ * Two answers, deliberately distinguishable — "no adapter exists" and "one
241
+ * exists and here is how to get it". An INSTALLED adapter is a third state,
242
+ * but it is not one this function ever needs to describe: `importMain`
243
+ * checks for an installed adapter before reaching here, and runs it instead
244
+ * (`EXTENSIONS#ADAPTEREXEC`, `cli/loader.mjs`'s `runImporter`) — reaching this
245
+ * function at all already means there is nothing installed to run.
246
+ */
247
+ export async function adapterOffer(source, { home } = {}) {
248
+ const name = basename(String(source ?? ''));
249
+ const ext = /(\.[A-Za-z0-9]+)$/.exec(name)?.[1]?.toLowerCase() ?? '';
250
+ const out = [`decklight import: don't know how to read ${name}`,
251
+ ' supported: .pptx, .key (macOS), or a Google Slides URL'];
252
+ if (!ext) return out;
253
+
254
+ const { adapterFor } = await import('./units.mjs');
255
+ const offered = adapterFor(ext, home);
256
+ if (!offered) return out;
257
+
258
+ out.push(` no adapter for ${ext} — ${offered.qualified} reads it:`,
259
+ ` decklight importer add ${offered.qualified}`);
260
+ return out;
261
+ }
262
+
263
+ export async function importMain(args = []) {
264
+ if (!args.length || args.includes('--help') || args.includes('-h')) {
265
+ console.log(USAGE);
266
+ return args.length ? 0 : 1;
267
+ }
268
+ const { opt } = argReader(args);
269
+ const VALUE = new Set(['-o', '--theme', '--build']);
270
+ const source = args.find((a, i) => !a.startsWith('-') && !VALUE.has(args[i - 1]));
271
+ if (!source) { console.error(`decklight import: needs a file or a Google Slides URL\n\n${USAGE}`); return 1; }
272
+
273
+ const theme = opt('--theme', 'midnight');
274
+ if (!existsSync(join(THEMES_DIR, `${theme}.css`))) {
275
+ const all = readdirSync(THEMES_DIR).filter((f) => f.endsWith('.css')).map((f) => f.replace(/\.css$/, ''));
276
+ console.error(`decklight import: no theme "${theme}"`);
277
+ console.error(` available: ${all.join(', ')}`);
278
+ return 1;
279
+ }
280
+ const build = opt('--build', 'auto');
281
+ if (!['auto', 'all', 'none'].includes(build)) {
282
+ console.error(`decklight import: --build must be auto, all or none (got "${build}")`);
283
+ return 1;
284
+ }
285
+
286
+ const out = outPath(source, opt('-o'));
287
+ if (existsSync(out) && !args.includes('--force')) {
288
+ console.error(`decklight import: ${out} already exists — pass --force to overwrite`);
289
+ return 1;
290
+ }
291
+
292
+ // ---- get a .pptx, whichever door we came in by ------------------------
293
+ const kind = sourceKind(source);
294
+ let bytes;
295
+ let cleanup = () => {};
296
+ try {
297
+ if (kind === 'pptx') {
298
+ if (!existsSync(source)) { console.error(`decklight import: no such file: ${source}`); return 1; }
299
+ bytes = readFileSync(source);
300
+ } else if (kind === 'keynote') {
301
+ if (!existsSync(source)) { console.error(`decklight import: no such file: ${source}`); return 1; }
302
+ console.error(`import: asking Keynote to export ${basename(source)} as PowerPoint…`);
303
+ const done = convertKeynote(source);
304
+ cleanup = done.cleanup;
305
+ bytes = readFileSync(done.file);
306
+ } else if (kind === 'gslides') {
307
+ console.error('import: downloading the deck from Google as .pptx…');
308
+ bytes = await fetchSlides(source);
309
+ } else if (kind === 'ppt') {
310
+ console.error('decklight import: .ppt is the pre-2007 binary format, which decklight cannot read.');
311
+ console.error(' Open it in PowerPoint or Keynote and save as .pptx first.');
312
+ return 1;
313
+ } else if (kind === 'url') {
314
+ console.error('decklight import: that URL is not a Google Slides presentation.');
315
+ console.error(' Expected https://docs.google.com/presentation/d/<id>/…');
316
+ return 1;
317
+ } else {
318
+ // The offer at the point of failure (UNITS#REST): the moment someone
319
+ // learns .marp is unsupported is the only moment they care which adapter
320
+ // reads it, so the answer belongs HERE rather than in a setup step
321
+ // nobody performs in advance. This is the ENGINES pattern.
322
+ //
323
+ // Cache-only, always: the lookup reads catalogs already on disk, so a
324
+ // command that worked offline before still does. With nothing cached it
325
+ // simply has nothing to add, and the message is the one it always was.
326
+ const ext = /(\.[A-Za-z0-9]+)$/.exec(basename(source))?.[1]?.toLowerCase() ?? '';
327
+ const { adapterFor, findUnit } = await import('./units.mjs');
328
+ const offered = ext ? adapterFor(ext) : null;
329
+ const installedAdapter = offered && findUnit('importer', offered.name);
330
+ if (!installedAdapter) {
331
+ for (const line of await adapterOffer(source)) console.error(line);
332
+ return 1;
333
+ }
334
+
335
+ // An installed adapter runs (EXTENSIONS#ADAPTEREXEC, SPEC
336
+ // EXTENSIONS_ADAPTERS) — bytes in, one HTML string of section markup
337
+ // out, the same in-process trust model `bundle --transform` already
338
+ // uses. It has no per-slide report the way the built-in PowerPoint path
339
+ // does (that shape is deliberately not part of the v1 adapter
340
+ // contract), so it writes the deck and returns here rather than
341
+ // falling into the `convert()` pipeline below.
342
+ if (!existsSync(source)) { console.error(`decklight import: no such file: ${source}`); return 1; }
343
+ console.error(`import: reading ${basename(source)} with ${offered.name}…`);
344
+ const { runImporter } = await import('./loader.mjs');
345
+ const { html: sectionsHtml } = await runImporter(offered.name, readFileSync(source));
346
+
347
+ const title = basename(out).replace(/\.html$/, '').replace(/-/g, ' ').replace(/^./, (c) => c.toUpperCase());
348
+ writeFileSync(out, deckHtml([sectionsHtml], { title, theme }));
349
+ const slideCount = (sectionsHtml.match(/<section[\s>]/gi) ?? []).length;
350
+ const kb = Math.round(readFileSync(out).length / 1024);
351
+ console.error(`${out} · ${slideCount} slide(s) · theme ${theme} · ${kb} KB · imported via ${offered.name}`);
352
+ return 0;
353
+ }
354
+ } catch (e) {
355
+ console.error(`decklight import: ${e.message}`);
356
+ return 1;
357
+ }
358
+
359
+ // ---- convert ----------------------------------------------------------
360
+ let result;
361
+ try {
362
+ result = convert(unzip(bytes), { build });
363
+ } catch (e) {
364
+ console.error(`decklight import: ${e.message}`);
365
+ return 1;
366
+ } finally {
367
+ cleanup();
368
+ }
369
+
370
+ const verbose = args.includes('-v') || args.includes('--verbose');
371
+ let dropped = 0;
372
+ for (const row of result.report) {
373
+ if (row.hidden) {
374
+ const t = decodeEntities((row.title ?? '').replace(/<[^>]+>/g, ''));
375
+ console.error(` ${String(row.n).padStart(3)} ⊘ hidden slide skipped${t ? ` — ${t}` : ''}`);
376
+ continue;
377
+ }
378
+ // the title is HTML by now; the terminal wants the words back
379
+ const name = decodeEntities((row.title ?? '(no title)').replace(/<[^>]+>/g, '')).slice(0, 44);
380
+ if (row.drops.length) {
381
+ dropped += row.drops.length;
382
+ console.error(` ${String(row.n).padStart(3)} ⚠ ${name}${row.did.length ? ` — ${row.did.join(' · ')}` : ''}`);
383
+ for (const d of row.drops) console.error(` ${d}`);
384
+ } else if (verbose) {
385
+ console.error(` ${String(row.n).padStart(3)} ${name}${row.did.length ? ` — ${row.did.join(' · ')}` : ''}`);
386
+ }
387
+ }
388
+
389
+ const title = basename(out).replace(/\.html$/, '').replace(/-/g, ' ').replace(/^./, (c) => c.toUpperCase());
390
+ writeFileSync(out, deckHtml(result.sections, { title, theme }));
391
+ const kb = Math.round(readFileSync(out).length / 1024);
392
+ console.error(`${out} · ${result.sections.length} slides · theme ${theme} · ${kb} KB`
393
+ + (dropped ? ` · ${dropped} thing(s) dropped — see ⚠ above` : ''));
394
+ if (!verbose && !dropped) console.error(' everything converted; -v lists each slide');
395
+ return 0;
396
+ }
397
+
398
+ if (isMain(import.meta.url)) process.exit(await importMain(process.argv.slice(2)));