@treasure-ai/treasure-deck 0.0.0-stage → 2026.10.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 (110) hide show
  1. package/LICENSE.md +5 -0
  2. package/README.md +109 -2
  3. package/dist/analytics.d.ts +34 -0
  4. package/dist/analytics.js +93 -0
  5. package/dist/analytics.js.map +1 -0
  6. package/dist/attrs.d.ts +10 -0
  7. package/dist/attrs.js +22 -0
  8. package/dist/attrs.js.map +1 -0
  9. package/dist/build.d.ts +67 -0
  10. package/dist/build.js +247 -0
  11. package/dist/build.js.map +1 -0
  12. package/dist/check.d.ts +30 -0
  13. package/dist/check.js +142 -0
  14. package/dist/check.js.map +1 -0
  15. package/dist/chrome.d.ts +20 -0
  16. package/dist/chrome.js +162 -0
  17. package/dist/chrome.js.map +1 -0
  18. package/dist/cli.d.ts +2 -0
  19. package/dist/cli.js +246 -0
  20. package/dist/cli.js.map +1 -0
  21. package/dist/dev.d.ts +28 -0
  22. package/dist/dev.js +557 -0
  23. package/dist/dev.js.map +1 -0
  24. package/dist/diagrams.d.ts +18 -0
  25. package/dist/diagrams.js +57 -0
  26. package/dist/diagrams.js.map +1 -0
  27. package/dist/highlight.d.ts +7 -0
  28. package/dist/highlight.js +26 -0
  29. package/dist/highlight.js.map +1 -0
  30. package/dist/hot.d.ts +31 -0
  31. package/dist/hot.js +34 -0
  32. package/dist/hot.js.map +1 -0
  33. package/dist/media.d.ts +24 -0
  34. package/dist/media.js +82 -0
  35. package/dist/media.js.map +1 -0
  36. package/dist/parse.d.ts +109 -0
  37. package/dist/parse.js +313 -0
  38. package/dist/parse.js.map +1 -0
  39. package/dist/patch.d.ts +22 -0
  40. package/dist/patch.js +53 -0
  41. package/dist/patch.js.map +1 -0
  42. package/dist/pdf.d.ts +10 -0
  43. package/dist/pdf.js +53 -0
  44. package/dist/pdf.js.map +1 -0
  45. package/dist/render.d.ts +101 -0
  46. package/dist/render.js +513 -0
  47. package/dist/render.js.map +1 -0
  48. package/dist/scaffold.d.ts +27 -0
  49. package/dist/scaffold.js +83 -0
  50. package/dist/scaffold.js.map +1 -0
  51. package/dist/themecheck.d.ts +34 -0
  52. package/dist/themecheck.js +228 -0
  53. package/dist/themecheck.js.map +1 -0
  54. package/docs/adrs/2026-10-03-chrome-over-devtools.md +29 -0
  55. package/docs/adrs/2026-10-03-fixed-canvas.md +25 -0
  56. package/docs/adrs/2026-10-03-four-layouts-plus-attributes.md +25 -0
  57. package/docs/adrs/2026-10-03-hybrid-pdf-over-devtools.md +25 -0
  58. package/docs/adrs/2026-10-03-keyword-lines-and-one-attribute-syntax.md +36 -0
  59. package/docs/adrs/2026-10-03-one-behavior-instead-of-settings.md +30 -0
  60. package/docs/adrs/2026-10-03-overflow-is-reported-not-hidden.md +27 -0
  61. package/docs/adrs/2026-10-03-single-file-html.md +26 -0
  62. package/docs/adrs/2026-10-03-strict-build-forgiving-preview.md +31 -0
  63. package/docs/adrs/2026-10-04-edit-in-place-by-alignment.md +28 -0
  64. package/docs/adrs/2026-10-04-editor-in-the-deck-page.md +31 -0
  65. package/docs/adrs/2026-10-04-edits-are-line-range-patches.md +35 -0
  66. package/docs/adrs/2026-10-04-per-slide-hot-swap.md +33 -0
  67. package/docs/adrs/2026-10-04-theme-colors-derive-in-css.md +32 -0
  68. package/docs/adrs/2026-10-05-host-owns-undo.md +26 -0
  69. package/docs/adrs/2026-10-07-anonymous-access-metrics.md +38 -0
  70. package/docs/adrs/2026-10-14-dev-links-media-by-url.md +25 -0
  71. package/docs/adrs/2026-10-14-media-dir-for-the-publish-limit.md +28 -0
  72. package/docs/adrs/2026-10-14-videos-are-inlined-images.md +28 -0
  73. package/docs/adrs/2026-10-15-public-npm-under-labs-terms.md +37 -0
  74. package/docs/adrs/README.md +34 -0
  75. package/docs/commands.md +104 -0
  76. package/docs/editor.md +114 -0
  77. package/docs/syntax.md +157 -0
  78. package/docs/themes.md +134 -0
  79. package/package.json +68 -4
  80. package/runtime/base.css +354 -0
  81. package/runtime/edit-core.cjs +877 -0
  82. package/runtime/embed.js +5259 -0
  83. package/runtime/hot.js +136 -0
  84. package/runtime/runtime.js +729 -0
  85. package/skills/treasure-deck/SKILL.md +136 -0
  86. package/templates/deck.md +78 -0
  87. package/templates/specimen/specimen.md +104 -0
  88. package/templates/theme/assets/mark.svg +1 -0
  89. package/templates/theme/theme.css +97 -0
  90. package/templates/theme/theme.yaml +7 -0
  91. package/themes/default/theme.css +183 -0
  92. package/themes/default/theme.yaml +6 -0
  93. package/themes/editorial/theme.css +168 -0
  94. package/themes/editorial/theme.yaml +7 -0
  95. package/themes/gold/assets/gem.svg +130 -0
  96. package/themes/gold/theme.css +303 -0
  97. package/themes/gold/theme.yaml +7 -0
  98. package/themes/pastel/theme.css +187 -0
  99. package/themes/pastel/theme.yaml +6 -0
  100. package/themes/treasure-ai/assets/gem-line.svg +7 -0
  101. package/themes/treasure-ai/assets/gem.png +0 -0
  102. package/themes/treasure-ai/assets/gem.svg +25 -0
  103. package/themes/treasure-ai/assets/glass.svg +12 -0
  104. package/themes/treasure-ai/assets/logo-white.png +0 -0
  105. package/themes/treasure-ai/assets/logo.png +0 -0
  106. package/themes/treasure-ai/theme.css +239 -0
  107. package/themes/treasure-ai/theme.yaml +6 -0
  108. package/themes/wvlet/assets/wvlet-icon.svg +27 -0
  109. package/themes/wvlet/theme.css +238 -0
  110. package/themes/wvlet/theme.yaml +6 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.js","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AACxC,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAClC,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAClC,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,WAAW,EAAE,SAAS,EAAE,OAAO,EAA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,IAAI,GAAG,CAAC,CAAC,CAAC,EAAE,4BAA4B,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,0BAA0B,CAAC,CAAC;YACnK,MAAM;QACR,CAAC;QACD,KAAK,QAAQ;YACX,KAAK,MAAM,IAAI,IAAI,aAAa,EAAE;gBAAE,OAAO,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC,IAAI,SAAS,CAAC,IAAI,CAAC,CAAC,QAAQ,CAAC,WAAW,IAAI,EAAE,EAAE,CAAC,CAAC;YACpH,MAAM;QACR;YACE,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;YAC5B,IAAI,GAAG,IAAI,GAAG,KAAK,MAAM,IAAI,GAAG,KAAK,QAAQ;gBAAE,OAAO,CAAC,QAAQ,GAAG,CAAC,CAAC;IACxE,CAAC;AACH,CAAC;AAED,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAU,EAAE,EAAE;IAC/C,IAAI,CAAC,CAAC,CAAC,YAAY,SAAS,CAAC;QAAE,MAAM,CAAC,CAAC;IACvC,OAAO,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC;IACrC,OAAO,CAAC,QAAQ,GAAG,CAAC,CAAC;AACvB,CAAC,CAAC,CAAC"}
