excalideck 0.0.1 → 0.2.1

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/main.mjs ADDED
@@ -0,0 +1,394 @@
1
+ // The excalideck CLI. It follows Ed's CLI contract 1.0 (https://github.com/edspencer/cli-contract): `serve` is the
2
+ // foreground name and the default, flags belong to their commands, errors are `excalideck: <message>` on stderr
3
+ // with the usage after them, and the exit codes are the shared ones. See AGENTS.md for the parts left out.
4
+ import { existsSync, readFileSync, readdirSync, statSync, watch, writeFileSync } from "node:fs";
5
+ import { basename, dirname, join, relative, resolve } from "node:path";
6
+ import { pathToFileURL } from "node:url";
7
+ import { spawn } from "node:child_process";
8
+ import { check, formatReport } from "../src/check.js";
9
+ import { EXIT } from "../src/contract/exit-codes.js";
10
+ import { createOutput, exitQuietlyOnEpipe, reportUsageError, UsageError } from "../src/contract/output.js";
11
+ import { runBusyCommand } from "../src/contract/busy-client.js";
12
+ import { DOCTOR_HELP, DOCTOR_USAGE, parseDoctorArgs, runDoctor } from "./doctor.mjs";
13
+ import { runRecord, runRender } from "./media.mjs";
14
+ import { openBrowser, serveDeck } from "./serve.mjs";
15
+ import { DEFAULT_PORT, EXAMPLE_DECK, home, NAME, ROOT, VERSION } from "./paths.mjs";
16
+
17
+ /** The command names, which win over a deck file of the same name (SPEC §1): that file is given as ./check. */
18
+ const COMMANDS = ["serve", "new", "build", "dev", "check", "render", "record", "busy", "doctor", "help"];
19
+
20
+ const USAGE = `Usage: excalideck [serve] [deck.excalidraw] [--port <n>] [-o] [-q]
21
+ excalideck new <name> · build <talk.mjs> · dev <talk.mjs|deck.excalidraw>
22
+ excalideck check <deck.excalidraw> [--json] [--verbose]
23
+ excalideck render <deck.excalidraw> [--out <dir>] [--frame <n>] [--scale <n>]
24
+ excalideck record <deck.excalidraw> [--out <file.webm>] [--width <n>] [--hold <ms>]
25
+ excalideck busy [--json]
26
+ excalideck doctor [--json] [--offline]
27
+ excalideck --help | --version
28
+ `;
29
+
30
+ const HELP = `excalideck ${VERSION}: present Excalidraw files as slide decks that morph between frames
31
+
32
+ Usage: excalideck [serve] [deck.excalidraw] [options]
33
+
34
+ serve present a deck in the browser, until Ctrl-C. It's the default: \`excalideck deck.excalidraw\`
35
+ is \`excalideck serve deck.excalidraw\`. With no deck, the one .excalidraw file here; with
36
+ none here, the bundled example. The page reloads when the file changes. A deck named like a
37
+ command (check, render, …) is given as ./check.
38
+ new <name> start a talk: writes <name>.mjs, a script that builds <name>.excalidraw.
39
+ build <talk.mjs> run the script, then check what it wrote. Re-run it after every edit.
40
+ dev <talk.mjs> build, check and serve, then do it again on every save.
41
+ check <deck> layout problems slide by slide, and what each transition will morph. --json, --verbose.
42
+ render <deck> a PNG per slide, plus sheet.png with all of them. Needs Playwright.
43
+ record <deck> a .webm of the deck playing through. Needs Playwright.
44
+ busy [--json] is the one running here busy? Exits 0 (no), 75 (yes) or 3 (nothing is running).
45
+ doctor check excalideck can run here, with a fix for each problem. --json, --offline.
46
+
47
+ Options:
48
+ --port <n> the port to serve on (default ${DEFAULT_PORT})
49
+ -o, --open open it in your browser, once it answers
50
+ -q, --quiet print only the first line, \`excalideck <version>: <url>\`
51
+ -v, --version print the version
52
+ -h, --help print this; \`excalideck <command> --help\` for one command
53
+
54
+ Player keys: → next · ← back · 1-9 jump · O overview · R replay · T/A other transitions and appear styles ·
55
+ S slow motion · L load another file · F full screen · ? all keys.
56
+
57
+ It listens on 127.0.0.1 only, and reads the deck from disk: nothing is uploaded anywhere. While it runs,
58
+ ~/.excalideck/runtime.json says where it is. Docs: https://excalideck.edspencer.net
59
+ `;
60
+
61
+ const SERVE_USAGE = `Usage: excalideck [serve] [deck.excalidraw] [--port <n>] [-o|--open] [-q|--quiet]
62
+ `;
63
+ const NEW_USAGE = `Usage: excalideck new <name>
64
+ `;
65
+ const BUILD_USAGE = `Usage: excalideck build <talk.mjs>
66
+ `;
67
+ const DEV_USAGE = `Usage: excalideck dev <talk.mjs|deck.excalidraw> [--port <n>] [-o|--open]
68
+ `;
69
+ const CHECK_USAGE = `Usage: excalideck check [deck.excalidraw] [--json] [--verbose]
70
+ `;
71
+ const RENDER_USAGE = `Usage: excalideck render [deck.excalidraw] [--out <dir>] [--frame <n>] [--scale <n>]
72
+ `;
73
+ const RECORD_USAGE = `Usage: excalideck record [deck.excalidraw] [--out <file.webm>] [--width <n>] [--hold <ms>]
74
+ `;
75
+ const BUSY_USAGE = `Usage: excalideck busy [--json]
76
+ `;
77
+
78
+ const BUSY_HELP = `excalideck busy: is the excalideck running here busy?
79
+
80
+ ${BUSY_USAGE}
81
+ --json one JSON document on stdout
82
+
83
+ Presenting holds nothing that a restart would lose, so a running excalideck is never busy: this exits 0 while
84
+ one is presenting, and 3 when none is. It's here so scripts can ask every one of these tools the same question.
85
+ It finds the one running here through ~/.excalideck/runtime.json.
86
+ `;
87
+
88
+ const CHECK_HELP = `excalideck check: what's wrong with a deck, and what it will do between slides.
89
+
90
+ ${CHECK_USAGE}
91
+ --json one JSON document on stdout
92
+ --verbose every finding, including the small ones, and full lists
93
+
94
+ Per slide: labels that don't fit their box, overlapping boxes, arrows crossing a box, text too small to read.
95
+ Per transition: what morphs, what re-attaches, what clones, what enters and what leaves. It exits 1 if any
96
+ slide has an error, so it can gate a build.
97
+ `;
98
+
99
+ /** Which flags each command takes. A flag on a command that can't act on it is a usage error (SPEC §1). */
100
+ const FLAGS = {
101
+ serve: { port: "number", open: "bool", quiet: "bool" },
102
+ dev: { port: "number", open: "bool", quiet: "bool" },
103
+ check: { json: "bool", verbose: "bool" },
104
+ render: { out: "string", frame: "number", scale: "number" },
105
+ record: { out: "string", width: "number", hold: "number" },
106
+ busy: { json: "bool" },
107
+ doctor: { json: "bool", offline: "bool" },
108
+ new: {},
109
+ build: {},
110
+ };
111
+ const SHORT = { o: "open", q: "quiet" };
112
+
113
+ const out = createOutput({ tool: NAME });
114
+ exitQuietlyOnEpipe();
115
+
116
+ /** The usage printed after a usage error: the command's own, once we know which command it is. */
117
+ let usage = USAGE;
118
+
119
+ // ── parsing ───────────────────────────────────────────────────────────────────
120
+
121
+ function whyNotMine(key, command) {
122
+ const owner = Object.entries(FLAGS).find(([c, table]) => c !== command && table[key]);
123
+ if (owner) return `\`${command}\` has no --${key}; that's \`excalideck ${owner[0]} --${key}\``;
124
+ return `unknown option --${key}`;
125
+ }
126
+
127
+ /** Reads one command's arguments. Returns "help", or `{ values, positionals }`. Throws UsageError. */
128
+ function parseFlags(args, command) {
129
+ const table = FLAGS[command] ?? {};
130
+ const values = {}, positionals = [];
131
+ for (let i = 0; i < args.length; i++) {
132
+ const a = args[i];
133
+ if (a === "-h" || a === "--help") return "help";
134
+ if (a === "-v" || a === "--version") return "version";
135
+ if (a === "--") { positionals.push(...args.slice(i + 1)); break; }
136
+ let key, inline;
137
+ if (a.startsWith("--")) {
138
+ const eq = a.indexOf("=");
139
+ key = eq < 0 ? a.slice(2) : a.slice(2, eq);
140
+ if (eq >= 0) inline = a.slice(eq + 1);
141
+ } else if (/^-[A-Za-z]$/.test(a)) {
142
+ key = SHORT[a.slice(1)];
143
+ if (key === undefined) throw new UsageError(`unknown option ${a}`);
144
+ } else if (a.startsWith("-") && a !== "-") {
145
+ throw new UsageError(`unknown option ${a}`);
146
+ } else {
147
+ positionals.push(a);
148
+ continue;
149
+ }
150
+ const type = table[key];
151
+ if (type === undefined) throw new UsageError(whyNotMine(key, command));
152
+ if (type === "bool") {
153
+ if (inline !== undefined) throw new UsageError(`--${key} takes no value`);
154
+ values[key] = true;
155
+ continue;
156
+ }
157
+ const raw = inline ?? args[++i];
158
+ if (raw === undefined || raw === "") throw new UsageError(`--${key} needs ${type === "number" ? "a number" : "a value"}`);
159
+ if (type === "number") {
160
+ const n = Number(raw);
161
+ if (!Number.isFinite(n)) throw new UsageError(`--${key} needs a number (got ${raw})`);
162
+ values[key] = n;
163
+ } else values[key] = raw;
164
+ }
165
+ return { values, positionals };
166
+ }
167
+
168
+ const only = (positionals, what, command) => {
169
+ if (positionals.length > 1) throw new UsageError(`\`${command}\` takes one ${what} (got ${positionals.length})`);
170
+ return positionals[0];
171
+ };
172
+
173
+ /** The deck to work on: the one named, the one .excalidraw file here, or (serving) the bundled example. */
174
+ function resolveDeck(given, { example = false } = {}) {
175
+ if (given !== undefined) {
176
+ const file = resolve(given);
177
+ if (!existsSync(file) || !statSync(file).isFile()) throw new UsageError(`no such file: ${given}`);
178
+ return file;
179
+ }
180
+ let here = [];
181
+ try { here = readdirSync(process.cwd()).filter((f) => f.endsWith(".excalidraw")).sort(); } catch { /* unreadable cwd */ }
182
+ if (here.length === 1) return resolve(here[0]);
183
+ if (here.length > 1) throw new UsageError(`there are ${here.length} decks here (${here.slice(0, 4).join(", ")}${here.length > 4 ? ", …" : ""}); name the one you mean`);
184
+ if (example) return EXAMPLE_DECK;
185
+ throw new UsageError("there's no .excalidraw file here; name the deck");
186
+ }
187
+
188
+ // ── commands ──────────────────────────────────────────────────────────────────
189
+
190
+ function runNode(script) {
191
+ return new Promise((res) => {
192
+ const p = spawn(process.execPath, ["--import", pathToFileURL(join(ROOT, "cli", "register.mjs")).href, script],
193
+ { stdio: "inherit", cwd: dirname(script) });
194
+ p.on("exit", (code) => res(code === 0));
195
+ });
196
+ }
197
+
198
+ /** Runs a builder script, then checks what it wrote. Returns the exit code. */
199
+ async function buildScript(script, { quiet = false } = {}) {
200
+ if (!existsSync(script)) return out.error(`no such file: ${relative(process.cwd(), script)}`);
201
+ if (!(await runNode(script))) return out.error(`${basename(script)} failed`);
202
+ const deckFile = script.replace(/\.(mjs|js)$/, ".excalidraw");
203
+ if (!existsSync(deckFile)) return out.error(`${basename(script)} wrote no ${basename(deckFile)} — does it call deck.save()?`);
204
+ const report = check(JSON.parse(readFileSync(deckFile, "utf8")));
205
+ if (!quiet) out.say(formatReport(report));
206
+ return report.errors ? EXIT.FAILED : EXIT.OK;
207
+ }
208
+
209
+ async function cmdNew(args) {
210
+ const parsed = parseFlags(args, "new");
211
+ if (parsed === "help") { out.say(NEW_USAGE.trimEnd()); return EXIT.OK; }
212
+ const given = only(parsed.positionals, "name", "new");
213
+ if (given === undefined) throw new UsageError("new needs a name: excalideck new my-talk");
214
+ const name = given.replace(/\.(mjs|js|excalidraw)$/, "");
215
+ const script = resolve(`${name}.mjs`);
216
+ if (existsSync(script)) return out.error(`${relative(process.cwd(), script)} already exists`);
217
+ writeFileSync(script, TEMPLATE.replace(/__NAME__/g, basename(name)));
218
+ const code = await buildScript(script, { quiet: true });
219
+ out.say(`wrote ${relative(process.cwd(), script)} and ${basename(name)}.excalidraw`);
220
+ out.say(`edit it, then: excalideck build ${relative(process.cwd(), script)} (or: excalideck dev ${relative(process.cwd(), script)})`);
221
+ return code;
222
+ }
223
+
224
+ async function cmdBuild(args) {
225
+ const parsed = parseFlags(args, "build");
226
+ if (parsed === "help") { out.say(BUILD_USAGE.trimEnd()); return EXIT.OK; }
227
+ const given = only(parsed.positionals, "script", "build");
228
+ if (given === undefined) throw new UsageError("build needs a script: excalideck build my-talk.mjs");
229
+ if (!/\.(mjs|js)$/.test(given)) throw new UsageError(`build takes the .mjs script, not the deck (try: excalideck build ${given.replace(/\.excalidraw$/, ".mjs")})`);
230
+ return buildScript(resolve(given));
231
+ }
232
+
233
+ function cmdCheck(args) {
234
+ const parsed = parseFlags(args, "check");
235
+ if (parsed === "help") { out.say(CHECK_HELP.trimEnd()); return EXIT.OK; }
236
+ const file = resolveDeck(only(parsed.positionals, "deck", "check"));
237
+ const json = parsed.values.json === true;
238
+ const report = check(JSON.parse(readFileSync(file, "utf8")));
239
+ const o = json ? createOutput({ tool: NAME, json: true }) : out;
240
+ if (json) o.result(report);
241
+ else o.say(formatReport(report, { verbose: parsed.values.verbose === true }));
242
+ return report.errors ? EXIT.FAILED : EXIT.OK;
243
+ }
244
+
245
+ async function cmdServe(args) {
246
+ const parsed = parseFlags(args, "serve");
247
+ if (parsed === "help") { out.say(HELP.trimEnd()); return EXIT.OK; }
248
+ if (parsed === "version") { out.say(VERSION); return EXIT.OK; }
249
+ const deckFile = resolveDeck(only(parsed.positionals, "deck", "serve"), { example: true });
250
+ return serveDeck({
251
+ deckFile, port: parsed.values.port ?? DEFAULT_PORT, open: parsed.values.open === true,
252
+ quiet: parsed.values.quiet === true, out,
253
+ ...(deckFile === EXAMPLE_DECK ? {
254
+ label: "the bundled example (Snapline)",
255
+ note: "No deck here, so this is the bundled example. `excalideck new my-talk` starts your own.",
256
+ } : {}),
257
+ });
258
+ }
259
+
260
+ async function cmdDev(args) {
261
+ const parsed = parseFlags(args, "dev");
262
+ if (parsed === "help") { out.say(DEV_USAGE.trimEnd()); return EXIT.OK; }
263
+ const given = only(parsed.positionals, "script or deck", "dev");
264
+ if (given === undefined) throw new UsageError("dev needs a script or a deck: excalideck dev my-talk.mjs");
265
+ const input = resolve(given);
266
+ if (!existsSync(input)) throw new UsageError(`no such file: ${given}`);
267
+ const isScript = /\.(mjs|js)$/.test(input);
268
+ const deckFile = isScript ? input.replace(/\.(mjs|js)$/, ".excalidraw") : input;
269
+ if (isScript) await buildScript(input);
270
+ else out.say(formatReport(check(JSON.parse(readFileSync(deckFile, "utf8")))));
271
+ const code = await serveDeck({
272
+ deckFile, port: parsed.values.port ?? DEFAULT_PORT, open: parsed.values.open === true,
273
+ quiet: parsed.values.quiet === true, out,
274
+ note: `Watching ${relative(process.cwd(), input)} — save to rebuild.`,
275
+ });
276
+ if (code !== undefined) return code;
277
+ let t;
278
+ watch(input, () => {
279
+ clearTimeout(t);
280
+ t = setTimeout(async () => {
281
+ out.warn(`\n── ${new Date().toLocaleTimeString()} rebuild`);
282
+ if (isScript) await buildScript(input);
283
+ else out.say(formatReport(check(JSON.parse(readFileSync(deckFile, "utf8")))));
284
+ }, 150);
285
+ });
286
+ return undefined;
287
+ }
288
+
289
+ function cmdRender(args) {
290
+ const parsed = parseFlags(args, "render");
291
+ if (parsed === "help") { out.say(RENDER_USAGE.trimEnd()); return EXIT.OK; }
292
+ const deckFile = resolveDeck(only(parsed.positionals, "deck", "render"));
293
+ return runRender({
294
+ deckFile,
295
+ out: resolve(parsed.values.out ?? `${deckFile.replace(/\.excalidraw$/, "")}-slides`),
296
+ frame: parsed.values.frame, scale: parsed.values.scale ?? 1,
297
+ }, out);
298
+ }
299
+
300
+ function cmdRecord(args) {
301
+ const parsed = parseFlags(args, "record");
302
+ if (parsed === "help") { out.say(RECORD_USAGE.trimEnd()); return EXIT.OK; }
303
+ const deckFile = resolveDeck(only(parsed.positionals, "deck", "record"));
304
+ return runRecord({
305
+ deckFile,
306
+ out: resolve(parsed.values.out ?? deckFile.replace(/\.excalidraw$/, ".webm")),
307
+ width: parsed.values.width ?? 1280, hold: parsed.values.hold ?? 1200,
308
+ }, out);
309
+ }
310
+
311
+ function cmdBusy(args) {
312
+ const parsed = parseFlags(args, "busy");
313
+ if (parsed === "help") { out.say(BUSY_HELP.trimEnd()); return EXIT.OK; }
314
+ if (parsed.positionals.length) throw new UsageError(`\`busy\` takes no argument (got ${parsed.positionals[0]})`);
315
+ const json = parsed.values.json === true;
316
+ return runBusyCommand({ home: home(), name: NAME, out: json ? createOutput({ tool: NAME, json: true }) : out });
317
+ }
318
+
319
+ function cmdDoctor(args) {
320
+ const parsed = parseDoctorArgs(args, UsageError);
321
+ if (parsed === "help") { out.say(DOCTOR_HELP.trimEnd()); return EXIT.OK; }
322
+ return runDoctor(parsed, parsed.json ? createOutput({ tool: NAME, json: true }) : out);
323
+ }
324
+
325
+ // ── dispatch ──────────────────────────────────────────────────────────────────
326
+
327
+ const USAGES = { serve: SERVE_USAGE, new: NEW_USAGE, build: BUILD_USAGE, dev: DEV_USAGE, check: CHECK_USAGE,
328
+ render: RENDER_USAGE, record: RECORD_USAGE, busy: BUSY_USAGE, doctor: DOCTOR_USAGE };
329
+
330
+ async function main(argv) {
331
+ const first = argv[0];
332
+ if (first === "-h" || first === "--help" || first === "help") { out.say(HELP.trimEnd()); return EXIT.OK; }
333
+ if (first === "-v" || first === "--version") { out.say(VERSION); return EXIT.OK; }
334
+ const command = first !== undefined && COMMANDS.includes(first) ? first : "serve";
335
+ const args = command === "serve" && first !== "serve" ? argv : argv.slice(1);
336
+ usage = USAGES[command] ?? USAGE;
337
+ switch (command) {
338
+ case "new": return cmdNew(args);
339
+ case "build": return cmdBuild(args);
340
+ case "dev": return cmdDev(args);
341
+ case "check": return cmdCheck(args);
342
+ case "render": return cmdRender(args);
343
+ case "record": return cmdRecord(args);
344
+ case "busy": return cmdBusy(args);
345
+ case "doctor": return cmdDoctor(args);
346
+ default: return cmdServe(args);
347
+ }
348
+ }
349
+
350
+ const TEMPLATE = `// __NAME__ — an excalideck talk. Build: excalideck build __NAME__.mjs Present: excalideck serve __NAME__.excalidraw
351
+ // Every frame is a slide. A shape with the same label on the next slide morphs into it.
352
+ import { Deck } from "excalideck";
353
+
354
+ const deck = new Deck();
355
+
356
+ {
357
+ const f = deck.frame("Title", { appear: "rise" });
358
+ f.text("__NAME__", { x: 800, y: 330, size: 96, align: "center" });
359
+ f.text("subtitle goes here", { x: 800, y: 470, size: 36, align: "center", color: "#495057" });
360
+ }
361
+
362
+ {
363
+ const f = deck.frame("Overview", { transition: "morph", appear: "draw" });
364
+ f.title("Overview");
365
+ const user = f.box("User", { x: 140, y: 400, shape: "ellipse", color: "orange" });
366
+ const app = f.box("Our System", { x: 640, y: 380, w: 320, h: 140, size: 32 });
367
+ const ext = f.box("Payment Provider", { x: 1200, y: 400, color: "gray" });
368
+ f.arrow(user, app, { label: "uses" });
369
+ f.arrow(app, ext);
370
+ }
371
+
372
+ {
373
+ const f = deck.frame("Inside", { transition: "zoom", appear: "pop" });
374
+ f.title("Inside");
375
+ const user = f.box("User", { x: 40, y: 400, shape: "ellipse", color: "orange" });
376
+ f.region("Our System", { x: 300, y: 160, w: 860, h: 600 }); // same label as the box → it grows into this
377
+ const web = f.box("Web Frontend", { x: 360, y: 410 });
378
+ const api = f.box("API", { x: 640, y: 410, color: "green" });
379
+ const db = f.box("Database", { x: 640, y: 590, shape: "ellipse", color: "violet" });
380
+ const ext = f.box("Payment Provider", { x: 1260, y: 410, color: "gray" });
381
+ f.arrow(user, web); f.arrow(web, api); f.arrow(api, db); f.arrow(api, ext);
382
+ }
383
+
384
+ deck.save(new URL("./__NAME__.excalidraw", import.meta.url).pathname);
385
+ `;
386
+
387
+ // Last, so TEMPLATE and every constant above it is initialised before a command runs.
388
+ try {
389
+ const code = await main(process.argv.slice(2));
390
+ if (code !== undefined) process.exitCode = code;
391
+ } catch (err) {
392
+ if (err instanceof UsageError) process.exitCode = reportUsageError(out, err, usage);
393
+ else { out.error(err.message); process.exitCode = EXIT.FAILED; }
394
+ }
package/cli/media.mjs ADDED
@@ -0,0 +1,118 @@
1
+ // `excalideck render` and `excalideck record`: the two commands that drive a real browser, so the only two that
2
+ // need Playwright. Everything else in excalideck runs on Node alone.
3
+ import { execFile } from "node:child_process";
4
+ import { createRequire } from "node:module";
5
+ import { mkdirSync, readFileSync, rmSync } from "node:fs";
6
+ import { basename, dirname, join, relative } from "node:path";
7
+ import { pathToFileURL } from "node:url";
8
+ import { EXIT } from "../src/contract/exit-codes.js";
9
+ import { createServer, listen } from "./server.mjs";
10
+ import { ROOT, VERSION } from "./paths.mjs";
11
+
12
+ /** Playwright from the project, from excalideck's own folder, or from a global install. */
13
+ export async function playwright(out) {
14
+ const tries = [process.cwd(), ROOT];
15
+ try {
16
+ const g = await new Promise((r) => execFile("npm", ["root", "-g"], (e, o) => r(e ? "" : o.trim())));
17
+ if (g) tries.push(join(g, "x"), join(g, "@playwright", "mcp", "x"));
18
+ } catch { /* no npm on PATH; the local tries may still work */ }
19
+ for (const from of tries) {
20
+ for (const name of ["playwright", "playwright-core"]) {
21
+ try { const m = await import(pathToFileURL(createRequire(join(from, "x.js")).resolve(name)).href); return m.default ?? m; }
22
+ catch { /* keep looking */ }
23
+ }
24
+ }
25
+ out.error("this command needs Playwright: npm install -D playwright && npx playwright install chromium");
26
+ out.warn(" Without it: `excalideck serve <deck>` and open <url>/player/?file=/deck.excalidraw&static&frame=N for slide N.");
27
+ return null;
28
+ }
29
+
30
+ const serveFor = (deckFile, outDir) =>
31
+ listen(createServer({ root: ROOT, version: VERSION, deckFile, outDir }).server, 0);
32
+
33
+ async function gotoFrame(page, base, n) {
34
+ await page.goto(`${base}/player/?file=/deck.excalidraw&static&frame=${n}`);
35
+ const count = await page.evaluate(() => window.__deck.ready);
36
+ await page.evaluate(() => document.fonts.ready);
37
+ await page.waitForTimeout(150);
38
+ return count;
39
+ }
40
+
41
+ /** A PNG per slide, plus sheet.png with all of them. */
42
+ export async function runRender(o, out) {
43
+ const pw = await playwright(out);
44
+ if (!pw) return EXIT.FAILED;
45
+ mkdirSync(o.out, { recursive: true });
46
+ const srv = await serveFor(o.deckFile, o.out);
47
+ const browser = await pw.chromium.launch();
48
+ try {
49
+ const data = JSON.parse(readFileSync(o.deckFile, "utf8"));
50
+ const frames = data.elements.filter((e) => e.type === "frame" && !e.isDeleted);
51
+ const W = frames[0]?.width ?? 1600, H = frames[0]?.height ?? 900;
52
+ const page = await browser.newPage({ viewport: { width: W, height: H }, deviceScaleFactor: o.scale });
53
+ const count = await gotoFrame(page, srv.base, o.frame ?? 1);
54
+ if (o.frame && (o.frame < 1 || o.frame > count)) return out.error(`there is no slide ${o.frame}: the deck has ${count}`);
55
+ const list = o.frame ? [o.frame] : Array.from({ length: count }, (_, i) => i + 1);
56
+ const names = [];
57
+ for (const n of list) {
58
+ if (!(n === 1 && !o.frame)) await gotoFrame(page, srv.base, n);
59
+ const name = `${String(n).padStart(2, "0")}.png`;
60
+ await page.screenshot({ path: join(o.out, name) });
61
+ names.push(name);
62
+ out.say(` ${join(relative(process.cwd(), o.out), name)}`);
63
+ }
64
+ if (names.length > 1) { // contact sheet: every slide on one image, to look at in one go
65
+ const cols = names.length <= 4 ? 2 : 3, tw = 800, th = Math.round((tw * H) / W);
66
+ await page.setViewportSize({ width: cols * (tw + 16) + 16, height: Math.ceil(names.length / cols) * (th + 44) + 16 });
67
+ await page.setContent(`<body style="margin:0;padding:8px;background:#f1f3f5;font:16px system-ui;display:flex;flex-wrap:wrap">${names.map((nm, i) =>
68
+ `<figure style="margin:8px;width:${tw}px"><img src="${srv.base}/out/${nm}" style="width:${tw}px;height:${th}px;display:block;background:#fff;box-shadow:0 1px 4px #0002"><figcaption style="padding-top:4px;color:#495057">${i + 1}</figcaption></figure>`).join("")}</body>`);
69
+ await page.waitForLoadState("networkidle");
70
+ await page.screenshot({ path: join(o.out, "sheet.png"), fullPage: true });
71
+ out.say(` ${join(relative(process.cwd(), o.out), "sheet.png")} ← all slides on one image`);
72
+ }
73
+ return EXIT.OK;
74
+ } finally {
75
+ await browser.close();
76
+ await srv.close();
77
+ }
78
+ }
79
+
80
+ /** A video of the deck playing through, one keypress per slide. */
81
+ export async function runRecord(o, out) {
82
+ const pw = await playwright(out);
83
+ if (!pw) return EXIT.FAILED;
84
+ const height = Math.round((o.width * 9) / 16);
85
+ const srv = await serveFor(o.deckFile);
86
+ const browser = await pw.chromium.launch();
87
+ const dir = join(dirname(o.out), ".excalideck-rec");
88
+ try {
89
+ const ctx = await browser.newContext({ viewport: { width: o.width, height }, recordVideo: { dir, size: { width: o.width, height } } });
90
+ const page = await ctx.newPage();
91
+ const t0 = Date.now(), at = () => ((Date.now() - t0) / 1000).toFixed(1).padStart(5);
92
+ await page.goto(`${srv.base}/player/?file=/deck.excalidraw`);
93
+ const count = await page.evaluate(() => window.__deck.ready);
94
+ const settle = async () => {
95
+ await page.waitForFunction(() => !window.__deck.busy, null, { timeout: 30000 });
96
+ await page.waitForTimeout(o.hold);
97
+ };
98
+ out.say(` ${at()}s slide 1/${count}`);
99
+ await settle();
100
+ for (let i = 1; i < count; i++) {
101
+ out.say(` ${at()}s slide ${i + 1}/${count}`);
102
+ await page.keyboard.press("ArrowRight");
103
+ await page.waitForTimeout(100);
104
+ await settle();
105
+ }
106
+ const video = page.video();
107
+ await ctx.close();
108
+ await video.saveAs(o.out);
109
+ await video.delete();
110
+ out.say(` ${at()}s end`);
111
+ out.say(`wrote ${relative(process.cwd(), o.out)} (times are approximate; to convert: ffmpeg -i ${basename(o.out)} -c:v libx264 -pix_fmt yuv420p ${basename(o.out, ".webm")}.mp4)`);
112
+ return EXIT.OK;
113
+ } finally {
114
+ rmSync(dir, { recursive: true, force: true });
115
+ await browser.close();
116
+ await srv.close();
117
+ }
118
+ }
package/cli/paths.mjs ADDED
@@ -0,0 +1,24 @@
1
+ // Where excalideck keeps its data, and how it finds its own package.
2
+ import { homedir } from "node:os";
3
+ import { dirname, join, resolve } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { readFileSync } from "node:fs";
6
+
7
+ export const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..");
8
+ export const PKG = JSON.parse(readFileSync(join(ROOT, "package.json"), "utf8"));
9
+ export const VERSION = PKG.version;
10
+ export const PACKAGE_NAME = PKG.name;
11
+
12
+ /** The product name, for the banner and messages (SPEC §3). */
13
+ export const NAME = "excalideck";
14
+ /** The environment prefix (SPEC §6): EXCALIDECK_IN_DOCKER, EXCALIDECK_UPDATE_HINT. */
15
+ export const ENV_PREFIX = "EXCALIDECK";
16
+
17
+ /** `~/.excalideck`, holding runtime.json. `$EXCALIDECK_HOME` overrides it (tests, a throwaway home). */
18
+ export const home = (base = process.env.HOME || homedir()) =>
19
+ process.env.EXCALIDECK_HOME?.trim() || join(base, ".excalideck");
20
+
21
+ export const DEFAULT_PORT = 5190;
22
+
23
+ /** The example deck shipped in the package, served when there's no deck to hand. */
24
+ export const EXAMPLE_DECK = join(ROOT, "examples", "snapline", "snapline.excalidraw");
@@ -0,0 +1,4 @@
1
+ // Loaded with `node --import` by `excalideck build/dev/new` so talk scripts can
2
+ // `import { Deck } from "excalideck"` without installing anything.
3
+ import { register } from "node:module";
4
+ register("./resolve-hook.mjs", import.meta.url);
@@ -0,0 +1,9 @@
1
+ const MAP = {
2
+ excalideck: new URL("../lib/excalideck.mjs", import.meta.url).href,
3
+ "excalideck/check": new URL("../src/check.js", import.meta.url).href,
4
+ "excalideck/scene": new URL("../src/scene.js", import.meta.url).href,
5
+ };
6
+ export async function resolve(specifier, context, next) {
7
+ if (MAP[specifier]) return { url: MAP[specifier], shortCircuit: true };
8
+ return next(specifier, context);
9
+ }
package/cli/serve.mjs ADDED
@@ -0,0 +1,77 @@
1
+ // `excalideck serve`: present a deck, until Ctrl-C. It follows the CLI contract (SPEC §3, §4, §8): the first
2
+ // stdout line is `excalideck <version>: <url>`, ~/.excalideck/runtime.json says where it is, and it stops cleanly
3
+ // on SIGTERM.
4
+ import { execFile } from "node:child_process";
5
+ import { relative } from "node:path";
6
+ import { EXIT } from "../src/contract/exit-codes.js";
7
+ import { removeRuntimeFile, writeRuntimeFile } from "../src/contract/runtime-file.js";
8
+ import { waitForReady } from "../src/contract/health.js";
9
+ import { createServer, HOST, listen } from "./server.mjs";
10
+ import { home, NAME, ROOT, VERSION } from "./paths.mjs";
11
+
12
+ export function openBrowser(url) {
13
+ const c = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
14
+ execFile(c, [url], () => {});
15
+ }
16
+
17
+ /**
18
+ * Starts the server and keeps running. Resolves with an exit code if it ends there (a port in use), or undefined
19
+ * once it's serving.
20
+ * @param {object} o deckFile, port, open, quiet, out, note (an extra stderr line, e.g. from `dev`)
21
+ */
22
+ export async function serveDeck(o) {
23
+ const { server } = createServer({ root: ROOT, version: VERSION, deckFile: o.deckFile, watch: true });
24
+ let listening;
25
+ try {
26
+ listening = await listen(server, o.port);
27
+ } catch (err) {
28
+ if (err.code !== "EADDRINUSE") throw err;
29
+ return o.out.error(`port ${o.port} is in use: is excalideck already running? (try --port)`);
30
+ }
31
+ const { base, url, port } = listening;
32
+
33
+ // SPEC §4: how `excalideck busy` finds this instance. 0600, written once it's listening, removed on a clean stop.
34
+ // Not being able to write it doesn't stop it serving.
35
+ const dataHome = home();
36
+ try {
37
+ writeRuntimeFile(dataHome, { pid: process.pid, port, url: base, version: VERSION });
38
+ } catch (err) {
39
+ o.out.warn(`${NAME}: couldn't write ${dataHome}/runtime.json (${err.message}); presenting anyway.`);
40
+ }
41
+ process.on("exit", () => { try { removeRuntimeFile(dataHome); } catch { /* it's going anyway */ } });
42
+
43
+ // The banner is the first line on stdout (SPEC §3). --quiet prints that line alone.
44
+ process.stdout.write(`${NAME} ${VERSION}: ${base}\n`);
45
+ if (!o.quiet) {
46
+ const rel = relative(process.cwd(), o.deckFile);
47
+ const where = o.label ?? (rel && !rel.startsWith("..") ? rel : o.deckFile);
48
+ process.stdout.write([
49
+ ` presenting ${where}`,
50
+ ` listening on ${HOST}:${port} (this machine only)`,
51
+ " → next · ← back · O overview · R replay · T/A other transitions · F full screen · ? keys",
52
+ "",
53
+ ].join("\n"));
54
+ if (o.note) process.stderr.write(`${o.note}\n`);
55
+ }
56
+
57
+ // Ctrl-C and SIGTERM stop it. Nothing is being written, so there's nothing to drain: close and go.
58
+ let stopping = false;
59
+ const stop = () => {
60
+ if (stopping) process.exit(EXIT.OK);
61
+ stopping = true;
62
+ server.close(() => { process.exitCode = EXIT.OK; });
63
+ setTimeout(() => process.exit(EXIT.OK), 2000).unref();
64
+ };
65
+ process.on("SIGINT", stop);
66
+ process.on("SIGTERM", stop);
67
+ // Windows has no SIGTERM: something stopping it there sends Ctrl-C or Ctrl-Break (SIGBREAK).
68
+ if (process.platform === "win32") process.on("SIGBREAK", stop);
69
+
70
+ if (o.open) {
71
+ void waitForReady({ url: base }).then((ready) => {
72
+ if (ready === "ready") openBrowser(url);
73
+ else o.warn?.(`${NAME}: ${base} didn't answer, so it wasn't opened.`);
74
+ });
75
+ }
76
+ return undefined;
77
+ }