@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,30 @@
1
+ import type { Deck } from './parse.js';
2
+ export interface Finding {
3
+ /** 1-based slide number, as on screen. */
4
+ slide: number;
5
+ /** Source line where the slide starts. */
6
+ line: number;
7
+ /** The `parts:` file the slide comes from, relative to the deck's folder; absent for the deck file itself. */
8
+ file?: string;
9
+ title: string;
10
+ severity: 'error' | 'warning';
11
+ message: string;
12
+ }
13
+ /** Code shrunk below this size (canvas px) to fit its panel is reported as hard to read. */
14
+ export declare const MIN_CODE_PX = 14;
15
+ /** Body text of a {fit} slide zoomed below this size (canvas px) is reported as hard to read. */
16
+ export declare const MIN_FIT_PX = 16;
17
+ /** Diagram labels scaled below this size (canvas px) are reported as hard to read. */
18
+ export declare const MIN_DIAGRAM_PX = 13;
19
+ export interface CheckOptions {
20
+ /** Also check with the table of contents column shown (narrower slides), when the deck doesn't show it already. */
21
+ toc?: boolean;
22
+ /** Write one PNG per slide into this folder. */
23
+ snapshots?: string;
24
+ }
25
+ /** Plain-text title of a slide, for messages. */
26
+ export declare function titleOf(deck: Deck, i: number): string;
27
+ /** Render a built deck in headless Chrome and report layout problems, slide by slide. */
28
+ export declare function checkDeck(html: string, deck: Deck, options?: CheckOptions): Promise<Finding[]>;
29
+ /** `talk.md:42: error: slide 7 "Title": content runs 38px past the bottom edge: p "…"` */
30
+ export declare function formatFinding(file: string, f: Finding): string;
package/dist/check.js ADDED
@@ -0,0 +1,142 @@
1
+ import { mkdirSync, writeFileSync } from 'node:fs';
2
+ import * as path from 'node:path';
3
+ import { evaluate, withDeckPage } from './chrome.js';
4
+ /** Code shrunk below this size (canvas px) to fit its panel is reported as hard to read. */
5
+ export const MIN_CODE_PX = 14;
6
+ /** Body text of a {fit} slide zoomed below this size (canvas px) is reported as hard to read. */
7
+ export const MIN_FIT_PX = 16;
8
+ /** Diagram labels scaled below this size (canvas px) are reported as hard to read. */
9
+ export const MIN_DIAGRAM_PX = 13;
10
+ /**
11
+ * Measures every slide in the page (slides lay out even while hidden) and returns raw problems:
12
+ * content past the body's padding box on any side, text wider than its box (an unbreakable word or URL),
13
+ * code panels still clipped after the runtime's fitting, and code shrunk below MIN_CODE_PX.
14
+ */
15
+ const MEASURE = `(() => {
16
+ const TOL = 2;
17
+ const text = (el) => (el.textContent || '').replace(/\\s+/g, ' ').trim().slice(0, 48);
18
+ const describe = (el) => el.tagName.toLowerCase() + (text(el) ? ' "' + text(el) + '"' : '');
19
+ return Array.from(document.querySelectorAll('.deck-stage > .slide')).map((slide) => {
20
+ const problems = [];
21
+ const body = slide.querySelector('.slide-body');
22
+ const cs = getComputedStyle(body);
23
+ const b = body.getBoundingClientRect();
24
+ // Screen px per canvas px: below 1 when the slide is scaled beside the table of contents. Measures are in
25
+ // canvas px, as the thresholds and the messages are.
26
+ const k = b.width / body.offsetWidth || 1;
27
+ const box = {
28
+ top: b.top + parseFloat(cs.paddingTop) * k, bottom: b.bottom - parseFloat(cs.paddingBottom) * k,
29
+ left: b.left + parseFloat(cs.paddingLeft) * k, right: b.right - parseFloat(cs.paddingRight) * k,
30
+ };
31
+ const worst = { top: [0], bottom: [0], left: [0], right: [0] };
32
+ const wide = [];
33
+ // Where the cut happens: the first block (in reading order) that crosses the bottom edge.
34
+ let firstCut;
35
+ for (const el of body.querySelectorAll('*')) {
36
+ // Pinned images float by design; SVG internals and code lines are covered by their container.
37
+ if (el.closest('.img-at, .notes') || (el.closest('svg') && el.tagName.toLowerCase() !== 'svg')) continue;
38
+ if (el.closest('pre.code') && !el.matches('pre.code')) continue;
39
+ const r = el.getBoundingClientRect();
40
+ if (r.width === 0 && r.height === 0) continue;
41
+ const over = { top: (box.top - r.top) / k, bottom: (r.bottom - box.bottom) / k, left: (box.left - r.left) / k, right: (r.right - box.right) / k };
42
+ if (!firstCut && over.bottom > TOL && el.matches('li, p, tr, pre, img, video, h1, h2, h3, h4, blockquote, .diagram, .img-figure')) firstCut = el;
43
+ // >= lets a descendant that ends at the same edge (the last li of a ul) name the problem.
44
+ for (const side in over) if (over[side] > TOL && over[side] >= worst[side][0]) worst[side] = [over[side], el];
45
+ if (el.matches('p, li, h1, h2, h3, h4, td, th, blockquote') && el.scrollWidth - el.clientWidth > TOL && getComputedStyle(el).overflow === 'visible') {
46
+ wide.push(el);
47
+ problems.push({ severity: 'error', message: 'text is wider than its column by ' + Math.round(el.scrollWidth - el.clientWidth) + 'px (a long word or URL?): ' + describe(el) });
48
+ }
49
+ }
50
+ for (const side in worst) {
51
+ const [px, el] = worst[side];
52
+ if (!px || wide.some((w) => w.contains(el))) continue;
53
+ const at = side === 'bottom' && firstCut ? ', from ' + describe(firstCut) : ': ' + describe(el);
54
+ problems.push({ severity: 'error', message: 'content runs ' + Math.round(px) + 'px past the ' + side + ' edge' + at });
55
+ }
56
+ // Mermaid scales a diagram to its column, so a wide one in a narrow column shrinks its labels with it.
57
+ for (const svg of body.querySelectorAll('pre.mermaid svg')) {
58
+ const vb = svg.viewBox && svg.viewBox.baseVal;
59
+ if (!vb || !vb.width) continue;
60
+ const scale = svg.getBoundingClientRect().width / k / vb.width;
61
+ const sizes = Array.from(svg.querySelectorAll('g.node text, g.edgeLabel text, text.actor, g.label text'))
62
+ .map((t) => parseFloat(getComputedStyle(t).fontSize) * scale).filter((n) => n > 0);
63
+ const px = Math.min.apply(null, sizes);
64
+ if (sizes.length && px < ${MIN_DIAGRAM_PX}) problems.push({ severity: 'warning', message: 'diagram labels render at ' + Math.round(px) + 'px, too small to read (a wide diagram in a narrow column? try flowchart TB, fewer nodes, or a wider column)' });
65
+ }
66
+ // {fit} slides: the runtime zoomed the body down (data-fit); say so when the text ends up small.
67
+ const fit = parseFloat(slide.getAttribute('data-fit') || '1');
68
+ const fitBox = slide.querySelector('.slide-content, .rows, .cols');
69
+ if (fit < 1 && fitBox) {
70
+ const px = parseFloat(getComputedStyle(fitBox).fontSize) * fit;
71
+ if (px < ${MIN_FIT_PX}) problems.push({ severity: 'warning', message: '{fit} shrank the text to ' + px.toFixed(1) + 'px (consider splitting the slide)' });
72
+ }
73
+ // A content slide with a title and nothing under it is usually a leftover: a stray --- before the real slide.
74
+ const content = slide.querySelector('.layout-content:not(.has-bg):not(.has-side) .slide-content');
75
+ if (content && !content.children.length && !content.textContent.trim()) {
76
+ problems.push({ severity: 'warning', message: 'the slide has a title and nothing else (a stray --- line?)' });
77
+ }
78
+ for (const d of body.querySelectorAll('pre.mermaid[data-error]')) {
79
+ problems.push({ severity: 'error', message: 'Mermaid diagram failed: ' + d.getAttribute('data-error') });
80
+ }
81
+ for (const pre of body.querySelectorAll('pre.code')) {
82
+ const size = parseFloat(getComputedStyle(pre).fontSize);
83
+ if (pre.scrollWidth - pre.clientWidth > TOL) problems.push({ severity: 'error', message: 'code is cut off at the right even at ' + size + 'px (shorten its longest line)' });
84
+ else if (pre.style.fontSize && size < ${MIN_CODE_PX}) problems.push({ severity: 'warning', message: 'code shrank to ' + size + 'px to fit (shorten its longest line, or give it more width)' });
85
+ if (pre.scrollHeight - pre.clientHeight > TOL) problems.push({ severity: 'error', message: 'code is cut off at the bottom by ' + Math.round(pre.scrollHeight - pre.clientHeight) + 'px' });
86
+ }
87
+ return problems;
88
+ });
89
+ })()`;
90
+ /** Run the measurements on an open deck page, with the table of contents in its current state. */
91
+ async function measure(cdp, sessionId) {
92
+ return evaluate(cdp, sessionId, MEASURE);
93
+ }
94
+ async function snapshot(cdp, sessionId, dir, count) {
95
+ mkdirSync(dir, { recursive: true });
96
+ for (let i = 0; i < count; i++) {
97
+ await evaluate(cdp, sessionId, `(() => { document.querySelectorAll('.deck-stage > .slide').forEach((s, k) => s.classList.toggle('active', k === ${i}));
98
+ return new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r))); })()`);
99
+ const { data } = await cdp.send('Page.captureScreenshot', { format: 'png', optimizeForSpeed: true }, sessionId);
100
+ writeFileSync(path.join(dir, `slide-${String(i + 1).padStart(2, '0')}.png`), Buffer.from(data, 'base64'));
101
+ }
102
+ }
103
+ /** Plain-text title of a slide, for messages. */
104
+ export function titleOf(deck, i) {
105
+ const s = deck.slides[i];
106
+ const heading = s.header ?? /^#{1,3}\s+.*$/m.exec(s.columns[0].markdown)?.[0] ?? '';
107
+ return heading.replace(/^#+\s+/, '').replace(/[*_`]/g, '').trim();
108
+ }
109
+ /** Render a built deck in headless Chrome and report layout problems, slide by slide. */
110
+ export async function checkDeck(html, deck, options = {}) {
111
+ return withDeckPage(html, async (cdp, sessionId) => {
112
+ const runs = [await measure(cdp, sessionId)];
113
+ const tocShown = await evaluate(cdp, sessionId, `document.querySelector('.deck').classList.contains('show-toc')`);
114
+ if (options.toc && !tocShown) {
115
+ // Toggling the class re-runs the runtime's code fitting through its observer; wait a frame for it.
116
+ await evaluate(cdp, sessionId, `(() => { document.querySelector('.deck').classList.add('show-toc');
117
+ return new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r))); })()`);
118
+ runs.push((await measure(cdp, sessionId)).map((ps) => ps.map((p) => ({ ...p, message: `with the table of contents shown, ${p.message}` }))));
119
+ await evaluate(cdp, sessionId, `document.querySelector('.deck').classList.remove('show-toc')`);
120
+ }
121
+ if (options.snapshots)
122
+ await snapshot(cdp, sessionId, options.snapshots, deck.slides.length);
123
+ const findings = [];
124
+ deck.slides.forEach((s, i) => {
125
+ for (const message of s.warnings ?? [])
126
+ findings.push({ slide: i + 1, line: s.line, file: s.file, title: titleOf(deck, i), severity: 'warning', message });
127
+ });
128
+ for (const run of runs) {
129
+ run.forEach((problems, i) => {
130
+ for (const p of problems) {
131
+ findings.push({ slide: i + 1, line: deck.slides[i].line, file: deck.slides[i].file, title: titleOf(deck, i), ...p });
132
+ }
133
+ });
134
+ }
135
+ return findings.sort((a, b) => a.slide - b.slide);
136
+ });
137
+ }
138
+ /** `talk.md:42: error: slide 7 "Title": content runs 38px past the bottom edge: p "…"` */
139
+ export function formatFinding(file, f) {
140
+ return `${f.file ? path.join(path.dirname(file), f.file) : file}:${f.line}: ${f.severity}: slide ${f.slide}${f.title ? ` "${f.title}"` : ''}: ${f.message}`;
141
+ }
142
+ //# sourceMappingURL=check.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"check.js","sourceRoot":"","sources":["../src/check.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AACnD,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAClC,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAY,MAAM,aAAa,CAAC;AAe/D,4FAA4F;AAC5F,MAAM,CAAC,MAAM,WAAW,GAAG,EAAE,CAAC;AAC9B,iGAAiG;AACjG,MA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KAAK,CAAC,CAAC;IACpD,CAAC,CAAC,CAAC;AACL,CAAC;AAED,0FAA0F;AAC1F,MAAM,UAAU,aAAa,CAAC,IAAY,EAAE,CAAU;IACpD,OAAO,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,CAAC,IAAI,KAAK,CAAC,CAAC,QAAQ,WAAW,CAAC,CAAC,KAAK,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,KAAK,GAAG,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC,OAAO,EAAE,CAAC;AAC9J,CAAC"}
@@ -0,0 +1,20 @@
1
+ /** Locate a Chromium-based browser; CHROME_PATH overrides the search. */
2
+ export declare function findChrome(): string;
3
+ /** Minimal Chrome DevTools Protocol client over Node's built-in WebSocket. */
4
+ export declare class Cdp {
5
+ private readonly ws;
6
+ private nextId;
7
+ private pending;
8
+ private constructor();
9
+ static connect(url: string): Promise<Cdp>;
10
+ send<T>(method: string, params?: Record<string, unknown>, sessionId?: string): Promise<T>;
11
+ close(): void;
12
+ }
13
+ export declare function evaluate<T>(cdp: Cdp, sessionId: string, expression: string): Promise<T>;
14
+ /**
15
+ * Open a built deck in headless Chrome at a 1280×720 viewport (scale 1), wait for `window.deckReady` (fonts,
16
+ * Mermaid diagrams, code fitting), then run `fn` on the page. Chrome and its temporary profile are cleaned up after.
17
+ */
18
+ export declare function withDeckPage<T>(html: string, fn: (cdp: Cdp, sessionId: string) => Promise<T>, options?: {
19
+ timeoutMs?: number;
20
+ }): Promise<T>;
package/dist/chrome.js ADDED
@@ -0,0 +1,162 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
3
+ import { tmpdir } from 'node:os';
4
+ import * as path from 'node:path';
5
+ import { pathToFileURL } from 'node:url';
6
+ import { DeckError } from './parse.js';
7
+ const CANDIDATES = {
8
+ darwin: [
9
+ '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
10
+ '/Applications/Chromium.app/Contents/MacOS/Chromium',
11
+ '/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge',
12
+ '/Applications/Brave Browser.app/Contents/MacOS/Brave Browser',
13
+ ],
14
+ linux: ['/usr/bin/google-chrome', '/usr/bin/google-chrome-stable', '/usr/bin/chromium', '/usr/bin/chromium-browser', '/snap/bin/chromium'],
15
+ win32: [
16
+ 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe',
17
+ 'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe',
18
+ 'C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe',
19
+ ],
20
+ };
21
+ /** Locate a Chromium-based browser; CHROME_PATH overrides the search. */
22
+ export function findChrome() {
23
+ const fromEnv = process.env.CHROME_PATH;
24
+ if (fromEnv) {
25
+ if (!existsSync(fromEnv))
26
+ throw new DeckError(`CHROME_PATH does not exist: ${fromEnv}`);
27
+ return fromEnv;
28
+ }
29
+ const found = (CANDIDATES[process.platform] ?? []).find((p) => existsSync(p));
30
+ if (!found)
31
+ throw new DeckError('no Chrome/Chromium found for PDF export; set CHROME_PATH to a Chromium-based browser');
32
+ return found;
33
+ }
34
+ /** Minimal Chrome DevTools Protocol client over Node's built-in WebSocket. */
35
+ export class Cdp {
36
+ ws;
37
+ nextId = 1;
38
+ pending = new Map();
39
+ constructor(ws) {
40
+ this.ws = ws;
41
+ ws.addEventListener('message', (ev) => {
42
+ const msg = JSON.parse(String(ev.data));
43
+ const p = msg.id !== undefined ? this.pending.get(msg.id) : undefined;
44
+ if (!p)
45
+ return;
46
+ this.pending.delete(msg.id);
47
+ if (msg.error)
48
+ p.reject(new DeckError(`Chrome: ${msg.error.message}`));
49
+ else
50
+ p.resolve(msg.result);
51
+ });
52
+ }
53
+ static connect(url) {
54
+ return new Promise((resolve, reject) => {
55
+ const ws = new WebSocket(url);
56
+ ws.addEventListener('open', () => resolve(new Cdp(ws)));
57
+ ws.addEventListener('error', () => reject(new DeckError(`cannot connect to Chrome at ${url}`)));
58
+ });
59
+ }
60
+ send(method, params = {}, sessionId) {
61
+ const id = this.nextId++;
62
+ this.ws.send(JSON.stringify({ id, method, params, ...(sessionId ? { sessionId } : {}) }));
63
+ return new Promise((resolve, reject) => this.pending.set(id, { resolve: resolve, reject }));
64
+ }
65
+ close() {
66
+ this.ws.close();
67
+ }
68
+ }
69
+ function launch(chrome, profile) {
70
+ const proc = spawn(chrome, [
71
+ '--headless=new',
72
+ '--disable-gpu',
73
+ '--hide-scrollbars',
74
+ '--no-first-run',
75
+ '--no-default-browser-check',
76
+ '--remote-debugging-port=0',
77
+ `--user-data-dir=${profile}`,
78
+ 'about:blank',
79
+ ]);
80
+ return new Promise((resolve, reject) => {
81
+ let log = '';
82
+ const timer = setTimeout(() => {
83
+ proc.kill();
84
+ reject(new DeckError('Chrome did not start within 20s'));
85
+ }, 20_000);
86
+ const onData = (chunk) => {
87
+ log += chunk.toString();
88
+ const m = /DevTools listening on (ws:\/\/\S+)/.exec(log);
89
+ if (m) {
90
+ proc.stderr.off('data', onData);
91
+ proc.stderr.resume(); // keep draining Chrome's log so it never blocks on a full pipe
92
+ clearTimeout(timer);
93
+ const exited = new Promise((done) => proc.once('exit', () => done()));
94
+ resolve({
95
+ wsUrl: m[1],
96
+ // Wait for Chrome to exit so its profile directory can be removed (at most 5s). The timer is cleared when
97
+ // Chrome exits first, or it would keep the process alive for the rest of the 5s.
98
+ kill: () => {
99
+ proc.kill();
100
+ let wait;
101
+ const late = new Promise((done) => { wait = setTimeout(done, 5_000); });
102
+ return Promise.race([exited, late]).finally(() => clearTimeout(wait));
103
+ },
104
+ });
105
+ }
106
+ };
107
+ proc.stderr.on('data', onData);
108
+ proc.once('exit', (code) => {
109
+ clearTimeout(timer);
110
+ reject(new DeckError(`Chrome exited (${code}) before it was ready`));
111
+ });
112
+ });
113
+ }
114
+ export async function evaluate(cdp, sessionId, expression) {
115
+ const r = await cdp.send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true }, sessionId);
116
+ if (r.exceptionDetails)
117
+ throw new DeckError(`page script failed: ${r.exceptionDetails.text}`);
118
+ return r.result.value;
119
+ }
120
+ /**
121
+ * Open a built deck in headless Chrome at a 1280×720 viewport (scale 1), wait for `window.deckReady` (fonts,
122
+ * Mermaid diagrams, code fitting), then run `fn` on the page. Chrome and its temporary profile are cleaned up after.
123
+ */
124
+ export async function withDeckPage(html, fn, options = {}) {
125
+ const chrome = findChrome();
126
+ const dir = mkdtempSync(path.join(tmpdir(), 'deck-chrome-'));
127
+ const page = path.join(dir, 'deck.html');
128
+ writeFileSync(page, html);
129
+ const { wsUrl, kill } = await launch(chrome, path.join(dir, 'profile'));
130
+ let cdp;
131
+ try {
132
+ cdp = await Cdp.connect(wsUrl);
133
+ const { targetId } = await cdp.send('Target.createTarget', { url: 'about:blank' });
134
+ const { sessionId } = await cdp.send('Target.attachToTarget', { targetId, flatten: true });
135
+ await cdp.send('Page.enable', {}, sessionId);
136
+ await cdp.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 720, deviceScaleFactor: 1, mobile: false }, sessionId);
137
+ await cdp.send('Page.navigate', { url: pathToFileURL(page).href }, sessionId);
138
+ const timeout = options.timeoutMs ?? 60_000;
139
+ const ready = await evaluate(cdp, sessionId, `new Promise((resolve) => {
140
+ const start = Date.now();
141
+ (function wait() {
142
+ if (document.readyState === 'complete' && window.deckReady) window.deckReady.then(() => resolve(true));
143
+ else if (Date.now() - start > ${timeout}) resolve(false);
144
+ else setTimeout(wait, 50);
145
+ })();
146
+ })`);
147
+ if (ready !== true)
148
+ throw new DeckError('the deck did not finish rendering before the timeout');
149
+ return await fn(cdp, sessionId);
150
+ }
151
+ finally {
152
+ cdp?.close();
153
+ await kill();
154
+ try {
155
+ rmSync(dir, { recursive: true, force: true, maxRetries: 3, retryDelay: 200 });
156
+ }
157
+ catch {
158
+ // A leftover temp profile is harmless; never fail over cleanup.
159
+ }
160
+ }
161
+ }
162
+ //# sourceMappingURL=chrome.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"chrome.js","sourceRoot":"","sources":["../src/chrome.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAC3C,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AACzE,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAClC,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAEvC,MAAM,UAAU,GAA6B;IAC3C,MAAM,EAAE;QACN,8DAA8D;QAC9D,oDAAoD;QACpD,gEAAgE;QAChE,8DAA8D;KAC/D;IACD,KAAK,EAAE,CAAC,wBAAwB,EAAE,+BAA+B,EAAE,mBAAmB,EAAE,2BAA2B,EAAE,oBAAoB,CAAC;IAC1I,KAAK,EAAE;QACL,4DAA4D;QAC5D,kEAAkE;QAClE,mEAAmE;KACpE;CACF,CAAC;AAEF,yEAAyE;AACzE,MAAM,UAAU,UAAU;IACxB,MAAM,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC,WAAW,CAAC;IACxC,IAAI,OAAO,EAAE,CAAC;QACZ,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC;YAAE,MAAM,IAAI,SAAS,CAAC,+BAA+B,OAAO,EAAE,CAAC,CAAC;QACxF,OAAO,OAAO,CAAC;IACjB,CAAC;IACD,MAAM,KAAK,GAAG,CAAC,UAAU,CAAC,OAAO,CAAC,QAAQ,CAAC,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,U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AAE,GAAG,EAAE,CAAC,CAAC;QAChF,CAAC;QAAC,MAAM,CAAC;YACP,gEAAgE;QAClE,CAAC;IACH,CAAC;AACH,CAAC"}
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,246 @@
1
+ #!/usr/bin/env node
2
+ import { writeFileSync } from 'node:fs';
3
+ import { execFileSync } from 'node:child_process';
4
+ import { homedir } from 'node:os';
5
+ import * as path from 'node:path';
6
+ import { buildDeck, builtinThemes, isThemePath, loadTheme, VERSION } from './build.js';
7
+ import { mediaDir, mediaWarnings } from './media.js';
8
+ import { DeckError } from './parse.js';
9
+ import { checkDeck, formatFinding } from './check.js';
10
+ import { checkTheme, formatThemeFinding } from './themecheck.js';
11
+ import { startDev } from './dev.js';
12
+ import { deckInfo, withAnalytics } from './analytics.js';
13
+ import { prerenderIfPossible, withMermaid } from './diagrams.js';
14
+ import { printPdf } from './pdf.js';
15
+ import { deckFileFor, initTheme, installSkill, newDeck } from './scaffold.js';
16
+ const USAGE = `Usage: deck <command> [options]
17
+
18
+ Commands:
19
+ new <talk.md | dir> [--title text] [--theme name] [--author name]
20
+ Start a deck from a starter outline (a folder gets <dir>/<dir>.md and images/)
21
+ build <deck.md> [-o out.html] [--theme name] [--media-dir dir]
22
+ Build a self-contained HTML page (default: next to the source). --media-dir
23
+ copies local videos into dir and links them, rather than inlining them.
24
+ pdf <deck.md> [-o out.pdf] [--theme name] [--vector]
25
+ Export a PDF that looks like the HTML (needs Chrome; CHROME_PATH overrides).
26
+ Backgrounds are captured as images; --vector keeps every layer as vectors.
27
+ check <deck.md> [--theme name] [--toc] [--snapshots dir]
28
+ Render every slide in headless Chrome and report overflow and clipped code,
29
+ with source lines; exits 1 on errors. --toc also checks with the table of
30
+ contents shown; --snapshots writes one PNG per slide.
31
+ editor <deck.md> [--port n] [--theme name] [--no-open]
32
+ Edit the deck in the browser: thumbnails, the current slide, and an editor
33
+ below it (formatted, or the file's Markdown) that saves to the files as you
34
+ type. Opens the browser unless --no-open; on 127.0.0.1 only. Without --port,
35
+ on 4300 or the next free port
36
+ dev <deck.md> [--port n] [--theme name]
37
+ Serve the deck with live reload: saving updates the slides that changed in
38
+ place; a theme or settings change reloads on the same slide. Without --port,
39
+ on 4300 or the next free port
40
+ themes List built-in themes
41
+ version Print the treasure-deck version (also --version, -v)
42
+ skill install [dir] Install the Claude skill for writing decks (default: ~/.claude/skills)
43
+ theme init <dir> [--from name] Scaffold a theme folder; use it with \`theme: ./<dir>\` in a deck.
44
+ --from copies a built-in theme to start from instead of the template.
45
+ theme check <name | dir> Check a theme: required tokens, every class styled, text contrast (WCAG AA)
46
+ [--snapshots dir] in light and dark, on a built-in specimen deck.
47
+
48
+ --theme takes a built-in name or a theme folder path (./my-theme).
49
+ `;
50
+ /** A path for messages: relative to the current directory when inside it, absolute otherwise. */
51
+ function shown(file) {
52
+ const rel = path.relative(process.cwd(), file);
53
+ return rel.startsWith('..') || path.isAbsolute(rel) ? path.resolve(file) : rel;
54
+ }
55
+ function outputPath(file, out) {
56
+ return out ?? file.replace(/\.md$/, '') + '.html';
57
+ }
58
+ async function build(file, out, theme, media) {
59
+ const dest = outputPath(file, out);
60
+ // A media folder on the command line is relative to the current directory, like -o.
61
+ const linker = media ? mediaDir(dest, path.resolve(media)) : undefined;
62
+ const built = buildDeck(file, { theme, mediaUrl: linker?.mediaUrl });
63
+ const { deck, theme: themeName } = built;
64
+ const html = withAnalytics(await prerenderIfPossible(built.html, (m) => console.warn(`warning: ${m}`), deck), deckInfo(file, built.title, themeName));
65
+ for (const m of mediaWarnings(Buffer.byteLength(html), built.inlined, built.videos, shown))
66
+ console.warn(`warning: ${m}`);
67
+ writeFileSync(dest, html);
68
+ console.log(`${shown(dest)}: ${deck.slides.length} slides, theme ${themeName}, ${(html.length / 1024).toFixed(0)} KB`);
69
+ linker?.prune();
70
+ if (linker?.copied.length) {
71
+ console.log(`${shown(path.resolve(media))}: ${linker.copied.length} video${linker.copied.length > 1 ? 's' : ''}, which the page links: keep the folder with it`);
72
+ }
73
+ return dest;
74
+ }
75
+ /** The author for a new deck: git's user.name when set. */
76
+ function gitUserName() {
77
+ try {
78
+ return execFileSync('git', ['config', 'user.name'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim() || undefined;
79
+ }
80
+ catch {
81
+ return undefined;
82
+ }
83
+ }
84
+ async function main(argv) {
85
+ const [cmd, ...rest] = argv;
86
+ if (cmd === 'version' || cmd === '--version' || cmd === '-v') {
87
+ console.log(VERSION);
88
+ return;
89
+ }
90
+ if (rest.includes('--help') || rest.includes('-h')) {
91
+ process.stdout.write(USAGE);
92
+ return;
93
+ }
94
+ const flag = (name) => {
95
+ const i = rest.indexOf(name);
96
+ const value = i >= 0 ? rest.splice(i, 2)[1] : undefined;
97
+ // A theme folder on the command line is relative to the current directory, not the deck.
98
+ return name === '--theme' && value && isThemePath(value) ? path.resolve(value) : value;
99
+ };
100
+ // Whatever is left after the flags is positional; a leftover option is a typo, never a file name.
101
+ const positional = () => {
102
+ const bad = rest.find((a) => a.startsWith('-'));
103
+ if (bad)
104
+ throw new DeckError(`unknown option ${bad} for ${cmd} (see deck --help)`);
105
+ return rest;
106
+ };
107
+ switch (cmd) {
108
+ case 'build': {
109
+ const out = flag('-o');
110
+ const theme = flag('--theme');
111
+ const media = flag('--media-dir');
112
+ if (!positional()[0])
113
+ throw new DeckError('build needs a deck Markdown file');
114
+ await build(rest[0], out, theme, media);
115
+ break;
116
+ }
117
+ case 'pdf': {
118
+ const out = flag('-o');
119
+ const theme = flag('--theme');
120
+ const vector = rest.includes('--vector');
121
+ if (vector)
122
+ rest.splice(rest.indexOf('--vector'), 1);
123
+ if (!positional()[0])
124
+ throw new DeckError('pdf needs a deck Markdown file');
125
+ const dest = out ?? rest[0].replace(/\.md$/, '') + '.pdf';
126
+ const { html, deck, theme: themeName } = buildDeck(rest[0], { theme });
127
+ await printPdf(withMermaid(html), dest, { rasterBackground: !vector });
128
+ console.log(`${shown(dest)}: ${deck.slides.length} pages, theme ${themeName}`);
129
+ break;
130
+ }
131
+ case 'check': {
132
+ const theme = flag('--theme');
133
+ const snapshots = flag('--snapshots');
134
+ const toc = rest.includes('--toc');
135
+ if (toc)
136
+ rest.splice(rest.indexOf('--toc'), 1);
137
+ if (!positional()[0])
138
+ throw new DeckError('check needs a deck Markdown file');
139
+ const file = rest[0];
140
+ const { html, deck } = buildDeck(file, { theme });
141
+ const findings = await checkDeck(withMermaid(html), deck, { toc, snapshots });
142
+ const name = shown(file);
143
+ for (const f of findings)
144
+ console.log(formatFinding(name, f));
145
+ const errors = findings.filter((f) => f.severity === 'error').length;
146
+ const warnings = findings.length - errors;
147
+ console.log(findings.length
148
+ ? `${name}: ${errors} error${errors === 1 ? '' : 's'}, ${warnings} warning${warnings === 1 ? '' : 's'} in ${deck.slides.length} slides`
149
+ : `${name}: ${deck.slides.length} slides, no problems found`);
150
+ if (snapshots)
151
+ console.log(`Snapshots: ${snapshots}/slide-NN.png`);
152
+ if (errors)
153
+ process.exitCode = 1;
154
+ break;
155
+ }
156
+ case 'dev':
157
+ case 'editor': {
158
+ const portFlag = flag('--port');
159
+ const port = portFlag === undefined ? undefined : Number(portFlag);
160
+ const theme = flag('--theme');
161
+ const take = (name) => rest.includes(name) && rest.splice(rest.indexOf(name), 1).length > 0;
162
+ // `dev --embed` is the editor as Treasure Work's dock starts it (no browser opened); kept for the dock.
163
+ const embed = cmd === 'editor' || take('--embed');
164
+ const open = cmd === 'editor' ? !take('--no-open') : undefined;
165
+ if (!positional()[0])
166
+ throw new DeckError(`${cmd} needs a deck Markdown file`);
167
+ const dev = startDev(rest[0], { port, theme, embed, open });
168
+ // Vite runs in middleware mode, so stopping is ours: close its watcher and channel, then the server.
169
+ let stopping = false;
170
+ const stop = () => {
171
+ if (stopping)
172
+ process.exit(1);
173
+ stopping = true;
174
+ dev.close().then(() => process.exit(0), () => process.exit(1));
175
+ };
176
+ for (const sig of ['SIGINT', 'SIGTERM', 'SIGHUP'])
177
+ process.on(sig, stop);
178
+ dev.listening.catch((e) => {
179
+ console.error(e.code === 'EADDRINUSE' && port !== undefined ? `deck ${cmd}: port ${port} is in use; choose another with --port` : `deck ${cmd}: ${e.message}`);
180
+ stopping = true;
181
+ dev.close().finally(() => process.exit(1));
182
+ });
183
+ break;
184
+ }
185
+ case 'new': {
186
+ const title = flag('--title');
187
+ const theme = flag('--theme');
188
+ const author = flag('--author') ?? gitUserName();
189
+ if (!positional()[0])
190
+ throw new DeckError('new needs a deck file (talk.md) or folder');
191
+ // flag() made a theme folder absolute; the frontmatter refers to it relative to the deck.
192
+ const deckDir = path.dirname(path.resolve(deckFileFor(rest[0])));
193
+ const themeRef = theme && isThemePath(theme) ? './' + path.relative(deckDir, theme).replace(/^\.\//, '') : theme;
194
+ const file = newDeck(rest[0], { title, theme: themeRef, author });
195
+ console.log(`${file}: new deck. Preview it with: deck dev ${file}`);
196
+ break;
197
+ }
198
+ case 'skill': {
199
+ if (positional()[0] !== 'install')
200
+ throw new DeckError('usage: deck skill install [dir]');
201
+ const dest = installSkill(rest[1] ? path.resolve(rest[1]) : path.join(homedir(), '.claude', 'skills'));
202
+ console.log(`Installed the treasure-deck skill to ${dest}`);
203
+ break;
204
+ }
205
+ case 'theme': {
206
+ const from = flag('--from');
207
+ const snapshots = flag('--snapshots');
208
+ if (positional()[0] === 'check') {
209
+ if (!rest[1])
210
+ throw new DeckError('usage: deck theme check <name | dir> [--snapshots dir]');
211
+ const target = isThemePath(rest[1]) ? path.resolve(rest[1]) : rest[1];
212
+ const { theme: name, findings } = await checkTheme(target, { snapshots });
213
+ for (const f of findings)
214
+ console.log(formatThemeFinding(name, f));
215
+ const errors = findings.filter((f) => f.severity === 'error').length;
216
+ const warnings = findings.length - errors;
217
+ console.log(findings.length ? `theme ${name}: ${errors} error${errors === 1 ? '' : 's'}, ${warnings} warning${warnings === 1 ? '' : 's'}` : `theme ${name}: no problems found (light and dark)`);
218
+ if (snapshots)
219
+ console.log(`Snapshots: ${snapshots}/<mode>-slide-NN.png`);
220
+ if (errors)
221
+ process.exitCode = 1;
222
+ break;
223
+ }
224
+ if (positional()[0] !== 'init' || !rest[1])
225
+ throw new DeckError('usage: deck theme init <dir> [--from <built-in theme>] | deck theme check <name | dir>');
226
+ const name = initTheme(rest[1], from);
227
+ console.log(`${rest[1]}: theme "${name}"${from ? ` (from ${from})` : ''}. Use it with \`theme: ./${path.basename(path.resolve(rest[1]))}\` in a deck next to it.`);
228
+ break;
229
+ }
230
+ case 'themes':
231
+ for (const name of builtinThemes())
232
+ console.log(`${name.padEnd(12)} ${loadTheme(name).manifest.description ?? ''}`);
233
+ break;
234
+ default:
235
+ process.stdout.write(USAGE);
236
+ if (cmd && cmd !== 'help' && cmd !== '--help')
237
+ process.exitCode = 1;
238
+ }
239
+ }
240
+ main(process.argv.slice(2)).catch((e) => {
241
+ if (!(e instanceof DeckError))
242
+ throw e;
243
+ console.error(`error: ${e.message}`);
244
+ process.exitCode = 1;
245
+ });
246
+ //# sourceMappingURL=cli.js.map