package/dist/dev.d.ts ADDED
@@ -0,0 +1,28 @@
1
+ import { type Server } from 'node:http';
2
+ export interface DevOptions {
3
+ /** The port to listen on. Without one, 4300, or the next free port after it when that one is taken. */
4
+ port?: number;
5
+ theme?: string;
6
+ /** Serve the editor (`deck editor`, or `deck dev --embed` for Treasure Work's dock): source map, postMessage
7
+ * bridge, POST /__patch, on 127.0.0.1 only. */
8
+ embed?: boolean;
9
+ /** `deck editor`: open the editor in the default browser once the server listens. */
10
+ open?: boolean;
11
+ /** Open a URL in the default browser (Preview ▾ in the editor); the system's opener unless given. */
12
+ openUrl?: (url: string) => Promise<void>;
13
+ }
14
+ /** Pasted and dropped images are saved here, next to the deck, as `deck new` lays a deck out; videos in media/. */
15
+ export declare const IMAGE_DIR = "images";
16
+ export declare const VIDEO_DIR = "media";
17
+ /** A new file name in `dir` for a pasted image or video: `pasted-20261004-153012.png`, then `-2`, `-3`… if taken. */
18
+ export declare function pastedName(dir: string, ext: string, now?: Date): string;
19
+ export interface DevServer {
20
+ server: Server;
21
+ /** The port the server listens on, once it does; rejects when it can't (the port given is taken, or 20 from
22
+ * 4300 up). */
23
+ listening: Promise<number>;
24
+ /** Stop watching and serving (Vite's file watcher and HMR channel too). */
25
+ close(): Promise<void>;
26
+ }
27
+ /** Serve a deck with live reload (`deck dev`). */
28
+ export declare function startDev(file: string, options: DevOptions): DevServer;
package/dist/dev.js ADDED
@@ -0,0 +1,557 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { pipeline } from 'node:stream';
3
+ import { createReadStream, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
4
+ import { execFile } from 'node:child_process';
5
+ import { createServer } from 'node:http';
6
+ import { createRequire } from 'node:module';
7
+ import { createServer as createNetServer } from 'node:net';
8
+ import * as path from 'node:path';
9
+ import { buildDeck, builtinThemes, isThemePath, joinStage, loadTheme, RUNTIME_DIR, themeDir, THEMES_DIR } from './build.js';
10
+ import { diffBuilds } from './hot.js';
11
+ import { DeckError } from './parse.js';
12
+ import { mediaType } from './render.js';
13
+ import { hasDiagrams, MERMAID_JS, withMermaid } from './diagrams.js';
14
+ import { applyPatch } from './patch.js';
15
+ import { createServer as createVite } from 'vite';
16
+ const DEFAULT_PORT = 4300;
17
+ /** How many ports from DEFAULT_PORT up to try before giving up. */
18
+ const PORT_TRIES = 20;
19
+ /** The system's opener: `open`, `start`, or `xdg-open`. */
20
+ function systemOpen(url) {
21
+ const [cmd, args] = process.platform === 'darwin' ? ['open', [url]]
22
+ : process.platform === 'win32' ? ['cmd', ['/c', 'start', '""', url]] : ['xdg-open', [url]];
23
+ return new Promise((resolve, reject) => execFile(cmd, args, (e) => (e ? reject(e) : resolve())));
24
+ }
25
+ function errorPage(message) {
26
+ return `<!doctype html><meta charset="utf-8"><title>Build error</title><body style="font:16px/1.5 ui-monospace,monospace;background:#1b1210;color:#ffd7c2;padding:40px"><h1 style="font-size:20px">Build error</h1><pre>${message.replace(/</g, '&lt;')}</pre></body>`;
27
+ }
28
+ /** A value for an inline <script>: JSON that can't close the script element. */
29
+ function scriptJson(value) {
30
+ return JSON.stringify(value).replace(/</g, '\\u003c');
31
+ }
32
+ /**
33
+ * Insert markup before the page's closing </body>: the last one, since the runtime's own text may mention the tag.
34
+ * Spliced rather than passed to String.replace, whose replacement would read `$&` in the inserted scripts.
35
+ */
36
+ function beforeBodyEnd(html, insert) {
37
+ const at = html.lastIndexOf('</body>');
38
+ return at < 0 ? html + insert : html.slice(0, at) + insert + html.slice(at);
39
+ }
40
+ /** The Lucide icons the editor's toolbar uses (lucide-static, ISC), inlined so the editor works offline. */
41
+ const ICONS = [
42
+ 'bold', 'italic', 'code', 'strikethrough', 'highlighter', 'link', 'pilcrow', 'heading-1', 'heading-2', 'heading-3',
43
+ 'list', 'list-ordered', 'quote', 'arrow-up', 'arrow-down', 'copy', 'eye-off', 'eye', 'trash-2',
44
+ 'align-left', 'align-center', 'align-right', 'layers', 'square-round-corner', 'square', 'file-code', 'chevron-down', 'settings',
45
+ 'presentation', 'external-link', 'plus', 'undo-2', 'redo-2', 'scissors', 'clipboard-paste', 'copy-plus', 'pin-off',
46
+ 'play', 'repeat', 'sliders-horizontal',
47
+ ];
48
+ let icons;
49
+ function iconScript() {
50
+ if (icons === undefined) {
51
+ const dir = path.join(path.dirname(createRequire(import.meta.url).resolve('lucide-static/package.json')), 'icons');
52
+ const svgs = {};
53
+ for (const name of ICONS) {
54
+ svgs[name] = readFileSync(path.join(dir, `${name}.svg`), 'utf8')
55
+ .replace(/<!--[\s\S]*?-->/g, '')
56
+ .replace(/\s+/g, ' ')
57
+ .replace(/ (width|height)="24"/g, ' $1="16"')
58
+ .replace(/ class="[^"]*"/, ' aria-hidden="true"')
59
+ .trim();
60
+ }
61
+ icons = `<script>window.__DECK_ICONS__ = ${scriptJson(svgs)};</script>`;
62
+ }
63
+ return icons;
64
+ }
65
+ // /present only: `e` goes back to editing. It closes this window when the editor opened it (the editor already
66
+ // follows the slides presented here), and otherwise opens the editor in this tab at the same slide.
67
+ const BACK_TO_EDITING = `<script>(function () {
68
+ var help = document.querySelector('.deck-help table');
69
+ if (help) help.insertAdjacentHTML('beforeend', '<tr><td><kbd>e</kbd></td><td>Back to editing</td></tr>');
70
+ document.addEventListener('keydown', function (e) {
71
+ if (e.key !== 'e' || e.metaKey || e.ctrlKey || e.altKey) return;
72
+ if (window.opener && !window.opener.closed) {
73
+ try { window.opener.focus(); } catch (err) { /* another origin */ }
74
+ window.close();
75
+ } else location.href = '/#/' + (parseInt(location.hash.slice(2), 10) || 1) + '/presented';
76
+ });
77
+ })();</script>`;
78
+ const MAX_PATCH_BYTES = 1 << 20;
79
+ const MAX_IMAGE_BYTES = 20 << 20;
80
+ const MAX_VIDEO_BYTES = 200 << 20;
81
+ function readBytes(req, max, what) {
82
+ return new Promise((resolve, reject) => {
83
+ let size = 0;
84
+ const chunks = [];
85
+ req.on('data', (c) => {
86
+ size += c.length;
87
+ if (size > max)
88
+ reject(new Error(`${what} is too large`));
89
+ else
90
+ chunks.push(c);
91
+ });
92
+ req.on('end', () => resolve(Buffer.concat(chunks)));
93
+ req.on('error', reject);
94
+ });
95
+ }
96
+ const readBody = async (req) => (await readBytes(req, MAX_PATCH_BYTES, 'patch')).toString('utf8');
97
+ /** Pasted and dropped images are saved here, next to the deck, as `deck new` lays a deck out; videos in media/. */
98
+ export const IMAGE_DIR = 'images';
99
+ export const VIDEO_DIR = 'media';
100
+ const IMAGE_EXT = {
101
+ 'image/png': 'png', 'image/jpeg': 'jpg', 'image/gif': 'gif', 'image/webp': 'webp', 'image/svg+xml': 'svg', 'image/avif': 'avif',
102
+ };
103
+ const VIDEO_EXT = {
104
+ 'video/mp4': 'mp4', 'video/webm': 'webm', 'video/quicktime': 'mov', 'video/x-m4v': 'm4v',
105
+ };
106
+ /** A new file name in `dir` for a pasted image or video: `pasted-20261004-153012.png`, then `-2`, `-3`… if taken. */
107
+ export function pastedName(dir, ext, now = new Date()) {
108
+ const p = (n) => String(n).padStart(2, '0');
109
+ const stamp = `${now.getFullYear()}${p(now.getMonth() + 1)}${p(now.getDate())}-${p(now.getHours())}${p(now.getMinutes())}${p(now.getSeconds())}`;
110
+ for (let i = 1;; i++) {
111
+ const name = `pasted-${stamp}${i > 1 ? `-${i}` : ''}.${ext}`;
112
+ if (!existsSync(path.join(dir, name)))
113
+ return name;
114
+ }
115
+ }
116
+ function isPatch(p) {
117
+ const o = p;
118
+ return (typeof o === 'object' && o !== null && typeof o.file === 'string' && typeof o.start === 'number' &&
119
+ typeof o.end === 'number' && typeof o.expected === 'string' && (typeof o.text === 'string' || o.text === null));
120
+ }
121
+ function json(res, status, body) {
122
+ res.writeHead(status, { 'Content-Type': 'application/json' });
123
+ res.end(JSON.stringify(body));
124
+ }
125
+ /**
126
+ * Answer a GET or HEAD for a local file with its type, in byte ranges when asked: a <video> seeks by them, and Safari
127
+ * plays one only with them. Its URL names the file's version (`v=`, see startDev), so the browser may keep it.
128
+ */
129
+ function sendFile(req, res, file) {
130
+ let size;
131
+ try {
132
+ size = statSync(file).size;
133
+ }
134
+ catch {
135
+ res.writeHead(404);
136
+ res.end();
137
+ return;
138
+ }
139
+ const headers = {
140
+ 'Content-Type': mediaType(file) ?? 'application/octet-stream', 'Accept-Ranges': 'bytes', 'Cache-Control': 'max-age=31536000, immutable',
141
+ };
142
+ let start = 0, end = size - 1;
143
+ const range = req.headers.range && /^bytes=(\d*)-(\d*)$/.exec(req.headers.range);
144
+ if (range && (range[1] || range[2])) {
145
+ if (range[1])
146
+ [start, end] = [Number(range[1]), range[2] ? Math.min(Number(range[2]), size - 1) : size - 1];
147
+ else
148
+ start = Math.max(0, size - Number(range[2]));
149
+ if (start > end || start >= size) {
150
+ res.writeHead(416, { 'Content-Range': `bytes */${size}` });
151
+ res.end();
152
+ return;
153
+ }
154
+ headers['Content-Range'] = `bytes ${start}-${end}/${size}`;
155
+ }
156
+ res.writeHead(headers['Content-Range'] ? 206 : 200, { ...headers, 'Content-Length': end - start + 1 });
157
+ if (req.method === 'HEAD' || size === 0)
158
+ res.end();
159
+ // pipeline closes the file when the browser drops the request, as a <video> does once it has what it needs.
160
+ else
161
+ pipeline(createReadStream(file, { start, end }), res, () => { });
162
+ }
163
+ /** Serve a deck with live reload (`deck dev`). */
164
+ export function startDev(file, options) {
165
+ const { port = DEFAULT_PORT, theme, embed = false, open = false, openUrl = systemOpen } = options;
166
+ const deckDir = path.dirname(path.resolve(file));
167
+ const deckName = path.basename(file);
168
+ // Local images and videos are linked by URL rather than inlined, so a rebuild only looks at their dates, and the
169
+ // pages stay small. GET /__file serves the files the latest builds linked, and nothing else; `v=` (the file's mtime) makes a
170
+ // file replaced under the same name load again.
171
+ const served = new Map();
172
+ const mediaUrl = (f) => {
173
+ const p = path.relative(deckDir, f).split(path.sep).join('/');
174
+ served.set(p, f);
175
+ // A {bg} image goes in url('…'), so its quote is escaped too.
176
+ return `/__file?p=${encodeURIComponent(p).replace(/'/g, '%27')}&v=${Math.floor(statSync(f).mtimeMs)}`;
177
+ };
178
+ // Files a patch may change: the deck and its parts, as of the last good build.
179
+ let editable = new Set([deckName]);
180
+ // Each rebuild gets a number. A page says which build it shows when it asks /__changes, and gets the changes from
181
+ // there to the latest build (src/hot.ts). The last few builds of each page are kept for that.
182
+ // Numbered from the clock, so a page left open across a restart of deck dev isn't taken for one of its builds.
183
+ let build = Date.now();
184
+ const history = { main: [], present: [] };
185
+ const remember = (page, snap) => {
186
+ // Errors in a row take one place, so typing through a broken frontmatter doesn't push out the good build
187
+ // that open pages still show (and reconnect from).
188
+ if (snap.error && history[page].at(-1)?.error)
189
+ history[page].pop();
190
+ history[page].push(snap);
191
+ if (history[page].length > 4)
192
+ history[page].shift();
193
+ return snap;
194
+ };
195
+ // The dev scripts (runtime/hot.js, and in the editor the bridge) are read on every rebuild and are part of the
196
+ // page's shell, so editing them reloads the preview like editing the runtime does. hot.js is a module (it uses
197
+ // import.meta.hot), loaded after Vite's client; its URL changes with its text.
198
+ let hot = '';
199
+ let vite;
200
+ const hotScript = (page) => `<script>window.__DECK_HOT__ = ${scriptJson({ page, build })};</script>` +
201
+ `<script type="module" src="/@vite/client"></script>` +
202
+ `<script type="module" src="/__deck/hot.js?v=${createHash('sha1').update(hot).digest('hex').slice(0, 8)}"></script>`;
203
+ const located = (e) => ({
204
+ ...(e instanceof DeckError ? { file: e.file ?? deckName, line: e.line } : { file: deckName }),
205
+ message: e.message,
206
+ });
207
+ let html = '';
208
+ let main = { build, shell: null, units: [] };
209
+ let sources = {};
210
+ // /present: the deck to present (no editor, no source map), built when first asked for after each rebuild,
211
+ // or right away while a /present page is open.
212
+ let presentHtml = null;
213
+ let presentSnap = main;
214
+ const present = () => {
215
+ if (!embed)
216
+ return html;
217
+ if (presentHtml === null) {
218
+ try {
219
+ const built = buildDeck(file, { theme, forgiving: true, mediaUrl });
220
+ const shell = withMermaid(built.shell, '/__mermaid.js', hasDiagrams(built.html));
221
+ presentSnap = remember('present', { build, shell: shell + hot, units: built.units });
222
+ presentHtml = joinStage(beforeBodyEnd(shell, hotScript('present') + BACK_TO_EDITING), built.units);
223
+ }
224
+ catch (e) {
225
+ presentSnap = remember('present', { build, shell: null, units: [], error: located(e) });
226
+ presentHtml = errorPage(e.message) + hotScript('present');
227
+ }
228
+ }
229
+ return presentHtml;
230
+ };
231
+ // Deck settings in the editor: the themes it offers (GET /__themes), and the deck built in one of them, to show its
232
+ // current slide in that theme (GET /__theme-preview?theme=&mode=, no editor and no live reload). Only those themes
233
+ // are built: the built-in ones, and the deck's own (a folder named in its frontmatter). Builds are kept until the
234
+ // next rebuild.
235
+ let deckTheme = 'default';
236
+ const themeChoices = () => {
237
+ const names = builtinThemes();
238
+ if (!names.includes(deckTheme))
239
+ names.push(deckTheme);
240
+ return names.flatMap((value) => {
241
+ try {
242
+ const t = loadTheme(value, deckDir);
243
+ return [{ value, name: t.manifest.name, description: t.manifest.description ?? '', defaultMode: t.manifest.default_mode ?? 'light' }];
244
+ }
245
+ catch {
246
+ return [];
247
+ }
248
+ });
249
+ };
250
+ let previews = new Map();
251
+ const themePreview = (value, mode) => {
252
+ if (!themeChoices().some((t) => t.value === value) || !['', 'light', 'dark'].includes(mode))
253
+ return null;
254
+ const key = `${value}|${mode}`;
255
+ let page = previews.get(key);
256
+ if (page === undefined) {
257
+ try {
258
+ const built = buildDeck(file, { theme: value, mode: (mode || undefined), forgiving: true, mediaUrl });
259
+ // A preview never takes the keys: the runtime focuses its window on load, which would take focus from the editor.
260
+ const shell = built.shell.replace('</head>\n<body>', '</head>\n<body><script>window.focus = function () {};</script>');
261
+ page = joinStage(withMermaid(shell, '/__mermaid.js', hasDiagrams(built.html)), built.units);
262
+ }
263
+ catch (e) {
264
+ page = errorPage(e.message);
265
+ }
266
+ previews.set(key, page);
267
+ }
268
+ return page;
269
+ };
270
+ const latest = (page) => (page === 'present' ? (present(), presentSnap) : main);
271
+ // What a page showing `build` needs to show the latest one: the changed slides (and, for the editor, the sources),
272
+ // a reload, or the build error to show over it. `erred`: the page shows an error, which an update clears even if
273
+ // no slide changed. A rebuild that changed nothing for the page still gives it the new build number (`noop`), so
274
+ // the build it asks from next stays among the kept ones.
275
+ const changesFor = (page, from, erred) => {
276
+ const next = latest(page);
277
+ const shows = history[page].find((h) => h.build === from) ?? null;
278
+ if (shows === next && !erred)
279
+ return null;
280
+ // An error outside the slides (frontmatter, theme) leaves a page showing a good build as it is, with the error
281
+ // over it; the next good build is compared with that one.
282
+ if (next.error && shows?.shell)
283
+ return { type: 'error', ...next.error };
284
+ const changes = diffBuilds(shows, next);
285
+ if (changes === 'reload')
286
+ return { type: 'reload' };
287
+ const withSources = embed && page === 'main';
288
+ // An edit can change the sources without changing any slide (a comment, trailing spaces).
289
+ if (!changes.length && !withSources && !erred)
290
+ return { type: 'update', build: next.build, noop: true };
291
+ return { type: 'update', build: next.build, units: next.units.length, changes, ...(withSources ? { sources } : {}) };
292
+ };
293
+ const rebuild = () => {
294
+ build++;
295
+ // The pages built after this (/present and theme previews too) link their files again.
296
+ served.clear();
297
+ presentHtml = null;
298
+ hot = readFileSync(path.join(RUNTIME_DIR, 'hot.js'), 'utf8');
299
+ const bridge = embed
300
+ ? iconScript() + ['edit-core.cjs', 'embed.js'].map((f) => `<script>${readFileSync(path.join(RUNTIME_DIR, f), 'utf8')}</script>`).join('')
301
+ : '';
302
+ try {
303
+ // Diagrams render from the bundled Mermaid, served below, so previews work offline and rebuilds stay fast.
304
+ // A slide that can't be built shows its error in its place, and the rest of the deck stays usable.
305
+ const built = buildDeck(file, { theme, sourceMap: embed, forgiving: true, mediaUrl });
306
+ for (const e of built.errors)
307
+ console.error(e.message);
308
+ previews = new Map();
309
+ if (!theme)
310
+ deckTheme = built.deck.meta.theme;
311
+ editable = new Set(Object.keys(built.sources));
312
+ sources = built.sources;
313
+ let shell = withMermaid(built.shell, '/__mermaid.js', hasDiagrams(built.html));
314
+ // Set before the runtime runs, so an embedded preview fits one slide into the box the editor leaves it.
315
+ // (The stylesheets mention <body> in comments, so the tag is found after </head>.)
316
+ if (embed)
317
+ shell = shell.replace('</head>\n<body>', '</head>\n<body><script>window.__DECK_EMBED__ = true;</script>');
318
+ main = remember('main', { build, shell: shell + hot + bridge, units: built.units });
319
+ // The bridge needs the exact source lines for each patch's `expected` and for the Markdown popover.
320
+ const sourcesScript = embed ? `<script>window.__DECK_SOURCES__ = ${scriptJson(sources)};</script>` : '';
321
+ html = joinStage(beforeBodyEnd(shell, hotScript('main') + sourcesScript + bridge), built.units);
322
+ console.log(`[${new Date().toLocaleTimeString()}] rebuilt`);
323
+ }
324
+ catch (e) {
325
+ const error = located(e);
326
+ const report = embed ? `<script>window.__DECK_BUILD_ERROR__ = ${scriptJson(error)};</script>` : '';
327
+ main = remember('main', { build, shell: null, units: [], error });
328
+ html = errorPage(error.message) + hotScript('main') + report + bridge;
329
+ console.error(error.message);
330
+ }
331
+ vite?.ws.send({ type: 'custom', event: 'deck:build', data: { build } });
332
+ };
333
+ rebuild();
334
+ let timer;
335
+ // The deck folder (Markdown, parts, images, a local theme.css), plus the built-in themes and runtime,
336
+ // so editing a theme's CSS also refreshes the preview.
337
+ const dirs = [deckDir, THEMES_DIR, RUNTIME_DIR];
338
+ // A theme folder outside the deck's (theme: ../brand) is watched as well.
339
+ const themeName = theme ?? (() => { try {
340
+ return buildDeck(file, { mediaUrl }).deck.meta.theme;
341
+ }
342
+ catch {
343
+ return undefined;
344
+ } })();
345
+ if (themeName && isThemePath(themeName)) {
346
+ const d = themeDir(themeName, theme ? process.cwd() : deckDir);
347
+ if (existsSync(d) && !d.startsWith(deckDir + path.sep))
348
+ dirs.push(d);
349
+ }
350
+ const changed = (name) => {
351
+ if (name.endsWith('.html'))
352
+ return;
353
+ clearTimeout(timer);
354
+ timer = setTimeout(rebuild, 80);
355
+ };
356
+ // POST /__patch applies a visual edit to the deck on disk, for running without a host page (inside Treasure
357
+ // Work, the host applies patches to its own editor buffer). It only listens on 127.0.0.1, and it requires a
358
+ // JSON body and a same-origin (or no) Origin, so other sites' pages can't send it edits.
359
+ const sameOrigin = (req) => {
360
+ const origin = req.headers.origin;
361
+ const own = server.address().port;
362
+ return !origin || origin === `http://127.0.0.1:${own}` || origin === `http://localhost:${own}`;
363
+ };
364
+ const patch = async (req, res) => {
365
+ if (!sameOrigin(req))
366
+ return json(res, 403, { ok: false, reason: 'cross-origin patch' });
367
+ if (!/^application\/json\b/.test(req.headers['content-type'] ?? '')) {
368
+ return json(res, 415, { ok: false, reason: 'send the patch as application/json' });
369
+ }
370
+ let p;
371
+ try {
372
+ p = JSON.parse(await readBody(req));
373
+ }
374
+ catch (e) {
375
+ return json(res, 400, { ok: false, reason: e.message });
376
+ }
377
+ if (!isPatch(p))
378
+ return json(res, 400, { ok: false, reason: 'a patch needs file, start, end, expected, and text' });
379
+ if (!editable.has(p.file))
380
+ return json(res, 403, { ok: false, reason: `${p.file} is not part of this deck` });
381
+ const target = path.join(deckDir, p.file);
382
+ const result = applyPatch(readFileSync(target, 'utf8'), p);
383
+ if (!result.ok)
384
+ return json(res, 409, result);
385
+ writeFileSync(target, result.source);
386
+ json(res, 200, { ok: true });
387
+ };
388
+ // POST /__open {slide} opens /present at that slide in the system's default browser (the editor's Preview ▾ menu).
389
+ // The URL is this server's own; only the slide number comes from the request.
390
+ const openInBrowser = async (req, res) => {
391
+ if (!sameOrigin(req))
392
+ return json(res, 403, { ok: false, reason: 'cross-origin request' });
393
+ let slide = 1;
394
+ try {
395
+ const n = Number(JSON.parse(await readBody(req)).slide);
396
+ if (Number.isInteger(n) && n > 0)
397
+ slide = n;
398
+ }
399
+ catch { /* slide 1 */ }
400
+ const url = `http://127.0.0.1:${server.address().port}/present#/${slide}`;
401
+ await openUrl(url);
402
+ json(res, 200, { ok: true, url });
403
+ };
404
+ // POST /__media saves an image or video pasted or dropped into the editor as images/pasted-<time>.<ext> (a video
405
+ // in media/) next to the deck, and answers with its path relative to the deck, for the editor to write into the
406
+ // Markdown (as a patch, so a host applies it). The file is written here even with a host page, which shares this
407
+ // server's origin. Same guards as /__patch.
408
+ const media = async (req, res) => {
409
+ if (!sameOrigin(req))
410
+ return json(res, 403, { ok: false, reason: 'cross-origin upload' });
411
+ const type = (req.headers['content-type'] ?? '').split(';')[0].trim().toLowerCase();
412
+ const video = type in VIDEO_EXT;
413
+ const ext = video ? VIDEO_EXT[type] : IMAGE_EXT[type];
414
+ if (!ext)
415
+ return json(res, 415, { ok: false, reason: 'send a PNG, JPEG, GIF, WebP, SVG, or AVIF image, or an MP4, WebM, or QuickTime video' });
416
+ const what = video ? 'video' : 'image';
417
+ const bytes = await readBytes(req, video ? MAX_VIDEO_BYTES : MAX_IMAGE_BYTES, `the ${what}`);
418
+ if (!bytes.length)
419
+ return json(res, 400, { ok: false, reason: `the ${what} is empty` });
420
+ const sub = video ? VIDEO_DIR : IMAGE_DIR;
421
+ const dir = path.join(deckDir, sub);
422
+ mkdirSync(dir, { recursive: true });
423
+ const name = pastedName(dir, ext);
424
+ writeFileSync(path.join(dir, name), bytes);
425
+ json(res, 200, { ok: true, path: `${sub}/${name}` });
426
+ };
427
+ // Vite, in middleware mode on this server: its HMR channel (a WebSocket on the same port), its client, the hot.js
428
+ // module, and the file watcher. Everything else is answered here. Requests for Vite's paths wait until it is up.
429
+ const deckPlugin = {
430
+ name: 'treasure-deck-dev',
431
+ resolveId: (id) => (id.split('?')[0] === '/__deck/hot.js' ? '\0deck-hot' : undefined),
432
+ load: (id) => (id === '\0deck-hot' ? hot : undefined),
433
+ // The deck's files aren't modules: their changes come to `changed` instead of Vite's own updates.
434
+ handleHotUpdate: () => [],
435
+ };
436
+ let ready;
437
+ const viteOwns = (url) => /^\/(@vite|@id|@fs|__deck|node_modules)\//.test(url);
438
+ const server = createServer((req, res) => {
439
+ const url = req.url ?? '/';
440
+ if (url.split('?')[0] === '/__changes') {
441
+ const q = new URL(url, 'http://localhost').searchParams;
442
+ // Without the editor, /present is the same page as /.
443
+ const page = embed && q.get('page') === 'present' ? 'present' : 'main';
444
+ return json(res, 200, changesFor(page, Number(q.get('build')), q.get('erred') === '1'));
445
+ }
446
+ if (viteOwns(url)) {
447
+ ready.then((v) => v.middlewares(req, res), () => { res.statusCode = 503; res.end(); });
448
+ return;
449
+ }
450
+ if (url.split('?')[0] === '/__file' && (req.method === 'GET' || req.method === 'HEAD')) {
451
+ const f = served.get(new URL(url, 'http://localhost').searchParams.get('p') ?? '');
452
+ if (f)
453
+ return sendFile(req, res, f);
454
+ res.writeHead(404);
455
+ res.end();
456
+ return;
457
+ }
458
+ if (req.url === '/__mermaid.js') {
459
+ res.writeHead(200, { 'Content-Type': 'text/javascript; charset=utf-8', 'Cache-Control': 'max-age=3600' });
460
+ res.end(readFileSync(MERMAID_JS));
461
+ return;
462
+ }
463
+ if (embed && req.url === '/__patch' && req.method === 'POST') {
464
+ patch(req, res).catch((e) => json(res, 500, { ok: false, reason: e.message }));
465
+ return;
466
+ }
467
+ if (embed && req.url === '/__open' && req.method === 'POST') {
468
+ openInBrowser(req, res).catch((e) => json(res, 500, { ok: false, reason: e.message }));
469
+ return;
470
+ }
471
+ if (embed && req.url === '/__themes')
472
+ return json(res, 200, { themes: themeChoices(), forced: theme ?? null });
473
+ if (embed && url.startsWith('/__theme-preview?')) {
474
+ const q = new URL(url, 'http://localhost').searchParams;
475
+ const page = themePreview(q.get('theme') ?? '', q.get('mode') ?? '');
476
+ if (page === null)
477
+ return json(res, 404, { ok: false, reason: 'not a theme this deck offers' });
478
+ res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
479
+ res.end(page);
480
+ return;
481
+ }
482
+ if (embed && req.url === '/__media' && req.method === 'POST') {
483
+ media(req, res).catch((e) => json(res, 500, { ok: false, reason: e.message }));
484
+ return;
485
+ }
486
+ res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
487
+ res.end(req.url?.split(/[?#]/)[0] === '/present' ? present() : html);
488
+ });
489
+ ready = createVite({
490
+ configFile: false,
491
+ root: deckDir,
492
+ appType: 'custom',
493
+ logLevel: 'warn',
494
+ clearScreen: false,
495
+ plugins: [deckPlugin],
496
+ optimizeDeps: { noDiscovery: true, include: [], entries: [] },
497
+ server: { middlewareMode: true, hmr: { server }, watch: { ignored: ['**/*.html', '**/node_modules/**', '**/.git/**'] } },
498
+ }).then((v) => {
499
+ vite = v;
500
+ v.watcher.add(dirs.filter((d) => d !== deckDir));
501
+ v.watcher.on('all', (_event, name) => changed(name));
502
+ return v;
503
+ });
504
+ ready.catch((e) => console.error(`deck dev: Vite didn't start: ${e.message}`));
505
+ // The editor endpoints stay on this machine; plain previews can still be opened from a phone on the LAN.
506
+ const listening = () => {
507
+ const at = `http://${embed ? '127.0.0.1' : 'localhost'}:${server.address().port}`;
508
+ // (The dock starts `deck dev --embed` and may read this line: it stays as it was for it.)
509
+ if (options.open !== undefined)
510
+ console.log(`Editing ${file}${theme ? ` (theme ${theme})` : ''} at ${at}`);
511
+ else
512
+ console.log(`Serving ${file}${theme ? ` (theme ${theme})` : ''}${embed ? ' for embedding' : ''} at ${at}`);
513
+ if (open)
514
+ openUrl(at + '/').catch(() => console.log(`Open ${at} in a browser to edit`));
515
+ };
516
+ // A port given with --port is used or fails; the default moves on to the next port while it's taken.
517
+ let tryPort = port;
518
+ let tries = options.port === undefined ? PORT_TRIES : 1;
519
+ // On all interfaces, macOS lets a server share a port with one on 127.0.0.1 only (an editor, the dock's
520
+ // `deck dev --embed`), and localhost then reaches either. So 127.0.0.1 is tried first.
521
+ const listen = () => {
522
+ if (embed)
523
+ server.listen(tryPort, '127.0.0.1');
524
+ else if (tryPort === 0)
525
+ server.listen(0);
526
+ else
527
+ probeThenListen();
528
+ };
529
+ const probeThenListen = () => {
530
+ const probe = createNetServer();
531
+ probe.once('error', (e) => server.emit('error', e));
532
+ probe.listen(tryPort, '127.0.0.1', () => probe.close(() => server.listen(tryPort)));
533
+ };
534
+ const started = new Promise((resolve, reject) => {
535
+ const failed = (e) => {
536
+ if (e.code !== 'EADDRINUSE' || --tries === 0)
537
+ return reject(e);
538
+ tryPort++;
539
+ listen();
540
+ };
541
+ server.on('error', failed);
542
+ server.once('listening', () => {
543
+ server.off('error', failed);
544
+ listening();
545
+ resolve(server.address().port);
546
+ });
547
+ });
548
+ listen();
549
+ const close = async () => {
550
+ clearTimeout(timer);
551
+ await ready.then((v) => v.close(), () => undefined);
552
+ server.closeAllConnections();
553
+ await new Promise((resolve) => server.close(() => resolve()));
554
+ };
555
+ return { server, listening: started, close };
556
+ }
557
+ //# sourceMappingURL=dev.js.map